My Technical Notes

Thursday, 14 March 2013

Sharepoint 2010 Alternative to the Session in ASP.NET

Sharepoint 2010 by default has the Session disabled by default. One could enable the Session or alternatively we can use SharePoint's in-built caching mechanism, where we use the methods, PartCacheRead and PartCacheWrite.

In order for us to use these methods we first need to inherit our Web Part from Microsoft.SharePoint.WebPartPages.WebPart:

public class MyWebPart : Microsoft.SharePoint.WebPartPages.WebPart

To the cache, we use the PartCacheWrite. For example, if we wanted to store something for 30 minutes for all users (note the Storage.Shared), we would write something like this:

PartCacheWrite(Storage.Shared, "my_key", "my_value", new TimeSpan(0, 30, 0));

Thereafter we can read from the cache:

PartCacheRead(Storage.Shared, "my_key")

What I noticed was that if I used Storage.Personal, then the cache would always return null, however Storage.Shared retains the value. Therefore what I devised was a set of utility methods which we could use to get and set values from the cache, on a per username basis:

public string PartCacheName(string key)
    return string.Format("{0}.{1}", SPContext.Current.Web.CurrentUser.LoginName, key);

public object GetPartCache(string key)
    return this.PartCacheRead(Storage.Shared, PartCacheName(key));

public void SetPartCache(string key, object value)
    this.PartCacheWrite(Storage.Shared, PartCacheName(key), value, new TimeSpan(0, 30, 0));

Apparently it is not slower to store the cache in the Shared area rather than the Personal area, which one internet resource has claimed.

No comments: