none
Creating a new SPSite: ValidateFormDigest() Failing

    Question

  • Hi

    Background first:

    We're upgrading our intranet from Sharepoint 2k3 to MOSS. Part of the
    functionality that we had was to allow the creation of a new site within the
    Sharepoint Portal from within MCRM via a web service call to a home built Web
    Service that was built against the Microsoft.SharePoint namespace and invoked
    that object model to create the new site.

    Since the upgrade to MOSS I've recreated the web service as a .NET 2.0
    implementation built against the latest version of the Microsoft.SharePoint
    assembly.

    We lookup the VirtualServer that we're interested in and pull its' sites
    collection. We then attempt to use the SPSiteCollection.Add(String, String,
    String, Int32, String, String, String, String) method to create the new site
    that we're after, at which point it all turns to custard and we get a
    NullReference Exception.

    System.NullReferenceException: Object reference not set to an instance of an
    object.
    at Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest()
    at
    Microsoft.SharePoint.Administration.SPSiteCollection.Add(SPContentDatabase
    database, String siteUrl, String title, String description, UInt32 nLCID,
    String webTemplate, String ownerLogin, String ownerName, String ownerEmail,
    String secondaryContactLogin, String secondaryContactName, String
    secondaryContactEmail, String quotaTemplate, String sscRootWebUrl, Boolean
    useHostHeaderAsSiteName)
    at Microsoft.SharePoint.Administration.SPSiteCollection.Add(String
    siteUrl, String title, String description, UInt32 nLCID, String webTemplate,
    String ownerLogin, String ownerName, String ownerEmail, String
    secondaryContactLogin, String secondaryContactName, String
    secondaryContactEmail, Boolean useHostHeaderAsSiteName)
    at Microsoft.SharePoint.Administration.SPSiteCollection.Add(String
    siteUrl, String title, String description, UInt32 nLCID, String webTemplate,
    String ownerLogin, String ownerName, String ownerEmail, String
    secondaryContactLogin, String secondaryContactName, String
    secondaryContactEmail)
    at Microsoft.SharePoint.Administration.SPSiteCollection.Add(String
    siteUrl, String title, String description, UInt32 nLCID, String webTemplate,
    String ownerLogin, String ownerName, String ownerEmail)
    at SharepointService.SharepointService.CreateClientSite(String
    crmAccountShortCode) in d:\Inetpub\Web
    Services\SharepointService2.0\App_Code\SharepointService.asmx.cs:line 248


    Now this was the way in which we had previously been working to get our new
    site. Does anyone have any suggestions as to what we can do to resolve this
    issue or just wiggle around it even ;)

    Cheers
    Sunday, February 18, 2007 8:24 PM

Answers

  • The other approach is just to disable form digest validation while your code is running

    Something along the lines of:
    Code Snippet

                SPWebApplication webApp = currentWeb.Site.WebApplication;
                bool formDigestEnabledStatus = webApp.FormDigestSettings.Enabled;
                webApp.FormDigestSettings.Enabled = false;

    //Do stuff to create sites here!

                webApp.FormDigestSettings.Enabled = formDigestEnabledStatus;



    Running with elevated permissions should be done with care and is a good idea in some cases.
    Tuesday, January 29, 2008 2:29 AM

All replies

  • Hi,

     

    Just ran into the same problem and have not found a way  to solve it yet.

    I was wondering if you got a solution by now.

     

    Regards,

     

    Vincent

    Wednesday, April 11, 2007 3:57 PM
  • We managed to skirt around the issue by disabling the validation.
    Not an ideal fix but it allowed us to achieve the ends that we required.
    Wednesday, April 11, 2007 8:49 PM
  • Thanks,

     

    Going down the webservices route now (createSite method on the admin webservice).

     

    Web_Reference_Folder_Name.Admin admService =    new Web_Reference_Folder_Name.Admin();
      admService.Credentials= System.Net.CredentialCache.DefaultCredentials;
      admService.CreateSite("http://Server_Name/sites/SiteCollection_Name",
            "Title", "Description", 1033, "STS#0",
            "Domain_Name\\User_Alias","User_Display_Name",
            "User_E-mail","","");

    Looks good sofar.

     

    Vincent

    Thursday, April 12, 2007 7:15 PM
  • I tried that route but had issues with trying to use a custom site definition, so we switched back to using the object model and turned off the validation options.

    -Gavin
    Monday, April 16, 2007 8:58 PM
  • how do you turn of validation in the site creation process? Thanks, I am having the same issue here too
    Tuesday, June 05, 2007 2:26 PM
  • It looks like you have to be in an asp.net application.  It you are making the calls from a webservice you can do this HttpContext.Current.Items["FormDigestValidated"] = true;.

     

    I think it is really stupid to make the api only callable from an asp.net web application.

     

    Chris

     

    Wednesday, August 01, 2007 12:20 PM
  • I also faced same problem when i was creating new site in siteCollection programmatically from site which is present in another site collection.

     

    To solve this problem i added following code in create childcontrol function of webpart

    Code Snippet

    SPGlobalAdmin globalAdmin = new SPGlobalAdmin();

    Context.Items[SPGlobalAdmin.RequestFromAdminPort] = true;

    Page.RegisterHiddenField("__REQUESTDIGEST", globalAdmin.AdminFormDigest);

     

     

     

    after that i added following line of code before performing create new site action

     

    Code Snippet

    Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest();

     

     

    One more thing that i did was, i ran my code of creating new site with Elevated Privileges.

     

    after that code is working properly. you can try this approach

    Wednesday, September 26, 2007 6:59 AM
  • The other approach is just to disable form digest validation while your code is running

    Something along the lines of:
    Code Snippet

                SPWebApplication webApp = currentWeb.Site.WebApplication;
                bool formDigestEnabledStatus = webApp.FormDigestSettings.Enabled;
                webApp.FormDigestSettings.Enabled = false;

    //Do stuff to create sites here!

                webApp.FormDigestSettings.Enabled = formDigestEnabledStatus;



    Running with elevated permissions should be done with care and is a good idea in some cases.
    Tuesday, January 29, 2008 2:29 AM
  • THis is also Nice option!!
    Thanks!!!
    Wednesday, January 30, 2008 10:57 AM
  • Hi All,

    I have been trying to associate a workflow through code.but i am getting this exception.

    for removing this i have tried all the above suggested practices.

    any help would be greatly appreciated.

    this is the actual code

     

    code in blue is running fine while the statement in red color causing eception.

     SPSecurity.RunWithElevatedPrivileges(delegate
                   {                  
                       web.AllowUnsafeUpdates = true;
                       web.Site.AllowUnsafeUpdates = true;
                       web.Site.CatchAccessDeniedException = false;
                       web.Site.WebApplication.UserDefinedWorkflowsEnabled = true;                 
                       web.Update();
                       // No association exist, so create a new association with this SharePoint List
                    
                       workflowAssociationObject = SPWorkflowAssociation.CreateListAssociation(
                                                   workflowTemplateObject,
                                                   paramWorkflowName,
                                                   workflowtTaskList,
                                                   workflowHistoryList);
                       // Now that the association exists, we can add the values of the Worfkow Parameters
                     
                       setWorkflowToListAssociationValues();

                                         
                       sharePointListAttachedTo.AddWorkflowAssociation(workflowAssociationObject);
                   });

     

     

    system.invalidoperationexception::{"Operation is not valid due to the current state of the object."}

    ex.Message:{"Operation is not valid due to the current state of the object."}

    innerexception:null

     

       at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
       at Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context)
       at Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest()
       at Microsoft.SharePoint.Workflow.SPWorkflowManager.AddAutoStartToList(SPList list, Boolean bCreate, Boolean bChange)
       at Microsoft.SharePoint.Workflow.SPWorkflowAssociationCollection.AddCore(SPWorkflowAssociation wa, Guid id, SPList list, Boolean forceUtilityListCreation)
       at Microsoft.SharePoint.Workflow.SPListWorkflowAssociationCollection.Add(SPWorkflowAssociation wa)
       at Microsoft.SharePoint.SPList.AddWorkflowAssociation(SPWorkflowAssociation workflowAssociation)
       at EOPClasses.EOPClasses.AssociateWorkflow.<CreateWFAssociation>b__0()
       at Microsoft.SharePoint.SPSecurity.CodeToRunElevatedWrapper(Object state)
       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 EOPClasses.EOPClasses.AssociateWorkflow.CreateWFAssociation(SPWeb tempWeb)
       at EOPUserControls.EOPClasses.DefinitionSCCT.CreateEOPForms(SPWeb web)
    • Proposed as answer by Peter_D503 Friday, February 27, 2009 6:08 AM
    Thursday, May 15, 2008 6:21 AM
  • You're elevated Privileges block is wrong.
     friendWizard wrote:

     SPSecurity.RunWithElevatedPrivileges(delegate
                   {                  
                       web.AllowUnsafeUpdates = true;
                       web.Site.AllowUnsafeUpdates = true;
                       web.Site.CatchAccessDeniedException = false;
                       web.Site.WebApplication.UserDefinedWorkflowsEnabled = true;                 
                       web.Update();
                       // No association exist, so create a new association with this SharePoint List
                    
                       workflowAssociationObject = SPWorkflowAssociation.CreateListAssociation(
                                                   workflowTemplateObject,
                                                   paramWorkflowName,
                                                   workflowtTaskList,
                                                   workflowHistoryList);
                       // Now that the association exists, we can add the values of the Worfkow Parameters
                     
                       setWorkflowToListAssociationValues();

                                         
                       sharePointListAttachedTo.AddWorkflowAssociation(workflowAssociationObject);
                   });

     





    You MUST re-create all references to your SPWebs and SPSites inside the elelvated block.


    Try something this:


    string siteUrl = web.Site.Url;

    string webUrl = web.Url;


     SPSecurity.RunWithElevatedPrivileges(delegate
                   {

    SPSite elevatedSite = new SPSite(siteUrl);

    SPWeb elevatedWeb = elevatedSite.OpenWeb(webUrl);                

                       elevatedWeb.AllowUnsafeUpdates = true;
                      
    elevatedWeb.Site.AllowUnsafeUpdates = true;
                      
    elevatedWeb.Site.CatchAccessDeniedException = false;
                      
    elevatedSite.WebApplication.UserDefinedWorkflowsEnabled = true;                 
                      
    elevatedWeb.Update();
                       // No association exist, so create a new association with this SharePoint List
                    
                       workflowAssociationObject = SPWorkflowAssociation.CreateListAssociation(
                                                   workflowTemplateObject,
                                                   paramWorkflowName,
                                                   workflowtTaskList,
                                                   workflowHistoryList);
                       // Now that the association exists, we can add the values of the Worfkow Parameters
                     
                       setWorkflowToListAssociationValues();

                      elevatedList = elevatedWeb.Lists["MyTargetList"]'                  
                       elevatedList.AddWorkflowAssociation(workflowAssociationObject);
                   });


    • Proposed as answer by Peter_D503 Friday, February 27, 2009 6:09 AM
    Thursday, May 15, 2008 7:59 AM
  • Hi Gavin,

    Thanks for your response.

    I have added Code access security policies to assembly from where the call took place.

    Now it is working.

     

     

    Tuesday, May 20, 2008 5:29 AM
  • Chris,

    I need to create Web Applications and Site collections dynamically. I am using a custom web service to do these tasks.

    I was getting the following exception:

    System.NullReferenceException: Object reference not set to an instance of an
    object.
    at Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest()
    at......
     

    I have put the suggested line i.e.  
    HttpContext.Current.Items["FormDigestValidated"] = true; in my code.

    It worked in case of creating web application, but in case of Site Collections Creation I am still getting the error.

    It would be great if you have any idea about the problem.


    Regards,
    Muhammad Fasih


    MCSD
    Monday, July 28, 2008 9:52 PM
  • Hi
    try adding following lines in your aspx page

    Add this line on aspx page from where you are going make new site collection and spweb objects in register tags section of page
     <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
        Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

    after that add  following line <SharePoint:FormDigest ID="FormDigest1" runat="server" />  inside <form> tag.

    and then try as while creating  custom pages we miss these two lines. in almost all sharepoint master pages where data is updated, these lines are present.


    Chinmay Vartak
    Tuesday, July 29, 2008 5:50 AM
  • Muhammad

    with using a custom web service you have no form digest to validate.

    I'd suggest using the code snipped I posted in the post above that is marked as an answer.

    Sorry I didn't reply sooner. with the move I'm not getting email alerts anymore :|
    Tuesday, August 12, 2008 3:54 AM
  • Hi i was getting the same error after adding the code in SPSecurity, it worked fine.:

    SPSecurity.RunWithElevatedPrivileges(delegate()

    { });

    Thursday, December 04, 2008 12:44 PM
  • I thought I had this fixed by using Gavin's fix above, but now I'm getting the dreaded: 

    "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."

    This is with:

    elevatedWeb.AllowUnsafeUpdates = true;
    elevatedWeb.Site.WebApplication.FormDigestSettings.Enabled = false; 
    elevatedWeb.Update();

    ...

    elevatedWorkflowList.AddWorkflowAssociation(association); 

    Very annoying. Any suggestions?

    Friday, February 27, 2009 7:19 AM
  • Ok... trap for young players... I had a for loop, so I have to re-state the AllowUnsafeUpdates each time  i.e.

    Not working:

    using (SPWeb elevatedWeb = elevatedSite.RootWeb)
    {
      elevatedWeb.AllowUnsafeUpdates = true;
      elevatedWeb.Update();       
     
      for (int i = 0; i < workflows.Length; i++)
      {
         ...
        elevatedWorkflowList.AddWorkflowAssociation(association);
        elevatedWorkflowList.Update();

    Working:

    using (SPWeb elevatedWeb = elevatedSite.RootWeb)

      for (int i = 0; i < workflows.Length; i++)
      {
        elevatedWeb.AllowUnsafeUpdates = true;
         elevatedWeb.Update();       

         ...
        elevatedWorkflowList.AddWorkflowAssociation(association);
        elevatedWorkflowList.Update();


         *phew*

     

    Friday, February 27, 2009 7:36 AM