DISP_E_EXCEPTION and Disposing the SPContext.Current Objects

Have you ever came across the situation where user wanted to delete the web part from their page using the browser and they get following error message – “Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION)). If you have permission, you can use this page to temporarily close Web Parts or remove personal settings. For more information, contact your site administrator.”

As hinted in the error message, if user has permission, they can access the web part maintenance page (_layouts/spcontnt.aspx?&url=) by appending “?contents=1” to the browser URL and manually delete the web part. In real world, this is not acceptable scenario. So, the real question here is what causes this dreaded generic message in the web part. There may be millions of reasons why SharePoint would throw an error but one of the reasons for this error message is you are disposing the SPContext.Current.Site or SPContext.Current.Web object in the code.

If you are accessing the SPContext.Current.Site or SPContext.Current.Web object in your code using the code snippet # 1 or code snippet # 2, it will dispose the SPContext.Current.Site or SPContext.Current.Web objects automatically. As per SPDisposeCheck Guidance, Microsoft.SharePoint.SPContext objects (SPContext.Current.Site & SPContext.Site as well as SPContext.Current.Web & SPContext.Web properties return SPSite and SPWeb objects respectively) will be disposed automatically by the SharePoint. If you dispose them manually, web part will throw the error.

Code Snippet # 1 = Wrong Way

using (SPWeb spWeb = SPContext.Current.Web)
 // Access the SPWeb Object
}//spWeb.Dispose() gets called automatically

Code Snippet # 2 = Wrong Way

SPWeb spWeb = SPContext.Current.Web

Code Snippet # 3 = Right Way – Do Not call Dispose()

SPWeb spWeb = SPContext.Current.Web

In Short, do not accidentally dispose a SPContext.Current.Site or SPContext.Current.Web objects in your web part otherwise user will receive the generic message for DISP_E_EXCEPTION.

This entry was posted in Uncategorized. Bookmark the permalink.