In this article we will be seeing how to resolve "UnauthorizedAccessException was unhandled by user code" in SharePoint event receiver.
I had one custom list "MyList" which contains two columns "Title" and "Service Account".
I had one group with Full control "Service Team". In the "Service Account" column I need to add all the users from the "Service Team" group.
I have written ItemAdded event receiver for adding the users from the "Service Team" group to the "Service Account" column.
public override void ItemAdded(SPItemEventProperties properties)Â Â Â Â Â Â
{
base.ItemAdded(properties);
SPSecurity.RunWithElevatedPrivileges(delegate()Â Â Â Â Â Â Â Â Â Â
{
SPWeb web = properties.Web;
SPListItem item = properties.ListItem;
SPGroup group = web.Groups["Service Team"];Â Â Â Â Â Â Â Â Â Â Â Â Â Â
web.AllowUnsafeUpdates = true;
SPFieldUserValueCollection UserCollection = new SPFieldUserValueCollection();
foreach (SPUser user in group.Users)Â Â Â Â Â Â Â Â Â Â Â Â Â Â
{
SPFieldUserValue UserName = new SPFieldUserValue(web, user.ID, user.LoginName);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
UserCollection.Add(UserName);Â Â Â Â Â Â Â Â Â Â Â Â Â Â
}Â Â Â Â Â Â Â Â Â Â Â Â Â Â
item["Service Account"] = UserCollection;Â Â Â Â Â Â Â Â Â Â Â Â Â Â
item.Update();Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
});Â Â Â Â Â Â
}
When the user with contribute access tried to add the column, users from the "Service Team" were not added to the column and I was getting the following error when I was debugging.
Even though I was using SPSecurity.RunWithElevatedPrivileges I was getting the error. That is because "when using SPSecurity.RunWithElevatedPrivileges, we need to open an elevated site context through a new SPSite object in order to really be elevated". Then I tried with the following code which added users to the columns successfully.
public override void ItemAdded(SPItemEventProperties properties)Â Â Â Â Â Â
{
base.ItemAdded(properties);
SPSecurity.RunWithElevatedPrivileges(delegate()Â Â Â Â Â Â Â Â Â Â
{
using(SPSite site=new SPSite (properties.SiteId))Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
{
using (SPWeb web = site.RootWeb)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
{Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
SPListItem item = properties.ListItem;
SPGroup group = web.Groups["Service Team"];Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
web.AllowUnsafeUpdates = true;
SPFieldUserValueCollection UserCollection = new SPFieldUserValueCollection();
foreach (SPUser user in group.Users)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
{
SPFieldUserValue UserName = new SPFieldUserValue(web, user.ID, user.LoginName);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
UserCollection.Add(UserName);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
}Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
item["Service Account"] = UserCollection;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
item.Update();Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
}Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
}Â Â Â Â Â Â Â Â Â Â
});Â Â Â Â Â Â
}
Comments