Pergunta

I'm migrating a SharePoint customization from MOSS 2007 to SharePoint Server 2010 (Win 2008), which creates the Site Collection programmatically. Problem is I'm unable to create the Site Collection using the code below. I have made sure that the Application Pool Account for the Web application, in which I'm creating Site Collections, is a member of Farm Administrators group and added as a Full Control (user) in Policy for Web Application (in CA).

I'm quite sure this is due to permissions but I'm clueless at the moment. So, any hints will be appreciated.

 SPSecurity.RunWithElevatedPrivileges(delegate()
 {
      using (SPSite tmpSite = new SPSite(site.ID))
      {
         using (SPWeb tmpWeb = tmpSite.OpenWeb(web.ID))  
          {
             SPWebApplication webApp = tmpWeb.Site.WebApplication;
             SPContentDatabase currentDB = webApp.ContentDatabases[webApp.ContentDatabases.Count - 1];
             tmpWeb.AllowUnsafeUpdates = true;

              try
              {
                  SPSite newsite= webApp.Sites.Add("sites/" + newWebUrl, title, itemDescription, 1053, "RSVArbetsgrupper#0", "testuser", "testuser", "test@mail.com");
                  properties.AfterProperties["WebbplatsURL"] = newsite.Url;

              }
              catch (Exception e)
              {
                  PortalLog.LogString("## Exception Occurred:ItemAdding Add New room** {0} || {1}", e.Message, e.StackTrace);
                                        properties.ErrorMessage = e.Message;
                                        properties.Cancel = true;                          
              }
          }
       }
   });

//I'm also providing the custom provisioning provider class, which gets called when new Site collection get created. The problem occurs while

linksList.EventReceivers.Add(SPEventReceiverType.ItemAdding,
                                              asmName,
                                              linksReceiverName);  

Here is the complete class:

 public class MyProvisioningProvider : SPWebProvisioningProvider
    {
        // <summary>
        // Gets called when a web is provisioning when the template
        // chosen has ProvisionAssembly and ProvionClass attributes
        // specified
        // </summary> 
        public override void Provision(SPWebProvisioningProperties props)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate(){
            using (SPWeb web = props.Web)
            {
                try
                {
                    // Create site from template'

                    web.AllowUnsafeUpdates = true;
                    web.ApplyWebTemplate("RSVArbetsgrupperHidden");   
                    SPList linksList = web.Lists["Länkar"];
                    string linksReceiverName = "NS_LinksItemEventReceiver";
                    linksList.EventReceivers.Add(SPEventReceiverType.ItemAdding,
                                              asmName,
                                              linksReceiverName);                         
                    AddListViewWebPart(web, linksList, "Right", 99, PartChromeType.Default, 0);                       
                    ApplyTheme(web, "RSV");
                    web.Update();                                               
                    web.AllowUnsafeUpdates = false;
                }

                catch (Exception e)
                {
                    PortalLog.LogString("## Exception Occurred:ItemAdding Add New room** {0} || {1}", e.Message, e.StackTrace);

                }
            }

            });
        }

    }

Here is the exception:

<nativehr>0x80070005</nativehr><nativestack></nativestack>
<nativehr>0x80070005</nativehr><nativestack></nativestack>
The site /sites/s9000002 could not be created.  The following exception occurred: <nativehr>0x80070005</nativehr><nativestack></nativestack>.

Note: I don't intend to use the Admin service to perform this task.

I have tested the same code for creating SC for OOTB Site Templatee but still no luck. The custom template that's mentioned in the code is deployed to the WFE.

Although, I do manage to create the Site Collection using the UI (Central Admin) both using the Application Pool account or Developer account. The problem only occurs while creating SC programetically.

ULS Logs

Exception attempting to ApplyWebTemplate to SPSite 

Microsoft.SharePoint.SPException: Security validation of this page is invalid. Click the Back button in your browser, refresh the page and try again. ---> 

System.Runtime.InteropServices.COMException (0x8102006D): The security validation of this page is invalid. Click the Back button in your browser, refresh the page and try again. 
at Microsoft.SharePoint.Library.SPRequestInternalClass.RegisterEventReceiver (String bstrUrl, String bstrListName, event receiver surgical operation, Guid guidId, String bstrName, guidSiteId Guid, Guid guidWebId, guidHostId Guid, Int32 dwHostType, Int32 dwSynchronization, Int32 dwType, Int32 dwSequenceNumber, String bstrAssembly, String bstrClass, Guid solutionId, bstrData String, String bstrFilter, Int32 dwCredential, contextObjectId Guid, Guid contextType, contextEventType Guid, Guid contextId, Guid contextCollectionId) 
at Microsoft.SharePoint.Library.SPRequest.RegisterEventReceiver (String bstrUrl, String bstrListName, event receiver surgery surgery guidId Guid, String bstrName, guidSiteId Guid, Guid guidWebId, guidHostId Guid, Int32 dwHostType, Int32 dwSynchronization, Int32 dwType, Int32 dwSequenceNumber, bstrAssembly String, String bstrClass, Guid solutionId, bstrData String, String bstrFilter, Int32 dwCredential, contextObjectId Guid, Guid contextType , contextEventType Guid, Guid contextId, Guid contextCollectionId) --- End of inner exception stack trace --- 
at Microsoft.SharePoint.SPGlobal.HandleComException (COMException comex) 
at Microsoft.SharePoint.Library.SPRequest.RegisterEventReceiver (String bstrUrl, String bstrListName , Event Receivers surgery surgery, Guid guidId, String bstrName, Guid guidSiteId, Guid guidWebId, Guid guidHostId, Int32 dwHostType, Int32 dwSynchronization, Int32 dwType, Int32 dwSequenceNumber, String bstrAssembly, String bstrClass, Guid solutionId, String bstrData, String bstrFilter, Int32 dwCredential, Guid contextObjectId, contextType Guid, Guid contextEventType, contextId Guid, Guid contextCollectionId) 
at Microsoft.SharePoint.SPEventReceiverDefinition.RegisterForSiteOrWebOrList (Operation operation, Boolean isMigration) 
at Microsoft.SharePoint.SPEventReceiverDefinitionCollection.Add (SPEventReceiverType receiver type, String assembly, String className) at Logica_Types_001. ArbetsgruppProvisioningProvider.Provision (SPWebProvisioningProperties props) 
at Microsoft.SharePoint.SPWeb.ApplyWebTemplate (String strWebTemplate) at Microsoft.SharePoint.Administration.SPSiteCollection.Add (SPContentDatabase database, SPSiteSubscription siteSubscription, SITEURL String, String title, String description, UInt32 nLCID, String webTemplate , String owner login, String owner name, String owner email, String secondary contact login, String secondary contact name, String secondary contact email, String quotaTemplate, sscRootWebUrl String, Boolean useHostHeaderAsSiteName) Attempting to delete the site collection.
Foi útil?

Solução

RunWithElevatedPrivileges requires its own SPWeb. If you reuse a existing SPWeb, you won't run elevated, but with the initial context.

A common approach applied to your code can be :

public class MyProvisioningProvider : SPWebProvisioningProvider
{
    // <summary>
    // Gets called when a web is provisioning when the template
    // chosen has ProvisionAssembly and ProvionClass attributes
    // specified
    // </summary> 
    public override void Provision(SPWebProvisioningProperties props)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate(){
        using (SPSite site = new SPSite(props.Web.Site.Id)) 
        {
        using (SPWeb web = site.OpenWeb(props.Web.Id))
        {
            try
            {
                // Create site from template'

                web.AllowUnsafeUpdates = true;
                web.ApplyWebTemplate("RSVArbetsgrupperHidden");   
                SPList linksList = web.Lists["Länkar"];
                string linksReceiverName = "NS_LinksItemEventReceiver";
                linksList.EventReceivers.Add(SPEventReceiverType.ItemAdding,
                                          asmName,
                                          linksReceiverName);                         
                AddListViewWebPart(web, linksList, "Right", 99, PartChromeType.Default, 0);                       
                ApplyTheme(web, "RSV");
                web.Update();                                               
                web.AllowUnsafeUpdates = false;
            }

            catch (Exception e)
            {
                PortalLog.LogString("## Exception Occurred:ItemAdding Add New room** {0} || {1}", e.Message, e.StackTrace);

            }
        }
        }
        });
    }
}

This code create new SPSite and SPWeb objects reflecting the same objects, but with the elevated context.

[Edit] More info in the RunWithElevatedPrivileges reference, especially :

An SPSite object created outside the delegate can be referenced inside the delegate, however, the methods and property assessors of the object run with the privileges of the user context in which the objects were created, not with the elevated privileges. The same point applies to SPWeb objects and any other objects. You must create new objects inside the delegate if you need to execute the members of the objects with elevated privileges. If the new object must represent the same persisted entity as an object created outside the delegate, then you must reference identification information from the externally created object and use it to create the new object within the delegate. For example, if web is a reference to an SPWeb object created before the call to RunWithElevatedPrivileges, then the following code shows you would use the ID of its parent SPSite object to construct a new SPSite object.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(web.Site.ID))
    {
    // implementation details omitted
    }
});

And

Important Important If secureCode includes any write operations, then the call to RunWithElevatedPrivileges should be preceded by a call of either SPUtility.ValidateFormDigest or SPWeb.ValidateFormDigest.

Outras dicas

I believe that with the constructor you are using, the last three properties need the SPUser.LoginName, SPUser.Name, and SPUser.Email. I've had trouble with site creation code in the past when these parameters were not correct.

Any reason why you are not capturing the actual exception in the catch block?

Please follow the link for SC creation details - http://blog.falchionconsulting.com/index.php/2009/07/custom-sharepoint-2007-site-collection-creation-page/. It describes the correct way of creation for site collection for users - WFE (not CA).

  • Check the centeral admin running with a service account
  • Do Site.WebApplication.FormDigestSettings.Enabled=false;
  • make sure that applywebtemplate running with long run process
Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top