Navigation Bar

Monday, 18 June 2012

Starting workflow programmatically

If you have an instance of SPListItem, and know the workflow association name, you can start it. First you need to find workflow assocation instance and tell SPSite.SPWorkflowManager to start your workflow.

Lets say I have a helper method that takes SPListItem and workfow association name.

private SPWorkflowAssociation GetWorkflowAssociationByName(SPListItem item, string workflowAssociationName)
{
    return item.ContentType.WorkflowAssociations.GetAssociationByName(workflowAssociationName, new System.Globalization.CultureInfo("en-US"));

}


public void StartWorkflow(SPListItem item, string associationName)
{
  try
   {                

//get workflow association object
workflowAssociation = GetWorkflowAssociationByName(item, associationName);                

if (workflowAssociation == null)
  throw new Exception(string.Format  ("Workflow association '{0}' could not be found in the list '{1}'", workflowAssociationName, item.ParentList.Title));

//start your workflow...
item.Web.Site.WorkflowManager.StartWorkflow(item, workflowAssociation, workflowAssociation.AssociationData);
   }            

   catch (SPException spEx)
   { //log your exception }
}


//that kicks off a associated workflow.
StartWorkflow(anInstanceOfSPListItem, "Masood - Approval workflow")

Below is the picture where higlighted box is the association name.


 

That's it. Happy coding.

2 comments:

  1. Hi Muhamamd,

    i am very new to sharepoint and have no idea how things work there.
    i am preparing a very simple notification for birthday wishes. i have created a data base for my team and i want sharepoint to send the emails to everyone if Birthday= today and also update it automatically for next time and keep repeating it without my intervention.
    please help me?

    sandhya

    ReplyDelete
  2. Hi Sandhya,

    You can write custom timer job that will read your list of users (who you want to send wishes) and match with current date and if it matches, send all of them to your custom message.

    I have created a project called "Template Manager" in codeplex and also I have written a blog about how to use it.

    If you need further assistance, you can post your queries in comments and I will reply you.

    Thanks,
    Muhammad Masood
    http://blog.mmasood.com

    ReplyDelete