Cache and practical use of file cache

Cache
Cache is a tool to manage state of a user. It store the processed page or we can say output of request or page parts to escape the repeating on every request and on parallel requests runtime return the results from Cache in place of process the whole request again. So it is to avoid the overhead of recreate the request. Cache is beneficial when same content or information request repeatedly.

Benefit
Cache benefit is related to performance. It increase performance by reducing overheads on server and decrease roundtrip by providing user cached output.

Type of Cache
Page output caching – store complete page in cache.
Page fragment caching – store any part of page.
Data caching – store application data into cache.

Where does cache stores?
Cache could be of 3 types based on storage. First memory cache stores on SRAM which is a high speed memory in processor. Second is disk cache which stores in primary memory. These are used for light thing but overhead on memory. Then a new version of cache in trend is file cache which stores in secondary memory as files. Here I will discuss File cache in details.

What is File Cache?

File cache is to store cached content on hard disk in the form for files to save memory overhead. We can implement it by overriding the functionality of Output cache provider and write our own class of Filecacheprovider. Dot net library provide way to override different methods of Outputcacheprovider class.
Following code show the way to implement it –

File cache implementation
// Create cache object –
[Serializable]
internal class CacheItem
{
public DateTime Expires;
public object Item;
}

//overriding Outputcacheprovider class to override cache add/remove/get/set
public class FileCacheProvider : OutputCacheProvider
{
private string _cachePath;
//a property to get/set file cache path
private string CachePath
{
get
{
if (!string.IsNullOrEmpty(_cachePath))
return _cachePath;

_cachePath = ConfigurationManager.AppSettings[“OutputCachePath”];
var context = HttpContext.Current;

if (context != null)
{
_cachePath = context.Server.MapPath(_cachePath);
if (!_cachePath.EndsWith(“\\”))
_cachePath += “\\”;
}

return _cachePath;
}
}
//add cache object to save as file with a key
public override object Add(string key, object entry, DateTime utcExpiry)
{
key = key.ToLower();
var path = GetPathFromKey(key);
if (File.Exists(path))
{

object res = Get(key);

if (res == null)

return entry;

return res;

}

using (var file = File.OpenWrite(path))
{

var item = new CacheItem { Expires = utcExpiry, Item = entry };

var formatter = new BinaryFormatter();

formatter.Serialize(file, item);

}

return entry;

}
//get cache item from the filecache by referin a key
public override object Get(string key)
{
key = key.ToLower();
Debug.WriteLine(“Cache.Get(” + key + “)”);

var path = GetPathFromKey(key);

if (!File.Exists(path))
return null;

CacheItem item = null;
try
{
using (var file = File.OpenRead(path))
{
var formatter = new BinaryFormatter();
item = (CacheItem)formatter.Deserialize(file);
file.Close();
}
}
catch {
Remove(key);
return null;
}

if (item == null || item.Expires <= DateTime.Now.ToUniversalTime())
{
Debug.WriteLine(“Expired: ” + item.Expires + ” <= ” + DateTime.Now.ToUniversalTime());
Remove(key);
return null;
}

return item.Item;
}
//Remove an refresh cache item from cache by using a key
public override void Remove(string key)
{
key = key.ToLower();
Debug.WriteLine(“Cache.Remove(” + key + “)”);

var path = GetPathFromKey(key);

if (File.Exists(path))
File.Delete(path);
}
//set or update cache item into a file
public override void Set(string key, object entry, DateTime utcExpiry)
{
key = key.ToLower();
Debug.WriteLine(“Cache.Set(” + key + “, ” + entry + “, ” + utcExpiry + “)”);

var item = new CacheItem { Expires = utcExpiry, Item = entry };
var path = GetPathFromKey(key);

using (var file = File.OpenWrite(path))
{
var formatter = new BinaryFormatter();
formatter.Serialize(file, item);
file.Close();
}
}
//support function to get path by using key of cache
private string GetPathFromKey(string key)
{
key = key.ToLower();
return CachePath + MD5(key) + “.txt”;
}
//support function to MD5 encrypt cache before storing
private string MD5(string s)
{
MD5CryptoServiceProvider provider;
provider = new MD5CryptoServiceProvider();
byte[] bytes = Encoding.UTF8.GetBytes(s);
StringBuilder builder = new StringBuilder();

bytes = provider.ComputeHash(bytes);

foreach (byte b in bytes)
builder.Append(b.ToString(“x2″).ToLower());

return builder.ToString();
}
}

About

I am a Microsoft certifies software professional working exclusively in web application development. I have started Icanpost.net for informative articles and blog. I am learning writing as I like to read and write. Love to write on any subject of my knowledge when free.

View all posts by