Solved

UnauthorizedAccess Exception: When copying Sharepoint 2010 list item

Posted on 2011-02-25
4
1,902 Views
Last Modified: 2012-05-11
I am looking for assistance to resolve an exception being thrown when I attempt to copy an
added Blog list item from one Sharepoint WebApplication/ContenctDB(Webapp0) to a Blog list on a different Sharepoint WebApplication(Webapp1).  The exception raised is
System.UnauthorizedAccessException, however I am the primary adminstrator for both sites,
plus I am executing the code using RunWithElevatedPrivileges.  Help decyphering the error
would be appreicated.

I have attached the code.

The Exception being thrown is:

Error loading and running event receiver CopyBlogListItem.CopyBlogListItem in CopyBlogListItem,
Version = 1.0.0.0,  Culture=neutral, PublicKeyToken=ac27c065e1c5c56b.
Additional information is below.

: CopyBlogListItem, SPSecurity.RunWithElevatedPrivileges(copyListItem):
Exception: [System.Exception: CopyBlogListItem, targetItem.Update():
Exception: [System.UnauthorizedAccessException:
                  <nativehr>0x80070005</nativehr>
                  <nativestack></nativestack>
   at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem
             (String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate,
               Boolean bPreserveItemVersion, Boolean bUpdateNoVersion, Int32& plID,
               String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion,
               Object& pvarAttachmentNames, Object& pvarAttachmentContents,
               Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, 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)
   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)
   at Microsoft.SharePoint.SPListItem.Update()
   at CopyBlogListItem.CopyBlogListItem.copyListItem()].
   at CopyBlogListItem.CopyBlogListItem.copyListItem()
   at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()
   at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess
                 (CodeToRunElevated secureCode)
   at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges
                 (WaitCallback secureCode, Object param)
   at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges
                 (CodeToRunElevated secureCode)
   at CopyBlogListItem.CopyBlogListItem.ItemAdded(SPItemEventProperties properties)].
namespace CopyBlogListItem
{
    public class CopyBlogListItem : SPItemEventReceiver
    {

        // Local variable to contain data passed in from sharepoint
        private SPItemEventProperties _properties;

        // Method called after a new item has been added
        public override void ItemAdded(SPItemEventProperties properties)
        {
            // set up a log file
            log = new HTMLFileLogging(c_logFileFolder, string.Format(LogFileName, properties.ListTitle, properties.OpenWeb().Title), true, false);
            // run under system account
            this.WriteToLog("ItemAdded: Executing Event Handler", true);

            _properties = properties;
            this.WriteToLog("ItemAdded: Properties Set", true);
            try
            {
                SPSecurity.RunWithElevatedPrivileges(copyListItem);
            }
            catch (Exception e)
            {
                throw new Exception("CopyBlogListItem, SPSecurity.RunWithElevatedPrivileges(copyListItem): Exception: [" + e.ToString() + "].");
            }
            this.WriteToLog("ItemAdded: Event Handler Complete", true);
            
        }
        private void copyListItem()
        {

            //Step 0: get a handle to the item that raised the event
            this.WriteToLog("copyListItem: Get handle to item", true);
            SPListItem item = _properties.ListItem;

            //step 1: Check category property to determine receiving site.
            //***initialize targetURL***
            this.WriteToLog("copyListItem: Initializing targetURL", true);
            this.WriteToLog("copyListItem: Item Category is " + item["Category"] + ".", true);
            string targetURL = "0";
            string targetCategory = "";
            if (item["Category"].ToString() == "1;#Energy Conservation")
            {
                this.WriteToLog("copyListItem: Match on Energy Conservation", true);
                targetURL = "http://Webapp1:8083/blog/";
                targetCategory = "1;#Energy Conservation";
            }
            this.WriteToLog("copyListItem: targetURL Set", true);

            // Open the site if targetURL is set
            if (targetURL != "0")
            {
                this.WriteToLog("copyListItem: Preparing to open targetSite", true);
                using (SPSite targetSite = new SPSite(targetURL))
                {
                    using (SPWeb targetWeb = targetSite.OpenWeb())
                    {
                        this.WriteToLog("copyListItem: targetSite Opened", true);
                        
                        //Step 2: Set target list to receive new item
                        this.WriteToLog("copyListItem: Setting targetList", true);
                        SPList targetList = targetWeb.Lists["Posts"];

                        //Step 3: Initialize target list to receive copy of new item
                        this.WriteToLog("copyListItem: Initializing targetList", true);
                        SPListItem targetItem = targetList.Items.Add();

                        //Step 4: Initialize item properties on target list.
                        this.WriteToLog("copyListItem: Initializing targetItem", true);
                        targetItem["Location"] = item["Location"].ToString();
                        targetItem["Title"] = item["Title"].ToString();
                        targetItem["Body"] = item["Body"].ToString();
                        targetItem["Category"] = targetCategory.ToString();
                        targetItem["Published"] = System.DateTime.Now;
                        this.WriteToLog("copyListItem: Update targetItem", true);
                        try
                        {
                            targetItem.Update();
                        }
                        catch (Exception e)
                        {
                            this.WriteToLog("ERROR(targetItem.Update):" + e.Message.ToString(), true);
                            throw new Exception("CopyBlogListItem, targetItem.Update(): Exception: [" + e.ToString() + "].");
                        }
                    }
                }
            }
            this.WriteToLog("copyListItem: Sub-Process Complete", true);
        }
   }
}

Open in new window

0
Comment
Question by:HAcalahan
  • 3
4 Comments
 

Author Comment

by:HAcalahan
ID: 34985158
Updated question
0
 

Author Comment

by:HAcalahan
ID: 34985172
Added C# zone
0
 
LVL 3

Accepted Solution

by:
KetGuru earned 500 total points
ID: 34995993
.
We had similar stuff and we tried that way but we have found that to run full method copylistitem under elevatedprevilages is not sufficient. so there are two thing you will have to do.

1. User elevated previlages at the time of targetItem.Update(); only if possible.
or
2. use impersonation for entire Copylistitem method.


0
 

Author Closing Comment

by:HAcalahan
ID: 35011425
Option 2: Impersonation worked great.   Thank you.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SharePoint 2013 6 20
Error when loading the database 16 55
SharePoint Online Security 5 43
C# Single Form 8 26
For SharePoint sites, particularly public-facing ones, there are times when adding JavaScript, Meta Tags, CSS Styles or other content to the page <head> section is more practical than modifying master pages.  For instance, you could add the jQuery l…
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
A short film showing how OnPage and Connectwise integration works.
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now