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

Implement ASP.NET custom XML file configuration

Rate me:
Please Sign up or sign in to vote.
4.60/5 (6 votes)
12 Feb 2013CPOL2 min read 23.2K   400   10  
We will see how to implement an ASP.NET web application and have an XML file for configuring some configuration parameters.

Introduction

We will see how to implement an ASP.NET web application and have an XML file for configuring some configuration parameters (a separate XML file other than web.config). Read the configuration parameters from this XML file from this web application and make sure that whenever the XML file is modified in the disk file (manually), the web application immediately reads the XML file and reloads the latest configuration parameters. I was trying to write a sample ASP.NET test application to implement this custom XML configuration.

Background

This article will help to develop any ASP.NET website which needs to load the configuration parameters from a separate XML file other than web.config. This article is not for beginner C# developers.

Using the code

The Settings.cs class holds the property I defined into the Settings.config XML file. I have taken only one parameter for testing purposes. My main concern is to understand the technique.

XML
//Settings.config xml 
<?xml version="1.0"?>
<Settings>
  <name>Test User</name>
</Settings>

The code:

C#
//Settings.cs
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace CustomXmlConfiguration.Configs
{
    /// <summary>
    /// This class is a structure of XML custom settings properties 
    /// </summary>
    [XmlRoot("Settings")]//serializable attribute
    public class Settings
    {
        [XmlElement("name")]//serializable attribute
        public string Name { get; set; }
    }
}

I have wrote a Manager class to call the base method to load the XML config into Settings class. The SettingLoader class is actually load the XML file and save it HTTPRuntime Cache as key pair. Every time when the LoadConfig method is called, it checks HTTPRuntime Cache if its return nulls then it load it from the XML file. If the XML file is changed manually the HTTPRuntime Cache return null and the XML file load again and save into Cache again.

C++
//SettingsManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CustomXmlConfiguration.Configs
{
    /// <summary>
    /// This manager helper class will provide the  Settings
    /// </summary>
    public class SettingsManager
    {
        /// <summary>
        /// This static property return the Settings class object from loading the configuration
        /// </summary>
        public static Settings WebSiteSettings
        {
            get
            {
                return SettingLoader.LoadConfig<Settings>();
            }
        }
    }
}
C#
//SettingLoader.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using CustomXmlConfiguration.Logger;

namespace CustomXmlConfiguration.Configs
{
    /// <summary>
    /// 
    /// </summary>
    internal sealed class SettingLoader
    {
        /// <summary>
        /// Private constructor
        /// </summary>
        private SettingLoader() { }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T LoadConfig<T>() where T : class
        {
            return LoadConfig<T>( null );
        }

        /// <summary>
        /// Return Settings object from cache or from the XML file  
        /// </summary>
        /// <typeparam name="T">The type we will passing</typeparam>
        /// <param name="fileName"> </param>
        /// <returns></returns>
        ///
        public static T LoadConfig<T>(string fileName) where T : class
        {
            T configObj = null;
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = HttpContext.Current.Server.MapPath
                    (string.Concat("~/", typeof(T).Name, ".config"));
                }
                string cacheKey = fileName;
                // Load the setting object from HttpRuntime Cache if the Settings.xml
                // file is not change recently after last Chache.
                configObj = HttpRuntime.Cache[cacheKey] as T;
                if (configObj == null)// 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));
                }
            }
            catch(Exception ex)
            {
                //write error log
                LogWriter.Instance.WriteToLog(ex.ToString());
                return null;
            }
            return configObj;
        }    
        /// <summary>
        /// Load the settings XML file and retun the Settings Type with Deserialize with XML content
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">File Name of the custom XML Settings file</param>
        /// <returns>The T type which we have have paased with LoadFromXml<T> </returns>
        private static T LoadFromXml<T>(string fileName) where T : class
        {
            FileStream fs = null;
            try
            {
                //Serialize of the Type
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                return (T)serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                //write error log
                LogWriter.Instance.WriteToLog(ex.ToString());
                return null;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
    }
}
C#
default.aspx page partial class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomXmlConfiguration.Configs;

namespace CustomXmlConfiguration
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Settings settings = SettingsManager.WebSiteSettings;
            //If get error to load the settings file then redirect to error page
            if (settings == null)
            {
                Response.Redirect("~/Error.aspx?msg=Website Configuration " + 
                  "problem! please contact with webmaster.");
            }
            lblShowSettings.Text = settings.Name;
        }
    }
}

I have attached the full source code to test the custom XML configuration. Please read the documentation.docx to run the sample code perfectly.

when you will run the web application you will see the custom config parameter value one the default.aspx page. Now open the Settings.config file and change the value from the XML file and refresh the page, we will get the latest configuration value from the XML.

I hope you will understand the technique, I have used an error logger to write the exception error but I skipped discussing the error logger in this article because this is out of our topic. If you have any questions please reply to this post.

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)
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --