This week I am tutoring a SharePoint 2007 development class over at Informator in Gothenburg, Sweden. Today we’ve been looking at Web Parts, creation of custom webparts and best practices for creating our custom solutions based on web parts.
I quickly coded up a sample which is caching items in a webpart – Huge server load is a major impact point for some organizations, making caching a strategically important choice if there’s much redundancy.
Anyway, you probably already know that it’s a good thing to cache your data once in a while if you’ve got heavy load and the data isn’t any “to-the-minute” critical information. So let’s get on with it..
Since people have been asking for a ‘simple sample’ of how to cache things in SharePoint – I thought that I would provide just that, a simple sample. For more in-depth information about caching and cachedependendies, check out Vince’s blog.
Check it out!
Web Part fetching items from a SPWeb object, looping all SPList objects and displaying the ItemCount property.
If there isn’t a cache object present, the iteration of the lists will be done immediately
If there is a cache object present, it will fetch the information from the cached object instead of iterating the lists, saving us some resources
This is the full code of the simple sample cache Web Part:
public class SimpleCache : System.Web.UI.WebControls.WebParts.WebPart
protected override void Render(System.Web.UI.HtmlTextWriter writer)
List lists = new List();
string status = "";
if (HttpRuntime.Cache["SimpleSampleCache"] == null)
status = "The following items are NOT fetched from the cache
SPWeb web = SPContext.Current.Web;
foreach (SPList list in web.Lists)
status = "The following items ARE fetched from the cache!
lists = (List)HttpRuntime.Cache["SimpleSampleCache"];
foreach (SPList l in lists)
writer.WriteLine(l.Title + " – " + l.ItemCount + " items
Summary & Download!
I always use the HttpRuntime or HttpContext objects to store and read my cached objects. You can of course use the built-in caching functionality of WSS 3.0 Web Parts if you feel that you have the need for it. However this approach works everytime, everywhere. Not just for Web Parts of course, but for any kind of ASP.NET hooked application.
You can download the sample project [here]
Thanks for tuning in,