Wednesday, November 11, 2009

Change Workflow Task Status from any SharePoint custom component

Scenario: I have a custom workflow running. I want to change status a task from another sharepoint custom component like webpart or so.

Approach:
If we update the workflow task directly by changing the status field value to Completed or to any other status, then usually workflow raises an exception "This task is currently locked by a running workflow and cannot be edited." To get rid of this error, you can use following routine:


private void CompleteTask(string taskTitle)
{
try
{
Hashtable taskHash = new Hashtable();
taskHash[SPBuiltInFieldId.TaskStatus] = "Completed";

string currentuser = SPContext.Current.Web.CurrentUser.Name.ToLower();
Guid siteID = SPContext.Current.Site.ID;
Guid webID = SPContext.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteID))
{
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
SPList wfTasksList = web.Lists["WorkflowTasks"];
SPQuery queryWFTasks = new SPQuery();
queryWFTasks.Query = <<>>;
queryWFTasks.ViewAttributes = "Scope=\"RecursiveAll\"";

SPListItemCollection wfTaskItems = wfTasksList.GetItems(queryWFTasks);

if (wfTaskItems.Count != 0)
{
foreach (SPListItem item in wfTaskItems)
{
if (item.Title.ToLower().Equals(taskTitle.ToLower()))
{
SPWorkflowTask.AlterTask(item, taskHash, true);
break;
}
}
}

web.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
// Log the exception here
}
}

No comments: