In order to implement collection configuration. You can use ConfigurationSection
and ConfigurationElementCollection
in your web.config.
One advantage of using ConfigurationSection
is that you can separate physical files of Menu configuration and rest of web.config configuration. That is very handful when publishing the app on host environments. (see this)
First you need to create Menu config class
public class MenuConfig : ConfigurationElement
{
public MenuConfig () {}
public MenuConfig (bool enabled, string description)
{
Enabled = enabled;
Description = description;
}
[ConfigurationProperty("Enabled", DefaultValue = false, IsRequired = true, IsKey =
true)]
public bool Enabled
{
get { return (bool) this["Enabled"]; }
set { this["Enabled"] = value; }
}
[ConfigurationProperty("Description", DefaultValue = "no desc", IsRequired = true,
IsKey = false)]
public string Description
{
get { return (string) this["Description"]; }
set { this["Description"] = value; }
}
}
Second define ConfigurationElementCollection
if menu collection
public class MenuCollection : ConfigurationElementCollection
{
public MenuCollection()
{
Console.WriteLineMenuCollection Constructor");
}
public MenuConfig this[int index]
{
get { return (MenuConfig)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public void Add(MenuConfig menuConfig)
{
BaseAdd(menuConfig);
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new MenuConfig();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MenuConfig) element).Port;
}
public void Remove(MenuConfig menuConfig)
{
BaseRemove(menuConfig.Port);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
}
Third create high level ConfigurationSection
that is entry point of your custom configuration
public class MenusConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Menus", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(MenuCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public MenuCollection Menus
{
get
{
return (MenuCollection)base["Menus"];
}
}
}
Use the section in web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MenusSection" type="{namespace}.MenusConfigurationSection, {assembly}"/>
</configSections>
<MenusSection>
<Menus>
<add Enabled="true" Description="Desc 1" />
<add Enabled="true" Description="Desc 1" />
</Menus>
</ServicesSection>
</configuration>