ObjectiveIn this article, I will show how to check improper disposing of instance of SharePoint classes in an assembly. SharePoint Dispose Check toolThis tool is available on CODEPLEX. Download this from HERE and install this. As of documentation of SharePoint Dispose Check tool on CODEPLEX; SPDisposeCheck is a tool to help you to check your assemblies that use the SharePoint API so that you can build better code. It provides assistance in correctly disposing of certain SharePoint objects to help you follow published best practice. This tool may not show all memory leaks in your code. Further investigation is advised if you continue to experience issues. After successful installation of the tool finds some time to have a look on documentation. You can find documentation in your Start ->All Programs How to use SPDisposeCheck?- Open command prompt
- Change directory to
 - Type SPDisposeCheck.exe ; it will show the options available
- If you want to redirect the output of an assembly check to a text file then just need to append standard redirect DOS operator as below
C:\\Program Files\..\..> SPDisposeCheck.exe assemblydll >> somefilename.text
Let us say, you have a code in class library something like below , using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace TestingDisposeinSharePoint
{
public class Class1
{
public void SnapOfContext()
{
SPSite site = new SPSite("http://c849uss:9722/Sites/Test1");
SPWeb web = site.OpenWeb();
}
}
}
In above code DISPOSE is not managed properly. So when we run DLL of above class library using SPDisposeCheck we will get below output. Name of the DLL we are testing is TestingDispeseinSharePoint.dll. This DLL is inside folder c:\disposecheckingdll
C:\Program Files\Microsoft\SharePoint Dispose Check>SPDisposeCheck.exe c:\disposecheckingdll\TestingDisposeinSharePoint.dll Output So, from output we can clearly see that SPSite and SPWeb instance is not properly disposed. Now let us modify the above code as below using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace TestingDisposeinSharePoint
{
public class Class1
{
public void SnapOfContext()
{
SPSite site = new SPSite("http://c849uss:9722/Sites/Test1");
SPWeb web = site.OpenWeb();
if (site != null)
site.Dispose();
if (web != null)
web.Dispose();
}
}
}
In above code we are properly handling the dispose of SharePoint instances. So on testing of updated DLL with
C:\Program Files\Microsoft\SharePoint Dispose Check>SPDisposeCheck.exe c:\disposecheckingdll\TestingDisposeinSharePoint.dll OutputThere is no error reported because all the dispose was properly managed. Conclusion In this article we saw how to use third party tool to check improper dispose on SharePoint API. Thanks for reading. |