Creating pairs of dynamic key pairs in the configuration section

I am writing a class to describe a configuration section, and I am looking for a possible method to satisfy the following scenario:

<plugins> <add name="resize" maxheight="500px" maxwidth="500px"/> <add name="watermark" font="arial"/> </plugins> 

If each item in the list may contain different properties, as well as the required property of the name. Setting a default partition is simple enough, but now I'm stuck on how to add 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; } } 
+4
source share
1 answer

In ConfigurationElement you can override OnDeserializeUnrecognizedAttribute() and then store additional attributes somewhere, like in a dictionary:

 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 handled the unassigned attribute and prevented the ConfigurationElement base class from throwing an exception, which it usually makes when you did not declare [ConfigurationProperty] for each attribute in config xml.

+3
source

Source: https://habr.com/ru/post/1412774/


All Articles