I want to have a custom section in my web.config like so:
<MyMainSection attributeForMainSection = "value foo">
<add name = "foo"
type = "The.System.Type.Of.Foo, Assembly, Qualified Name Type Name" />
<add name = "bar"
type = "The.System.Type.Of.Bar, Assembly, Qualified Name Type Name" />
</MyMainSection>
I have defined the following code:
using System.Configuration;
class MyMainSection : ConfigurationSection
{
/*I've provided custom implemenation.
Not including it here for the sake of brevity. */
[ConfigurationProperty("attributeForMainSection")]
public string AttributeForMyMainSection { get; set; }
[ConfigurationProperty("add")]
public AddElement TheAddElement { get; set; }
private class AddElement: ConfigurationElement
{
/* Implementation done */
}
}
Should this property TheAddElement
be IEnumerable<AddElement>
or just AddElement
if I want to allow multiple add elements?
The ConfigurationElement is an abstract class that is used to represent an XML element in a configuration file (such as Web. config). An element in a configuration file can contain zero, one, or more child elements. Because the ConfigurationElement class is defined as abstract, you cannot create an instance of it.
This element can be used in the application configuration file, machine configuration file (Machine. config), and Web. config files that are not at the application directory level.
Next we need to make the config file aware of the custom section by adding the section declaration to the configSections element in the Web. config or App. config file. If there is no configSections element, create one at the top of the file just after the opening configuration tag.
Neither, you would introduce a new ConfigurationCollectionElement instead e.g.
Section
class MyMainSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired=true, IsDefaultCollection=true)]
public AddElementCollection Instances
{
get { return (AddElementCollection) this[""]; }
set { this[""] = value; }
}
}
Collection
public class AddElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new AddElement();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((AddElement) element).Name;
}
}
Element
private class AddElement: ConfigurationElement
{
[ConfigurationProperty("name", IsKey=true, IsRequired=true)]
public string Name
{
get { return (string) base["name"]; }
set { base["name"] = value;
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With