Tuesday, November 8, 2011

Terminating/Canceling the Workflows

As we know some time it's bit trick to terminate/cancel a workflow.. Which made me create this web part, so that I can delegate my job to the power user so that they can manager it better! And also gives me some extra time to concentrate on my deadlines.

Challenges:
Very first that you need to have proper admin access to see "Terminate this workflow now" link
When you click on the workflow hyper link on the library item 


Here is the web part UI:





Note: ID is the document list item id; you can make more fancy by providing the file name or even loading the active workflow items once selected the document library name

Code for Process Button:
private void CancelWF(string ListName, string ItemId)
{
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {
   
using (SPSite siteColl = new SPSite(SPContext.Current.Site.Url))
    {
     
using (SPWeb site = siteColl.OpenWeb())
      {
      
if (site != null)
       {
       
try
        {
        
SPList workflowTasks = site.Lists["Tasks"];
         SPList doc = site.Lists[ListName];
         SPListItem docItem = doc.GetItemById(Convert.ToInt32(ItemId));

         foreach (SPListItem listItem in docItem.ListItems)
         {
          site.AllowUnsafeUpdates =
true;
          foreach (SPWorkflow itemWorkflow in listItem.Workflows)
          {
          
SPWorkflowManager.CancelWorkflow(itemWorkflow);
           _lblMessage.Text = string.Format(("Administratively Canceled Workflow for the ItemId: {0} / File Name : {1}"), ItemId, listItem.File.Name);
           _lblMessage.ForeColor = Color.Blue;
          }
          site.AllowUnsafeUpdates =
false;
        }
      }
     
catch (Exception ex)
      {
        HandleException(ex);
      }
     }
    }
   }
  });
}


End results: