Tuesday, December 10, 2013

Creating a custom sequential workflow similar with SharePoint OOTB approval workflow (5) cancel task(s) when item changed


Creating a custom sequential workflow similar with SharePoint OOTB Approval workflow (1) Association / Initiation Form
Creating a custom sequential workflow similar with SharePoint OOTB Approval workflow (2) Custom Activity, While Activity and Replicator Activity
Creating a custom sequential workflow similar with SharePoint OOTB Approval workflow (3) custom Content Type and custom Task Edit Form
Creating a custom sequential workflow similar with SharePoint OOTB approval workflow (4) End on first rejection
Creating a custom sequential workflow similar with SharePoint OOTB approval workflow (5) cancel task(s) when item changed
Creating a custom sequential workflow similar with SharePoint OOTB approval workflow (6) reassign task and request change

The EventHandlingScopeActivity is an activity that allows a workflow (or part of a workflow) to run while listening to events. In this case, onWorkflowItemChanged will be the event, the workflow will be canceled in this event.

Based on the workflow described in Creating a custom sequential workflow similar with SharePoint OOTB Approval workflow (2) Custom Activity, While Activity and Replicator Activity, drag from the toolbox and drop an EventHandlingScopeActivity under OnWorkflowActivated activity, and put the original whileActivity1, replicateTasks and spTaskActivity1 in EventHandlingScopeActivity like following:


Right click on "eventhandlingscopeactivity". Click on "view eventhandlers".
Now you get another view of the workflow. In my EventHandlingScopActivity I have an eventHandlersActivity1 with an EventDrivenActivity, wich has an onWorkflowItemChanged1 activity.  See following Diagram:


Following is the code in onWorkflowItemChanged1_Invoked event handler:

private void onWorkflowItemChanged1_Invoked(object sender, ExternalDataEventArgs e)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        workflowProperties.Web.AllowUnsafeUpdates = true;
        foreach (SPWorkflowTask WorkflowTask in workflowProperties.Workflow.Tasks)
        {
             WorkflowTask["Status"] = "Canceled";
             WorkflowTask["PercentComplete"] = 1.0f;
             WorkflowTask.Update();
        }
        SPWorkflowManager.CancelWorkflow(workflowProperties.Workflow);
        workflowProperties.Web.AllowUnsafeUpdates = false;
    });
}

The only problem is that after the workflow is canceled, the workflow tasks will be deleted automatically. This article: Prevent Workflow Tasks From Being Deleted looks like a solution, but I have not tried this yet.

No comments:

Post a Comment