R – Workflow Persistence for multiple workflows

workflowworkflow-foundation

This seems like an elementary question, but I can't find the answer anywhere:

I have several different types of long-running state machine workflows that I am working with across multiple host applications with a central database. I am using the SqlWorkflowPersistenceService to persist them. So say I have three workflow types WorkflowOne, WorkflowTwo, and WorkflowThree. An instance of each of those is started and persisted to the database by one user. Another user comes along and wants to make various changes, so they fire up the application. Now I can use the persistence service to give me a list of all the persisted instances but how do I know which is of type WorkflowOne and which is WorkflowTwo or WorkflowThree?

Best Answer

There are a few ways you can do this.

First option is to use the WorkflowPersistenceService itself and do something like:

var persistenceService = new SqlWorkflowPersistenceService("<<connection string>>");
var persistedWorkflows = persistenceService.GetAllWorkflows();
foreach (var persistedWorkflow in persistedWorkflows)
{
    var workflowInstance = workflowRuntime.GetWorkflow(persistedWorkflow.WorkflowInstanceId);
    var workflowDefinition = workflowInstance.GetWorkflowDefinition();
    Console.WriteLine(workflowDefinition.GetType().FullName);
}

Easy to do as you are already using the SqlWorkflowPersistenceService but it has the drawback of having to load all workflow instances into memory and you are responsible for removing them from memory.

The second option is to use workflow tracing:

    var trackingQuery = new SqlTrackingQuery("<<connection string>>");
    var queryOptions = new SqlTrackingQueryOptions()
    {
        WorkflowStatus = WorkflowStatus.Running
    };
    var runningWorkflows = trackingQuery.GetWorkflows(queryOptions);
    foreach (var runningWorkflow in runningWorkflows)
    {
        Console.WriteLine(runningWorkflow.WorkflowType);
    }

The advantage is you don't need to load the actual workflow definition into memory just to check it's type. The drawback is you have to add the SqlTrackingService as well with it's own database adding complexity and overhead.

Related Topic