May 25 2008

Load Configuration File Generically

Category: Tips and TricksJoeGeeky @ 11:25

Here is a quick tip for those of you who load configuration file sections at runtime.  This is an especially good tip for those of you who have a lot of custom configuration sections and want to keep from writing a lot of redundant code for each section type... Essentially, all you need to do is create a Generic Configuration Manager and place it on a commonly accessible library.  Once created you can use this to create custom configuration section instances as well as native .NET sections such as connectionStrings, appSettings, etc... Here is an example:

This example assumes you are using Web.Config files but this can easily be extended to support App.Config files, and Assembly Configuration Files.

using System;
using System.Configuration;
using System.Web.Configuration;
using System.Web.Hosting;
/// <summary>
/// Configuration File interop helper 
/// class. This will assist in accessing 
/// configuration file information
/// </summary>
public static class ConfigurationFile
{
    /// <summary>
    /// Retrieves a configuration section 
    /// instance from a configuration file 
    /// search all available configuration 
    /// file types
    /// </summary>
    /// <typeparam name="TYPE">The type of 
    /// the configuration to be retrieved
    /// </typeparam>
    /// <param name="sectionName">The name 
    /// (e.g. xml path) to the section to 
    /// be retrieved. This field is case 
    /// sensitive since it targets XML 
    /// elements</param>
    /// <returns>The requested section 
    /// instance or a default instance if 
    /// none was found</returns>
    public static TYPE GetConfigSection<TYPE>(string sectionName)
    {
        Configuration appConfig;
        try
        {
            //Open the application configuration file
            appConfig =WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
        }
        catch (ArgumentException)
        {
            //Section could not be retrieved...  
            appConfig = null;
        }
        //Create an instance member to hold
        //the retrieved section
        ConfigurationSection returnConfig = null;
        //If the config was openedn then try 
        //and get the section
        if (appConfig != null)
            returnConfig = appConfig.GetSection(sectionName);
        //If the section was not retrieved 
        //create a default instance otherwise
        //return what was loaded
        if (returnConfig == null)
            return Activator.CreateInstance<TYPE>();
        else
            return (TYPE)(object)returnConfig;
    }
}

Tags:

Comments

1.
John M. Wiseman John M. Wiseman United Kingdom says:

I had to read this post twice, because it was interesting. I read some of your other posts you do make some good points

2.
Kris Kingsly Kris Kingsly United States says:

Considerably, the article is really the freshest on this worthw hile topic. I concur with your conclusions and will eagerly look forward to your  forthcoming updates. Just saying thanks will not just be sufficient, for the exceptional clarity in your writing. I will at once grab your rss feed to stay informed of any updates. De lightful work and much success in your business enterprize!

3.
Kris Kingsly Kris Kingsly United States says:

Comfortabl y, the post is in reality the best on this noteworthy topic. I agree with your conclusions and will thirstily look forward to your incoming updates. Saying thanks will not just be enough, for the great lucidity in your writing. I will at once grab your rss feed to stay informed of any updates. Admirable work and much success in your business efforts!

4.
Mike Mit Mike Mit United States says:

Intimately, the post is actually the best on this valuable topic. I agree with your conclusions and will eagerly look forward to your  forthcoming updates. Saying thanks will not just be sufficient, for the exceptional lucidity in your writing. I will directly grab your rss feed to stay abreast of any updates. Authentic work and much success in your business dealings!

5.
Kevin Stacey Kevin Stacey United States says:

Considerably, the post is really the sweetest on this noteworthy topic. I fit in with your conclusions and will thirstily look forward to your upcoming updates. Saying thanks will not just be sufficient, for the extraordinary lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates. Good work and much success in your business efforts!

6.
Blake N. Lawrence Blake N. Lawrence says:

Hello! Good article. It sounds interesting. As many people working as marketer, I preferably work with Outlook as my email client and with the help of <a href="http://www.sortoutlookemail.com" target="_blank" title="Go to Email Sorter Wizard website">Email Sorter Wizard</a>, an Outlook add-on, I get all my email sorted. In your blog one can find tons of valuable info. Thanks.

7.
John John Australia says:

You wouldn't believe this but I have spent all day searching for some information about this.  You're a lifesaver, it was a great read and has helped me out to no end.  Kind regards,<a href=jerrysdietblog.leftlab.com/.../>My Site</a>

8.
Matthew Matthew Australia says:

You not going to believe this but I have spent all day digging for some info about this.  I wish I knew of this site earlier, it was a great read and has helped me out to no end.  this is my site by the way (if you are interested) - <a href=theblogs.net/.../>My Site</a>

9.
Mia Meany Mia Meany Ireland says:

I must say that overall I am very taken with this site.It is apparent that you know you subject matter and you are passionate about it. I wish I had got your ability to write. I have bookmarked your site and look forward to more updates.

10.
John Renova John Renova United States says:

I agree with you.Good post. I like your blog and have already bookmarked

11.
Cristine Tatham Cristine Tatham United Kingdom says:

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!

12.
Henry Henry United States says:

This is the best post on this topic i have ever read.

13.
Gamefly Gamefly United States says:

this is an amazing site.i am a regular follower of the articles.thank you for the information.keep sharing.

14.
Gamefly Gamefly United States says:

The piece of information you provided is enlighting in all perspective to development.

15.
Jaiden Jaiden United States says:

You got numerous positive points there. I made a search on the issue and found nearly all peoples will agree with your blog.

16.
Shena Sukhu Shena Sukhu says:

Dont forget that you should also have your email marketing system in place, you should have a lead capture or autoresponder on your site.If you dont have a site you can get a wordpress site done and hosted for very little money …around $250 gets you a customized professional wordpress site and google loves the wordpress structure and it ranks those sites very well.There are some very good internet marketing experts out there helping small businesses and for very reasonable costs.Prices may start at around $360 per month but you get value and there isnt an SEO out there offering to work for 10 bucks. Professional help is transparent, measureable and guaranteed for pre agreed targeted results. You get what you pay for.It can cut down your offline marketing costs too if you get it done properly. Thank you for this article! I've just found a  decisively  unbelievable   web 2.0 source  <A href="http://aggressivemarketing.info/">about  true marketing</A> Try it!

17.
Jorge Kapaun Jorge Kapaun United Kingdom says:

Hi buddy, your blog's design is simple and clean and i like it. Your blog posts are superb. Please keep them coming. Greets!!!

18.
Heidi Skagen Heidi Skagen United Kingdom says:

I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.

19.
Tori Tori United States says:

You got some great ideas there. I did a search on the issue and learnt most peoples will agree with your blog.

20.
Daria Villela Daria Villela United States says:

I wanted to thank you for this great read!! I definitely enjoying every little bit of it. I have you bookmarked to check out new stuff you post.

Comments are closed