Wednesday, 18 March 2009

Define custom application configuration section in C#

App.config section configuration

<configuration>
  <configSections>
    <sectionGroup name="section1">
      <section name="nvpconfig" type="MyCompany.NameValueConfiguration,MyCompany"/>
      <section name="customconfig" type="MyCompany.CustomConfiguration,MyCompany" />
    </sectionGroup> 
  </configSections>
  <section1>
    <nvpconfig>
      <properties>
        <add name="id" value="1" />
        <add name="name" value="One" />
        <add name="age" value="18" />
      </properties>
    </nvpconfig>
    <customconfig>
      <list>
        <add id="1" name="One" age="18"/>
        <add id="2" name="Two" age="21"/>
      </list>
    </customconfig>
  </section1>
</configuration>  

Simple name value pair section

namespace MyCompany
{
  public class NameValueConfiguration : System.Configuration.ConfigurationSection
  {
    [ConfigurationProperty("properties")]
    public NameValueConfigurationCollection properties
    {
      get
      {
        return (NameValueConfigurationCollection)this["properties"] ?? new NameValueConfigurationCollection();
      }
    }
  }
}

Custom section definition

namespace MyCompany
{
  public class CustomConfiguration : ConfigurationSection
  {
    [ConfigurationProperty("list")]
    public CustomConfigurationCollection jobs
    {
      get
      {
        return (CustomConfigurationCollection)this["list"] ?? new CustomConfigurationCollection();
      }
    }       
  }
  
  public class CustomConfigurationCollection : ConfigurationElementCollection
  {
    public CustomConfigurationElement this[int index]
    {
      get
      {
        return base.BaseGet(index) as CustomConfigurationElement;
      }
      set
      {
        if (base.BaseGet(index) != null)
        {
          base.BaseRemoveAt(index);
        }
          this.BaseAdd(index, value);
      }
    }
    protected override ConfigurationElement CreateNewElement()
    {
      return new CustomConfigurationElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
      return ((CustomConfigurationElement) element);
    }
  } 
  
  public class CustomConfigurationElement : ConfigurationElement
  {
    [ConfigurationProperty("id")]
    public string Id
    {
      get { return (string)this["id"]; }
      set { this["id"] = value; }
    }
    [ConfigurationProperty("name")]
    public string Name
    {
      get { return (string)this["name"]; }
      set { this["name"] = value; }
    }
    [ConfigurationProperty("age")]
    public string Age
    {
      get { return (string)this["age"]; }
      set { this["age"] = value; }
    }
  }  
}

No comments:

Post a Comment