Totally wrong way to use SPSite, SPWeb
Almost all Sharepoint developers know that you should dispose SPSite and SPWeb object you create in code. Doing so is not hard, you just enclose your objects in a using statement. I found the following piece of code in dozens of places in some legacy Sharepoint code created by people who should have known better:
SPSite site = null;
SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url);
web = site.OpenWeb();
//Blah Blah Blah
});
}
catch (Exception MyMethodException)
{
WriteErrorMessage(string.Format("MyMethodExceptionException : {0}", MyMethodExceptionException.Message));
}
finally
{
web.Dispose();
site.Dispose();
}
Looks like whoever wrote this code never heard of the using statement, in .NET since v1. It's not just that this code is more verbose than it needs to be. It also broadens the scope of the site and web variables and exposes them to abuse. This can be a serious problem if the code contains large methods, and this code has several 100+ line method.
Worse, it's easy to get it wrong by forgetting to put the finally clause. Indeed, there were dozens more places where the coder forgot the finally statement and wrote something like this:
SPSite site = null;
SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url);
web = site.OpenWeb();
//Blah Blah Blah
site.Dispose();
web.Dispose();
});
}
catch (Exception MyMethodException)
{
WriteErrorMessage(string.Format("MyMethodExceptionException : {0}", MyMethodExceptionException.Message));
}
Ouch! Guaranteed memory leak in case of exception! And this is how the code would look if using was used:
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
(SPSite site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url))
(SPWeb web = site.OpenWeb())
{
//Blah Blah Blah
}
});
}
catch (Exception MyMethodException)
{
WriteErrorMessage(string.Format("MyMethodExceptionException : {0}", MyMethodExceptionException.Message));
}