Sunday, 15 November 2009

Add List To App.Config

One can add list and not only a list to App.Config file of the .Net project. That can be done by declaring your own configuration element, say a ProductElement

class ProductElement : ConfigurationElement
{
  [ConfigurationProperty("name", IsKey=true, IsRequired=true)]
  public string Name
  {
    get { return this["name"]; }
  }

  [ConfigurationProperty("price")]
  public int Price
  {
    get { return Convert.ToInt32(this["price"]); }
  }
}

class ProductElementCollection : ConfigurationElementCollection
{
  protected override ConfigurationElement CreateNewElement()
  {
    return new ProductElement();
  }

  protected override object GetElementKey(ConfigurationElement element)
  {
    return ((ProductElement)element).Name;
  }
}

class ProductConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("products")]
   public ProductElementCollection Products
   {
      get { return (ProductElementCollection)this["products"]; }
   }
}

Use it in your app.config like that:

<configuration>
   <configSections>
      <section name="productConfigurationSection"
        type="MyNamespace.ProductConfigurationSection, MyAssembly" 
        requirePermission="false" />
   </configSections>
   <productConfigurationSection>
      <products>
         <add name="car" price="750000" />
         <add name="milk" price="13" />
      </products>
   </productConfigurationSection>
</configuration>

Note that Name is used as a key, so you cannot create 2 Products with the same name. But you can add more fields to the Product, just mark them accordingly. And from code you can access this section with:

ProductConfigurationSection section = (ProductConfigurationSection) ConfigurationManager.GetSection("productConfigurationSection");