Background: Trying to implement a list in app.config as per these examples:
- http://jopinblog.wordpress.com/2007/04/20/custom-configurationsections-in-net-20-config-files/
- http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/0f3557ee-16bd-4a36-a4f3-00efbeae9b0d
- Custom app.config section with a simple list of "add" elements
- Custom Configuration for app.config - collections of sections?
Goal: I am looking to resolve this error and have this working.
Error:
Unrecognized element 'lookupMapping'. (C: ...line 75)
Error produced on this line while debugging through:
LookupMappingsConfigSection section = (LookupMappingsConfigSection)config.Sections["lookupMappings"];
app.config snippets:
<configuration>
<configSections>
<section name="lookupMappings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.30319.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<lookupMappings>
<lookupMapping name="One" lookupName="foo" />
<lookupMapping name="Two" lookupName="foo" />
<lookupMapping name="Three" lookupName="foo" />
<lookupMapping name="Four" lookupName="foo" />
</lookupMappings>
</configuration>
Classes:
public class LookupMappingsInstanceElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("lookupName", IsRequired = true)]
public string LookupName
{
get { return (string)base["lookupName"]; }
set { base["lookupName"] = value; }
}
}
public class LookupMappingsConfigSection: ConfigurationSection
{
[ConfigurationProperty("lookupMappings", IsDefaultCollection = true, IsRequired = true)]
[ConfigurationCollection(typeof(LookupMappingsConfigCollection), AddItemName = "lookupMapping")]
public LookupMappingsConfigCollection Instances
{
get { return (LookupMappingsConfigCollection) this[""]; }
set { this[""] = value; }
}
}
public class LookupMappingsConfigCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new LookupMappingsInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LookupMappingsInstanceElement) element).Name;
}
public LookupMappingsInstanceElement this[int idx]
{
get { return (LookupMappingsInstanceElement)BaseGet(idx); }
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override string ElementName
{
get { return "lookupMapping"; }
}
}
Implementation c#:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
LookupMappingsConfigSection section = (LookupMappingsConfigSection)config.Sections["lookupMappings"]; // <--ERROR ON THIS LINE
LookupMappingsInstanceElement entry1 = section.Instances[0];
LookupMappingsInstanceElement entry2 = section.Instances[1];