Thursday, October 06, 2005

Web Application Settings With XML

The Web.config file of an ASP.Net web application is a good place to store settings for the application (see Reading from the Web.config File). However, one problem I’ve run into is editing the Web.config resets the web application. I needed a way to change settings for several dynamic user controls without resetting the whole application.
The class below will load the file from cache or the file system. It is then available to retrieve the node value requested. In addition, naming the file with a “.config” extension instead of “.xml” will prevent IIS from serving the xml file to browsers.

Additional functions can be added to provide short cuts to frequently accessed values, such as database settings.


using System;
using System.Web;
using System.Xml;
using System.Web.Caching;

namespace WebTools
{
public class Settings
{
private XmlDocument m_XmlDoc = null;

public Settings(string XMLSettingsFile)
{
m_XmlDoc = new System.Xml.XmlDocument();
// Check if file can be loaded from cache
if (HttpContext.Current != null && HttpContext.Current.Cache[XMLSettingsFile]!= null)
{
m_XmlDoc = (XmlDocument)HttpContext.Current.Cache[XMLSettingsFile];
}
else
{
string filePath = null;
// Get the complete file path
filePath = HttpContext.Current.Server.MapPath(XMLSettingsFile);

m_XmlDoc = new System.Xml.XmlDocument();
m_XmlDoc.Load(filePath);

//save in a file based cache
if (HttpContext.Current != null)
{
HttpContext.Current.Cache.Insert(XMLSettingsFile,m_XmlDoc,new CacheDependency(filePath));
}
}
}

public string GetValue( string nodePath)
{
XmlNodeReader myXmlNodeReader;
myXmlNodeReader = new System.Xml.XmlNodeReader(m_XmlDoc.SelectSingleNode(nodePath).FirstChild);
myXmlNodeReader.Read();
return myXmlNodeReader.Value();
}
}
}

0 Comments:

Post a Comment

<< Home