Tuesday, August 05, 2008

Impersonation in SharePoint 2007 OM

Whenever you are developing anything for SharePoint 2007 and that piece of code needs to perform some admin tasks which are not possible with the current user context, you are left with no other option but to impersonate.

Impersonation within SharePoint 2003 was not so easy. Although you can find the helper class easily on Internet but still you need to add that class to your solution and perform few calls which sometimes becomes quite irritating. It was a common issue with SharePoint 2003.

Thankfully, that issue has been addressed in SharePoint 2007 and now we have impersonation as part of SharePoint OM. It is as easy as calling a delegate. If you are familier with anonymous methods, you can get the idea from the following piece of code that how easy it is to elevate user's rights within SharePoint 2007.

SPWeb web = SPContext.Current.Web;
SPUser user = web.CurrentUser;

// the calling user

// Uses the SHAREPOINT\system creds with the SPUser's identity reference of user SPSecurity.RunWithElevatedPrivileges(delegate() {

web.AllowUnsafeUpdates = true;
SPList theList = web.Lists[listName];
SPListItem record = theList.Items.Add();
record["User"] = user;
// calling user
record.Update();
web.AllowUnsafeUpdates = false;

});

No comments: