2

It seems I cannot use SPList.GetItemById(int) or SPList.GetItemByUniqueId(Guid) or Web.GetListItem(string) to get an item that is checked out. I have tried all three and all three result in a "File does not exist" exception.

An alternative method is to use SPQuery, which I have not tried, but have read that this too will not work.

Question: Are there any alternatives that will work?

What I'm trying to achieve
I have an ItemAdded event receiver. Files that are added to my document library remain checked out when they are first uploaded because I have fields that are mandatory for every file in the list that must be completed by the user before the file can be checked in.

I want to break permission inheritance on every file that is uploaded, hence the ItemAdded event receiver. Most users will not have permissions to set unique permissions on items, therefore have to use SPSecurity.RunWithElevatedPrivileges, and we know when we use this we must obtain new references to all our objects.

This is what I have at the moment; all attempts to get the list item fail:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteId))
    {
        using (SPWeb web = site.OpenWeb(webId))
        {
            SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();

            try
            {                
                //Get item by ID
                //  SPList list = web.Lists[listTitle];
                //  SPListItem thisitem = list.GetItemById(itemId);

                //Get item by unique ID
                //  SPListItem thisitem = list.GetItemByUniqueId(itemGuid);

                //Get item by url
                //  string url = SPUrlUtility.CombineUrl(web.ServerRelativeUrl, item.Url);
                //  SPListItem thisitem = web.GetListItem(url);

                //Get item from event properties
                //  SPListItem thisitem = properties.ListItem;

                web.AllowUnsafeUpdates = true;
                thisitem.BreakRoleInheritance(false);
                web.AllowUnsafeUpdates = true;
                /* Assign unique permissions here */
                rh.DisableEventFiring();
                thisitem.Update();
            }
            catch
            {

            }
            finally
            {
                web.AllowUnsafeUpdates = false;
                rh.EnableEventFiring();
            }
        }
    }
});
2

In the end I got around this issue by assigning temporary values to the required fields, updating the item, checking it in, then running the above piece of code with the addition of a check out before calling thisitem.update(), then assigning the required fields back to null.

Not ideal but it works.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.