Saturday, August 6, 2011

How to unlock the locked tasks in Sharepoint Workflow

Sometimes in Sharepoint Workflow, tasks will get locked and you will not be able to proceed further.

These locks are placed to prevent the task being updated simultaneously. The workflow runtime locks tasks by setting a field (WorkflowVersion)and persisting that to the database.

if workflowversion is 1 then the tasks are "not locked". Any value apart from "1" symbolises that these tasks are "locked".

Ideally to remove the locks, we need to update WorkflowVersion of the task to "1".

Here you go, the sample for it.


public static void UnlockWorkflowTasks(string siteUrl, string webUrl, string listName)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb(webUrl))
                {
                    SPList list = web.Lists[listName];
                    SPListItemCollection items = list.Items;

                    foreach (SPListItem item in items)
                    {
                        SPWorkflowCollection workflows = item.Workflows;
                        foreach (SPWorkflow workflow in workflows)
                        {
                            SPWorkflowTaskCollection tasks = workflow.Tasks;
                            foreach (SPWorkflowTask task in tasks)
                            {
                                if (task[SPBuiltInFieldId.WorkflowVersion].ToString() != "1")
                                {
                                    task[SPBuiltInFieldId.WorkflowVersion] = 1;
                                    task.SystemUpdate();
                                }
                            }
                        }
                    }
                }
            }
        }


Happy Coding :)

6 comments:

  1. The code works for me, but when I try to re-approve the workflow task locked again

    ReplyDelete
  2. The code works for me, but when I try to re-approve the workflow task locked again

    ReplyDelete
  3. Great post Jay!

    I had the same problem on workflow tasks and used the following powershell script:

    $list=$spweb.Lists["workflow test list"]
    Foreach ($item in $list.Items)
    {
    $workflows = $item.workflows
    Foreach ($workflow in $workflows)
    {
    $tasks = $workflow.Tasks
    Foreach ($task in $tasks)
    {
    $task[[Microsoft.SharePoint.SPBuiltInFieldId]::WorkflowVersion] = 1
    $task.Systemupdate()
    }
    }
    }

    Then the workflow tasks where not locked any more!
    Tanks,
    Joachim.

    ReplyDelete
  4. Elvys, I'm experiencing the same issue - I can unlock the task but they lock again. Did you find any reason why the tasks were locking in the first place?

    ReplyDelete
    Replies
    1. Yes, Workflow Services were running on different servers in the farm at the same time

      Delete
  5. Where do I add/execute this code? Please help.

    ReplyDelete