Sunday, October 12, 2008

Caching in WebParts

Scenario:
You want to use caching in webpart

Solution:
Webpart is just like any other WebControl and can use caching object.

Code:

using System; 
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web;

namespace TrainingSamples {

public class SimpleCache: System.Web.UI.WebControls.WebParts.WebPart {

protected override void Render (System.Web.UI.HtmlTextWriter writer) {

base.Render (writer);

List<SPList> lists = new List<SPList>();
string status = "";

if (HttpRuntime.Cache["SimpleSampleCache"] == null)
{
status = "The following items are NOT <strong> </ strong> fetched from the cache <br/>";

SPWeb web = SPContext.Current.Web;
foreach(SPList list in web.Lists)
{
lists.Add (list);
}

HttpRuntime.Cache.Add( "SimpleSampleCache" lists, null DateTime.MaxValue, TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Default, null);
}
else
{
status = "The following items ARE <strong> </ strong> fetched from the cache! <br/>";
list = (List<SPList>) HttpRuntime.Cache["SimpleSampleCache"];
}

writer.Write (status);

foreach (l in SPList lists)
{
writer.WriteLine (l.Title + "-" + + l.ItemCount "items <br/>");
}
}
)
)
Note:
Another best practice is consider loading the data from SharePoint objects into a DataSet or DataTable if caching is required.
Article:
http://blogs.msdn.com/modonovan/archive/2005/04/27/412505.aspx

0 comments: