Well I feel the need to start sharing. Though I don't know what I'll share, mostly what I learn is from other blogs. But who cares? No one knows who I am yet anyway, right?
So what do I have to talk about today? My incessant need to continuously find a "better way". There's this project of mine, that I've been working on for about 2 years now. The problem is I keep having to put it only hold for various reasons. (I'm sure others can relate) The problem is, when I come back to it, and look over the code, I'm disgusted. Over my "break" from the code, I've continued to read, and learn, and now that I've picked my project up again, I know of a "better way" or simply just want to apply some knowledge I've learned.
This project started off as a basic ASP.NET web site using SubSonic as my tool of choice for access the database. And now? It's an ASP.NET MVC application using the entity framework. Speaking of which, Hat's off the the ASP.NET MVC devs!
So what hunk of code do I have today? Well this CacheManager tool I've been messin around with. Here's the primary static method I'm using.
public static T HandleCache<T>(IQueryable<T> Query, object Value, int? MinToExpire)
{
var keyName = string.Format("{0}_{1}", typeof(T), Value);
if (HttpContext.Current.Cache[keyName] != null && HttpContext.Current.Cache[keyName] is T)
return (T)HttpContext.Current.Cache[keyName];
var item = Query.FirstOrDefault();
if (item != null)
{
if (MinToExpire.HasValue)
HttpContext.Current.Cache.Add(keyName, item, null, DateTime.MaxValue, new TimeSpan(0, MinToExpire.Value, 0), CacheItemPriority.Normal, null);
else
HttpContext.Current.Cache.Insert(keyName, item);
}
return item;
}
See, I'm lazy... I just want to call something like:
var account = CacheManager.HandleCache<Account>(m_AccounService.GetAccount().WithID(UserID), UserID, 20);
And poof have my Account object (If it exists) and have it all cached up and ready to go. I just feel like there could be a better way.