views:

475

answers:

2

I have my own custom configuration sections but would like to create a new element that has simple key/values inside it. Now I have a working version but it seems quite a lot of code for such a simpler task. Is there an improved way of doing things?

Below is a stripped out version of my config and custom configuration class.

web.config

<myRootNode>
    <myNode>
        <add key="a" value="" />
        <add key="b" value="" />
        <add key="c" value="" />
        ...
    </myNode>
    ...any other nodes
</myRootNode>

Custom Configuration Class

public class MyRootNode : ConfigurationSection
{
    [ConfigurationProperty("myNode")]
    public MyNodeElement MyNode
    {
        get { return (MyNodeElement)this["myNode"]; }
    }
}

[ConfigurationCollection(typeof(BaseElement), AddItemName = "add")]
public class MyNodeElement : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new BaseElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((BaseElement)element).Key;
    }

    public BaseElement this[int index]
    {
        get { return this.BaseGet(index) as BaseElement; }
    }
}

public class BaseElement : ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get { return this["key"].ToString(); }
    }

    [ConfigurationProperty("value", IsRequired = true)]
    public string Value
    {
        get { return this["value"].ToString(); }
    }
}
+5  A: 

Something like this I guess:

  <configSections>
      <section name="validationXsds"  type="System.Configuration.DictionarySectionHandler, System/>
  </configSections>


  <validationXsds>
    <add key="http://schemas.xmlsoap.org/soap/envelope/" value="http://dev.ei.directv.com/schemas/xmlsoap/envelope.xsd"/&gt;
    <add key="http://schemas.xmlsoap.org/soap/encoding/" value="http://dev.ei.directv.com/schemas/xmlsoap/encoding.xsd"/&gt;
    <add key="http://ei.directv.com/schemas/envelope/v3_0" value="http://dev.ei.directv.com/schemas/envelope/v3.0/Envelope.xsd"/&gt;
  </validationXsds>

IDictionary xsds = (IDictionary)WebConfigurationManager.GetSection("validationXsds");
zvolkov
+6  A: 

Doing this manually requires way too much effort. You can have Visual Studio create the section for you with the Configuration Section Designer add-in.

John Rasch
Requires Visual Stuiod 2008 or greater.
David Liddle