Monday, July 11, 2016

Associating SharePoint 2013 Workflow to a list

SharePoint 2013 supports Workflow Manager workflows. Which means they totally different with 2010 workflows. In reality what happens is that we publish a subscription for the particular list. Though its been a while SharePoint 2013 has come, I have seen many people struggling without getting this done. So I thought its worth sharing a sample code snippet with an explanation.

To get a detailed explanation, we need to have a little understanding on the following classes. 


WorkflowServiceManager - This is the class used for configuring and upgrading of an installation of a Microsoft Azure Workflow
WorkflowDeploymentService - This class manages workflow definitions and workflow activity authoring.
WorkflowDefinition - Represents a SharePoint workflow definition and includes the workflow properties. 
WorkflowDefinitionCollection - Client object collection of WorkflowDefinition class.
WorkflowSubscription - Class responsible for having subscriptions to the external workflow hosts such as Azure workflows.

WorkflowServicesManager workflowServicesManager = new WorkflowServicesManager(currentWeb);
WorkflowDeploymentService workflowDeploymentService 
= workflowServicesManager.GetWorkflowDeploymentService();
WorkflowDefinitionCollection workflowDefinitions 
= workflowDeploymentService.EnumerateDefinitions(publishedDefinitionsOnly);

// We can loop through the definitions.
foreach (WorkflowDefinition workflowDefinition in workflowDefinitions)
{ 
  if(workflowDefinition.DisplayName.Equals(expectedDefinitionName)
  {
      WorkflowSubscription workflowSubscription = new WorkflowSubscription();
      workflowSubscription.DefinitionId = workflowDefinition.Id;
      workflowSubscription.Enabled = true;
      workflowSubscription.EventSourceId = listGuid;
      workflowSubscription.Name = workflowDefinition.DisplayName;
      // Event types when the workflow need to trigger such as Item Adding, Update and Manual
      workflowSubscription.EventTypes = eventTypes;
      workflowSubscription.SetProperty("TaskListId", taskListID);
      workflowSubscription.SetProperty("HistoryListId", historyListID);
      workflowSubscription.SetProperty("FormData, string.Empty);

      WorkflowSubscriptionService workflowSubscriptionService 
= workflowServicesManager.GetWorkflowSubscriptionService();
      workflowSubscriptionService.PublishSubscriptionForList(workflowSubscription, listGuid);
  }
}

No comments:

Post a Comment