0

I'm holding a custom configuration section in machine.config of following structure:

<CustomSettings>
   <add key="testkey" local="localkey1" dev="devkey" prod="prodkey"/>
</CustomSettings>

Now, i want to be able to override the same key settings by storing the overrides in app.config like this:

<CustomSettings>
   <add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings>

So that when i read it in code i'll get - dev="devkey1", prod="prodkey1", local="localkey1"

Problem is that when i read my custom config section like this:

CustomConfigurationSection section = ConfigurationManager.GetSection("CustomSettings") as CustomConfigurationSection;

i get an error stating that the key has already been added:

"The entry 'testkey' has already been added."

I modified making the ConfigElementCollection.Add function to check if the same key already exists but it didn't work.

Any ideas?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Uri Abramson
  • 6,005
  • 6
  • 40
  • 62

2 Answers2

0

you should delete the key first, try

<CustomSettings>
   <remove key="testkey"/>
   <add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings> 

That should do the trick

3dd
  • 2,520
  • 13
  • 20
  • But this will not "merge" the values. i'll end up getting only dev=devkey1, prod=prodkey1 and will lose the machine.config setting. – Uri Abramson Apr 24 '13 at 10:18
  • Yes you'll loose them, perhaps split them into different keys, and then read them one by one, the ones you want to override you can delete – 3dd Apr 24 '13 at 10:41
0

I ended up overriding BaseAdd in the ConfigurationElementCollection:

protected override void BaseAdd(ConfigurationElement element)
    {


 CustomConfigurationElement newElement = element as CustomConfigurationElement;

      if (base.BaseGetAllKeys().Where(a => (string)a == newElement.Key).Count() > 0)
      {
        CustomConfigurationElement currElement = this.BaseGet(newElement.Key) as CustomConfigurationElement;

        if (!string.IsNullOrEmpty(newElement.Local))
          currElement.Local = newElement.Local;

        if (!string.IsNullOrEmpty(newElement.Dev))
          currElement.Dev = newElement.Dev;

        if (!string.IsNullOrEmpty(newElement.Prod))
          currElement.Prod = newElement.Prod;
      }
      else
      {
        base.BaseAdd(element);
      }
    }

I hope it helps...

Uri Abramson
  • 6,005
  • 6
  • 40
  • 62