Wednesday, October 17, 2012

Programmatically locating and cancelling running workflows associated with a content type

If you're looking for a way to programmatically cancel all running workflows associated with a specific content type (i.e. a custom content type called "Enterprise Document" is highlighted in this example) across all of the document libraries contained within a given site collection, I've put together some code that can do this as follows:

Guid siteId = new Guid("siteIdGuid");
using (SPSite site = new SPSite(siteId))
{
    foreach (SPWeb web in site.AllWebs)
    {
        // Only iterate through document libraries since this content type is associated with documents
        foreach (SPList list in web.GetListsOfType(SPBaseType.DocumentLibrary))
        {
            // Make certain the content type exists in the library so you don't waste cycles stepping through a document library that doesn't contain it
            SPContentType ctEntDoc = list.ContentTypes["Enterprise Document"];
            if (ctEntDoc != null)
            {
                foreach (SPListItem item in list.Items)
                {
                    // Only cancel active workflows that are associated with items of this content type
                    if (item.ContentType.Name == "Enterprise Document")
                    {
                        SPWorkflowManager mgr = site.WorkflowManager;
                        SPWorkflowCollection activeWFs = mgr.GetItemActiveWorkflows(item);
                        foreach (SPWorkflow activeWF in activeWFs)
                        {
                            SPWorkflowManager.CancelWorkflow(activeWF);
                        }
                    }
                }
            }
        }
    }
}



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.