Monday 9 November 2015

New instance of this workflow template are currently disallowed

When you try to start workflow programmatically you might encounter following error

New instance of this workflow template are currently disallowed

The root cause of this error is multiple version of workflow is associated with list. You can check it in List Seeitngs -> Workflow settings.

Here is the code that generates the error:

public static void StartWorkflow(SPListItem listItem, SPSite spSite, string wfName)
        {
            SPList parentList = listItem.ParentList;
            SPWorkflowAssociationCollection associationCollection = parentList.WorkflowAssociations;
            foreach (SPWorkflowAssociation association in associationCollection)
            {
                if (association.Name.ToString().ToLower() == wfName.ToLower())
                {
                    association.AssociationData = string.Empty;
                    // this line throws error for old instance of workflow
                    spSite.WorkflowManager.StartWorkflow(listItem, association, association.AssociationData);

                }
            }
        }

Resolution:

SPWorkflowAssociation class has a property called Enabled. It check whether new instance for this workflow is allowed or not. We will use it in our code block to stop the workflow to start.

Here is the error free code:

public static void StartWorkflow(SPListItem listItem, SPSite spSite, string wfName)
        {
           
                SPList parentList = listItem.ParentList;
                SPWorkflowAssociationCollection associationCollection = parentList.WorkflowAssociations;
                foreach (SPWorkflowAssociation association in associationCollection)
                {
                    if (association.BaseTemplate.Name.ToString().ToLower() == wfName.ToLower())
                    {
                        if (association.Enabled) // check if new instance is allowed.
                        {
                            //spSite.AllowUnsafeUpdates = true;
                            var data = association.AssociationData;
                            spSite.WorkflowManager.StartWorkflow(listItem, association, data);
                            //spSite.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }

No comments:

Post a Comment