Creating dynamic keyvalue pairs within a config section
asp.net, c#, configuration
Solution
In your `ConfigurationElement` you can override `OnDeserializeUnrecognizedAttribute()` and then store the extra attributes somewhere, in a Dictionary for example:
public class PluginElement : ConfigurationElement
{
public IDictionary<string, string> Attributes { get; private set; }
public PluginElement ()
{
Attributes = new Dictionary<string, string>();
}
protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
{
Attributes.Add(name, value);
return true;
}
}
Returning `true` from `OnDeserializeUnrecognizedAttribute` indicates that you've handled the unrecongnized attribute, and prevents the `ConfigurationElement` base class from throwing an exception, which it normally does when you haven't declared a `[ConfigurationProperty]` for every attribute in the config xml.
Problem
I'm writing a class to describe a config section and I'm looking for a possible method to cater to the following scenario: ``` <plugins> <add name="resize" maxheight="500px" maxwidth="500px"/> <add name="watermark" font="arial"/> </plugins> ``` Where each item in the list can contain different properties as well as the required name property. Setting up the default section is simple enough but I'm now stuck as how to add the dynamic key/value pairs. Any ideas? ``` /// <summary> /// Represents a PluginElementCollection collection configuration element /// within the configuration. /// </summary> public class PluginElementCollection : ConfigurationElementCollection { /// <summary> /// Represents a PluginConfig configuration element within the /// configuration. /// </summary> public class PluginElement : ConfigurationElement { /// <summary> /// Gets or sets the token of the plugin file. /// </summary> /// <value>The name of the plugin.</value> [ConfigurationProperty("name", DefaultValue = "", IsRequired = true)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } // TODO: What goes here to create a series of dynamic // key/value pairs. } /// <summary> /// Creates a new PluginConfig configuration element. /// </summary> /// <returns> /// A new PluginConfig configuration element. /// </returns> protected override ConfigurationElement CreateNewElement() { return new PluginElement(); } /// <summary> /// Gets the element key for a specified PluginElement /// configuration element. /// </summary> /// <param name="element"> /// The <see cref="T:System.Configuration.ConfigurationElement"/> /// to return the key for. /// </param> /// <returns> /// The element key for a specified PluginElement configuration element. /// </returns> protected override object GetElementKey(ConfigurationElement element) { return ((PluginElement)element).Name; } } ```