none
Operation is not valid due to the current state of the object while creating workflow

    Question

  • Hi,
    I read the post regarding the error from this blog and followed the steps.
    I am using the following code and getting the error "Operation is not valid due to the current state of the object" at the highlighted line. Please help.

     protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
            
    //            string siteUrl = web.Site.Url;
     
    //string webUrl = web.Url;
     SPSecurity.RunWithElevatedPrivileges(delegate
                   {
    SPSite elevatedSite = new SPSite("mySiteurl");

    SPWeb elevatedWeb = elevatedSite.OpenWeb();
    SPList elevatedList = elevatedWeb.Lists["Comments"];
    SPList historyList = null;                          // Workflow history list
    SPList taskList = null;                             //Workflow task list
    SPWorkflowTemplate workflowTemplate = null;         // Workflow template
    SPWorkflowAssociation workflowAssociationObject = null;   // Workflow association

                       elevatedWeb.AllowUnsafeUpdates = true;
                       elevatedWeb.Site.AllowUnsafeUpdates = true;
                       elevatedWeb.Site.CatchAccessDeniedException = false;
                       elevatedSite.WebApplication.UserDefinedWorkflowsEnabled = true;                 
                       elevatedWeb.Update();


                       workflowTemplate = elevatedWeb.WorkflowTemplates.GetTemplateByName("Approval", System.Globalization.CultureInfo.CurrentCulture);
                       // Try to get workflow history list
                       try
                       {
                           historyList = elevatedWeb.Lists["Workflow History"];
                       }
                       catch (ArgumentException exc)
                       {
                           // Create workflow history list
                           Guid listGuid = elevatedWeb.Lists.Add("Workflow History", "", SPListTemplateType.WorkflowHistory);
                           historyList = elevatedWeb.Lists[listGuid];
                           historyList.Hidden = true;
                           historyList.Update();
                       }

                       // Try to get workflow tasks list
                       try
                       {
                           taskList = elevatedWeb.Lists["Workflow Tasks"];
                       }
                       catch (ArgumentException exc)
                       {
                           // Create workflow tasks list
                           Guid listGuid = elevatedWeb.Lists.Add("Workflow Tasks", "", SPListTemplateType.Tasks);
                           taskList = elevatedWeb.Lists[listGuid];
                           taskList.Hidden = true;
                           taskList.Update();
                       }


                       // No association exist, so create a new association with this SharePoint List
                    
                       workflowAssociationObject = SPWorkflowAssociation.CreateListAssociation(workflowTemplate,"My Workflow", taskList, historyList);
                                       
                       // Set workflow parameters
                       workflowAssociationObject.AllowManual = false;
                       workflowAssociationObject.AutoStartCreate = true;
                       workflowAssociationObject.AutoStartChange = false;
                      
                       elevatedList = elevatedWeb.Lists["Comments"];
                      elevatedList.AddWorkflowAssociation(workflowAssociationObject);
                   });


            }
            catch (Exception ex)
            {
        Response.Write(ex.Message);

            }
        }

    Wednesday, March 18, 2009 9:47 AM

All replies

  • Hi Rinku,

    This sounds a very similar problem to the following post, and so could be worth posting the solution I eventually went for here as well - hopefully this might help anyone googling this problem in future. (http://social.msdn.microsoft.com/Forums/en/sharepointworkflow/thread/e56ff593-cea5-4091-a1fb-9d7e6565af30)

    ---

    I experienced this problem when using the SharePoint SDK to automatically associate Workflows with Document Libraries when integrating SharePoint with Microsoft CRM.

    To problem was triggered when a custom Web Service operating on a separate Virtual Directory (port 85) on the SharePoint Server was invoking the SharePoint SDK to associate a Workflow to a Document Library - whenever the code included the following line:

      associateWorkflow.AutoStartChange = true;

    The code would then either hit the error identified above as 'Operation is not valid due to the state of the object' - reading various articles on SharePoint development determined that this is a common permissions error where the running Context does not have the permissions over SharePoint to run the relevant SharePoint SDK methods.  This error is usually overcome via the use of the Run with Elevated Privileges, as per the following article:

    http://vspug.com/ssa/2007/11/25/operation-is-not-valid-due-to-the-current-state-of-the-object/

    without the RunWithElevatedPrivileges, the following error will be returned:

    Object reference not set to an instance of an object.
    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 MSCRM.SP.Webservice.WebserviceMethods.CreateWorkflowAssociation(String library)

    This elevated security provides the relevant context to run most SharePoint SDK operations, including associating a Workflow with a Document Library or Content Type.

    However it appears not to include the relevant context for creating the association as Automatically Starting on Change or Update for a Document Library or Content Type - hence the following error stack when the AddWorkflowAssociation or UpdateWorkflowAssociation method is executed when the Workflow Association includes either .AutoStartChange = true or .AutoStartUpdate = true. 

    Operation is not valid due to the current state of the object.
    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 MSCRM.SP.Webservice.WebserviceMethods.<>c__DisplayClassb.<CreateWorkflowAssociation>b__7() in [CodeFile]:line 179   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 MSCRM.SP.Webservice.WebserviceMethods.CreateWorkflowAssociation(String library)

    This appears to be also true for running update Child Content Types from a Parent Content Type (via the
    UpdateWorkflowAssociationsOnChildren method), this would make sense as the Workflow Association operations is similar.

    I presume this is an intentional part of the SharePoint SDK to stop malious code elevating privileges to then automatically associate Workflows that will then automatically fire - as this could potentially be open to abuse.

    The solution I found to this was to look at the Custom Webservice I was working with (on Port 85), realise that this was existing outside the SharePoint website (Port 80) and so move the Webservice into the normal SharePoint website such that the Service would run with the correct context to run these sensitive SharePoint SDK operations.

    Following this article about creating a new Webservice that runs from the SharePoint website then allowed me to move the code from running http://localhost:85/MSCRM_SP_Webservice.asmx to running as http://localhost/_vti_bin/MSCRM_SP_Webservice.asmx, and then the same code worked perfectly.

    http://www.walisystems.com/articles/SPS/uplservice/v1/creating%20a%20custom%20web%20service.htm

    Not sure if this is too late to help the chaps who have posted the similar problems here - however this took me hours to realise and then fix, so hopefully this posting can help anyone who finds themself in a similar position.

    Kind Regards, Paul.
    • Proposed as answer by P McQ Tuesday, June 07, 2011 10:07 AM
    Monday, October 19, 2009 11:52 AM