Suppose we want to create a custom config section in this following manner
<queryTypes>
<queryType name=“qt1“ value=“qt1 value“></queryType>
<queryType name=“qt2“ value=“qt2 value“></queryType>
</queryTypes>
For implementing the above custom section we need to first define a class inheriting from ConfigurationSection class
Add reference to System.Configuration dll.
Create a new config section class in the following manner
// implement ConfiguraionSection class
class QueryTypesSection : ConfigurationSection
{
public QueryTypesSection()
{
}
[ConfigurationProperty(“”, IsDefaultCollection = true)]
public QueryTypesCollection QueryTypes
{
get
{
return (QueryTypesCollection)base[“”];
}
}
}
// Represents a configuration element containing a collection of child elements
public sealed class QueryTypesCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new QueryTypeElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((QueryTypeElement)element).Name;
}
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
protected override string ElementName
{
get
{
return “queryType”;
}
}
}
// Defining QueryTypeElement with name and value attribute
public sealed class QueryTypeElement : ConfigurationElement
{
// defining name attribute
[ConfigurationProperty(“name”, IsRequired = true)]
public string Name
{
get
{
return (string)this [“name”];
}
set
{
this[“name”] = value;
}
}
// defining value attribute
[ConfigurationProperty(“value”, IsRequired = true)]
public string Value
{
get
{
return (string)this[“value”];
}
set
{
this[“value”] = value;
}
}
}
Now to register your custom section do the following
<configSections>
<section name=“queryTypes“ type=“namespace.QueryTypesSection, namespace “ />
</configSections>
And to use it within the application
QueryTypesSection queryTypeSection = (QueryTypesSection)ConfigurationManager.GetSection(“queryTypes”);
QueryTypesCollection queryTypeCollection = queryTypeSection.QueryTypes;
foreach (QueryTypeElement se in queryTypeCollection)
{
string name=se.Name;
string value = se.Value;
}
That’s it…
Just a quick message to say thanks. Every other ConfigurationSection / ConfigurationElementCollection / ConfigurationElement implementation I found prior to yours didn’t quite work. Yours did. So thanks.
LikeLike
Thanks in advanced,
I have a lot of time for resolved this problem.
LikeLike
Nice example. One question – what if I want to add some ConfigurationElement to ConfigurationElementCollection ? I’ve tried to use :
public void Add(ConfigurationElement element)
{
BaseAdd(element);
}
but without success – got “The configuration is read only.” exception. Any workaround ?
LikeLike