Question

I am working on supporting code in a custom event receiver developed about 6 years ago... There was no source code, so we had to reflect the production assembly, and are working on cleaning it up before working.

In the code, I came across this, and I can't tell why it would be done, and I don't know enough about SharePoint to be able to know if there is a reason it has to be done this way, or if the original coder was an idiot (both are possible...)

public override void ItemAdded(SPItemEventProperties properties)
{
    Trace.WriteLine("ItemAdded() invoked.");
    base.DisableEventFiring();
    base.ItemAdded(properties);

    try
    {
        SPContext context = SPContext.GetContext(properties.OpenWeb());
        SPUserToken userToken = context.Site.SystemAccount.UserToken;

        using (SPSite site = new SPSite(context.Site.ID, userToken))
        using (SPWeb web = site.OpenWeb(context.Web.ID))
        {
            SPListItem listItem = null;
            try
            {
                listItem = web.GetListItem(properties.ListItem.Url);
                web.AllowUnsafeUpdates = true;
            }
            catch
            {
                Trace.WriteLine("No Url properties, we must be running in CLI mode. Exiting...");
            }
            if (listItem != null)
            {
                SPList parentList = listItem.ParentList;
                listItem = parentList.GetItemById(properties.ListItemId);
            }
            ...
        }
    }
    catch (Exception ex)
    {
        Trace.WriteLine(ex.ToString());
    }
    finally
    {
        base.EnableEventFiring();
    }
}

It just seems like this is getting the SPListItem by multiple ways, when it is passed in in the properties object... Same for the Website.. So, I guess my question is since they end up just getting the List item by the properties anyways through the list, is there really any reason to go through all the other checks/methods to just throw the value away in the end?

Était-ce utile?

La solution

The difference is that it's not getting the list item using the current user's credentials; it's grabbing it using the system account's credentials.

The system account may have permissions surrounding the list item that the current user does not.

That said, there are most certainly easier ways of getting the list items, and there's no reason to get it several times like that, even if getting it once may be appropriate.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top