Friday, December 17, 2010

How to get a list of running workflows in a document library

Getting a list of workflows that are running on a list library or document library is pretty straightforward. Essentially, all we need to do is get a handle on the site, get a handle on the list, loop through the list's items, then for each item, loop through that item's workflows collection, then for each workflow, look at its InternalState and if its set to "Running", its, uhh, running. You could remove the IF statement from the code below and display all workflows for the current item to see whats Running, Completed, Locked, or Canceled. Once you have a handle on the workflow, you could then do whatever else you might need to do with it. What if you wanted to be emailed every time a workflow got locked? In my case, I have a document library with items that may have workflows running on them. As these workflows have due dates, I need to look at all running workflows in the list, and if today is past their due date, I want to stop these workflows. I will then put this code in a SharePoint timer job that will execute daily. In fact, I will post an article on this in the coming days or weeks after I actually do it! This is using VS2008/MOSS2007 and the code is in VB, but it would be extremely easy to rewrite in C#. I would imagine this would work in SharePoint 2010, but I haven't tested yet. If anyone wants to copy/paste it in 2010 and test it for the rest of us, we'd love a confirmation!

For simplicity's sake, we will create a console application that will access our SharePoint site and loop through the document library's workflows to find the running ones.

1. in Visual Studio, click File -> New Project -> Windows -> Console Application

2. it defaults to ConsoleApplication1, leave it and click OK

3. in Solution Explorer, right-click ConsoleApplication1, click Add Reference

4. browse to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\ and select Microsoft.SharePoint.dll

5. above Module Module1, add:
Import Microsoft.SharePoint

6. inside Sub Main(), add:
Dim site As New SPSite("http://my_sp_site_here")   'get site
Dim list As SPList = site.RootWeb.Lists("my_document_library") 'get document library

For Each item As SPListItem In list.Items 'for each item in library
For Each wrkflw As Workflow.SPWorkflow In item.Workflows 'for current item's list of workflows
If wrkflw.InternalState.ToString = "Running" Then 'if current workflow is running
Console.WriteLine(wrkflw.InstanceId.ToString) 'display it's instance id
End If
Next
Next

Console.WriteLine()
Console.Write("Press ENTER to continue")
Console.ReadLine()

1 comment:

  1. Thanks for this interesting and informative article. These tips really give the good results when we are implementing SharePoint Solutions.

    ReplyDelete