Monday, August 25, 2008

How to get workflow instance of a Task item

This post is about finding which workflow a task item is associated to. For example if you have a workflow setup on a document library which creates a task in a task list everytime that workflow is initiated and you want to do an action further when a task is created. Now this sounds pretty straightforward that you can attach an event handler with a Task list and do the needful. But remember that the particular Task list can be used for many workflows and you want to run your event only for a particular WorkFlow.

What you can do is, Task list exposes few properties which are hidden which tells the exact workflow information. The three properties which are of our interests are:

Workflow List ID (This represents the document library ID from where the workflow was initiated)
Workflow Item ID (This represents the document for which the work flow is initiated)
ows_WorkflowInstanceID (This is the workflow instance id of the workflow that has been setup for document library. This will help us to get the workflow type)

Let me show you a code snippet to get these details:


public override void ItemAdded(SPItemEventProperties properties)
{
try
{

SPListItem taskItem = properties.ListItem;

//Check if the item added is a Workflow related or not
if (taskItem["Workflow List ID"] != null)
{
SPWeb web = properties.OpenWeb();
Guid sourceListID = new Guid(taskItem["Workflow List ID"].ToString());
SPList sourceList = web.Lists.GetList(sourceListID, true);
int sourceListItemID = Convert.ToInt32(taskItem["Workflow Item ID"]);
SPListItem sourceListItem = sourceList.GetItemById(sourceListItemID);


//Get the workflow instance id from Task item
Guid taskWorkflowInstanceID = new Guid(taskItem["ows_WorkflowInstanceID"].ToString());

//Get the workflow object
SPWorkflow wf = sourceListItem.Workflows[taskWorkflowInstanceID ]

//Get the workflow association object
SPWorkflowAssociation wfAss = sourceList.WorkflowAssociations[wf.AssociationId];
try
{
//Check if the associated workflow is of type Disposition Approval
//This GUID will be same in every MOSS install
if (wfAss.BaseId.Equals(new Guid("dd19a800-37c1-43c0-816d-f8eb5f4a4145")))
{
//if the workflow is of type disposition then do your action
}

catch (ArgumentException argex)
{
}
}
}

}

}
catch (SPException spex)
{
}
catch (Exception ex)
{
}

}



You will notice that I am checking the base id of the Workflow Association object this gives us the workflow type which has been setup for the document library. In this case I am checking if the base id is of same type of the Disposition workflow. This GUID will be same in every MOSS install. Now in next post I will tell you how you can attach this event receiver with a Task list template type.

2 comments:

Anonymous said...

awesome post this has saved me time.

Anonymous said...

Thank you

Dogpile
Powered By Blogger