Sunday, July 19, 2015

Create Config Objects from AppSettings

Providing configuration settings is a vital task that all applications need. Unfortunately dealing with ConfigurationSections and IConfigurationSectionHandlers can be annoying.

That is why I created a simple little extension method to create complex objects from your app settings. The extension works with a NameValueCollection, and can create primitive types, complex objects, collections, dictionaries, and even recursive properties.

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TestConfig.Int" value="1" />
    <add key="TestConfig.String" value="Hello" />
    <add key="TestConfig.DateTime" value="1/2/2015" />
    <add key="TestConfig.TimeSpan" value="00:01:00" />
    <add key="TestConfig.Enum" value="Moon" />
    <add key="TestConfig.NullableIntA" value="2" />
    <add key="TestConfig.NullableIntB" value="" />
  </appSettings>
</configuration>

Test

[Fact]
public void CreateSimpleObject()
{
    var result = ConfigurationManager.AppSettings.CreateObject<TestConfig>();
 
    Assert.NotNull(result);
    Assert.Equal(1, result.Int);
    Assert.Equal(42, result.IntWithDefault);
    Assert.Equal("Hello", result.String);
    Assert.Equal(new DateTime(2015, 1, 2), result.DateTime);
    Assert.Equal(TimeSpan.FromMinutes(1), result.TimeSpan);
    Assert.Equal(TestEnum.Moon, result.Enum);
    Assert.Equal(2, result.NullableIntA);
    Assert.Null(result.NullableIntB);
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics