Generic Config Collection Section
Alle Collection Items müssen einen Schlüssel beinhalten und dazu erstellen wir ein Interface
public interface IKeyElement
{object Key { get;}}
Dieses Interface wird in der Generischen Klasse verwendet.
public class GenericElementCollection<T> : ConfigurationElementCollection where T : ConfigurationElement, IKeyElement, new()
{
public GenericElementCollection(){ } protected override ConfigurationElement CreateNewElement()
{return new T();}public T this[int index]
{
get{return (T)BaseGet(index);}
set
{
if (BaseGet(index) != null)
{BaseRemoveAt(index);}
BaseAdd(index, value);
}
}
new public T this[string Name]
{get{return (T)BaseGet(Name);}}
public int IndexOf(T element)
{return BaseIndexOf(element);}
public void Add(T element)
{BaseAdd(element);}
protected override void BaseAdd(ConfigurationElement element)
{BaseAdd(element, false);}
public void Remove(T element)
{if (BaseIndexOf(element) >= 0){BaseRemove((element as IKeyElement).Key);}}
public void RemoveAt(int index)
{BaseRemoveAt(index);}
public void Remove(string key)
{BaseRemove(key);}
public void Clear()
{BaseClear();}
public override ConfigurationElementCollectionType CollectionType
{get{return ConfigurationElementCollectionType.AddRemoveClearMapAlternate;}}
protected override object GetElementKey(ConfigurationElement element)
{return (element as IKeyElement).Key;}
}
Beispiel:
public class MySection : ConfigurationSection
{
[ConfigurationProperty("gruppen")]
[ConfigurationCollection(typeof(GenericElementCollection<GruppenElement>), AddItemName = "gruppe")]
public GenericElementCollection<GruppenElement> GruppenCollection
{
get { return this["gruppen"] as GenericElementCollection<GruppenElement>; }
}
}Ein Klassen Element:public class GruppenElement : ConfigurationElement, IKeyElement
{
[ConfigurationProperty("name", DefaultValue = "", IsRequired = true)]
public String Name
{get{return (String)this["name"];}}[ConfigurationProperty("startUrl", DefaultValue = "", IsRequired = false)]
public String StartUrl
{get{ return (String)this["startUrl"]; } public object Key
{get { return Name; }}
}
Configuration
<section name="SectionNameAusDerSectionDefinition" type="Configuration.MySection"
allowLocation="true" allowDefinition="Everywhere" /><SectionNameAusDerSectionDefinition>
<gruppen>
<gruppe name="name1" startUrl=www.darkleo.com>
<gruppe name="name2" startUrl=www.darkleo.com/blog>
<gruppen>
</SectionNameAusDerSectionDefinition>