Di seguito sono riportate le classi che devono essere aggiunte per per gestire liste di elementi nel file App.Config:
[ConfigurationCollection(typeof(Item),
CollectionType = ConfigurationElementCollectionType.BasicMapAlternate)]
public class ItemCollection : ConfigurationElementCollection
{
internal const string ItemPropertyName = "item";
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMapAlternate; }
}
protected override string ElementName
{
get { return ItemPropertyName; }
}
protected override bool IsElementName(string elementName)
{
return (elementName == ItemPropertyName);
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Item)element).Name;
}
protected override ConfigurationElement CreateNewElement()
{
return new Item();
}
public override bool IsReadOnly()
{
return false;
}
}
public class Item : ConfigurationElement
{
[ConfigurationProperty("name")]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("address")]
public string Address
{
get { return (string)base["address"]; }
set { base["address"] = value; }
}
}
Ora nella classe UrlSection è possibile inserire una proprietà di tipo ItemCollection:
[ConfigurationProperty("items", IsRequired = false, IsKey = false, IsDefaultCollection = true)]
public ItemCollection Items
{
get { return ((ItemCollection)(base["items"])); }
set { base["items"] = value; }
}
Di seguito viene riportato un riepilogo del file di configurazione contenente la sezione personalizzata come definito nell'esempio precedente.
xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="CustomSection" type="UrlsSection, UrlsSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
configSections>
<CustomSection name="Contoso" url="http://www.contoso.com" >
<items>
<item name="item1" address="www.albertoschiassi.it" />
<item name="item2" address="www.pippopluto.it" />
items>
CustomSection>
configuration>
CustomAppConfig (part 2).zip