.NET, F#, Programming

How to read settings from configuration file in F#

During the work on one of the projects I had to make connection to the SQL server to fetch data. Most of the development time I spent in F# interactive – I create some sort of scratchpad script file (with fsx extension) and run VSCode with Ionide extension. This works like a charm with all features you expect from modern code editor like autocomplete, linting and syntax highlighting. Having built-in REPL allows you to use NuGet packages, load files with F# code, reference managed assemblies and execute selected parts of the code by pressing Alt+Enter directly in editor.

During development you could keep connection string in constant or variable, but at some stage, when you finalize project you want to move everything to config file. There is a problem related to this however. The way how default executable treated depends on the context. In case of F# project the default executable is the current project .config file. In case of F# interactive it is Fsi.exe.config. So solution which works fine for your F# project will fail when you run from F# interactive. I will show you how you can make it work in both contexts.

So, how to read configuration file in your F# project? Well, one great and simple option is just to use AppSettings type provider. It will expose your app.config in a strongly typed way. If you don’t know what type providers are please refer to the documentation. There is no direct analogy in C# to this concept. As author of F# language said:

A design-time component that computes a space of types and methods on-demand…

An adapter between data/services and the .NET type system…

On-demand, scalable compile-time provision of type/module definitions…

Don Syme

However in this post I would like to show you how you can create a simple abstraction to read connection string (or any other section like appSettings) and what caveats are on your way. Assume we have following app.config file in the root folder of our demo app:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="NinjaConnectionString" connectionString="Server=(localdb)\MsSqlLocalDb;Database=NinjaDb;Trusted_Connection=True;"/>
    </connectionStrings>
</configuration>

Solution for F# projects

Let’s create Configuration.fs file and start with class definition for our configuration abstraction:

type NinjaConfiguration() = class
    static member ConnectionString = ()
end

Ok, now we need a function to read a config file (assuming you have your configuration file in bin folder and named {project-executable}.config). Just add this section to your fsproj to copy app.config from your project’s root to bin on each build:

<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
        <Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\ninja_app.dll.config" />
</Target>

The function to read connection strings could look like this:

let private tryGetConnectionString (connectionStrings: ConnectionStringSettingsCollection) name =
    seq { for i in 0..connectionStrings.Count - 1 -> connectionStrings.[i] }
    |> Seq.tryFind(fun cfg -> cfg.Name = name)
    |> function
    | Some cs -> Some cs.ConnectionString
    | _ -> None

The signature of the function is

(ConnectionStringSettingsCollection -> string -> string option)

It takes ConnectionStringSettingsCollection and name of the connection element in your app.config and returns option of string with it’s value or None.

On line 2 we create a F# sequence expression to wrap standard .NET collection type. This will allow us to use any idiomatic F# language constructs which applicable to collections (think of all functions in Seq module, pipe operator, etc.).

On line 3 we immediately benefit from it by piping all elements from connection string section to Seq.tryFind and using lambda function to find only setting we need by name parameter. This will iterate over all entries in connection strings and compare it against Name property of ConnectionStringSettings class. If it finds an entry, Some of ConnectionStringSettings will be returned, otherwise None.

Lines 4-6 just extract connection string from it with a simple pattern matching.

Let’s update NinjaConfiguration class:

type NinjaConfiguration() = class
    static member ConnectionString = 
        tryGetConnectionString ConfigurationManager.ConnectionStrings "NinjaConnectionString"
end

This is already working code, however without error handling it is not complete, so let’s add try-with section to be sure that when file is missing we not bubble up runtime exception in your face:

type NinjaConfiguration() = class
    static member ConnectionString = 
        try
            tryGetConnectionString ConfigurationManager.ConnectionStrings "NinjaConnectionString"
        with
            | Failure (_) -> None
end

Much better. If there is a problem with finding or opening configuration file we return None. Same for the case when there no connection string with NinjaConnectionString name found. Put it all together we should come up with this code:

module Ninja.Configuration

open System.Configuration

let private tryGetConnectionString (connectionStrings: ConnectionStringSettingsCollection) name =
    seq { for i in 0..connectionStrings.Count - 1 -> connectionStrings.[i] }
    |> Seq.tryFind(fun cfg -> cfg.Name = name)
    |> function
    | Some cs -> Some cs.ConnectionString
    | _ -> None

type NinjaConfiguration() = class
    static member ConnectionString =
        try
            tryGetConnectionString ConfigurationManager.ConnectionStrings "NinjaConnectionString"
        with
           | Failure(_) -> None
end

Extending solution to work in F# interactive

Previous solution works fine when you run it with F5 in VSCode or Visual Studio IDE or via dotnet run command line. But how to make it work in F# interactive?

Let’s create simple scratchpad.fsx to use NinjaConfiguration in F# interactive:

#r "nuget: System.Configuration.ConfigurationManager" // install NuGet package needed for Configuration.fs
#load "Configuration.fs" // load our NinjaConfiguration class

open Ninja.Configuration // open module so that type will be available for use
let connStr = NinjaConfiguration.ConnectionString

val connStr : string option = None. 

App.config in the same folder where scratchpad.fsx and Configuration.fs. So why result is None? The answer is that default path for lookup will be fsi.exe and since we used ConfigurationManager.ConnectionStrings it will start search config file from global scope (machine.config). So to solve that issue we need to set current directory for F# interactive and map configuration file to that folder. To make it work in both contexts we need to add conditional compiler directive (let’s call it COMPILED). Let’s make final changes to our code in Configuration.fs to the following snippet:

module Ninja.Configuration

open System.Configuration

let [<Literal>] private DbConnectionStringName = "NinjaConnectionString"

let private tryGetConnectionString (connectionStrings: ConnectionStringSettingsCollection) name =
    seq { for i in 0..connectionStrings.Count - 1 -> connectionStrings.[i] }
    |> Seq.tryFind(fun cfg -> cfg.Name = name)
    |> function
    | Some cs -> Some cs.ConnectionString
    | _ -> None

type NinjaConfiguration() = class
    static member ConnectionString =
        try
            // Executes in F# project/solution when provided COMPILED compilation directive
            #if COMPILED 
                tryGetConnectionString ConfigurationManager.ConnectionStrings DbConnectionStringName
            #else // Executes in script environment (fsx file)
                System.IO.Directory.SetCurrentDirectory (__SOURCE_DIRECTORY__)
                let fileMap = ExeConfigurationFileMap()
                fileMap.ExeConfigFilename <- "app.config"
                let config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
                tryGetConnectionString config.ConnectionStrings.ConnectionStrings DbConnectionStringName
            #endif
        with
           | Failure(_) -> None
end

After change re-execute following lines in the script:

#load "Configuration.fs" // load our NinjaConfiguration class

open Ninja.Configuration // open module so that type will be available for use
let connStr = NinjaConfiguration.ConnectionString

Now result is:

val connStr: string option = Some "Server=(localdb)\MsSqlLocalDb;Database=NinjaDb;Trusted_Connection=True;"

After adjustments the code in Configuration.fs will work in both cases: as a part of F# project or in F# interactive. Same principle applies to any IO: if you want your code to work in both contexts you need to take this in consideration.

Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s