F# Data Abstraction Layer For C#

If you have read my previous articles, you'll see I have a strong interest in detangling as much plumbing code as possible from the business logic.  This makes for much more cohesive code that is more robust and easier to change as the domain we are modeling changes.  This is important because domain level code changes at a different rate than the plumbing code and tends to be a bit more atomic.  Plumbing code will usually change infrequently in comparison to domain code, especially as the code base matures.  The plumbing changes usually have much more dramatic effects such as cascading breaks because it is tied to the domain logic in multiple laces.  So if we have plumbing that works, it's best not to knock about the old reliable pipes while we're cranking on the wrench to tweak the domain. 

Also, I really like the compact syntax of F#.   We can do a lot more with much less code and the 'flow' of the code is very easy to change in relation to other F# constructs as compared to C#, where the structure of the code is easier to change in relation to other C# constructs.  Also, programming multithreaded code is much simpler in F#.  Usually most coding challenges just naturally lean towards either an OOP or functional approach. The really cool thing is that both languages boil down to IL so we can build an assembly in F# and (with a few helper classes) consume it with C# or vice versa.

As a teaser, I'll show you the consumer of the F# library first:

Let's say I have a simple business object:

  1. class Test  
  2. {  
  3.     public Int32 TestID { getset; }  
  4.     public String Name { getset; }  
  5. }
And a simple table:

image001.png

And all I have to do to get the data out is this:

  1. public static IEnumerable<Test> GetAllTests()  
  2. {  
  3.     const String sql = "select testid, name from tbTest";  
  4.     return Execute.Command(sql, CommandType.Text,  
  5.         rec =>  
  6.         {  
  7.             return new Test  
  8.             {  
  9.                 TestID = rec.GetInt32(0),  
  10.                 Name = rec.GetString(1)  
  11.             };  
  12.         });  
  13. }
Or if I want to take advantage of an asynchronous call to sql server I can build a method and provide a callback method for when the operation is complete (which is actually marshaled back to the calling thread).
  1. private static void GetAllTestsAsync(Action<Test[]> callback)  
  2. {  
  3.     Int32  
  4.         idOrdinal = -1,  
  5.         nameOrdinal = -1;  
  6.     const String sql = "select testid, name from tbTest";  
  7.     Execute.CommandAsync<Test>(  
  8.         sql,  
  9.         CommandType.Text,  
  10.         rec =>  
  11.         {  
  12.             return new Test  
  13.             {  
  14.                 TestID = rec.GetInt32(idOrdinal),  
  15.                 Name = rec.GetString(nameOrdinal)  
  16.             };  
  17.         },  
  18.         callback);  

Notice how all the object lifetime management is gone (using blocks around IDisposables) and all the C# plumbing to perform asynchronous calls is gone.  Even though we are selecting from a SqlServer datatbase, there is not a single reference to anything in the System.Data.SqlClient namespace. 

The F# code.

The F# code for the utility is very small.  Below is all the code needed for our abstraction layer.  We have two classes: the Param class for providing a holder for data needed for building SqlDataParameters, and a CommandData class for passing in all our query input.

  1. #light  
  2. namespace Cochran.FSharpData  
  3.   open System.Data  
  4.   open System.Data.SqlClient  
  5.  // TODO: Handle output parameters  
  6.   type Param =  
  7.     { Name:string  
  8.       Value:System.Object }  
  9.   type CommandData =  
  10.     { sql: string  
  11.       parameters: Param array  
  12.       cmdType: CommandType  
  13.       connectionString: string };; 
The rest of our code lives in a 'Fetcher' module that is compiled to a static class is where the work is done.  After we import our namespaces, I wrote a few extension methods for converting the SqlCommand asynchronous methods to a format we can consume in an F# async workflow.
  1. module public Fetcher =  
  2.   open System.Data  
  3.   open System.Data.SqlClient  
  4.   open System.Configuration  
  5.   open System.Xml  
  6.   // extension methods so we can  
  7.   // execute the commands asynchronously  
  8.   type internal System.Data.SqlClient.SqlCommand with  
  9.     member x.ExecuteReaderAsync() =  
  10.       Async.BuildPrimitive(x.BeginExecuteReader, x.EndExecuteReader)  
  11.     member x.ExecuteNonQueryAsync() =  
  12.       Async.BuildPrimitive(x.BeginExecuteNonQuery, x.EndExecuteNonQuery)  
  13.     member x.ExecuteXmlReaderAsync() =  
  14.       Async.BuildPrimitive(x.BeginExecuteXmlReader, x.EndExecuteXmlReader) 
Next (still in the 'Fetcher' module), we have a builder method to make a SqlCommand from our input.
  1. let internal BuildCommand connection (data:CommandData) =  
  2.     let result =  
  3.       new SqlCommand(data.sql, connection)  
  4.     let parameters =  
  5.       data.parameters  
  6.       |> Seq.map (fun p -> new SqlParameter(p.Name, p.Value))  
  7.       |> Seq.to_array  
  8.     result.CommandType <- data.cmdType  
  9.     result.Parameters.AddRange(parameters)  
  10.     result 
Now we have our calls to the SqlCommand which we execute asynchronously.  First we provide a asynchronous call to the ExecuteReader().  This code has a few interesting things I'd like to point out.  First we take advantage of the workflow syntax to build our sequence (an enumerator) and also execute our async call.  Because the enumerator is lazy executed, we have to make sure it is fully executed before the SqlDataReader goes out of scope and is disposed or we will get an exception because the reader will be closed.
  1. let internal ReadAndMapAsync data (premap:IDataReader -> unit) (mapper:IDataRecord -> 'a) =  
  2.     let mapReader (rdr:IDataReader) =  
  3.       seq { while rdr.Read() do yield mapper rdr } // seq workflow  
  4.     async { // async workflow  
  5.             use connection =  
  6.               new SqlConnection (data.connectionString)  
  7.             connection.Open()  
  8.             use command =  
  9.               BuildCommand connection data  
  10.             let! rdr =  
  11.               command.ExecuteReaderAsync()  
  12.             premap rdr  
  13.             let result = mapReader rdr  
  14.             return result |> Seq.to_array } 
  15. // note: we need to avoid lazy calculation here... or the reader will have been disposed 
The async calls to ExecuteNonQuery() and ExecuteXmlReader() are fairly simple in comparison.
  1. let internal GetXmlAsync data =  
  2.   async {  
  3.       use connection = new SqlConnection (data.connectionString)  
  4.       use command = BuildCommand connection data  
  5.       use! rdr = command.ExecuteXmlReaderAsync()   
  6.       return rdr.ReadOuterXml() }  
  7. let internal ExecuteNonQueryAsync data =  
  8.   async {  
  9.     use connection = new SqlConnection (data.connectionString)  
  10.     use command = BuildCommand connection data  
  11.     let! result = command.ExecuteNonQueryAsync()  
  12.     return result }   
And finally we have our publically exposed surface are of the module which consists of the synchronous calls and their asynchronous equivalents with the callback methods.
  1. // Synchronous methods    
  2. let ReadAndMap data premap mapper = Async.Run(ReadAndMapAsync data premap mapper)    
  3. let GetXml data = Async.Run(GetXmlAsync data)  
  4. let ExecuteNonQuery data = Async.Run(ExecuteNonQueryAsync data)  
  5. // Async methods with postbacks  
  6. let ReadAndMapAsyncWithPostback data premap mapper postback = Async.SpawnThenPostBack(ReadAndMapAsync data premap mapper, postback)  
  7. let GetXmlAsyncWithPotback data postback = Async.SpawnThenPostBack(GetXmlAsync data, postback)  
  8. let ExecuteNonQueryAsyncWithPostback data postback = Async.SpawnThenPostBack(ExecuteNonQueryAsync data, postback) 
That is all the F# code required for the utility.  We have a complete abstraction layer in a file with only 82 lines.

C#/F# interop

Consuming F# code with C# is relatively straightforward as long as you know which C# constructs to use.  The first thing we need to do is add references to both the F# utility (above) and also the FSharp.Core library (from the GAC).  We will look at building a few helper methods in order to seamlessly connect with our F# utility library.

Here is the surface of our F# module as C# sees it:

  1. public static class Fetcher  
  2. {  
  3.     public static int ExecuteNonQuery(CommandData data);  
  4.     public static void ExecuteNonQueryAsyncWithPostback(CommandData data, FastFunc<int, Unit> postback);  
  5.     public static string GetXml(CommandData data);  
  6.     public static void GetXmlAsyncWithPotback(CommandData data, FastFunc<string, Unit> postback);  
  7.     public static T[] ReadAndMap<T>(CommandData data, FastFunc<IDataReader, Unit> premap, FastFunc<IDataRecord, T> mapper);  
  8.     public static void ReadAndMapAsyncWithPostback<T>(CommandData data, FastFunc<IDataReader, Unit> premap, FastFunc<IDataRecord, T> mapper, FastFunc<T[], Unit> postback);  
  9. }
FSharp has a construct that can be thought of as another manifestation of a C# delegate called a FastFunc<T,U>.  This is the type of object that the 'premap' and 'mapper' parameters in the ReadAndMap() method  will be expecting.  To make the call 'clean' we need a way to get FastFunc<T,U> objects from  the delegates we are familiar with in C#.  Fortunately, there is an implicit conversion between a Converter<T,U> delegate and a FastFunc<T, U> class.  This means we can pass in Converter<T,U> delegates wherever a FastFunc<T,U> is expected and the implied conversion method will automatically be called for us.
  1. public abstract class FastFunc<T, U>  
  2. {  
  3.     public FastFunc();  
  4.     [OverloadID("FromConverter")]  
  5.     public static implicit operator FastFunc<T, U>(Converter<T, U> f);  
  6.     [OverloadID("ToConverter")]  
  7.     public static implicit operator Converter<T, U>(FastFunc<T, U> f);  
  8.     public abstract override U Invoke(T __p1);  
  9.     public static V InvokeFast2<V>(FastFunc<T, FastFunc<U, V>> f, T t, U u);  
  10.     public static W InvokeFast3<V, W>(FastFunc<T, FastFunc<U, FastFunc<V, W>>> f, T t, U u, V v);  
  11.     public static X InvokeFast4<V, W, X>(FastFunc<T, FastFunc<U, FastFunc<V, FastFunc<W, X>>>> f, T t, U u, V v, W w);  
  12.     public static Y InvokeFast5<V, W, X, Y>(FastFunc<T, FastFunc<U, FastFunc<V, FastFunc<W, FastFunc<X, Y>>>>> f, T t, U u, V v, W w, X x);  

One of the small things we'll have to manually take care of is the calling of FastFunc<T,U> that expect a 'Unit' type.   F#'s 'Unit" is equivalent to C#'s 'null' and a F# FastFunc<T, Unit> is really the same thing as a C# Action<T> or a method that does not return anything  even though it actually returns 'null'.
  1. public static T[] ReadAndMap<T>(CommandData data, FastFunc<IDataReader, Unit> premap, FastFunc<IDataRecord, T> mapper); 
So we'll create an extension method to convert an Action<T> into a Conversion<T,Unit> which can then be implicitly converted to a FastFunc<T, Unit>.
  1. internal static class DelegateExtensionMethods  
  2. {  
  3.     public static Converter<T, Unit> ToConverter<T>(this Action<T> action)  
  4.     {  
  5.         return new Converter<T, Unit>(value =>  
  6.         {  
  7.             action(value);  
  8.             return null;  // equivilant to F# 'Unit'  
  9.         });  
  10.     }  
  11. }
It would also be nice to get the connection string from the configuration file, so we'll handle this in a class we can use to easily instantiate the CommandData class defined in our F# utility.
  1. internal static class CommandDataFactory  
  2. {  
  3.     private static String GetConnectionString()  
  4.     {  
  5.         return ConfigurationManager.ConnectionStrings["db"].ConnectionString;  
  6.     }  
  7.     public static CommandData Build(String sql, CommandType type)  
  8.     {  
  9.         return Build(sql, type, new Param[0]);  
  10.     }  
  11.     public static CommandData Build(String sql, CommandType type, Param[] parameters)  
  12.     {  
  13.         return new CommandData(sql, parameters, type, GetConnectionString());  
  14.     }  

And finally we'll build a class to hide the small bit of interop plumbing.  The method below builds our command and calls the F# module.  The purpose of this class is to give us complete isolation from any plumbing and provide a simple surface with only C# constructs that we can consume from any C# code using the utility.  Notice how it serves to isolate any remaining "messy" plumbing (in this case, having to convert Action<T> to a FastFunc<T, Unit>) from the consumer.  This allows us to change the underlying implementation in the future without paying too high a price as long as the 'Execute' class surface area does not change.
  1. public static class Execute  
  2. {  
  3.     public static IEnumerable<T> Command<T>(String sql, CommandType type, Action<IDataReader> onPreMap, Converter<IDataRecord, T> onMap, params Param[] parameters)  
  4.     {  
  5.         CommandData data = CommandDataFactory.Build(sql, type, parameters);  
  6.         return Fetcher.ReadAndMap<T>(data, onPreMap.ToConverter(), onMap);  
  7.     }  

One thing to note is that consuming the F# construct "Async.SpawnThenPostBack()" actually marshals the callback to the thread calling the method.  This is very convenient for win form apps because we can execute the async calls and not have to explicitly call the "Form.Invoke()" to get the main thread back.  The downside to this is that we need to ensure that we have a SynchronizationContext set up for the callback to behave correctly.

For command line apps, we can put this initializing code in a static constructor or in the Main() method:

  1. class Program  
  2. {  
  3.     static Program()  
  4.     {  
  5.         System.Threading.SynchronizationContext  
  6.             .SetSynchronizationContext(new SynchronizationContext());  
  7.     }  
  8. }
If we are consuming our F# utility through a dll, the SynchronizationContext will need to be set at some point.  I think throwing a meaningful exception is probably the best bet for helping the developer consuming our C# library to make sure implementation is correct as in the following code:
  1. public static class Execute  
  2. {  
  3.     private const String  
  4.         c_SynchronizationContextNotSetMessage = @"  
  5. In order for async calls to work, F# needs the SynchronizationContext set.  
  6. In WinForms this is taken care of automatically, if you are using a dll/command line,  
  7. you can set the context using the following code:  
  8. System.Threading.SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());  
  9. ";  
  10.     public static void AssertSynchronizationContextIsSet()  
  11.     {  
  12.         if (null == SynchronizationContext.Current)  
  13.             throw new InvalidOperationException(c_SynchronizationContextNotSetMessage);  
  14.     }  
  15.     public static void CommandAsync(String sql, CommandType type, Action<Int32> callback, params Param[] parameters)  
  16.     {  
  17.         AssertSynchronizationContextIsSet();  
  18.         CommandData data = CommandDataFactory.Build(sql, type, parameters);  
  19.         Fetcher.ExecuteNonQueryAsyncWithPostback(  
  20.             data,  
  21.             callback.ToConverter());  
  22.     }  

Wrap-Up

So, as you can see, with very minimal code to maintain, we have a complete abstraction from ADO.NET and now our domain code can safely live on its own isolated code island.  One of the cool things about this approach is how easy it is to consume F# so we can take advantages of its strengths and at the same time have C# do what it does best.  There is still a small bit of plumbing to convert C# Action<T> delegates to the Converter<T,Unit> (so we can get to a F# FastFunc<T,U>)  but other than that, it is a pretty clean interaction between the two different language's constructs.  It would be really nice to eventually see an implicit conversion from an Action<T> to a FastFunc<T,Unit> baked into F# at some point.

The more I use F#, the more I see how applicable it is in real-world scenarios that lend themselves to a functional programming approach.  This becomes a powerful combination when used in conjunction with C# where each approach can play to its strengths. 

Until next time,
Happy coding


Similar Articles