Search This Blog

Monday, January 25, 2016

Programmatically Start Workflow in SharePoint 2013 using Client Object Model



 public void StartWorkflow()
 {
 try
 {
 ClientContext clientContext = new ClientContext("http://www.xyz.com/sites/ABC");
string listName = "Test";
 List list = clientContext.Web.Lists.GetByTitle(listName);
 clientContext.Load(list);
 clientContext.ExecuteQuery();

 CamlQuery camlQuery = new CamlQuery();
 camlQuery.ViewXml = "<View/>";

 ListItemCollection itemColl = list.GetItems(camlQuery);
 clientContext.Load(itemColl);
 clientContext.ExecuteQuery();

 foreach (ListItem item in itemColl)
 {

 clientContext.Load(item);
 clientContext.ExecuteQuery();


 var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
 // connect to the deployment service
 var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();

 // connect to the subscription service
 var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();



 // get all installed workflows
 var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);
 clientContext.Load(publishedWorkflowDefinitions);
 clientContext.ExecuteQuery();

 // display list of all installed workflows
 /*foreach (var workflowDefinition in publishedWorkflowDefinitions)
 {
 Console.WriteLine("{0} - {1}", workflowDefinition.Id.ToString(), workflowDefinition.DisplayName);
 }*/


 //Guid newGuid = new Guid("92F3EC44-8DDB-4B00-9369-37B07FCD37E2");

 // get all workflow associations
 var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByList(list.Id);

 // This line will is used to get the association by providing the workflow GUID.
 //var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(newGuid);

 clientContext.Load(workflowAssociations);
 clientContext.ExecuteQuery();

 // find the first association
 var firstWorkflowAssociation = workflowAssociations.First();
 // connect to the instance service
 var workflowInstanceService = workflowServicesManager.GetWorkflowInstanceService();

 // start the workflow
 var startParameters = new Dictionary<string, object>();
 workflowInstanceService.StartWorkflowOnListItem(firstWorkflowAssociation, item.Id, startParameters);
 clientContext.ExecuteQuery();
 }

 }

 catch (Exception ex)
 {
   Throw ex;
 }
 }

No comments:

Post a Comment