Sunday, January 30, 2011

Impersonation in Event Receiver

Recently faced an issue while working with Event Receivers. That is, current user need to impersonate with higher privilege account. Normally we do that with application pool account. 


Th problem here is, if you try to use event receiver's 'property' object to access the current web or the list item, the impersonation never works there. For example, following piece of code will use current user credentials, not the application pool account permission.


SPSecurity.RunWithElevatedPrivilege(delgate
{
properties.ListItem.Delete();
});


For using impersonation, you need to create a separate instances of SPWeb, then access your items.



SPSecurity.RunWithElevatedPrivilege(delgate
{
  using(SPSite site = new SPSite(properties.WebUrl))
  {
     using(SPWeb web = site.OpenWeb())
     {
         //access your items here.
     }
  }
});