Alexandru
Alexandru

Reputation: 12892

Key-less elements in ConfigurationElementCollection

When you inherit ConfigurationElementCollection:

public class Directories : ConfigurationElementCollection
{
    ...
}

ConfigurationElementCollection requires an implementation for GetElementKey(System.Configuration.ConfigurationElement).

But I don't care about keys since I have a custom configuration section like this:

<directorySection>
  <directories>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\0" dropOffDirectory="C:\Users\User\Documents\DropOff\0"/>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\0" dropOffDirectory="C:\Users\User\Documents\DropOff\0"/>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\1" dropOffDirectory="C:\Users\User\Documents\DropOff\1"/>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\2" dropOffDirectory="C:\Users\User\Documents\DropOff\2"/>
  </directories>
</directorySection>

It can have multiple elements, and each element is key-less, and this structure should allow for duplicates (as above). So what should I do in this case?

Upvotes: 1

Views: 877

Answers (2)

Theo Brinkman
Theo Brinkman

Reputation: 311

This is a very old question, but I just ran into this issue.

Here's the general data structure I'm working with, though I'll probably tweak the actual implementation as it goes:

<filter>
    <group type="and|or|not">
        <condition field="..." operator="..." value="...">
        <group type="...">
            <condition field="..." operator="..." value="...">
        </group>
    </group>
</filter>

I came up with this as the solution.

protected override System.Object GetElementKey(System.Configuration.ConfigurationElement element)
{
    return (this.BaseIndexOf(element));
}

Upvotes: 0

Oleg Nesterov
Oleg Nesterov

Reputation: 79

Try to use ObjectIDGenerator like this

[ConfigurationCollection(typeof(SchedulerTaskItem), AddItemName = "Task")]
public class SchedulerTaskCollection: ConfigurationElementCollection
{
    private static readonly ObjectIDGenerator idGenerator = new ObjectIDGenerator();

    protected override ConfigurationElement CreateNewElement()
    {
        return new SchedulerTaskItem();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        bool firstTime;
        return idGenerator.GetId(element, out firstTime);
    }
}

Upvotes: 4

Related Questions