Friday, May 1, 2009

Error Update WF Task

The Error

I ran into a rather interesting error as a result of me finding this error. I was getting the following:

This task is currently locked by a running workflow and cannot be edited

What I was trying to do was update a task list item that was generated from a WF workflow. I had a situation where the Assigned To field had not been properly set, and I wanted to modify the existing item. I could get this error in numerous ways. For instance, you cannot access the Assigned To field by going to task itself but if you select Edit in Datasheet you have the ability to update it.

As well I had written a little a small code snippet to update the task as well.

private static void UpdateTaskAssignedTo(string siteURL, string web,
string taskListName, string loginName, string email, int itemID)
{
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb(web))
{
SPListItemCollection listItems = web.Lists[taskListName].Items;
SPListItem listItem = listItems.GetItemById(itemID);

web.AllowUnsafeUpdates = true;

SPUser user = web.AllUsers.GetByEmail(email);
SPFieldUserValue fieldUser = new SPFieldUserValue(web, user.ID, user.LoginName);
listItem["Assigned To"] = fieldUser;
listItem.SystemUpdate(false);

web.AllowUnsafeUpdates = false;
}
}
}

What would happen if did either the task would get updated as expected, however if I tried to update it again I would get the above error.

WORSE – the workflow task item will not start up the workflow again – for all intensive purposes it will seem that the workflow is stuck.

The Issue

I found this blog, among a few others discussing the issue. Several claimed this as a "bug" for WF and MOSS. It is not once I sat down and started thinking about it. The issue has to do with the task correlating to the WF workflow instance.

If you have built a custom workflow in MOSS, you will know that if you put in a OnTaskChanged event in your workflow basically the WF workflow is waiting for task to be updated. When you go to update the task by clicking on the task directly you will be taken to Workflow Form (InfoPath in most cases) which will submit back to the WF server within MOSS to start back up the workflow. However, if you access the task list item by other means (examples above), you are changing the state of the task itself and the WF instance gets out of sync.

The Resolution

It is pretty simple; all you need to do is add an action to the state for an Update. So put a dropdown on your IP form with the actions that a user can do like Approve, Deny or Update. Approve or Deny will move the workflow to a completely different state however, the Update will call back to the current state. The task will be recreated (so it is good practice to delete the task in the StateFinializationActivity. This is why I like to use K2 blackpearl instead to avoid this……

No comments: