How to use ASP.Net Cache settings to automatically read and update values from an XML file when the file is updated, and how to lookup a value in the XML file.
.Net surprises me every day. I think about how I want to do things and then I dig a little (some time a lot) into .Net components and viola, I find it provides some new interesting functionality that I didn't know about before.
I recently wanted to implement some features for using configuration values for an ASP.NET application. My requirements were as follows.
- Implement an Admin page to allow writing / updating the configuration file.
- Use an XML file format for the configuration data.
- Cache the data in the IIS cache once read
- Update the cache if the XML file was updated
- I did not want to utilize a database
- Since these would be updated frequently, I did not want to utilize the web.config
I found the ASP.NET Cache.Insert method to be the key for my needs. By creating a Cache Dependency tied to the configuration file, when the file is updated, it will automatically update the cache. This is the same behavior as the web.config file, but without some of the same permission access issues when trying to write to the file.
I could have used a NameValueCollection to do the same thing, but I wanted to use the DataSet in this instance. I added the PrimaryKey value to the DataSet and .Net took care of the lookup of the data with Rows.Find().
Note: In order to write to an XML file via ASP.NET code, the directory must have write permissions enabled on the IIS user account (ASPNET, or Network Service, or the ID used in the application pool, or virtual directory).
The code for this particular logic was placed in the App_Code directory, so it could be accessed from code as well as ASP.NET pages via something like the following.
C# Code Example located in the App_Code directory
1: public static String CustomSettings(String keyValue)
3: DataSet oDS;
4: String szXMLFileName;
5: String foundValue = "";
6: oDS = (DataSet)System.Web.HttpContext.Current.Cache["Settings"];
7: if (oDS == null)
9: szXMLFileName = SettingFileName();
10: oDS = new DataSet();
13: CacheDependency oCacheDependency;
14: oCacheDependency = new CacheDependency(szXMLFileName);
16: System.Web.HttpContext.Current.Cache.Insert("Settings", oDS, oCacheDependency);
20: DataColumn oKeyCols = new DataColumn;
21: DataTable oTable;
22: DataRow oRow;
24: oTable = oDS.Tables["Attribute"];
25: oKeyCols = oTable.Columns["Key"];
26: oTable.PrimaryKey = oKeyCols;
28: oRow = oTable.Rows.Find((object)keyValue);
29: if (oRow != null)
31: foundValue = (string)oRow["Value"];
34: return foundValue;
Settings.xml located in the App_Data directory
1: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
6: <Text>Page Title Prefix</Text>
11: <Text>Page Title Suffix</Text>
12: <Value> - Tim-Stanley.com</Value>
16: <Text>Site Name</Text>
21: <Text>Copyright Name</Text>
22: <Value>TSI Systems LLC</Value>