Sunday, June 18, 2006

Best practices writing webparts for sharepoint

This is one of the most important articles I have read lately: Using Disposable Windows SharePoint Services Objects

What it explains is that when you develop web parts and use the sharepoint objects (like spsite and spweb) you have to dispose of them because the garbage collector wont.

The article also contains code examples for the recommended three ways to do this: 1. use "dispose" 2. use "using" 3. use "try, catch, and finally blocks"


Example for using "using":
String str;

using(SPSite oSPsite = new SPSite("http://server"))
{
  using(SPWeb oSPWeb = oSPSite.OpenWeb())
   {
       str = oSPWeb.Title;
       str = oSPWeb.Url;
   }
}  
Example for using "try, catch, and finally blocks":
String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;

try
{
   oSPSite = new SPSite("http://server");
   oSPWeb = oSPSite.OpenWeb(..);

   str = oSPWeb.Title;
}
catch(Exception e)
{
}
finally
{
   if (oSPWeb != null)
     oSPWeb.Dispose();

   if (oSPSite != null)
      oSPSite.Dispose();
}


I would recommend that every web part developer go through this article and maybe even print it and nail it to his monitor...

No comments: