Thursday, February 22, 2007

.Net Caching Rocks!

OK, I can't believe how cool .Net's built in Caching is. Here is the scenario. I need to query an Oracle database that I don't have anything but select permissions on. So, executing stored procedures and definitely can't create a stored procedure. So, what am I to do? Embed the query in code? That may be fine for small queries, but what if you query is quite long and complex. Sure, technically it can be put in the code, but who wants to maintain it. My solution was to put it in a file that is read from the file system at runtime. The problem is that the file system is hit everytime. So, I decided to cache it using the caching built into .Net. Below is my method that does this. The part that is so cool is that I can set a dependency for when an item in the cache is removed. As it turns out, one of the dependencies is a filename and path. If the file changes the cache is automatically notified. That is magic! :) using System.Web.Caching; .... public string LoadSQL(string filename) { object sqlObj = HttpContext.Current.Cache.Get(filename); string sql = string.Empty; if (sqlObj == null) { string path = HttpContext.Current.Request.PhysicalApplicationPath; string filenameAndPath = string.Format(@"{0}SQL\{1}", path, filename); using (StreamReader reader = new StreamReader(filenameAndPath, true)) { sql = reader.ReadToEnd(); System.Web.Caching.CacheDependency dependency = new CacheDependency(filenameAndPath); HttpContext.Current.Cache.Add(filename, sql, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null); return sql; } } else { sql = sqlObj as string; } return sql; }

No comments: