Question

I have the SharePoint 2013 site collection called "site1"

i have one list and one document library in that site collection, i written a event receiver to move the list item attachment into document library and after moving the list item attachment i'm updating a filed in that list with that document URL after that i'm deleting the attachment form that list item. below is the code i'm using

public override void ItemAdded(SPItemEventProperties properties)
    {
        base.ItemAdded(properties);

        this.EventFiringEnabled = false;


        if (properties.List.Title.Equals("ListName", StringComparison.CurrentCultureIgnoreCase))
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {                       
                    MoveAttachments(properties);
                    DeleteAttachments(properties);                        
                });
                properties.ListItem.Update();
            }
            catch (Exception ex)
            {
                CreateLog.Create(ex.StackTrace);
                CreateLog.Create(ex.Message);
            }

        }

        this.EventFiringEnabled = true;
    }

public override void ItemUpdated(SPItemEventProperties properties)
    {
        base.ItemUpdated(properties);
        this.EventFiringEnabled = false;   
        if (properties.List.Title.Equals("ListName", StringComparison.CurrentCultureIgnoreCase))
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    MoveAttachments(properties);
                    DeleteAttachments(properties);
                });
                properties.ListItem.Update();
            }
            catch (Exception ex)
            {
                CreateLog.Create(ex.StackTrace);
                CreateLog.Create(ex.Message);
            }
        }


        this.EventFiringEnabled = true;
    }

public void MoveAttachments(SPItemEventProperties properties)
    {
        string siteURL = properties.Web.Url;
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite tSite = new SPSite(siteURL))
            {
                using (SPWeb tWeb = tSite.OpenWeb())
                {
                    //Move Hiring Req Attachments
                    if (properties.List.Title.Equals("ListName", StringComparison.CurrentCultureIgnoreCase))
                    {
                        try
                        {
                            SPList docDestination = tWeb.Lists["LibraryName"];
                            SPFolder fldRoot = tWeb.Folders[docDestination.Title];
                            SPFileCollection flColl = null;
                            SPList list = tWeb.Lists["ListName"];
                            SPListItem listItem = properties.ListItem;

                            if (listItem.Attachments != null && listItem.Attachments.Count > 0)
                            {
                                foreach (String strName in listItem.Attachments)
                                {
                                    flColl = fldRoot.Files;
                                    SPListItem listtem = docDestination.Items.Add();
                                    SPFile FileCopy = listItem.ParentList.ParentWeb.GetFile(listItem.Attachments.UrlPrefix + strName);
                                    string extention = FileCopy.Name.Substring(FileCopy.Name.LastIndexOf('.'));
                                    string fileName = listItem["Title"].ToString().Replace(" ", "_");

                                    string buildfilename = fileName + extention;
                                    string destFile = flColl.Folder.Url + "/" + buildfilename;
                                    byte[] fileData = FileCopy.OpenBinary();
                                    SPFile flAdded = flColl.Add(destFile, fileData, tWeb.CurrentUser, tWeb.CurrentUser, Convert.ToDateTime(listItem[SPBuiltInFieldId.Created]), Convert.ToDateTime(listItem[SPBuiltInFieldId.Modified]));
                                    SPListItem item = flAdded.Item;
                                    item[SPBuiltInFieldId.Created] = Convert.ToDateTime(listItem[SPBuiltInFieldId.Created]);
                                    item[SPBuiltInFieldId.Modified] = Convert.ToDateTime(listItem[SPBuiltInFieldId.Modified]);

                                    flAdded.Item.Update();

                                    listItem["DocumentURL"] = siteURL + "/" + item.Url;
                                    listItem.Update();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            CreateLog.Create(ex.StackTrace);
                            CreateLog.Create(ex.Message);
                        }
                    }
                }
            }                     
        });

    }


public void DeleteAttachments(SPItemEventProperties properties)
    {
        string siteURL = properties.Web.Url;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite tSite = new SPSite(siteURL))
            {
                using (SPWeb tWeb = tSite.OpenWeb())
                {

                    if (properties.List.Title.Equals("ListName", StringComparison.CurrentCultureIgnoreCase))
                    {
                        try
                        {
                            SPListItem listItem = properties.ListItem;

                            List<string> fileNames = new List<string>();

                            if (listItem["Attachments"] != null)
                            {
                                foreach (string fileName in listItem.Attachments)
                                {
                                    fileNames.Add(fileName);
                                }
                                foreach (string fileName in fileNames)
                                {
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        listItem.Attachments.Delete(fileName);
                                    });
                                }
                            }
                            listItem.Update();
                        }
                        catch (Exception ex)
                        {
                            CreateLog.Create(ex.StackTrace);
                            CreateLog.Create(ex.Message);
                        }
                    }
                }
            }
        });
    }

I have to sharepoint group called "contributors" and "users" contributor group have the editwithoutdelete permissions and users group have only add permissions to that list. when the contributors group members added the list item the code is working fine but when the users group members added the list item it is throwing the below error.

at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessException ex) at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bUnRestrictedUpdateInProgress, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback) at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32& ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents, String filename, Boolean bPreserveItemUIVersion) at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents, String filename, Boolean bPreserveItemUIVersion) at Microsoft.SharePoint.SPListItem.Update() at TA.Tech360.HD.HiringReqEventReciever.HiringReqEventReciever.<>c_DisplayClass24.b_23()-------->8/11/2013 7:03:23 AM

0x80070005-------->8/11/2013 7:03:23 AM

Can any one help me.

thanks in advance.

No correct solution

OTHER TIPS

You need to get everything you are updating from the elevated web. In MoveAttachments and DeleteAttachments methods, change the following line:

SPListItem listItem = properties.ListItem;

which retrieves the listItem NOT as administrator but as the current user (which probably does not have required permissions), to this:

SPListItem listItem = tWeb.Lists[properties.ListId].GetItemById(properties.ItemId);

this retrieves the listItem REALLY as an administrator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top