Wednesday, July 15, 2009

Starting workflow Programmatically using object model SPWorkflowAssociationCollection , SPWorkflowAssociation, SPWorkflowManager

We will discuss here how to start the SharePoint workflow dynamically in an Event receiver. I am using ItemAdded Event to start the workflow, if mail settings are allowed, to send group mails instantaneously

I have earlier discuss about creating event receiver and how to associate it with List. Lets focus here for now on starting the workflow

public override void ItemAdded(SPItemEventProperties properties)
{
try
{
base.ItemAdded(properties);
if (isGlobalMailAllowed(properties))
{
//Mails are allowed at site level, start workflow to send mails
StartThisWorkflow(properties, strWorkflowAlertGUID);
}
}
catch (Exception ex)
{}
}



///
/// Starts a workflow associated to a list programmatically.
///

///
///
private void StartThisWorkflow(SPItemEventProperties properties, string strWorkflowID)
{
try
{
SPListItem listItem = properties.ListItem;
SPWeb web = properties.OpenWeb(); //Following best programming practices for Event handler to get spweb object
SPSite site = web.Site;
SPWorkflowManager manager = site.WorkflowManager;
SPList parentList = listItem.ParentList;
SPWorkflowAssociationCollection associationCollection = parentList.WorkflowAssociations;
LookupAndStartWorkflow(listItem, manager, associationCollection, strWorkflowID);
}
catch (Exception ex)
{}
}

///
/// Lookup and start the workflow.
///

///
///
///
///
private static void LookupAndStartWorkflow(SPListItem listItem, SPWorkflowManager manager,
SPWorkflowAssociationCollection associationCollection,
string workflowId)
{
foreach (SPWorkflowAssociation association in associationCollection)
{
Guid workflowGuid = new Guid(workflowId);
if (association.BaseId == workflowGuid)
{
string data = association.AssociationData;
SPWorkflow wf = manager.StartWorkflow(listItem, association, data);
}
}
}

Thanks to the miguelisidoro @
http://blogit.create.pt/blogs/miguelisidoro/archive/2008/07/05/SharePoint-2007-_2D00_-Start-a-Workflow-Programmatically.aspx

Cheers!!!

No comments:

Post a Comment