Click here to Skip to main content
Click here to Skip to main content

Writing a complex custom configuration section

, 2 Jul 2009
Rate this:
Please Sign up or sign in to vote.
Technorati Tags: C#,.Net FrameworkHere i posted another entry, showing implementation of a simple configuration section, now consider following listing          <add name=&#8221;FirstAssembly.FirstType&#8221; assembly=&#8221;FirstAssembly&#8221; shoul

Here I posted another entry, showing implementation of a simple configuration section. Now consider following listing: 

<customSection>
  <elements>
     <add name="FirstAssembly.FirstType" assembly="FirstAssembly" shouldrun="true" />
     <add name="SecondAssembly.SecondType" assembly="SecondAssembly" shouldrun="true" />
  </elements>
</customSection>

Here we have "n" number of elements in the custom configuration section. To handle this kind of scenario, System.Configuration namespace provides you with the ConfigurationPropertyCollection class and ConfigurationPropertyCollectionAttribute class. Your can use ConfigurationPropertyCollection to programmatically write your configuration section and ConfigurationPropertyCollectionAttribute can be used to do the same job declaratively.

There are the following steps involved in creating a custom configuration section handler with multiple entries.

  1. Define a class (say CustomElement) to represent configuration section by inheriting it from ConfigurationElement class
  2. Define a class to represent your configuration collection (say CustomElementCollection) by inheriting it from ConfigurationElementCollection. This will hold a collection of the type you defined in step 1
  3. Define a class to represent your custom section (say CustomSection) by inheriting it from ConfigurationSection and implement a property of the type that you defined in step 2

Here is the listing for CustomElement class

public class CustomElement : ConfigurationElement
{
    public CustomElement()
    {
    }

    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get { return (string)this["name"]; }
        set { this["name"] = value; }
    }

    [ConfigurationProperty("assembly", IsRequired = true)]
    public string Assembly
    {
        get { return (string)this["assembly"]; }
        set { this["assembly"] = value; }
    }

    [ConfigurationProperty("shouldrun", IsRequired = true)]
    public bool ShouldRun
    {
        get { return (bool)this["shouldrun"]; }
        set { this["shouldrun"] = value; }
    }
}

and here is the listing for CustomElementCollection class. Its implementation is similar to any other Collection class.

public class CustomeElementCollection : ConfigurationElementCollection
{
    public CustomeElementCollection()
    {
        CustomElement myElement = (CustomElement)CreateNewElement();
        Add(myElement);
    }

    public void Add(CustomElement customElement)
    {
        BaseAdd(customElement);
    }

    protected override void BaseAdd(ConfigurationElement element)
    {
        base.BaseAdd(element, false);
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.AddRemoveClearMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new CustomElement();
    }

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

    public CustomElement this[int Index]
    {
        get
        {
            return (CustomElement)BaseGet(Index);
        }
        set
        {
            if (BaseGet(Index) != null)
            {
                BaseRemoveAt(Index);
            }
            BaseAdd(Index, value);
        }
    }

    new public CustomElement this[string Name]
    {
        get
        {
            return (CustomElement)BaseGet(Name);
        }
    }

    public int indexof(CustomElement element)
    {
        return BaseIndexOf(element);
    }

    public void Remove(CustomElement url)
    {
        if (BaseIndexOf(url) >= 0)
            BaseRemove(url.Name);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
        BaseRemove(name);
    }

    public void Clear()
    {
        BaseClear();
    }
}

and finally, here is the listing for CustomSection class,

class CustomSection : ConfigurationSection
{
    CustomElement element;
    public CustomSection()
    {
        element = new CustomElement();
    }

    [ConfigurationProperty("elements", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(CustomeElementCollection), AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public CustomeElementCollection Elements
    {
        get
        {
            return (CustomeElementCollection)base["elements"];
        }
    }
}

Next, add following settings to your configuration file

<configSections>
  <section name="customSection" type="ConfigurationDemo.CustomSection, ConfigurationDemo" />
</configSections>

<customSection>
  <elements>
    <add name="FirstAssembly.FirstType" assembly="FirstAssembly" shouldrun="true" />
    <add name="SecondAssembly.SecondType" assembly="SecondAssembly" shouldrun="true" />
  </elements>
</customSection>

In the end, put this custom section to use like this:

CustomSection myCustomSection = (CustomSection)ConfigurationManager.GetSection("customSection");

foreach (CustomElement element in myCustomSection.Elements)
{
    if (element.Name != null && element.Name != "")
    {
        string name = element.Name;
        string assembly = element.Assembly;
        bool shouldrun = element.ShouldRun;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

aftabahmed.net
Software Developer (Senior)
United States United States
Being an software developer, trying to understand the problem, trying to figure out how best it can be solved and then going through the joy of implementing a solution, continously improving it and watching it becoming part of peoples live has been my passion and primary reason that i love my job so much.
 
I specialise in .Net Framework, C# language, ASP.Net, Distributed Applications using WCF and Web Services (WS.* and REST), WPF, WF and Ajax along with SQL Server.
 
I have sense of accomplishment and satisfaction that i have been involved in many successful software development projects since last 9 years and since last 6 years i have been working on this exciting technology called .Net Framework and it brings me such a joy that since then both .Net Framework and Myself (professionally!) have been growing together. Next destination in our journey is “THE CLOUD”.

Comments and Discussions

 
SuggestionGreat, one comment PinmemberMrJono2-Jul-14 17:21 
GeneralMy vote of 4 PinmemberMember 1006582526-Sep-13 6:03 
GeneralEdited & Questions PinsubeditorIndivara23-Jan-11 23:19 
QuestionBut how can I write new section into the config file by code? Pinmemberatongmu51819-Jul-10 0:29 
GeneralThis is not complex PinmemberRad Andy22-Oct-09 4:40 
GeneralThanks PinmemberPaolo Benjamin T. Briones13-Jul-09 18:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140902.1 | Last Updated 2 Jul 2009
Article Copyright 2009 by aftabahmed.net
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid