Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a basic custom configuration section?

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(); }
    }
}
like image 995
David Avatar asked Jun 15 '09 17:06

David


1 Answers

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"/>
    <add key="http://schemas.xmlsoap.org/soap/encoding/" value="http://dev.ei.directv.com/schemas/xmlsoap/encoding.xsd"/>
    <add key="http://ei.directv.com/schemas/envelope/v3_0" value="http://dev.ei.directv.com/schemas/envelope/v3.0/Envelope.xsd"/>
  </validationXsds>

IDictionary xsds = (IDictionary)WebConfigurationManager.GetSection("validationXsds"); 

Update: in .NET 4.0 I'm using

 type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
like image 94
Stop Putin Stop War Avatar answered Oct 11 '22 20:10

Stop Putin Stop War