SharePoint 2013 introduced a new set of API to work with new workflow model. In my previous post I described how to access workflows associated with a list/list item and access workflow properties. In this post I’ll describe how to run SharePoint 2013 workflow programmatically.
First you need to create instance of WorkflowServicesManager, then you need to find out the subscription (which actually represent the workflow association). Finally you can run the workflow with WorkflowInstance Service as shown below:
var 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); }
In the StartWorkflowOnListItem, if you have any input parameters (which you usually pass from workflow initiation form), you can pass the input paramters as a dictionary. Otherwise, you can pass an empty dictionary.
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 an user who is not system account and who has a user profile.