how to have custom attribute in ConfigurationElementCollection?

jojo picture jojo · Jan 12, 2012 · Viewed 24.2k times · Source

for configuration as following

<MyCollection default="one">
  <entry name="one" ... other attrubutes />
  ... other entries
</MyCollection>

when implement a MyCollection, what should i do for the "default" attribute?

Answer

Simon Mourier picture Simon Mourier · Jan 16, 2012

Let's suppose you have this .config file:

<configuration>
    <configSections>
        <section name="mySection" type="ConsoleApplication1.MySection, ConsoleApplication1" /> // update type  & assembly names accordingly
    </configSections>

    <mySection>
        <MyCollection default="one">
            <entry name="one" />
            <entry name="two" />
        </MyCollection>
    </mySection>
</configuration>

Then, with this code:

public class MySection : ConfigurationSection
{
    [ConfigurationProperty("MyCollection", Options = ConfigurationPropertyOptions.IsRequired)]
    public MyCollection MyCollection
    {
        get
        {
            return (MyCollection)this["MyCollection"];
        }
    }
}

[ConfigurationCollection(typeof(EntryElement), AddItemName = "entry", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class MyCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new EntryElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        return ((EntryElement)element).Name;
    }

    [ConfigurationProperty("default", IsRequired = false)]
    public string Default
    {
        get
        {
            return (string)base["default"];
        }
    }
}

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

you can read the configuration with the 'default' attribute, like this:

    MySection section = (MySection)ConfigurationManager.GetSection("mySection");
    Console.WriteLine(section.MyCollection.Default);

This will output "one"