Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
App.Config and Custom Configuration Sections
I am sure that most of you have needed to use the App.Config file before to put different sort of startup/init data before.  And I am also sure that most of you have wanted to create your own structure for the file, but have resorted to using the built in <appSettings> node and retrieved the value in code using ConfigurationManager.AppSettings[ "MyKey" ]. 

Well, I have for a long time wanted to figure out how to use the built in ConfigurationSection class in order to describe and load my own data format.  After a few hours of trial and error along with googling for help I have finaly figured out how do create my own data structure and use it within my application.

In order to load this information in from the App.Config file there are several classes taht are needed. 
  1. ConfigurationSection -- This is the returned object that will hold onto your custom element
  2. ConfigurationElementCollection-- This is the element that you create the describes your collection of data
  3. ConfigurationElement -- This is the element that you create that will describe your object/entity for the data.


Getting Started.

You first need to create your app.Config file if you don't already have that.  After you have your app.config file created, open it up and copy/paste the following lines of code between the <configuration> nodes

This is the configuartion section of the app.config file.  It is here you setup/create your custom section definition.
The name of the section will need to match the name of the custom section settings that will be created below.  The type is the type of object that will hold onto the custom settings.  The first part is the full path (with namespace) of the class the second is the name of the assembly.

  <configSections>

    <!--

      name = This needs to match the name of the section that the settings are stored

      type = is a 2 part value.  Part 1 is the full path (w/ namespace to the class that will hold

          this data.  Part 2 is the name of the assembly this class is found in.

    -->

    <section name="StartupFolders" type="ConfigSectionTester.StartupFoldersConfigSection, ConfigSectionTester"/>   

  </configSections>


Next you will need to create your custom section that will hold your data.  copy/paste the following lines of code between the <configuration> nodes, but after the <configSections> node you created above.

This is the custom data section that will be implemented via your custom data model.

  <StartupFolders>

    <Folders>

      <add folderType="A" path="c:\foo" />

      <add folderType="B" path="C:\foo1" />

    </Folders>

  </StartupFolders>

Now that your app.config file is created lets move the the class files you will need that will store and interact with the app.config file.

First you will need to create your ConfigurationSection class that will hold onto the data that was retrieved from the app.config file

This s the custom section handler that is needed in order to get the process rolling.  As you can see this inherits from ConfigurationSection which allows us to be able to populate this from the ConfigurationManager at runtime.

The ConfigurationProperty( "Folders" ) needs to match the name of the root node that will contain all our your data items (see above for example).
The FoldersCollection class name will be created later and is the collection that will hold each of your custom config elements.

    /// <summary>

    /// The Class that will have the XML config file data loaded into it via the configuration Manager.

    /// </summary>

    public class StartupFoldersConfigSection : ConfigurationSection

    {

        /// <summary>

        /// The value of the property here "Folders" needs to match that of the config file section

        /// </summary>

        [ConfigurationProperty( "Folders" )]

        public FoldersCollection FolderItems

        {

            get { return ( (FoldersCollection)( base[ "Folders" ] ) ); }

        }

    }


Next you will need to create the ConfigurationElementCollection class that will hold onto the collection of custom elements.

Here is the collection class that holds onto each of the custom elements that are described in the app.config class.

    /// <summary>

    /// The collection class that will store the list of each element/item that

    ///        is returned back from the configuration manager.

    /// </summary>

    [ConfigurationCollection( typeof( FolderElement ) )]

    public class FoldersCollection : ConfigurationElementCollection

    {

        protected override ConfigurationElement CreateNewElement()

        {

            return new FolderElement();

        }

 

        protected override object GetElementKey( ConfigurationElement element )

        {

            return ( (FolderElement)( element ) ).FolderType;

        }

 

        public FolderElement this[int idx ]

        {

            get

            {

                return (FolderElement) BaseGet(idx);

            }

        }

    }

Finally you will need to create your ConfigurationElement class that will hold and describe your custom data from the app.config file.

This is the class that will hold onto the data for your custom section element in the app.config file.  The ConfigurationProperty("folderType") needs to map to the xml attribute name in the app.config file for each of the elements you wish to use.  The other values such as DefaultValue="", IsKey=true, IsRequired=true are here only to show the different options that are available to you.
 

    /// <summary>

    /// The class that holds onto each element returned by the configuration manager.

    /// </summary>

    public class FolderElement : ConfigurationElement

    {

 

        [ConfigurationProperty("folderType", DefaultValue="", IsKey=true, IsRequired=true)]

        public string FolderType

        {

            get

            {

                return ((string) (base["folderType"]));

            }

            set

            {

                base["folderType"] = value;

            }

        }

 

        [ConfigurationProperty( "path", DefaultValue = "", IsKey = false, IsRequired = false )]

        public string Path

        {

            get

            {

                return ( (string)( base[ "path" ] ) );

            }

            set

            {

                base[ "path" ] = value;

            }

        }

 

    }


Now that we have all the data and classes setup, here is how you actually get the data out of the app.config file and into your custom data model.
NOTE: You will need to reference the System.Configuration namespace in order for this to work.

                StartupFoldersConfigSection section = (StartupFoldersConfigSection)ConfigurationManager.GetSection( "StartupFolders" );

 

                if ( section != null )

                {

 

                    System.Diagnostics.Debug.WriteLine( section.FolderItems[ 0 ].FolderType );

                    System.Diagnostics.Debug.WriteLine( section.FolderItems[ 0 ].Path );

                }



Well, here you have it.  A complete example on how to create a custom configuration section that can be read into your own custom data model.


Posted 11-13-2006 6:24 AM by Derik Whittaker
Filed under:

[Advertisement]

Comments

Jezzer wrote re: App.Config and Custom Configuration Sections
on 11-23-2006 10:02 AM

Pretty cool but cant really read it with those scrollbars

Focus wrote re: App.Config and Custom Configuration Sections
on 12-04-2006 12:47 AM

Agreed.  It really takes away from the articles worth.

Bob wrote re: App.Config and Custom Configuration Sections
on 12-13-2006 1:26 PM

Haters... I thought this was an excellent post. Short, sweet and to the point.  Who cares about the scroll bars.  Thanks for the great post!

bmx nininja wrote re: App.Config and Custom Configuration Sections
on 12-15-2006 2:37 AM

Great, exactly what i needed... the msdn documentation is a bit confusing... Great post!

Craig wrote re: App.Config and Custom Configuration Sections
on 12-22-2006 7:48 PM

Can you please post your resulting app.config file as well?  I think I have all the steps right, but am getting a configuration initialization error...

Thai wrote re: App.Config and Custom Configuration Sections
on 12-26-2006 3:42 AM

In the code:  

           set

           {

               base[ "path" ] = value;

           }

I have an error regarding config file is read only

Joey wrote re: App.Config and Custom Configuration Sections
on 01-22-2007 2:25 AM

Very cool. Also if you add this to your FoldersCollection class:

     new public FolderElement this[string key]

       {

           get

           {

               return (FolderElement )BaseGet(key);

           }

       }

you can access by key (l.e. section.FolderItems["A"]) just like appSettings

Bryce K. Nielsen wrote re: App.Config and Custom Configuration Sections
on 02-08-2007 7:07 PM

Does this work in VS2005? My System.Configuration has no ConfigurationSection type nor a ConfigurationProperty attribute...

-BKN

Bryce K. Nielsen wrote re: App.Config and Custom Configuration Sections
on 02-09-2007 5:31 PM

n/m, I figured it out. In addtion to using System.Configuration, I needed to add a reference to System.Configuration.

Thanks,

-BKN

Derek Noonan wrote re: App.Config and Custom Configuration Sections
on 03-02-2007 5:29 AM

Jezzer/Focus,

If you view the page in Firefox and hit CTRL + SHIFT + S it'll remove all the styles allowing you to see it clearly. This functionality is provided by the Web Developer toolbar AFAIK but there's a similar offering available for IE IIRC.

Best regards,

Derek

Guru wrote re: App.Config and Custom Configuration Sections
on 03-14-2007 6:36 AM

Wow

Wonder full article.

Truly appreciate your efforts

You made things as softas butter

thank you very much

guru

Nanook wrote re: App.Config and Custom Configuration Sections
on 03-24-2007 5:49 AM

Use this code to save the config.

Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

StartupFoldersConfigSection section = (StartupFoldersConfigSection)cfg.Section["StartupFolders"];

if ( section != null )

{

   System.Diagnostics.Debug.WriteLine( section.FolderItems[0].FolderType );

   System.Diagnostics.Debug.WriteLine( section.FolderItems[0].Path );

   section.FolderItems[0].Path = "C:\\Nanook";

   cfg.Save(); //set a break on the next line of code and check the <exename>.vshost.exe.config file in your debug folder

}

Venkat Morampudi wrote re: App.Config and Custom Configuration Sections
on 04-18-2007 6:33 PM

Thank You very much for posting the article. It helped a lot

AKP wrote re: App.Config and Custom Configuration Sections
on 09-18-2007 2:55 AM

If I want to add a new child inside Folderitems How can I do that

AKP wrote re: App.Config and Custom Configuration Sections
on 09-18-2007 3:10 AM

How Can i add new child nodes using CreateNewElement.

Majesh wrote re: App.Config and Custom Configuration Sections
on 09-18-2007 3:15 AM

How Can I access CreateNewElement

Ahmad Abu Raddad wrote re: App.Config and Custom Configuration Sections
on 10-08-2007 4:15 AM

Thanks mate, excellent post

Kiran Chand wrote re: App.Config and Custom Configuration Sections
on 01-10-2008 8:39 AM

Can anybody explain me the same in VB.Net? I feel this to be greek and latin

Derik Whittaker wrote re: App.Config and Custom Configuration Sections
on 01-10-2008 8:44 AM

@Kiran,

The only difference for vb would be switching out the syntax from c#.

For example, you way you declare attributes changes, the way you declare objects changes.  But the core objects you use and they way you implement to code does not.

tim wrote re: App.Config and Custom Configuration Sections
on 02-20-2008 7:32 PM

i am getting an error that the section variable is NULL when i try to use it.

Carol wrote re: App.Config and Custom Configuration Sections
on 04-29-2008 9:15 AM

thanks for your example.. This is one of the few custom configSection examples that I've gotten to work!

Chad wrote re: App.Config and Custom Configuration Sections
on 06-24-2008 2:14 PM

Thanks!  Just what I needed.

D wrote re: App.Config and Custom Configuration Sections
on 07-09-2008 3:17 PM

This was very helpful.  You rock.

nisha wrote re: App.Config and Custom Configuration Sections
on 08-17-2008 8:10 AM

I am also always getting a NULL returned from section variable - I have copied the code exactly as it appears.

What am i missing?!

kent wrote re: App.Config and Custom Configuration Sections
on 08-26-2008 12:12 PM

NULL returned in section variable?

Perhaps your App.config file isn't quite right.

It isn't explicitly stated in the article above how to create the App.config file. Create it through the 'Project' menu item, 'Add New Item' submenu item, and choose 'Application Configuration File' template.

Be sure this config file is coded exactly as follows:

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

<configuration>

 <configSections>

 <!--

     name = This needs to match the name of the section that the settings are stored

     type = is a 2 part value.  Part 1 is the full path (w/ namespace to the class that will hold

         this data.  Part 2 is the name of the assembly this class is found in.

   -->

 <section name="StartupFolders" type="ConfigSectionTester.StartupFoldersConfigSection, ConfigSectionTester"/>

 </configSections>

 <StartupFolders>

   <Folders>

     <add folderType="A" path="c:\foo" />

     <add folderType="B" path="C:\foo1" />

   </Folders>

 </StartupFolders>

</configuration>

Also, be sure your code files reference the exact same spelling as the App.config file for the words "StartupFolders", "Folders", "folderType", and "path".

simon wrote re: App.Config and Custom Configuration Sections
on 09-08-2008 12:26 AM

Really useful article that works straight out of the box :-)

After hours of searching and trying lots of different things which didn't work the way I needed this was a breath of fresh air - thanks for taking the time to write this article.

richardb wrote re: App.Config and Custom Configuration Sections
on 09-08-2008 1:30 PM

Nice. I would like to move the code to a dll in .net 3.5 to incorporate into different apps.

Any suggestions/comments on how to perform this?

richardb wrote re: App.Config and Custom Configuration Sections
on 09-08-2008 2:01 PM

I have been able to get this to work in a dll. However, dll or not I cannot get the code to work with an app.config file which has an appSettings section.

Does anyone know why I get "Configuration System Failed to Initialize" [ConfigurationErrorsException"?

misterbussey wrote re: App.Config and Custom Configuration Sections
on 09-08-2008 2:30 PM

I have been able to get this to work in a dll. However, dll or not I cannot get the code to work with an app.config file which has an appSettings section.

Does anyone know why I get "Configuration System Failed to Initialize" [ConfigurationErrorsException"?

Talish wrote re: App.Config and Custom Configuration Sections
on 09-11-2008 2:28 AM

One of the classic article regarding app.config. thanks for sharing your experience with juniors thanks a lot....

Morteza wrote re: App.Config and Custom Configuration Sections
on 09-23-2008 9:23 AM

Good article, but i have an error too.

"An error occurred creating the configuration section handler for StartupFolders: Could not load file or assembly 'ConfigSectionTester' or one of its dependencies. The system cannot find the file specified."

i do exactly your codes.

please put  your correct file for download.

mdebot wrote re: App.Config and Custom Configuration Sections
on 09-30-2008 11:18 AM

Wow, great article.  Thanks much!!!

Morteza, I believe the "ConfigSectionTester" should be changed to the namespace for your configuration class.  I was getting same error that you were before I changed the "ConfigSectionTester" text to the namespace of my configuration class

hans wrote re: App.Config and Custom Configuration Sections
on 10-24-2008 4:24 AM

Great post, exactly what I was looking for! Thx!

Karen wrote re: App.Config and Custom Configuration Sections
on 10-24-2008 8:16 PM

Great job, it is exact what i need.

I got "Configuration System Failed to Initialize" [ConfigurationErrorsException" error msg , but after i moved the whole configSections part on the top of the

configuration, then it works fine.

Shiva wrote re: App.Config and Custom Configuration Sections
on 02-12-2009 3:13 PM

Excellent Post Derik !

You have explained this in a simple, crisp and clear manner. Thank you :)

-Shiva

http://mycodetrip.com

Oleg wrote re: App.Config and Custom Configuration Sections
on 03-24-2009 8:26 AM

Great article, thanks.

How about the more complex case like the one below?

<StartupFolders>

   <Folders>

     <Folder folderType="A" path="c:\foo" />

     <Folder folderType="B" path="C:\foo1" />

   </Folders>

 </StartupFolders>

Any one knows how to handle it?

Thanks

Oleg wrote re: App.Config and Custom Configuration Sections
on 03-24-2009 8:29 AM

Great article, thanks.

How about the more complex case like the one below?

<StartupFolders>

   <Folders>

     <Folder folderType="A" path="c:\foo" />

     <Folder folderType="B" path="C:\foo1" />

   </Folders>

 </StartupFolders>

Any one knows how to handle it?

Thanks

Guo Huang wrote re: App.Config and Custom Configuration Sections
on 03-27-2009 8:13 PM

Oleg , It is Easy, one line of code.

[ConfigurationCollection( typeof( FolderElement ) ), AddItemName = "Folder"]

   public class FoldersCollection : ConfigurationElementCollection

   {

Kostkac wrote re: App.Config and Custom Configuration Sections
on 04-08-2009 7:15 AM

GOOD JOB!!

PS: classes taht are needed.  

Greg wrote re: App.Config and Custom Configuration Sections
on 07-09-2009 1:47 PM

I was having a problem with the section variable being null, as have others on this topic.  I believe this issue is caused because I am using an app.config file for a DLL.  It seems that when attempting to obtain the custom settings, it goes straight to the app.config for whatever application is running it vs. the app.config for the DLL.  Way to go Microsoft.....

nishant singh wrote re: App.Config and Custom Configuration Sections
on 08-11-2009 9:21 AM

One important thing to make this code work is that

the <configSections> node should be the first node after <configuration> and in any case should be before  <appSettings> otherwise it will not work.

Nishant wrote re: App.Config and Custom Configuration Sections
on 08-11-2009 9:23 AM

 <configSections> should be the first node immediately after <configuration> else it will throw exception in Initialization.

Guillermo Gutierrez wrote re: App.Config and Custom Configuration Sections
on 08-11-2009 2:33 PM

This article is exactly what I needed. I have an additional question:

How can we get an item count just like using the "ConfigurationManager.AppSettings.Count"?

Predrag wrote re: App.Config and Custom Configuration Sections
on 09-28-2009 11:14 AM

Very good post, thank's.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)