When working with tasks in a SharePoint workflow project you can get an event when a task changed but is hard to actually detect what changed as the event does not return enough information.
The following picture shows the regular flow to work with a task in workflow framework:
So the minimum activities required are:
- CreateTask to create the task
- While to wait until the task is considered completed
- OnTaskChanged to receive any changes to the task
- CompleteTask to complete the task and continue.
All the task related activities needs to be bind to the same correlation token. If your workflow will have multiple workflow make sure that you are creating multiple correlation tokens for each task.
Now there are few other properties that are used during the lifetime of the task. I will only mention here the properties that are specific to the problem at hand
CreateTask activity needs to have the TaskProperties bind so it can use it to create the task item.
OnTaskChanged activity needs to have both AfterProperties and BeforeProperties bind so it can fill with values when your code is called.
Now the problem is that when the OnTaskChanged invoked event gets called the BeforeProperties seems to not contain any data where the AfterProperties seems to contain the current information.
Jus taking the example of checking to see if the task was reassigned by using the AssignedTo property for before and after properties as miss-directed by the MSDN and SDK does not work because the BeforeProperties.AssignedTo is null most if not all the times.
So what can we do now?
Let’s think how else we can get the before properties:
When we create the task we set the TaskProperties.AssignedTo to a person or group that we want to execute on the task. First time when the task is changed in any way we get the event with AfterProperties. Now we know if the AssignedTo was changed by checking if it is different than the original one that we specified when we created the task. If after that we copy the AssignedTo from AfterProperties into the TaskProperties when the task gets changed we can detect if the AssignedTo changed without using the BeforeProperties at all.
This is my solution:
- Forgot about BeforeProperties.
- Each time when a task gets changed detect the changes by checking AfterProperties against TaskProperties.
- After you execute the necessary code into the change event copy all necessary properties from AfterProperties back to the TaskProperties (this is your before properties now that you cache inside your workflow)
- Do not just blindly assigned the AfterProperties over the TaskProperties as it will not contain all the properties all the time. AfterProperties contains only the task item properties that have changed so you will need to manually parse it back into the TaskProperties.
If you are still with me and your head did not explode over this explanation drop me a line.