Wednesday, February 23, 2011

Custom Configuration Sections

If you want to define your own custom configuration sections, since appSettings and connectionStrings are just not cutting it, but you do not want to go through the hassle of writing and defining entire classes to handle configuration section data, you will probably want to utilize one of the 3 built-in (but less well known) configuration sections:


  1. SingleTagSectionHandler
  2. DictionarySectionHandler
  3. NameValueSectionHandler
This article, though a bit old (from the days of .Net 1.1) provides a good explanation and description of how to use these configuration section handlers:
Though the article references the System assembly for the System.Configuration.DictionarySectionHandler and the NameValueSectionHandler, as you may recall, Microsoft moved System.Configuration into its own separate assembly as of .NET 2.0, therefore, you simply need to reference System.Configuration.DictionarySectionHandler or System.Configuration.NameValueSectionHandler respectively without the comma ",System".
<section name="dictionarySample" type="System.Configuration.DictionarySectionHandler"/>

<section name="mySection" type="System.Configuration.NameValueSectionHandler" />

Of course, being that the Configuration library methods have changed since then, some of the provided code is inaccurate.  However, the change is very minor.
Instead of using  

NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database");


you simply use this instead
NameValueCollection db = (NameValueCollection)ConfigurationManager.GetSection("Database");

As you probably already know, ConfigurationSettings is deprecated in favor of using ConfigurationManager (or WebConfigurationManager) for handling Configuration Management and retrieval.
Also, if you wish to avoid casting exceptions, you can modify the above code to the following:
NameValueCollection db = ConfigurationManager.GetSection("Database") as NameValueCollection;
 

Once you know to substitute ConfigurationSettings.GetConfig with ConfigurationManager.GetSection, the remainder of the coding is much the same!
Below are examples for each of the SectionHandlers:
var singleTagSection = ConfigurationManager.GetSection("sampleSection") as Hashtable;

var setting1 = singleTagSection["setting1"];

var setting2 = singleTagSection["setting2"];

var setting3 = singleTagSection["setting3"];
var dictSection = ConfigurationManager.GetSection("dictionarySample") as Hashtable;
var nvSection = ConfigurationManager.GetSection("mySection") as NameValueCollection;

No comments:

Post a Comment