Thursday, September 29, 2011

A Simple AppSettings Type Provider

With the F# 3.0 Developer Preview now available, I've been spending a decent chunk of my free time playing with Type Providers. With the announcement of the introductory guide and samples for authoring type providers I've had a hard time putting down the computer to sleep (let alone eat).

After a fair amount of experimentation, I've written my first type provider. It is admittedly quite simple and isn't production quality, but it has been a fun exercise. The basic idea is to read the appSettings elements from a config file, parse the values appropriately, and interact with them in a type safe way.

The sample config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="test2" value="Some Test Value 5"/>
        <add key="TestInt" value="102"/>
        <add key="TestBool" value="True"/>
        <add key="TestDouble" value="10.01"/>
    </appSettings>
</configuration>
Here's the TypeProvider code:

Lastly, here's an example of how to use it.
#r "System"
#r @"bin\debug\AppSettingsTypeProvider.dll"

open System
open AppSettingsTypeProvider

type settings = AppSettings<"App.config">
printfn "Test2 String: %s" settings.test2 
printfn "Test Int: %i" settings.TestInt 
printfn "Test Bool: %b" settings.TestBool  
printfn "Test Double: %f" settings.TestDouble

No comments:

Post a Comment

Post a Comment