Friday, March 2, 2012

How to cancel inprogress workflow?

How to cancel inprogress workflow?

SPWorkflowCollection itemWorkflowCollection= listItem.Workflows;
foreach (SPWorkflow itemWorkflow in itemWorkflowCollection)
{
//cycle workflows associated to the item (listItem)
if (!itemWorkflow.IsCompleted && itemWorkflow.InternalState == SPWorkflowState.Running)
{
foreach (SPWorkflowTask taskWorkflow in itemWorkflow.Tasks)
{
//cycle throught all tasks associated to the workflow
//if task is not completed
if (taskWorkflow["PercentComplete"].ToString() != "1")
{
//you can cancel or change the running tasks before canceling the workflow
taskWorkflow["Status"] = "Canceled";
taskWorkflow["PercentComplete"] = 1;
web.AllowUnsafeUpdates = true;
taskWorkflow.Update();
}
}
SPWorkflowManager.CancelWorkflow(itemWorkflow);
}
}
Enjoi...