Click here to Skip to main content
15,896,606 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.50/5 (8 votes)
7 May 2009CPOL1 min read 47.6K   480   40   4
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
<?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.

C#
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

C#
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.

C#
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

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

How To Use

C#
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)


Written By
Software Developer (Senior)
China China
http://huobazi.aspxboy.com/
http://dotnetHelpdesk.com/

Comments and Discussions

 
GeneralMy vote of 5 Pin
DARSHAN MODANI10-Apr-12 4:59
DARSHAN MODANI10-Apr-12 4:59 
QuestionHow to use multiple custom XML file Pin
KishorePVK10-Feb-11 10:32
KishorePVK10-Feb-11 10:32 
QuestionWill be better this? Pin
robertoqzs1-Jul-10 19:44
robertoqzs1-Jul-10 19:44 
GeneralSome useful links for you Pin
vSoares8-May-09 3:34
professionalvSoares8-May-09 3: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.