Thursday, December 11, 2014

Work with 2013 Workflow Instances Programmatically

Hello everyone!

Like in one of my previous posts we had been studying to start workflows programmatically, today we shall work with it properties.

If you would like to get WorkflowInstance of your started or terminated workflow over the SPListItem, you need to use new 2013 workflow API, because the old 2010 workflow API will not work. Let's dive!

This code will not work for 2013 workflows based on MS Workflow Manager:
 SPWorkflow wf = new SPWorkflow(SPContext.Current.Web, wfID); 
 SPWorkflowCollection wfs = item.Workflows;
because of new Workflow Manager API.

Instead of this, you must call to instances through the WorkflowServicesManager. For example, you know parameters:

SPWeb web, Guid ListId, int ItemId, Guid workflowID

This "workflowID" is aka WorkflowInstanceName in WrkStat.aspx parameters - workflow instance view page. To get workflow instance do:
public static WorkflowInstance GetItemWFInstance(SPWeb web, Guid ListId, int ItemId, Guid workflowID)
{
    WorkflowServicesManager workflowServiceManager = new WorkflowServicesManager(web);
    var workflowInstanceService = workflowServiceManager.GetWorkflowInstanceService();
    return workflowInstanceService.EnumerateInstancesForListItem(ListId, ItemId)
        .Cast<WorkflowInstance>().First(i => i.Id == workflowID);
}

WorkflowInstance has properties, but it may be not enough for development purposes:
  • ContextListId
  • CurrentItemUrl
  • InitiatorUserId
  • ItemGuid
  • ItemId
  • ParentContentTypeId
  • RetryCode
  • UniqueId 
And that is all properties. Well, really not a lot.

What about Task List ID for example? Let's try to find this one.

We shall find an instance property - WorkflowSubscriptionId - and we'll find what we want by using subscription property definitions:
public static Guid GetInstanceTaskListId(SPWeb web, WorkflowInstance instance)
{
    var manager = new WorkflowServicesManager(web);
    var subscriptionService = manager.GetWorkflowSubscriptionService();
    var subscription = subscriptionService.GetSubscription(instance.WorkflowSubscriptionId);
    return new Guid(subscription.PropertyDefinitions["TaskListId"]);
}
There you can find else 80 properties of workflow definition.

Happy workflow developing!

No comments:

Post a Comment