Friday, March 26, 2010

Caching the PropertyBag in WSS3.0

For one of the req i have got the chance to go through the CKS code.Here i would like to onboard the code snippet.
The below code illustrates how to use Lock(),HttpRuntime.Cache and SPproperybag etc.
public class BlogSettings
{
private readonly object _Lock = new object();
private static readonly Cache Cache = HttpRuntime.Cache;
private SPWeb _CurrentWeb;
///
/// cached WebProperties
///

private readonly SPPropertyBag _WebProperties;
///
/// always create a new BlogSettings object to be able to store WebProperties
///

///
public BlogSettings(SPWeb oWeb)
{
_CurrentWeb = oWeb;
_WebProperties = null;
}
///
/// read BlogSettings from Cache. if the cache is not available, read blogsettings and store them in the cache (with sliding expiration).
/// this BlogSettings object is read only!
///

public BlogSettings(string url)
{
string webUrl = GetWebUrl(url);
string blogSettingsCacheName = string.Format("EBE{0}", webUrl);
lock (_Lock)
{
// try to get blogsettings for this webUrl from the cache
var blogSettings = Cache[blogSettingsCacheName] as SPPropertyBag;
if (blogSettings != null)
{
Trace.WriteLine("Using cached BlogSettings (webUrl=" + webUrl + ")");
}
else
{
// read blogsettings from web
Trace.WriteLine("Reading BlogSettings and store them in the cache (webUrl=" + webUrl + ")");
using (var site = new SPSite(url))
using (var web = site.OpenWeb())
{
var bs = new BlogSettings(web);
blogSettings = web.Properties;
int cacheTimeout = bs.PageOutputCacheTimeout;
Cache.Add(blogSettingsCacheName,
blogSettings,
null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(cacheTimeout),
CacheItemPriority.Normal,
null);
}
}
_WebProperties = blogSettings;
}
}

No comments: