neděle 3. ledna 2010

SharePoint - Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION)

In one of my WebParts I was using this little piece of code to get the current user from SharePoint:

//values I wanted to work with
String name, email;

//get the currnet SPWeb
//THE PROBLEM: You should not dispose after calling GetContextWeb Method
using (SPWeb lWeb = SPControl.GetContextWeb(this.Context))
SPUser lUser = lWeb.CurrentUser;
name = lUser.Name;
email = lUser.Email;

after executing this I've got the folowing exception:

(Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Došlo k výjimce. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

I have googled a bit and found the solution:

//get the currnet user
SPUser lUser = SPContext.Current.Web.CurrentUser;
//work with it as you need
name = lUser.Name;
email = lUser.Email;

In the MSDN Best Practices you can find, that when using the SPControl.GetContextWeb() or SPControl.GetContextSite() method you should not dispose the created objects.