1

I have small console application with this code:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(args[0]))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists["ER Test List"];

            SPListItem item = list.AddItem();

            item["Title"] = "Test CommandLine";

            item.Update();

            item = list.GetItemById(item.ID);

            item["Title"] = "Test CommandLine Updated";

            item.Update();
        }
    }
});

This code only Open site, Open Web, load list, creates list item in it and update same list item. There is no problem.

The ContentType of created item has one custom event receiver:

public class TestListEventReceivers : SPItemEventReceiver
{
    public override void ItemAdded(SPItemEventProperties properties)
    {
        SPCommonUtils.RunWithElevatedPrivilegesThread(delegate
        {
            try
            {
                SPListItem item = properties.ListItem;
            }
            catch(Exception ex) { /* report error */}
        });
    }
}

Using previous Add and Update method this event receiver fails with UnauthorizedAccessException. Problem is with all events (ItemAdding, ItemUpdated, ItemAdding, ItemUpdating). There is exception when code try to access: properties.List, properties.ListItem. If i run code on top without Elevated Privileges everything works fine.

In case of error I still can access to item by opening all objects using properties.ListItemId, properties.ListId, properties.WebId and properties.SiteId. But I would like to know why is it so? If I update given item in ElevatedPriviledged why the EventReceiver is not called in same context? Event receiver are running in same process (my console application) i think that call of Event receivers is somewhere in ListItem.Update method. But ListItem is called opened in ElevatedPrivileges Context so the Event Receivers has to be called in same context? Have someone deep knowledge, how are the event receiver called and how they put SPList and SPListItem to their properties?

EDIT: I tested code mentioned on top of this post in custom Layout page. In this case behavior is different from console application. List and ListItem property of properties object in event receiver are loaded and usable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.