Custom configuration sections - KISS method

1k Views Asked by At

I have an app.config section I want to define, as a simple IDictionary<string, IDictionary<string, string>> that would look something like this in the app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="ServiceInstances" type="MyProject.Configuration, MyProject"/>
    </configSections>
    <ServiceInstances>
        <ServiceInstance name="service1">
            <kvp key="key1" value="value1"/>
            <kvp key="key2" value="value2"/>
        </ServiceInstance>
        <ServiceInstance name="service2">
            <kvp key="key3" value="value3"/>
            <kvp key="key2" value="value2"/>
        </ServiceInstance>
    </ServiceInstances>
</configuration>

All of the tutorials I'm seeing seem to get pretty deep into this, I'm just looking for a quick and dirty way to do this:

IDictionary<string, string> foo = Configuration.GetDictionary("service1");
IDictionary<string, string> bar = Configuration.GetDictionary("service2");

It seems like this should literally be a few lines of code, but the tutorials seem to be complicating it unnecessarily. Is there a quick answer for this, and if so, can someone show me what it should look like?

2

There are 2 best solutions below

2
On BEST ANSWER

You can use Configuration section designer to do the dirty job:

http://csd.codeplex.com/

It has visual studio designer support, generates sample configuration, just so far has one problem - in case of VS2012 requires VS2010 to be installed, but I think that will be fixed soon.

1
On

First you parse your XML file into the Dictionary<string, Dictionary<string, string>>. That looks like this:

public Dictionary<string, Dictionary<string, string>> getDictionary()
{
    XmlDocument doc = new XmlDocument();
    doc.Load(@"path/to/file.xml");

    Dictionary<string, Dictionary<string, string>> outer = new Dictionary<string, Dictionary<string, string>>();
    Dictionary<string, string> inner;

    //cycle through outer nodes
    foreach (XmlNode service in doc.SelectNodes("/configuration/ServiceInstances/ServiceInstance"))
    {
        inner = new Dictionary<string, string>();
        //cycle through inner nodes
        foreach (XmlNode kvp in service.SelectNodes("kvp"))
        {
            inner.Add(kvp.Attributes["key"].Value, kvp.Attributes["value"].Value);
        }
        outer.Add(service.Attributes["name"].Value, inner);
    }

    return outer;
}

And then you can call your dictionaries like this:

var foo = getDictionary();
Dictionary<string,string> bar = foo["service1"];