Oct 30, 2013

Adding Custom Configuration Section in Web.config

Recently I faced an issue where i had to read multiple key information for same settings from Web.config (as shown below):

<seacrhConfiguration>
  <add verticalName="Search1" verticalShard="server:9998" />
  <add verticalName="Search2" verticalShard="server:9999" />
</seacrhConfiguration>

You will need to three classes inheriting from System.Configuration namespace: ConfigurationSection, ConfigurationElementCollection, and ConfigurationElement as shown below:

using System;
using System.Collections.Generic;
using System.Configuration;

public class SearchConfigSection : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    public SearchConfigCollection Instances
    {
        get { return (SearchConfigCollection)this[""]; }
        set { this[""] = value; }
    }
}
public class SearchConfigCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new SearchConfigInstanceElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((SearchConfigInstanceElement)element).VerticalName;
    }
}
public class SearchConfigInstanceElement : ConfigurationElement
{
    [ConfigurationProperty("verticalName", IsKey = true, IsRequired = true)]
    public string VerticalName
    {
        get { return (string)base["verticalName"]; }
        set { base["verticalName"] = value; }
    }

    [ConfigurationProperty("verticalShard", IsRequired = true)]
    public string VerticalShard
    {
        get { return (string)base["verticalShard"]; }
        set { base["verticalShard"] = value; }
    }
}


Now modify the web.config to include the new configurations:
<configSections>
 <section name="seacrhConfiguration" type="<AssemblyName+Namespace>.SearchConfigSection, <AssemblyName>" />
</configSections><seacrhConfiguration>
  <add verticalName="Search1" verticalShard="server:9998" />
  <add verticalName="Search2" verticalShard="server:9999" />
</seacrhConfiguration>

Read the configuration settings on page like:
string states = string.Empty;
SearchConfigSection sec = (SearchConfigSection)System.Configuration.ConfigurationManager.GetSection("seacrhConfiguration");
foreach (SearchConfigInstanceElement i in sec.Instances)
{
    states += string.Format("Name:{0} connectionName:{1}" + System.Environment.NewLine, i.VerticalName, i.VerticalShard);
}