Custom Configuration Sections in app.config or web.config

There are certain scenarios where we need to define our own custom configuration section. I have recently faced one where I had to Store the key value pairs as given below.

Download Full Source Code

<FilterHashKey>
  <FilterKeys>
    <add key="722ACP" value="722ACP" />
    <add key="722ARI" value="722ARI" />
    <add key="722BIA" value="722BIA" />
    <add key="722MHI" value="722MHI" />
    <add key="722PSP" value="722PSP" />
    <add key="722TCP" value="722TCP" />
    <add key="722OCS" value="722OCS" />
    <add key="722KCD" value="722KCD" />
    <add key="722KRT" value="722KCD" />
  </FilterKeys>
</FilterHashKey>

It should be flexible enough so that the users can add or delete the key values at any point of time without building and deploying the code again and again for every changes.

Before I get into this topic I guess you should get yourself familiarise yourself with the following few terms.

  • ConfigurationSection -- This is the returned object that will hold onto your custom element
  • ConfigurationElementCollection-- This is the element that you create the describes your collection of data
  • ConfigurationElement -- This is the element that you create that will describe your object/entity for the data.

Now add a app.config or web.config in your application if you don't have one already present.

Once you finished adding the app.config. Add the following few lines inside the <configSections>

   1: <configSections>
   2:   <section name="FilterHashKey" type="CustomConfigApp.ConfigHelper, CustomConfigApp"/>
   3: </configSections>

Here in the configuration above the name attribute should be exactly same as of the Custom configuration section which is given below

   1: <FilterHashKey>
   2:   <FilterKeys>
   3:     <add key="722ACP" value="722ACP" />
   4:     <add key="722ARI" value="722ARI" />
   5:     <add key="722BIA" value="722BIA" />
   6:     <add key="722MHI" value="722MHI" />
   7:     <add key="722PSP" value="722PSP" />
   8:     <add key="722TCP" value="722TCP" />
   9:     <add key="722OCS" value="722OCS" />
  10:     <add key="722KCD" value="722KCD" />
  11:     <add key="722KRT" value="722KCD" />
  12:   </FilterKeys>
  13: </FilterHashKey>

In the section given above we have given the actual data which is going to hold the key value pairs information.

Now since our app.config file is ready with all the information, lets move to the code where we are going to use some if the System.Configuration classes and methods. To start with this I had created a file called ConfigHelper.cs. This class consists of three classes namely ConfigHelper (derived from ConfigurationSection), FilterHashKeyCollection, (derived from ConfigurationElementCollection) and FilterHashKeyElement (derived from ConfigurationElement). The code of which is given below.

   1: using System.Configuration;
   2:  
   3: namespace CustomConfigApp
   4: {
   5:     public class ConfigHelper : ConfigurationSection
   6:     {
   7:         /// <summary>
   8:         /// The value of the property here "Folders" needs to match that of the config file section
   9:         /// </summary>
  10:         [ConfigurationProperty("FilterKeys")]
  11:         public FilterHashKeyCollection HashKeys
  12:         {
  13:             get { return ((FilterHashKeyCollection)(base["FilterKeys"])); }
  14:         }
  15:     }
  16:  
  17:     /// <summary>
  18:     /// The collection class that will store the list of each element/item that
  19:     /// is returned back from the configuration manager.
  20:     /// </summary>
  21:     [ConfigurationCollection(typeof(FilterHashElement))]
  22:     public class FilterHashKeyCollection : ConfigurationElementCollection
  23:     {
  24:         protected override ConfigurationElement CreateNewElement()
  25:         {
  26:             return new FilterHashElement();
  27:         }
  28:  
  29:         protected override object GetElementKey(ConfigurationElement element)
  30:         {
  31:             return ((FilterHashElement)(element)).Key;
  32:         }
  33:  
  34:         public FilterHashElement this[int idx]
  35:         {
  36:             get
  37:             {
  38:                 return (FilterHashElement)BaseGet(idx);
  39:             }
  40:         }
  41:     }
  42:  
  43:     /// <summary>
  44:     /// The class that holds onto each element returned by the configuration manager.
  45:     /// </summary>
  46:     public class FilterHashElement : ConfigurationElement
  47:     {
  48:         [ConfigurationProperty("key", DefaultValue = "", IsKey = true, IsRequired = true)]
  49:         public string Key
  50:         {
  51:             get
  52:             {
  53:                 return ((string)(base["key"]));
  54:             }
  55:             set
  56:             {
  57:                 base["key"] = value;
  58:             }
  59:         }
  60:  
  61:         [ConfigurationProperty("value", DefaultValue = "", IsKey = false, IsRequired = false)]
  62:         public string Value
  63:         {
  64:             get
  65:             {
  66:                 return ((string)(base["value"]));
  67:             }
  68:             set
  69:             {
  70:                 base["value"] = value;
  71:             }
  72:         }
  73:     }
  74: }

Here the ConfigurationSection helps us to populate the custom handler at runtime from the ConfigurationManager. The ConfigurationProperty(“FilterKeys”) should match the root node that contains all the items in app.config. FilterHashCollection is holding each of the custom config elements and finally the class FilterHashElement will describe the custom data from app.config file. The ConfigurationProperty(“key’) needs to map to the  xml element in the app.config one-to-one for each of the element.

Now that we have all the data and classes setup, here is how you actually get the data out of the app.config file and into your custom data model.

   1: ConfigHelper section = (ConfigHelper)ConfigurationManager.GetSection("FilterHashKey");
   2: if (section != null)
   3: {
   4:     foreach(FilterHashElement element in section.HashKeys)
   5:         Console.WriteLine(String.Format("Key {0}, Value {1} ", element.Key, element.Value));
   6:  
   7:     Console.WriteLine("\nPress any key to exit...");
   8:     Console.ReadLine();
   9: }

Well that’s it, you can refer http://msdn.microsoft.com/en-us/library/2tw134k3.aspx for more information. And you can download the sample code from here.  Hope this help.

~Brij Mohan

Published Friday, April 22, 2011 6:56 PM by mohanbrij

Comments

# re: Custom Configuration Sections in app.config or web.config

Sunday, April 24, 2011 5:51 AM by paulbentley

I like to use this approach as a more OO or typed way of putting settings in web.config

I have always felt that <appSettings> is harder to understand what the keys should be and the values they can take.  You often end up looking in the code to see where the values are used to know what they can be!

Good post.