Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom app.config Config Section Handler

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> 
like image 572
BuddyJoe Avatar asked Apr 17 '09 04:04

BuddyJoe


People also ask

What is configSections in app config?

Configuration sections have two parts: a configuration section declaration and the configuration settings. We can put configuration section declarations and configuration settings in the machine configuration file or in the application configuration file.

What is configuration section?

The configuration section is an optional section for programs and classes, and can describe the computer environment on which the program or class is compiled and executed.

Can we add app config file in class library?

You generally should not add an app. config file to a class library project; it won't be used without some painful bending and twisting on your part. It doesn't hurt the library project at all - it just won't do anything at all.


1 Answers

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:

  • Sample config
  • Collection and element classes
  • Config section class
like image 176
Luke Quinane Avatar answered Nov 21 '22 20:11

Luke Quinane