Geeks With Blogs
Adrian Hara Working through the .NET maze

Searching for a way to check if a workflow is running on a list item (useful, for example, in an item event handler), I found some code like this:

        public static bool IsWorkflowRunning(SPListItem listItem, Guid workflowId)
        {
            foreach (SPWorkflow workflow in listItem.Workflows)
            {
                if (workflow.ParentAssociation.BaseTemplate.Id == workflowId &&
                    workflow.InternalState == SPWorkflowState.Running)
                {
                    return true;
                }
            }
            return false;
        }

What this code does is iterate the workflows list for the item (point to remember: listItem.Workflows contains not only running workflows, but also cancelled or otherwise) and checks the InternalState for the given workflow id. While it might seem ok, as I found out the hard way, it's not. Correct way to check is like so:

        public static bool IsWorkflowRunning(SPListItem listItem, Guid workflowId)
        {
            foreach (SPWorkflow workflow in listItem.Workflows)
            {
                if (workflow.ParentAssociation.BaseTemplate.Id == workflowId &&
                    (workflow.InternalState & SPWorkflowState.Running) == SPWorkflowState.Running)
                {
                    return true;
                }
            }
            return false;
        }

The somewhat subtle thing to notice is the check: it denotes that the SPWorkflowState is an enum decorated with the [Flags] attribute, which means that the check has to be changed like above.

Posted on Wednesday, August 13, 2008 5:00 PM Sharepoint Gotchas | Back to top


Comments on this post: How to check if a sharepoint 2007 workflow is running

# re: How to check if a sharepoint 2007 workflow is running
Requesting Gravatar...
Hi,

I have a similar issue. I hav a document Library with an OOB approval workflow associated with it. The workflow starts when a new item is added to the document library. And once the document is completely approved, the workflow is completed and that is when I need an event receiver which can check if the workflow is complete and the status of the document is "Approved" and exceute some custom code.

I used the code you provided above in my ItemUpdated Event receiver to check if the workflow is complete, but how do I check it...can you give me more ideas on this issue

Thanks a lot
Left by mkzp9 on Sep 25, 2008 5:13 AM

# re: How to check if a sharepoint 2007 workflow is running
Requesting Gravatar...
Thank you it works fine...
Left by KC on Mar 02, 2011 4:51 AM

Your comment:
 (will show your gravatar)


Copyright © Adrian Hara | Powered by: GeeksWithBlogs.net