forked from microsoft/fsharplu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Configuration.fs
70 lines (60 loc) · 2.64 KB
/
Configuration.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
////
//// Accessing settings from .Net app.config configuration
////
module Microsoft.FSharpLu.Configuration
open System.Configuration
open System.Reflection
open System.Runtime.CompilerServices
open Microsoft.FSharpLu
/// Read a configuration value.
/// Default implementation: read from the application configuration manager
let mutable public tryGetConfigValue =
fun (key:string) ->
match System.Configuration.ConfigurationManager.AppSettings.Get(key) with
| null -> None
| v -> Some v
/// Read a configuration value
let public getConfigValue key =
tryGetConfigValue key |> Option.orDo (fun () -> invalidOp (sprintf "Configuration key %s missing from config file" key))
/// Set a configuration value
let mutable public setConfigValue =
fun key value ->
System.Configuration.ConfigurationManager.AppSettings.Set(key, value)
/// Get an array type value from the configuration file
let public getConfigArray name =
getConfigValue name
|> Text.splitNoEmptyEntries [|';'; '\t'; '\n'; '\r'|]
|> Array.map (Text.trim [|' '|])
/// Use a user-specified .config file
let public loadCustomConfig filePath =
let configFileMap = new ExeConfigurationFileMap(ExeConfigFilename = filePath)
let config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)
if config.AppSettings = null || config.AppSettings.Settings = null then
invalidOp (sprintf "Settings missing from config file: %s" filePath)
let settings = config.AppSettings.Settings
tryGetConfigValue <- fun (key:string) ->
match settings.[key] with
| null -> None
| v -> Some v.Value
setConfigValue <- fun (key:string) value ->
if settings.[key] <> null then
settings.Remove(key)
settings.Add(key, value)
config
/// Try loading a custom config file
let public tryLoadConfigFile configFile =
File.getExistingFile configFile
|> Option.map loadCustomConfig
/// Load configuration from a custom app.config file
let public loadConfigFile configFile =
tryLoadConfigFile configFile
|> Option.orDo (fun () -> invalidOp (sprintf "Config file missing: %s " configFile))
/// Try loading the configuration file next to the calling assembly
[<MethodImpl(MethodImplOptions.NoInlining)>]
let tryLoadConfigFileNextToAssembly () =
let callingAssembly = Assembly.GetCallingAssembly()
let path = sprintf "%s.config" callingAssembly.Location
path
|> File.getExistingFile
|> Option.map loadCustomConfig
|> ignore