Starting workflow from eventhandler


I just wanted to make quick post about starting the workflow from code. You might want to use this stuff in your eventhandlers for starting workflows automatically in some weird scenarios. But no more explaining since this is pretty straightforward. Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  SPUser person = ...; // TODO: get your user
  // TODO: get correct list item (or use properties.ListItem inside your event handler)
  SPWorkflowManager manager = listItem.Web.Site.WorkflowManager;
  SPWorkflowAssociationCollection associationCollection = listItem.ParentList.WorkflowAssociations;
  foreach (SPWorkflowAssociation association in associationCollection)
  {
    // TODO: find the correct workflow association in the list:
    if (association.Name.ToLower().Equals("myworkflow") == true)
    {
      String data = association.AssociationData;
      if (person != null)
      {
        data = association.AssociationData.Replace(
          "<my:CC></my:CC>",
          "<my:CC><my:Person><my:DisplayName>" +
          person.Name + "</my:DisplayName><my:AccountId>" +
          person.LoginName + "</my:AccountId><my:AccountType>User</my:AccountType></my:Person></my:CC>");
      }
      // Hit the go!
      SPWorkflow wf = manager.StartWorkflow(listItem, association, data, true);
    }
  }

In my example I start approval workflow. So I’ll get my SPUser who will be set to CC in the workflow and then find the right workflow association. It’s important to understand that the workflow needs to be correctly set in that list… without it this stuff won’t work. You can test it by starting workflow manually and see if it’s working.

It was quick post about working eventhandlers and workflows… those are pretty important part of MOSS 2007.

Anyways… happy hacking!

J

Comments (0)

Skip to main content