Click here to Skip to main content
13,861,604 members
Click here to Skip to main content
Add your own
alternative version

Stats

39.1K views
470 downloads
40 bookmarked
Posted 31 Mar 2009
Licenced CPOL

How to Build a Custom XML Configuration (NOT web.config) for ASP.NET

, 7 May 2009
Rate this:
Please Sign up or sign in to vote.
How to build a Custom XML Configuration (NOT web.config) for ASP.NET

Introduction

A frequently asked question in the ASP.NET community is 'How to Build a Custom XML Configuration for ASP.NET' or 'How to use my own config files in ASP.NET'. Today let's do it together.

If you want to use your custom config settings, you can inherit the IConfigurationSectionHandler if your .NET version is 1.x. You can also inherit the ConfigurationSection if your .NET version is 2.0.

If you want to store your config settings in another file NOT Web.config, you can use some serializable class to serialize the class to XML file / deserialize from XML file and push it to ASP.NET cache. When the file is modified, the CONFIG instance will be changed immediately.

What This Article Consists Of?

How to configure an application using XML/CONFIG files, NOT web.config.

Using the Code

A demo custom config file like this one can set your site URL and theme name.

<?xml version="1.0"?>
<websiteConfig>
  <siteUrl><![CDATA[http://huobazi.aspxboy.com/]]></siteUrl>
  <themeConfig defaultTheme="Red">
    <theme name="Blue" />
    <theme name="Red" />
    <theme name="Black" />
  </themeConfig>
</websiteConfig>

We want to store it in our own config file NOT web.config.
.NET provides a great thing, that is serialize/deserialize. We can use a serializable class, and it can be deserialized from our XML config files.

namespace Huobazi.XiaHouWeni.CSDN.TestWebapplication
{
    [XmlRoot( "websiteConfig" )]//Here is a serializable attribute
    public class WebsiteConfiguration
    {
        [XmlElement("siteUrl")]//Here is a serializable attribute
        public string SiteUrl { get; set; }
        [XmlElement( "themeConfig" )]//Here is a serializable attribute
        public ThemeConfig ThemeConfig { get; set; }
    }
}

Other Classes for Theme Setting

public class ThemeConfig
    {
        [XmlAttribute( "defaultTheme" )]//Here is a serializable attribute
        public string DefaultThemeName { get; set; }
        [XmlElement( "theme" )]//serializable attribute
        public ThemeCollection Themes { get; set; }
        private Theme DefaultTheme
        {
            get { return Themes[DefaultThemeName]; }
        }
    }
    public class Theme
    {
        [XmlAttribute( "name" )]//serializable attribute
        public string Name { get; set; }
    }
    public class ThemeCollection : KeyedCollection<string, Theme>
    {
        protected override string GetKeyForItem(Theme item)
        {
            return item.Name;
        }
    }

Then we write a helper class to Load the Settings from the XML config file and insert it into ASP.NET cache.

internal sealed class ConfigLoader
    {
        private ConfigLoader() { }
        public static T LoadConfig<T>() where T : class
        {
            return LoadConfig<T>( null );
        }
        public static T LoadConfig<T>(string fileName) where T : class
        {
            if ( string.IsNullOrEmpty( fileName ) )
            {
                fileName = HttpContext.Current.Server.MapPath
			( string.Concat( "~/", typeof( T ).Name ,".config") );
            }
            string cacheKey = fileName;
            T configObj =  HttpRuntime.Cache[cacheKey] as T;
            if ( configObj == null )// Here we try populate the config from cache
            {
                configObj = LoadFromXml<T>( fileName );
                // insert the config instance into cache use CacheDependency
                HttpRuntime.Cache.Insert( cacheKey, configObj, 
			new System.Web.Caching.CacheDependency( fileName ) );
            }
            return configObj;
        }
        private static T LoadFromXml<T>(string fileName) where T : class
        {
            FileStream fs = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer( typeof( T ) );
                fs = new FileStream( fileName, FileMode.Open, FileAccess.Read );
                return (T)serializer.Deserialize( fs );
            }
            catch ( Exception ex )
            {
                return null;
            }
            finally
            {
                if ( fs != null )
                {
                    fs.Close( );
                }
            }
        }

A ConfigManager Class

public static class ConfigManager
{
    public static WebsiteConfiguration WebSitConfig
    {
        get
        {
            return ConfigLoader.LoadConfig<WebsiteConfiguration>( );
        }
    }
}

How To Use

this.txtSiteUrl.Text = ConfigManager.WebSitConfig.SiteUrl;
this.txtCurrentThemeName.Text = ConfigManager.WebSitConfig.ThemeConfig.DefaultThemeName;
this.themeGrid.DataSource = ConfigManager.WebSitConfig.ThemeConfig.Themes;
this.themeGrid.DataBind( );

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Huobazi(Marble.M.Wu)
Software Developer (Senior)
China China
http://huobazi.aspxboy.com/
http://dotnetHelpdesk.com/

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
DARSHAN MODANI10-Apr-12 5:59
memberDARSHAN MODANI10-Apr-12 5:59 
QuestionHow to use multiple custom XML file Pin
KishorePVK10-Feb-11 11:32
memberKishorePVK10-Feb-11 11:32 
QuestionWill be better this? Pin
robertoqzs1-Jul-10 20:44
memberrobertoqzs1-Jul-10 20:44 
GeneralSome useful links for you Pin
vSoares8-May-09 4:34
professionalvSoares8-May-09 4:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.190214.1 | Last Updated 8 May 2009
Article Copyright 2009 by Huobazi(Marble.M.Wu)
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid