Click here to Skip to main content
Click here to Skip to main content

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

By , 7 May 2009
 

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)

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberDARSHAN MODANI10 Apr '12 - 4:59 
QuestionHow to use multiple custom XML filememberKishorePVK10 Feb '11 - 10:32 
QuestionWill be better this?memberrobertoqzs1 Jul '10 - 19:44 
GeneralSome useful links for youmembervSoares8 May '09 - 3:34 

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

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