Thursday, August 21, 2014

Start SharePoint 2013 workflow programmatically


In this post I’ll describe how to start SharePoint 2013 workflow programmatically. If you tried to start SharePoint 2013 workflow using SharePoint 2010 using “WorkflowManager” then it won’t be worked, you need to use new SharePoint 2013 set of API to work with new workflow model.

1.        First you need to include “Microsoft.SharePoint.WorkflowServicesBase.dll” from “\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.WorkflowServicesBase\v4.0_15.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.WorkflowServicesBase.dll”

2.       Then you need to create instance of “WorkflowServicesManager”, then need to find out the subscription (which actually represent the workflow association).

3.       Finally you can run the workflow with WorkflowInstance Service as shown below:
 
 
 
 WorkflowServicesManager workflowServiceManager = new WorkflowServicesManager(web);
 var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
           
 //get all workflows associated with the list
 var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(listId);
 
 //run all workflows associated with the list
 foreach (var workflowSubscription in subscriptions)
 {
     //initiation parameters
     var inputParameters = new Dictionary<string, object>();
     inputParameters.Add("MyProperty", "MyValue");
 
     workflowServiceManager.GetWorkflowInstanceService().StartWorkflowOnListItem(workflowSubscription, itemId, inputParameters);
 }

 
4.      In the “StartWorkflowOnListItem”, if you have any input parameters (which you usually pass from workflow initiation form), you can pass the input parameters as a dictionary. Otherwise, you can pass an empty dictionary.

5.       Similarly you can terminate or suspend workflows using Workflow Instance Service.

For your information, workflow will not run if you use an elevated web in WorkflowServicesManager. You need to make sure you are running the code with a user who is not “system account” and who has a user profile.