j3d j3d - 3 months ago 14
C# Question

How to create multiple configuration items of different types

Is it possible to have list of configuration items of different types as shown here below?

<exception name ="exception1" host="myhostname">
<block user="joe"/>
<block user="peter"/>
<allow user="admin"/>
<exception name ="exception2" host="anotherhostname">
<block user="sue"/>
<block user="danny"/>
<allow user="johnny"/>

I’m trying to define a configuration that let me block or allow users on a given hostname. If I had only elements of type
, then it would have been quite easy:

class AllowCollection : ConfigurationElementCollection
protected override ConfigurationElement CreateNewElement()
return new AllowElement();

protected override object GetElementKey(ConfigurationElement element)
return ((AllowElement) element).User;

public AllowElement this[int index]
get { return (AllowElement) BaseGet(index); }

public new AllowElement this[string key]
get { return (AllowElement) BaseGet(key); }

class AllowElement : ConfigurationElement
[ConfigurationProperty("user", IsKey = true, IsRequired = true)]
public string User
get { return (string) base["user"]; }

How do I also add the
configuration item? Is it actually possible?


Basically, you'll have to override IsElementName to provide checking for the valid item names (block and allow, in your case). You'll need to map those valid values to the AddItem name property of ConfigurationCollection too, as comma separated strings.

You'll also have to override CollectionType as to return ConfigurationElementCollectionType.BasicMapAlternate.

Then you'll need to change that AllowElement of yours as to be a generic element that will support both allow and block. The link sample uses a Enum, but you could do whatever you fancy. On the CreateNewElement you'll handle the elementName and return your generic element set with the correct type identifier.

Here's the link to Derek says, where you can find an implementation to my suggestion on a section named Collection items with varying element name

Sorry about the copy-pasted link, but I guess a link to a solution that looks exactly what you need is better then a giant blob of code with nothing but the class names being different.