Sunday 11 September 2011

SPWorkflowEventReceiver class and WorkflowStarting, WorkflowStarted, WorkflowPostponed and WorkflowCompleted events. How receive events from WorkFlows

Finally Microsoft has provided us with some kind of mechanism to interact with our nice worflows in Sharepoint 2010. In the previous versions of Sharepoint we did not have access to all these events.

Well SPWorkflowEventReceiver is an elegant class you can implement with your event receivers, in fact is part of it. When you create an event receiver you CAN SELECT a workflow event receiver. This is quite mad in some ways, because you expect to have your own “workflow event receiver” project but instead you have to share your lunch with “event receivers” anyway, they are really good friends, and never cause trouble.

SPWorkflowEventReceiver implements four events:

  • WorkflowCompleted
  • WorkflowPostponed
  • WorkflowStarted
  • WorkflowStarting

The only thing you need to do it is override the events in a class that implement SPWorkflowEventReceiver. After that you can register that with SPWeb, SPSite or SPSite. You can make it easier, go to Visual Studio->Sharepoint->2010->Event Receiver and in the last dialog select List Workflows.

These are the events provided by SPWorkflowEventReceiver after the project has been created:

image

This is the famous class automatically created:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace EventReceiverProject2.EventReceiver1
{
    /// <summary>
    /// List Workflow Events
    /// </summary>
    public class EventReceiver1 : SPWorkflowEventReceiver
    {
       /// <summary>
       /// A workflow is starting.
       /// </summary>
       public override void WorkflowStarting(SPWorkflowEventProperties properties)
       {
           base.WorkflowStarting(properties);
       }
       /// <summary>
       /// A workflow was started.
       /// </summary>
       public override void WorkflowStarted(SPWorkflowEventProperties properties)
       {
           base.WorkflowStarted(properties);
       }
       /// <summary>
       /// A workflow was postponed.
       /// </summary>
       public override void WorkflowPostponed(SPWorkflowEventProperties properties)
       {
           base.WorkflowPostponed(properties);
       }
       /// <summary>
       /// A workflow was completed.
       /// </summary>
       public override void WorkflowCompleted(SPWorkflowEventProperties properties)
       {
           base.WorkflowCompleted(properties);
       }
    }
}

As you can see it works in the same way than event receivers. I will do a step by step, but I don’t think is worth it. Just create a workflow point it to a list and deploy it. Create an event receiver after that and be sure you select this option (this one is pointing to the Document Library):


image


Enjoy!

No comments: