0

i have a sharepoint problem. I have an event handler on a list and whenever someone adds a new item in the list I want to create a new web with the required details. The problem comes when a diferent user that is not site collection admin adds the item. On the Web.Webs.Add() method i get the error:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)). 

Note that I'm using the SPSecurity.RunWithElevatedPrivileges delegate.

Here is a code sample:

public override void ItemAdded(SPItemEventProperties properties)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
            string url = "the url";
            if (Array.IndexOf(properties.Web.Webs.Names, url) >= 0)
            {
              properties.Web.Webs.Delete(url);
            }
            SPWeb newWeb = properties.Web.Webs.Add(url, "title", "description", properties.Web.Language, "STS#1", false, false);
    });
}

Thanks.

Björn Kaiser
  • 9,882
  • 4
  • 37
  • 57

1 Answers1

0

I got it. The problem was that the web I was calling was not elevated, so I did somting like this:

 public override void ItemAdded(SPItemEventProperties properties)
        {
            SPWeb web = properties.Web;
            SPListItem currentItem= properties.ListItem;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(web.Site.ID))
                {
                    using (SPWeb elevWeb = site.OpenWeb(web.ID))
                    {
                        SPList elevList = ListUtils.GetList(elevWeb, "list");
                        SPListItem elevItem = elevList.Items[currentItem.UniqueId];
                        elevWeb.AllowUnsafeUpdates = true;
                        string url = "the url";
                        if (Array.IndexOf(elevWeb.Webs.Names, url) >= 0)
                        {
                            elevWeb.Webs.Delete(url);
                        }
                        SPWeb newWeb = elevWeb.Webs.Add(url, "title", "description", elevWeb.Language, "STS#1", false, false);
                    }
                }
            });
        }