2011-06-26

How to Check Workflow Status programmatically

Today I'll show checking all workflow statuses in SharePoint site programmatically. Sometimes you may want to check workflow statuses are error or not.

You need workflow status name (list column) when you get a item's workflow status. But you can't get workflow status name from SPWorkflow properties directly. You need to use SPWorkflow.AssociationId property and SPList.WorkflowAssociations property to get workflow status.


The sample code is here.

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

// This is Console Application //

SPSite site = new SPSite("http://sharepoint-site");
SPWeb web = site.OpenWeb();

foreach (SPList list in web.Lists)
{
    foreach (SPListItem item in list.Items)
    {
        foreach (SPWorkflow workflow in item.Workflows)
        {
            try
            {
                Console.WriteLine("item url : " + item.Url);
                Console.WriteLine("workflow name : " + list.WorkflowAssociations[workflow.AssociationId].Name);
                Console.WriteLine("workflow status : " + item[list.WorkflowAssociations[workflow.AssociationId].Name]);
                Console.WriteLine();
            }
            catch (ArgumentException)
            {
                //ArgumentException is throwed if the workflow is not exist in the list column. 
                Console.WriteLine("Workflow name : {0} is already not exist in List title : {1}.", 
                    list.WorkflowAssociations[workflow.AssociationId].Name, list.Title);
            }
        }
    }
}

The result is like this :
item url : Lists/Announcement01/1_.000
workflow name : Approval01
workflow status : 2
Workflow status is displayed as a number. The workflow status number are related to SPWorkflowStatus Enumeration. For example, number 2 means "InProgress".

5 comments:

  1. any suggestion please help me ...
    now above code shows the item's current workflow status ..
    if the item has already previous workflow,
    how to get the prevous workflow's status?

    ReplyDelete
  2. You may get the previous workflow's status Workflow History list.
    SPWorkflow.HistoryList
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.workflow.spworkflow.historylist(office.12).aspx

    ReplyDelete
  3. To convert the workflow status integer to a string representation, use the GetStatusChoices method of the workflow template as below:

    int statusInt = item[list.WorkflowAssociations[workflow.AssociationId].Name]);
    StringCollection allStatuses = workflow.ParentAssociation.BaseTemplate.GetStatusChoices(item.Web);
    string statusString = allStatuses[statusInt]

    ReplyDelete
  4. how to archive documents from document set?

    ReplyDelete
  5. how do i count number of approved work flow in the custom list.

    ReplyDelete