31

What is the correct way to pick up the list of "pages" via a class that inherits from System.Configuration.Section if I used a app.config like this?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="XrbSettings" type="Xrb.UI.XrbSettings,Xrb.UI" />
  </configSections>

  <XrbSettings>
    <pages>
      <add title="Google" url="http://www.google.com" />
      <add title="Yahoo" url="http://www.yahoo.com" />
    </pages>
  </XrbSettings>

</configuration>
tshepang
  • 12,111
  • 21
  • 91
  • 136
BuddyJoe
  • 69,735
  • 114
  • 291
  • 466
  • You should also check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject. - [Unraveling the mysteries of .NET 2.0 configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx) - [Decoding the mysteries of .NET 2.0 configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration2.aspx) - [Cracking the mysteries of .NET 2.0 configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration3.aspx) Highly recommended, well written and extremely helpful! – marc_s Apr 17 '09 at 05:28
  • Also, if you find yourself creating configuration sections frequently, there's the [Configuration Section Designer](https://github.com/hybridview/ConfigurationSectionDesigner/wiki), a graphical Domain-Specific Language designer for designing configuration sections. – John Saunders Apr 17 '09 at 14:17

1 Answers1

31

First you add a property in the class that extends Section:

[ConfigurationProperty("pages", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(PageCollection), AddItemName = "add")]
public PageCollection Pages {
    get {
        return (PageCollection) this["pages"];
    }
}

Then you need to make a PageCollection class. All the examples I've seen are pretty much identical so just copy this one and rename "NamedService" to "Page".

Finally add a class that extends ObjectConfigurationElement:

public class PageElement : ObjectConfigurationElement {
    [ConfigurationProperty("title", IsRequired = true)]
    public string Title {
        get {
            return (string) this["title"];
        }
        set {
            this["title"] = value;
        }
    }

    [ConfigurationProperty("url", IsRequired = true)]
    public string Url {
        get {
            return (string) this["url"];
        }
        set {
            this["url"] = value;
        }
    }
}

Here are some files from a sample implementation:

KevinDeus
  • 11,988
  • 20
  • 65
  • 97
Luke Quinane
  • 16,447
  • 13
  • 69
  • 88