Saturday, July 25, 2015

Cascading AppSettings from Multiple Config Files

In my previous blog post I talked about creating complex configuration objects from AppSettings. I really like this practice, but it can cause your config files to grow pretty large. One solution is to break your app.config into multiple files using the SectionInformation.ConfigSource property.

This also has the added side effect of allowing you to include defaults and overrides by having those settings cascade. I have created an extension method to combine a series of NameValueCollections, such as an AppSettings section. You can also grab this code from the GitHub project.

Combine Extension

public static NameValueCollection Combine(
    this NameValueCollection collection, 
    params NameValueCollection[] collections)
{
    var result = new NameValueCollection { collection };
 
    foreach (var subCollection in collections)
        foreach (var key in subCollection.AllKeys)
        {
            if (result.AllKeys.Contains(key))
                continue;
 
            var value = subCollection[key];
            result.Add(key, value);
        }
 
    return result;
}

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

Saturday, July 11, 2015

Common.Logging.NLog40

The Common.Logging team accepted my pull request, and there is now a Common.Logging.NLog40 package to support NLog 4.

Enjoy,
Tom

Real Time Web Analytics