Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C#

Dynamic Application Configuration Solution

Rate me:
Please Sign up or sign in to vote.
4.43/5 (5 votes)
7 Aug 2007CPOL3 min read 36.6K   389   22  
Another simple way to work with complex updatable configuration in .NET applications
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1378
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Configuration;

namespace Configuration
{
    public static class SampleConfigurationManager
    {
        private const string STR_CONFIG_FILE_NAME = @"C:\Projects\DynamicConfiguration\ConfigBuildProvider\Test\Sample.xml";
        private const string STR_CACHE_KEY = "SampleCacheKey";
        private const string STR_CACHE_BACKUP_KEY = "SampleCacheBackupKey";
        private static readonly XmlSerializer xs = new XmlSerializer(typeof(Sample));
        private static string ConfigFileName
        {
            get
            {
                string fileName = ConfigurationManager.AppSettings["SampleConfigurationFile"];
                if (!String.IsNullOrEmpty(fileName))
                    return fileName;

                return STR_CONFIG_FILE_NAME;
            }
        }
        private static Cache cache
        {
            get
            {
                if (HttpContext.Current == null)
                    return HttpRuntime.Cache;

                return HttpContext.Current.Cache;
            }
        }
        private static void Save(Sample data, bool refresh)
        {
            if (data == null)
                return;

            using (FileStream fs = File.OpenWrite(ConfigFileName))
            {
                xs.Serialize(fs, data);
            }
            if (refresh)
            {
                Sample dummy = Data;
            }
        }
        private static void SetCache(Sample data, CacheDependency fileDependancy)
        {
            cache.Add(STR_CACHE_BACKUP_KEY, data, null,
                                    Cache.NoAbsoluteExpiration, new TimeSpan(24, 0, 0),
                                    CacheItemPriority.High, null);
            cache.Add(STR_CACHE_KEY, data, fileDependancy,
                Cache.NoAbsoluteExpiration, new TimeSpan(24, 0, 0),
                CacheItemPriority.High, null);
        }
        /// <summary>
        /// Gets or sets the configuration data.
        /// </summary>
        /// <value>The data.</value>
        public static Sample Data
        {
            get
            {
                Sample data = (Sample)cache[STR_CACHE_KEY];
                if (data == null)
                {
                    string path = null;
                    try
                    {
                        using (FileStream fs = File.OpenRead(ConfigFileName))
                        {
                            // Get full path for use as dependancy
                            path = fs.Name;
                            data = (Sample)xs.Deserialize(fs);
                        }
                    }
                    catch
                    {
                        Trace.WriteLine(String.Concat("Error reading configuration file ", ConfigFileName));
                    }
                    if (data == null)
                    {
                        data = (Sample)cache[STR_CACHE_BACKUP_KEY];
                        if (data == null)
                            return null;
                    }
                    SetCache(data, new CacheDependency(path));
                }
                return data;
            }
            set
            {
                if (File.Exists(ConfigFileName))
                    SetCache(value, new CacheDependency(ConfigFileName));
                else
                    SetCache(value, null);
            }
        }
        /// <summary>
        /// Saves this configuration instance.
        /// </summary>
        public static void Save()
        {
            Save(Data, false);
        }
        /// <summary>
        /// Saves the specified configuration data.
        /// </summary>
        /// <param name="data">The data.</param>
        public static void Save(Sample data)
        {
            Save(data, true);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Web Developer
Israel Israel
Leon works as Chief Architect at SRL Group. He leads architectural design and development of various enterprise level projects.
You can meet him on user groups, conferences and forums dedicated to Architecture, ASP.NET, Team System etc. or join him for the next white water rafting adventure

Comments and Discussions