Monday, 18 June 2012

Starting workflow programmatically

If you have an instance of SPListItem, and know the workflow association name, you can start it. First you need to find workflow assocation instance and tell SPSite.SPWorkflowManager to start your workflow.

Lets say I have a helper method that takes SPListItem and workfow association name.

private SPWorkflowAssociation GetWorkflowAssociationByName(SPListItem item, string workflowAssociationName)
    return item.ContentType.WorkflowAssociations.GetAssociationByName(workflowAssociationName, new System.Globalization.CultureInfo("en-US"));


public void StartWorkflow(SPListItem item, string associationName)

//get workflow association object
workflowAssociation = GetWorkflowAssociationByName(item, associationName);                

if (workflowAssociation == null)
  throw new Exception(string.Format  ("Workflow association '{0}' could not be found in the list '{1}'", workflowAssociationName, item.ParentList.Title));

//start your workflow...
item.Web.Site.WorkflowManager.StartWorkflow(item, workflowAssociation, workflowAssociation.AssociationData);

   catch (SPException spEx)
   { //log your exception }

//that kicks off a associated workflow.
StartWorkflow(anInstanceOfSPListItem, "Masood - Approval workflow")

Below is the picture where higlighted box is the association name.


That's it. Happy coding.