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:
- class Test
- {
- public Int32 TestID { get; set; }
- public String Name { get; set; }
- }

And all I have to do to get the data out is this:
- public static IEnumerable<Test> GetAllTests()
- {
- const String sql = "select testid, name from tbTest";
- return Execute.Command(sql, CommandType.Text,
- rec =>
- {
- return new Test
- {
- TestID = rec.GetInt32(0),
- Name = rec.GetString(1)
- };
- });
- }
- private static void GetAllTestsAsync(Action<Test[]> callback)
- {
- Int32
- idOrdinal = -1,
- nameOrdinal = -1;
- const String sql = "select testid, name from tbTest";
- Execute.CommandAsync<Test>(
- sql,
- CommandType.Text,
- rec =>
- {
- return new Test
- {
- TestID = rec.GetInt32(idOrdinal),
- Name = rec.GetString(nameOrdinal)
- };
- },
- callback);
- }
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.
- #light
- namespace Cochran.FSharpData
- open System.Data
- open System.Data.SqlClient
- // TODO: Handle output parameters
- type Param =
- { Name:string
- Value:System.Object }
- type CommandData =
- { sql: string
- parameters: Param array
- cmdType: CommandType
- connectionString: string };;
- module public Fetcher =
- open System.Data
- open System.Data.SqlClient
- open System.Configuration
- open System.Xml
- // extension methods so we can
- // execute the commands asynchronously
- type internal System.Data.SqlClient.SqlCommand with
- member x.ExecuteReaderAsync() =
- Async.BuildPrimitive(x.BeginExecuteReader, x.EndExecuteReader)
- member x.ExecuteNonQueryAsync() =
- Async.BuildPrimitive(x.BeginExecuteNonQuery, x.EndExecuteNonQuery)
- member x.ExecuteXmlReaderAsync() =
- Async.BuildPrimitive(x.BeginExecuteXmlReader, x.EndExecuteXmlReader)
- let internal BuildCommand connection (data:CommandData) =
- let result =
- new SqlCommand(data.sql, connection)
- let parameters =
- data.parameters
- |> Seq.map (fun p -> new SqlParameter(p.Name, p.Value))
- |> Seq.to_array
- result.CommandType <- data.cmdType
- result.Parameters.AddRange(parameters)
- result
- let internal ReadAndMapAsync data (premap:IDataReader -> unit) (mapper:IDataRecord -> 'a) =
- let mapReader (rdr:IDataReader) =
- seq { while rdr.Read() do yield mapper rdr } // seq workflow
- async { // async workflow
- use connection =
- new SqlConnection (data.connectionString)
- connection.Open()
- use command =
- BuildCommand connection data
- let! rdr =
- command.ExecuteReaderAsync()
- premap rdr
- let result = mapReader rdr
- return result |> Seq.to_array }
- // note: we need to avoid lazy calculation here... or the reader will have been disposed
- let internal GetXmlAsync data =
- async {
- use connection = new SqlConnection (data.connectionString)
- use command = BuildCommand connection data
- use! rdr = command.ExecuteXmlReaderAsync()
- return rdr.ReadOuterXml() }
- let internal ExecuteNonQueryAsync data =
- async {
- use connection = new SqlConnection (data.connectionString)
- use command = BuildCommand connection data
- let! result = command.ExecuteNonQueryAsync()
- return result }
- // Synchronous methods
- let ReadAndMap data premap mapper = Async.Run(ReadAndMapAsync data premap mapper)
- let GetXml data = Async.Run(GetXmlAsync data)
- let ExecuteNonQuery data = Async.Run(ExecuteNonQueryAsync data)
- // Async methods with postbacks
- let ReadAndMapAsyncWithPostback data premap mapper postback = Async.SpawnThenPostBack(ReadAndMapAsync data premap mapper, postback)
- let GetXmlAsyncWithPotback data postback = Async.SpawnThenPostBack(GetXmlAsync data, postback)
- let ExecuteNonQueryAsyncWithPostback data postback = Async.SpawnThenPostBack(ExecuteNonQueryAsync data, postback)
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:
- public static class Fetcher
- {
- public static int ExecuteNonQuery(CommandData data);
- public static void ExecuteNonQueryAsyncWithPostback(CommandData data, FastFunc<int, Unit> postback);
- public static string GetXml(CommandData data);
- public static void GetXmlAsyncWithPotback(CommandData data, FastFunc<string, Unit> postback);
- public static T[] ReadAndMap<T>(CommandData data, FastFunc<IDataReader, Unit> premap, FastFunc<IDataRecord, T> mapper);
- public static void ReadAndMapAsyncWithPostback<T>(CommandData data, FastFunc<IDataReader, Unit> premap, FastFunc<IDataRecord, T> mapper, FastFunc<T[], Unit> postback);
- }
- public abstract class FastFunc<T, U>
- {
- public FastFunc();
- [OverloadID("FromConverter")]
- public static implicit operator FastFunc<T, U>(Converter<T, U> f);
- [OverloadID("ToConverter")]
- public static implicit operator Converter<T, U>(FastFunc<T, U> f);
- public abstract override U Invoke(T __p1);
- public static V InvokeFast2<V>(FastFunc<T, FastFunc<U, V>> f, T t, U u);
- public static W InvokeFast3<V, W>(FastFunc<T, FastFunc<U, FastFunc<V, W>>> f, T t, U u, V v);
- 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);
- 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);
- }
- public static T[] ReadAndMap<T>(CommandData data, FastFunc<IDataReader, Unit> premap, FastFunc<IDataRecord, T> mapper);
- internal static class DelegateExtensionMethods
- {
- public static Converter<T, Unit> ToConverter<T>(this Action<T> action)
- {
- return new Converter<T, Unit>(value =>
- {
- action(value);
- return null; // equivilant to F# 'Unit'
- });
- }
- }
- internal static class CommandDataFactory
- {
- private static String GetConnectionString()
- {
- return ConfigurationManager.ConnectionStrings["db"].ConnectionString;
- }
- public static CommandData Build(String sql, CommandType type)
- {
- return Build(sql, type, new Param[0]);
- }
- public static CommandData Build(String sql, CommandType type, Param[] parameters)
- {
- return new CommandData(sql, parameters, type, GetConnectionString());
- }
- }
- public static class Execute
- {
- public static IEnumerable<T> Command<T>(String sql, CommandType type, Action<IDataReader> onPreMap, Converter<IDataRecord, T> onMap, params Param[] parameters)
- {
- CommandData data = CommandDataFactory.Build(sql, type, parameters);
- return Fetcher.ReadAndMap<T>(data, onPreMap.ToConverter(), onMap);
- }
- }
For command line apps, we can put this initializing code in a static constructor or in the Main() method:
- class Program
- {
- static Program()
- {
- System.Threading.SynchronizationContext
- .SetSynchronizationContext(new SynchronizationContext());
- }
- }
- public static class Execute
- {
- private const String
- c_SynchronizationContextNotSetMessage = @"
- In order for async calls to work, F# needs the SynchronizationContext set.
- In WinForms this is taken care of automatically, if you are using a dll/command line,
- you can set the context using the following code:
- System.Threading.SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
- ";
- public static void AssertSynchronizationContextIsSet()
- {
- if (null == SynchronizationContext.Current)
- throw new InvalidOperationException(c_SynchronizationContextNotSetMessage);
- }
- public static void CommandAsync(String sql, CommandType type, Action<Int32> callback, params Param[] parameters)
- {
- AssertSynchronizationContextIsSet();
- CommandData data = CommandDataFactory.Build(sql, type, parameters);
- Fetcher.ExecuteNonQueryAsyncWithPostback(
- data,
- callback.ToConverter());
- }
- }
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
MichaelPosted Apr 14, 2009, 6:31 PM
It's interesting but I see nothing particularly compelling about doing this data interface in F# rather than C#