0
votes

I am having a sharepoint sitecollection which has two sites say site1 and site2.

I have a user, have contribute premission in site1 and read permission in site2.

I wrote a event receiver on item added in a list1 in site1 for moving the same record in a list2 in site2.

public override void ItemAdded(SPItemEventProperties properties)    
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
 using (SPSite site = properties.OpenSite())
 {
   using (SPWeb web = site.OpenWeb("/site2"))
   {
    web.AllowUnsafeUpdates = true;
    SPList list = web.Lists["List2"];
    SPListItem item = list.Items.Add();
    item["Title"] = "test";
    item.Update();
    web.AllowUnsafeUpdates = false;
   }
  }
 });
   }

I tried with RunWithElevatedPrivileges even AllowUnsafeUpdates but Unfortunately it is not working in my case. on Update() it throws UnauthorizedAccessException.

{System.UnauthorizedAccessException:
    <nativehr>0x80070005</nativehr><nativestack></nativestack>

I am using sharepoint 2010 sp1 with aug2012 cumulative updates.

2
As an aside, you don't need the inner using clause for the SPWeb as disposing the owning SPSite will dispose any webs opened from it, and you should safely revert the AllowUnsafeUpdates in a finally block in an outer try/finally block. Right now, if it blows up you may leave the unsafe flag active.x0n

2 Answers

2
votes

you have to initiate the new context of the spsite from the site id:

SPSecurity.RunWithElevatedPrivileges(delegate() { 
 using (SPSite site = new SPSite(item.Web.Site.ID)) 
 { 
  using (SPWeb web = site.OpenWeb("1")) 
  { 
   SPListItem curritem = web.Lists[item.ListItems.List.Title].Items.GetItemById(item.ID); 
  } 
 }
});
1
votes

In my case, in a dev enviroment, i just put the user that does the deploy, or debug mode in: site collection administrators and it works. No more exceptions like that.

I'm running a PowerShell Script with the user that is in the site collection administrators and doesn't necessary add a SPSecurity or RunWith...