.NET .config files are a nice but limited way to configure all kinds of .NET applications. They're especially good for configuring stuff that can be boiled down into simple name/value pairs, like database connection strings, directory locations, etc. I've found that when you need to configure an application with more complex data, like categories of arrayed name/value pairs for example, config files become a bit unwieldy. Often, this kind of thing gets put into the backend data store, or in some other persistent storage, such as XML. But I recently had a need to store some more complex configuration data, and because of its nature, I couldn't store it in the Database and I went looking for a way to customize .config files.
Thanks to my friend Brandon Boyd's example, I ended up adding a custom configuration section to my .config file. This approach let me define a new section in my config file, which I could use to add multiple configuration items. I could then treat these as an array in code.
The specific task at hand was to store a list of address to send notifications when the database has certain problems, like timeouts, etc.. Obviously storing this in the database wouldn't work. So to make this really simple, you only have to do two things:
1) First you have to declare your new section's group and name. Add a Section Group and Section Name to the <configSections> element of your config file to do this. The Group and Section “Name“ property will become the XML Element you use in your config file.
<configSections>
<sectionGroup name="ExceptionRouting">
<section name="RoutingList" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</sectionGroup>
</configSections>
2) Add the configuration section using the named elements. Within your innermost section, you can have name/value pairs. Here's mine:
<ExceptionRouting>
<RoutingList>
<add key="OLE DB provider 'MSDASQL' reported an error." value=“btompkins@vit.org,bboyd@vit.org"/>
<add key="The timeout period elapsed prior to completion of the operation or the server is not responding." value="btompkins@vit.org"/>
<add key="General network error. Check your network documentation." value="btompkins@vit.org“/>
</RoutingList>
</ExceptionRouting>
Once this is set up, you can use the GetConfig method to get back your name/value pairs. As you can see, I've keyed my routing list based on the Exception.Message text that I'm interested in routing. Now, I can run all Exceptions through a method like the one below, which will determine if the given exception needs to be routed to someone's inbox.
public
static void RouteException(System.Exception ex)
{
NameValueCollection nvc = (NameValueCollection)
System.Configuration.ConfigurationSettings.GetConfig("ExceptionRouting/RoutingList");
if(nvc[key] != null)
{
string [] routes = nvc[key].Split(new char[] {','});
foreach(string strRoute in routes)
{
// .. Send Message Here
}
}
}
-Brendan