Tuesday, June 02, 2015

Removing multiple version of Workflow

This is simple workaround on removing multiple version of Workflow those associated with item.
Running the multiple versions of the workflow,long running instances of the workflow those are often leads to collapse the SharePoint's workflow  related timer jobs.

You have to follow always the best practices while you are publishing the SPD workflow such as stop / cancel the previous workflow or set no new instances on the previous workflow.

Here is code work around on removing the old instances of workflows from the SharePoint List item.

public void RemovePreviousWFInstances(SPListItem listItem)
        {
            using (var web = listItem.Web)
            {
                web.AllowUnsafeUpdates = true; 
                using (var site = web.Site)
                {
                   SPWorkflowManager manager = site.WorkflowManager;
                    foreach (SPWorkflow instance in manager.GetItemWorkflows(listItem))
                    {
                        if (instance.ParentAssociation.Name.Contains("Previous"))
                        {
                            manager.RemoveWorkflowFromListItem(instance);
                        }
                    }
                }
                web.AllowUnsafeUpdates = false;
            }
        }