Created
October 7, 2011 00:22
-
-
Save dmohl/1269106 to your computer and use it in GitHub Desktop.
AppSettings Type Provider with FSharpx.TypeProviderDSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SampleTypeProviderWithFSharxDSL | |
open FSharpx.TypeProviders.DSL | |
open Microsoft.FSharp.Core.CompilerServices | |
open Samples.FSharpPreviewRelease2011.ProvidedTypes | |
open System | |
open System.Configuration | |
open System.IO | |
open System.Reflection | |
let rootNamespace = "SampleTypeProviderWithFSharxDSL" | |
let thisAssembly = Assembly.GetExecutingAssembly() | |
let tryParseWith func = func >> function | |
| true, value -> Some value | |
| false, _ -> None | |
let (|Bool|_|) = tryParseWith Boolean.TryParse | |
let (|Int|_|) = tryParseWith Int32.TryParse | |
let (|Double|_|) = tryParseWith Double.TryParse | |
let addTypedAppSettings (cfg:TypeProviderConfig) (configFileName:string) (tyDef:ProvidedTypeDefinition) = | |
try | |
let filePath = Path.Combine(cfg.ResolutionFolder, configFileName) | |
let fileMap = ExeConfigurationFileMap(ExeConfigFilename=filePath) | |
let appSettings = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None).AppSettings.Settings | |
Seq.iter (fun (key) -> | |
tyDef | |
|+> match (appSettings.Item key).Value with | |
| Int fieldValue -> literalField key fieldValue | |
| Bool fieldValue -> literalField key fieldValue | |
| Double fieldValue -> literalField key fieldValue | |
| fieldValue -> literalField key fieldValue | |
|> addXmlDoc (sprintf "Returns the value from the appSetting with key %s" key) | |
|> ignore) appSettings.AllKeys | |
tyDef | |
with | |
| exn -> tyDef | |
let typedAppSettings (cfg:TypeProviderConfig) = | |
erasedType<obj> thisAssembly rootNamespace "AppSettings" | |
|> staticParameter "configFileName" (fun typeName configFileName -> | |
erasedType<obj> thisAssembly rootNamespace typeName | |
|> addTypedAppSettings cfg configFileName ) | |
[<TypeProvider>] | |
type public SampleAppSettingProvider(cfg:TypeProviderConfig) as this = | |
inherit TypeProviderForNamespaces() | |
do this.AddNamespace(rootNamespace, [typedAppSettings cfg]) | |
[<TypeProviderAssembly>] | |
do () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment