Chapter 21. The K2 Event Bus

Anthony Petro

The book to this point has shown that K2 blackpearl is an incredible platform for modeling business processes and information. Sometimes factors external to the process can affect its performance or logic and processes should be able to adapt to these events both internal and external to the process. Event monitoring allows users to affect change and address issues that affect the process without having to remodel the process. The K2 Event Bus is the event-modeling platform for K2 blackpearl.

The K2 Event Bus provides the infrastructure and tools to allow business users to model notifications and custom actions based on events in K2 workflow processes, SmartObjects, line-of-business (LOB) systems, and single or recurring schedules. The events are configured to evaluate and execute policies independent of the context of a workflow process or LOB system activity, such as a SmartObject Create method. The policies can range from simple e-mail notifications configured in the K2 Workspace to fully customized .NET code.

This chapter will cover the following topics:

  • Key features of K2 Event Bus

  • K2 Event Bus Architecture

  • Exposing process definitions and data as SmartObjects

  • The K2 Event Bus Scheduler

  • Configuring the Event Bus

  • A walkthrough of using the Event Bus

  • Troubleshooting tips and tricks

Key Features of the Event Bus

Event-Driven Business Process Management (EDBPM) combines Business Process Management (BPM) with Complex Event Processing (CEP) to bring greater business flexibility, agility, and real-time information to distributed systems.[21] The Event Bus is a key piece of the K2 platform that enables the integration of CEP with BPM. Event-driven scenarios made possible by the Event Bus allow process-driven applications to react to events from line-of-business (LOB) systems and other sources relevant to the business, increasing process flexibility and business agility in response to a changing business environment.

The Event Bus provides rich features for business users and developers alike. The following sections provide a quick overview of the key features of the Event Bus.

Open and Extensible Architecture

The Event Bus provides a set of generic application programming interfaces (APIs) for registering and recording events, mapping and resolving context data, executing policies, and working with message queue systems.

Refer to the K2 Developer Reference topics "How to register new events with the Event Bus" for information about scheduling events, and "How to add a 3rd-party Event Recorder to the K2 blackpearl server" for information about raising new events.

Separating Events from Actions

The Event Bus separates the act of raising an event from the action that must be taken for events that have been raised. This allows more than one event to call the same action.

Pluggable Event Systems

The Event Bus provides a set of programming interfaces that allow any system to be registered as part of the event management toolset. Once a system is registered, users can begin to subscribe to events raised by that LOB system. For example, an organization can configure its proprietary Human Resources applications event for Create New Employee as an event in the Event Bus. Once this HR system is registered, end users can begin to create notifications, or subscriptions, that evaluate when the Create New Employee event is raised from the HR LOB system. The user then has the full power of the Event Bus to determine what conditions of Create New Employee are important to monitor and what actions must be taken when those conditions evaluate to True.

Built-In Event Handlers

The Event Bus is preconfigured with event handlers for K2 Workflow and K2 SmartObjects. The events for the K2 SmartObjects on the K2 server, as well as K2 Workflow events, are made available for users to subscribe to. All the events are available throughout the K2 blackpearl platform, such as reports and forms via the ADO.NET provider and the Notification Events wizards, as shown in Figure 21-1. For more information on how data and events are exposed for K2 Workflow processes, see the "Exposing Process Information through SmartObjects" section in this chapter.

Figure 21-1

Figure 21.1. Figure 21-1

Pluggable Message Queuing

The Event Bus uses message queuing to allow for asynchronous events. All registered events are put on the queue for processing. The events are then pulled from the queue and evaluated to determine if any action needs to be taken. The message queuing infrastructure implements a pluggable architecture that allows any message queuing system to be used by the Event Bus. The Microsoft Message Queuing (MSMQ) interfaces are provided by and used by default by the Event Bus.

Independent Policy Management

All policies that are evaluated or executed by the Event Bus are created and maintained independently in the policy management system. This allows organizations to manage their business policies independent of the usage of those policies. Users simply consume a policy as part of an event registration process.

At the time of this writing, the policy management system available is an Event Bus–specific version of the SmartFunction engine. This engine is only available to the K2 Event Bus APIs and UIs and has no additional policy management tooling.

Conditional Policies

Although it is possible to register an event and perform an action as a result of that event firing, it is often necessary to apply a policy to the event to determine if an action is necessary given the current condition. The Event Bus allows for the registration of a conditional policy that will be evaluated when the event is fired. Conditional polices are managed independent of the Event Bus, allowing for maximum flexibility within an organization and for modeling events independent of policies and actions.

Conditional Policies are available only via the API.

Action Policies

The action policy allows a business user to configure the action the Event Bus must perform independent of the event system. Typical actions are Send an Email or Start a Workflow Process. The Notification action policy is provided for users with K2 blackpearl.

See Chapter 20 for an example of how to register for notifications via K2 Workspace.

Subscription Model

The subscription model allows users to register for system-level events through wizard-driven tools that abstract the complexity of the underlying data and policies. Typical event management systems require administrator access and intimate knowledge of the underlying system to configure notifications. The subscription model allows business users to take ownership of this configuration.

Architecture of the K2 Event Bus

The Event Bus component of the K2 platform consists of three hosted servers — the Event Bus Management Server, the Event Bus server, and the Event Bus Scheduler, which are shown in Figure 21-2. The flow of data is shown in the Figure 21-7, but it is important to note here that the Event Bus Scheduler utilizes the SourceCode.EventBus.ClientRecorder assembly to schedule events on single or recurring schedules, such as the Last Friday of every Month (see The Event Bus Scheduler section later in this chapter for more details). The scheduler events, along with the recorders for workflow, SmartObjects, and custom events, are processed using Microsoft Messaging Queuing (MSMQ) to either send notifications or call static methods in custom assemblies.

  • Event Bus Server: Responsible for the event system in the K2 environment. This includes server level events as well as process- and SmartObject-level events.

  • Event Bus Management Server: Responsible for the management interfaces surrounding the Event Bus.

  • Event Bus Scheduler Server: Responsible for the management interfaces surrounding the Event Bus scheduling service.

Figure 21-2

Figure 21.2. Figure 21-2

Event Bus Data Flow

The Event Bus has been architected from the ground up with generic components and interfaces throughout the entire platform. All built-in and custom events that are registered with the Event Bus are done so through the Generic Client Event Recorder. This ensures that the tooling provided for managing events and notifications is consistent regardless of the source of the event. To ensure reliable processing of all events without locking or contention issues, the architecture implements the use of a message queue to allow events to be raised independent of their processing. The Generic Client Event Recorder will raise all events that have been registered with the context data that was configured for that event. This happens independent of any processing of the event. The event action and the context data is simply put on the message queue for processing by the Event Bus server.

Figure 21-3 shows how data flows from workflow, SmartObject, and custom Event Recorders through to the message queue (MSMQ) to then be processed by the Event Bus. The processing of events will likely involve a notification or execution of a policy/action or SmartObject method. Typically, these events are configured to send notifications or execute custom code via K2 Workspace, but they can also be programmatically configured.

Since there is no current tooling in K2 blackpearl, schedules can only be programmatically configured.

Figure 21-3

Figure 21.3. Figure 21-3

The policy aspect of the Event Bus shown in Figure 21-3 is provided by the SmartFunction hosted server. Currently, this server is used only by the Event Bus. It cannot be extended, and it will be superseded by a different policy engine in the future.

The sample code listed later in this chapter will walk through the various pieces of configuration.

Event Bus Server

The Event Bus Server (see Figure 21-4) is composed of multiple components and makes up the heart of the event features of the K2 platform. Each component is described in this section.

Figure 21-4

Figure 21.4. Figure 21-4

Event Recorder

The Event Recorder is responsible for actually registering the events that the Event Bus will be listening for. There are several events available through workflow and SmartObject events as well as custom events that implement the Generic Client Recorder interfaces. The registered events will be sent to the configured queue by the Event Recorder.

Event Bus Engine

The Event Bus Engine is the execution engine for the entire event management system. It receives events from the queue, evaluates policies and executes the registered actions. In the case of any exceptions, the Event Bus Engine is also responsible for logging the exceptions.

Event Bus Store

The Event Bus utilizes ADO.NET 2.0 for much of the interaction between the Event Bus server and the Event Bus Store. The Event Bus Store holds the details for all registered events (Workflow, SmartObjects, and Custom) as well as the policies (Conditional and Action). The Event Bus store consists of two main databases: Event Bus and Event Bus Scheduler. Please see the Developer Reference for more information on the databases, tables, and stored procedures that make up the Event Bus Store.

Event Recorder

As Figure 21-5 shows, the Event Recorder serves as the gateway between the Event Bus and source system for the actual events that are being managed. Although the source system is actually where the events happen, it is through the Event Recorder that the events become part of the Event Bus.

Figure 21-5

Figure 21.5. Figure 21-5

System Event Recorder

The events of the source system are exposed to the Event Bus through a custom Event Recorder. All Event Recorders, including the built-in workflow and SmartObject Event Recorders, implement the interfaces of the Generic Client Event Recorder. The system-specific Event Recorders contain the logic for subscribing to events from source system through Event Bus event handlers. These event handlers utilize the Generic Client Event Recorder to raise the events to the Event Bus.

Generic Client Event Recorder

The Generic Client Event Recorder will retrieve context data belonging to the executing event and provide the ability to store that data. The context data from the events is serialized and deserialized throughout the processing of the event. When the source system raises the event, it will be responsible for storing any context data necessary for processing of the event. This context data is usually configured as part of registering a source system event. To ensure consistent processing of all Event Bus events, the context data is serialized through interfaces in the Generic Client Event Recorder. When the Event Bus processes the source system event, it will utilize these same interfaces to deserialize the context data. The Generic Client Event Recorder is also responsible for the actual queuing of the source system event.

Event Bus Engine

The Event Bus Engine (see Figure 21-6) provides the gateway between the message queue system, the policy engine, and the user interfaces for configuring the Event Bus.

Figure 21-6

Figure 21.6. Figure 21-6

Event Queue

The Event Queue is where all the source system events and their context data are stored. The Event Bus engine utilizes the Event Queue to process events independently of the actual event firing. This allows the source systems to reliably raise all events without waiting for the Event Bus to process those events. The Event Queue will store all the events, and their context data, until it has the cycles to process those events. Ideally, this is within milliseconds of the original event, but under load it may take longer.

The important thing to note is that all events will be processed and the source system will not be affected by this processing.

Event Store

The Event Store consists of two main databases:

  • EventBus: Stores information about the Event Bus and configured notifications.

  • EventBusScheduler: Stores information about the Event Bus Scheduler, which provides a mechanism to raise events to the Event Bus using single or recurring schedules.

These databases store the list of events that are to be managed by the Event Bus as well as the mappings of their context data. It is important to note that nothing specific to the actual event is stored in the Event Bus store. The specific events and the context data for that event are stored on the Event Queue for processing. Once processed, that event and context data is disposed and no longer accessible.

Policy Engine

When the Event Bus engine processes events from the queue it will likely execute policies in the form of .NET methods and utilize the context data from the source system. The policies are stored and executed via the SmartFunction hosted server. Failed policy executions are logged and retried. The retry count is configurable and, if exceeded, the Event Bus Engine will log an exception.

At the time of this writing, the policy engine that currently ships with K2 blackpearl does not support policies other than action policies. Conditional policies are dependent upon future releases.

Some common failures to watch for include unexpected or missing context data fields and lost connections. Remember that the source system will raise an event and must put the event and the context data on the queue. It is later that the Event Bus engine will process that event with the context data through the execution of policies. Managing for this disconnected processing is key to building custom events.

Event Administration

The Event Bus engine can be fully managed in code via the APIs. The Event Bus architecture was built from the ground up to ensure flexibility and extensibility. The transparency of the administrative features is a great example of this. The Event Bus currently has business user tooling for creating e-mail notifications for any event managed by the Event Bus. Additionally, there is tooling for executing custom policies in the form of static .NET methods for registered events. This business user tooling is just scratching the surface of the Event Bus administration APIs, and more business user tooling will be available in the future, including registration for schedule-based events.

Exposing Process Information through SmartObjects

Business processes in organizations typically have two main elements of information that are part of the design-time and run-time process information — the process instance data (what actions were taken for an instance of the process) and the data that is associated with the process instance.

Every business process that is designed in an organization will have certain actions that can be performed on it. These actions are determined when the process is designed. Some of the actions are standard actions, such as Start Process. Others are more specific to the type of process such as Begin Order Approval. A process also generates and contains data during execution. This data is also defined during design time and can be set, but only after an instance of the process is created. So when a user performs an action, such as Start Process for instance, you can first set some data on the instance. This concept of setting data and performing actions is similar to setting properties and executing methods on SmartObjects. This means that exposing processes and data as SmartObjects fits nicely into the SmartObject model. For more information about SmartObjects, see Chapter 7.

Let's walk through the following scenario.

An organization builds an Order Approval process that presents an approver with a form to review the order and determine if it should be Approved or Declined. An e-mail indicating the results is then sent to the Originator of the process.

Most processes consist of a number of activities and events. Some events may require input from a user and are called client events. Other events can be executed without any user interface (UI) and are called server events. The example process has three activities: Order Approval, Order Approved, and Order Declined.

The Order Approval activity has one client event called Approve Order. The Order Approved activity has a server event called Send Approved Email. The Order Declined activity has a server event called Send Declined Email. The full process is shown in Figure 21-7.

Figure 21-7

Figure 21.7. Figure 21-7

As with processes, client events can also have actions. In this case the Approve Order client event has actions Approved and Declined. Also like with processes, activities can also have data that are only in the scope for that activity. In the example there is only an Order ID that is defined as data on the process level.

When a process is deployed, SmartObjects are optionally created for the process itself and for each client event in the process. These are the only entities of a process that can have actions performed on them. So in the example there will be a SmartObject created for the Order Approval Process and for the Approve Order client event.

As for the data, because Order ID is defined at the process level, Order ID becomes a property on all entities (process and client events). If Order ID were only defined for the Order Approval activity, it would have been a property of the Approve Order client event SmartObject and not on the Order Approval Process SmartObject (see Figure 21-8).

Figure 21-8

Figure 21.8. Figure 21-8

Now that you understand where the data for a process sits, let's look at how it flows (see Figure 21-9).

Figure 21-9

Figure 21.9. Figure 21-9

When the process is deployed, you have a choice to generate the SmartObjects during the deploy task of the process. If you choose not to generate the SmartObjects and later need them, you can always do so manually afterwards. This option is configured on the process properties dialog.

You have the option to choose which objects are created (see Figure 21-10). By default, if you check only Create Workflow SmartObjects and don't specify any other options, this will create only the Process SmartObject and no client SmartObjects. You specifically have to check those you want enabled. Having some of these turned off by default enhances performance and will not put extra load on the server for objects that are never used. Figure 21-10 shows two checkboxes that affect the SmartObjects generated for the process. The same is true concerning the reporting SmartObjects created with Create Workflow Reporting SmartObjects; the only difference is that by default it is checked to be created and you can specify activity objects as well (see the product documentation for more details).

Figure 21-10

Figure 21.10. Figure 21-10

So how does this apply to the K2 Event Bus?

The ability to represent all business process information — activity instance data, process instance data, data associated with the process that can be both internal and external in a LOB system as business entities — is unique to K2. Once the traditional workflow information is exposed as a SmartObject, all the power of the SmartObject system K2 offers is now available, from dynamic forms and application building to reporting, including intelligent access to all the process information and their related entities without needing to write code or SQL syntax queries to create the relationships, custom applications, other process designs, and the Event Bus to name a few.

The Event Bus Scheduler

The Event Bus Scheduler is used to schedule time-based events. These could be events that occur on a particular day and time or that recur on a regular basis. Scheduled events are not raised by another system but are created and executed entirely within the Event Bus. LOB systems that raise recurring events can and should probably be used for recurring events that need some interaction with the Event Bus, but if you don't have a system for these events and you would like to give your business users access to a scheduling engine, use the Event Bus Scheduler. Keep in mind that the scheduler will not execute custom code nor will it execute policies for use by the Event Bus.

Events are raised in the same way as in the Event Bus by the use of Event Recorders, and there are two ways of consuming your events as set up by your business users:

  1. Schedules can be linked to an Event Bus event in order to execute your policies as the schedules are executed.

  2. Custom assemblies can be written to handle your schedules by implementing the appropriate Scheduler interface. These need to be added as Event Recorders in the scheduler configuration file.

The authoring of a schedule uses standard scheduling patterns. The patterns supported by the Event Bus Scheduler are:

  • Interval

  • Daily

  • Weekly

  • Monthly

  • Yearly

These occurrence patterns can be used together with an occurrence range to specify the parameters of your schedule. The occurrence range can be specified in one of the following two methods:

  • Begin and End Dates

  • Number of Occurrences

By using the predeveloped Event Bus Scheduler Event Recorder, you can create a schedule and link it to an Event Bus policy to be executed. Using the Scheduling API, you can create a schedule with the following code sample:

private void SpecificDateSchedule (object sender, EventArgs e)
    {
      SchedClient.ScheduleAuthoring scheduleClient;
      SchedAuth.Schedule schedule;
      int scheduleID = 0;

      try

    {
        //***** SPECIFIC DATE *****
        schedule = new SchedAuth.Schedule((int)SchedAuth.RecurrenceType.Yearly);
        //Setup Schedule
        schedule.Name = "Specific Date Schedule1";
        schedule.Description = "This schedule executes on 18th of January yearly at
15:39";
        //Setup Range
        schedule.RecurrenceRange.Occurrences = 1; //Could also use the
RecurrenceRange.StartDate and EndDate to specify a range
        //Setup Pattern
        schedule.RecurrencePatternYearly.DayX = 18;
        schedule.RecurrencePatternYearly.EveryXMonth = 01;
        schedule.RecurrencePatternYearly.StartTime = new SchedAuth.Time(15, 39);

        //Open Connection and save schedule
        scheduleClient = new SchedClient.ScheduleAuthoring();
        scheduleClient.CreateConnection();
        scheduleClient.Connection.Open(GetConnectionString());
        scheduleID = scheduleClient.UpdateSchedule(schedule);
        AddSolutionPolicy(scheduleID); //This is where the schedule is linked to the
executing policy
        MessageBox.Show("Done");
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
      finally
      {
        schedule = null;
        scheduleClient = null;
      }
    }

To link the schedule created above to an Event Bus policy, the AddSolutionPolicy function would be similar to creating Event Bus events, but you would specify a different Event Type, as in the following example:

private void AddSolutionPolicy(int scheduleID)
    {
      EBClient.EventAuthoring eventClient;
      EBAuthor.CustomEvent customEvent;
      EBAuthor.PolicyMapping policyMapping;
      EBAuthor.SourceField sourceField;
      try
    {
        //***** Add the Event to Execute for the schedule *****
        //Create Event
        customEvent = new EBAuthor.CustomEvent(
          0,
          "Test Schedule Event",
"Description",
          scheduleID.ToString(),
          "OnScheduleExecute",
          (int)SourceCode.EventBus.Common.Enumerators.EventType.Scheduled_Event);
        //Add the action policy
        policyMapping = new EBAuthor.PolicyMapping(0, "C:\Windows\SolutionEvent.dll", "SolutionEvent.Job", "Void TestJob()");

        customEvent.ActionPolicyMappings.Add(policyMapping);
        //Save the custom event
        eventClient = new EBClient.EventAuthoring();
        eventClient.CreateConnection();
        eventClient.Connection.Open(GetConnectionString());
        eventClient.UpdateCustomEvent(customEvent);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
      finally
      {
        sourceField = null;
        policyMapping = null;
        customEvent = null;
        eventClient = null;
      }
    }

An example scenario for creating a monthly schedule is to automatically generate a department's sales report and mail the report to all the relevant sales representatives. You could also automatically create a sales discussion meeting if the sales figures are below 10% of the budgeted estimates.

Note that currently there is no UI to author schedules so everything must be done using the API. Refer to the EventBusScheduler Management Application http://k2underground.com/k2/ProjectHome.aspx?ProjectID=90 on K2 Underground for an example of using the Event Bus Scheduler. It may require a K2 Underground account.

Event Bus Configuration Settings

There are several configuration (.config) files that are useful in understanding settings that control how the Event Bus functions:

  • SourceCode.EventBus.Server.Config

  • SourceCode.EventBus.Mapping.dll.config

  • SourceCode.EventBus.ClientRecorder.dll.config

  • SourceCode.EventBus.EventAdmin.dll.config

This section includes descriptions and important settings for each configuration file.

SourceCode.EventBus.Server.Config

This configuration file is located at C:Program FilesK2 blackpearlHost ServerBin and is used for controlling many aspects of the Event Bus server.

  • eventbusserverconnection: Database connection for the Event Bus database.

  • SmartFunctionconnectionstring: Host Server connection for the SmartFunction server.

  • sendmailpolicyname: Policy name of the SmartFunction to be used to send mail.

  • sendmailpolicynamespace: Namespace name of the SmartFunction to be used to send mail.

  • sendmailpolicymajorversion: Version number of the SmartFunction to be used to send mail.

  • sendmailfrom: The address to be used as the from address for all the worklist item notifications.

  • notificationtemplatepath: The path to the notification template to be used for worklist item notifications.

  • eventbusserverdependencies: The dependencies needed to be able to successfully handle events for both the workflow and SmartObject events. These class names are used in the Event Bus server to check if these servers are already hosted. If these servers are not successfully hosted, the Event Bus server will idle for a few seconds before trying to determine if the dependencies are hosted, and it will keep on trying to verify these dependencies until they are successfully hosted.

  • msmqpath: The queue path to the processing queue.

  • msmqerrorpath: The queue path to the error queue.

  • eventqueuingassembly: The assembly to be used to retrieve messages from a queue.

  • eventqueuingtype: The assembly type to be used to retrieve messages from a queue.

  • assembliesconfigfilepath: The path to the configuration file to be used to load the available assemblies that can be used to execute as conditions and actions.

  • eventbuffersize: The max item count of the buffer to be used to retrieve items to be processed. This is only used at startup and if there are unprocessed items in the database.

  • eventpollinginterval: The interval in milliseconds to be used to release items serviced by multiple servers that might be in an error state. If two servers are used to process items out of the same database, and one server gets an item to process and the server goes down for some reason, then this item will be released after the specified interval, and thus be picked up by the second server for processing.

  • eventrecorders: Used to load assemblies to be used for custom recorders. For example, if you want to create a file system watcher to raise events when a file is copied to a specified folder, the Event Bus server can load this file system watcher assembly for you.

  • mappings: This section hosts all the data provider and resolver assemblies to be used for creating run-time data and then resolving these values at run time. When adding a third-party system for eventing, this is where you would add the custom data providers. Remember that when adding assembly info in this section, you need to also add the appropriate information to the SourceCode.EventBus.Mapping.dll.config file.

SourceCode.EventBus.Mapping.dll.config

This configuration file is located at C:Program FilesK2 blackpearlHost ServerBin and is used for mapping contextual data from the event to the Event Bus.

  • resolvers: This section is where the resolver assemblies need to be added and is also discussed in the mappings description in the SourceCode.EventBus.Server.Config settings section.

  • umconnectionstring: The connection string to connect to the UserRoleManager in order to resolve users, roles, and groups.

SourceCode.EventBus.ClientRecorder.dll.config

This configuration file is located at C:Program FilesK2 blackpearlHost ServerBin and is used for managing the generic Event Recorder settings.

  • eventqueuing: If this setting is set to Internal the client recorder will use the default referenced MSMQ message provider. If it is not set to Internal, then the values from the eventqueuingassembly and eventqueuingtype settings are used to send messages to the messaging queue.

  • eventbusclientconnection: The database connection for the Event Bus database. This is only used to get the policy mappings needed to resolve data for the events to be executed.

  • writelog: If this is set to True then errors will be raised and logged to the Event Bus database.

  • logfilepath: The path to the log file.

  • mappingconfigpath: Path to the mapping assembly configuration file.

SourceCode.EventBus.EventAdmin.dll.config

This configuration file is located at C:Program FilesK2 blackpearlHost ServerBin and is used for controlling some administrative aspects of the Event Bus.

  • dependancyconnectionstring: The connection to the Dependency server. This is used to add dependencies on SmartObjects or SmartFunctions.

  • smartobjectdependancyclassid, smartfunctiondependancyclassid, scheduledependancyclassid, eventbusdependancyclassid, and dependancyobjectbrowserids: These will not be discussed here, as these settings should never be changed other than at installation.

  • categoryconnectionstring: The Host Server connection string for categories, which is used to link certain events to a category.

  • worklistnotificationcategoryid, managementeventcategoryid, and runtimeeventcategoryid: These IDs are used to save worklist item notifications to their respective categories and should not be changed.

Troubleshooting the Event Bus

The following is a list of things to keep in mind when working with the Event Bus.

  • Ensure that you can successfully execute the static methods of your Custom Events from a console application before configuring them as Custom Events in K2 Workspace.

  • Start with simple SmartBox SmartObjects and ensure that all the interfaces are working as expected with Event Bus before configuring the SmartObject to utilize non-SmartBox Service Objects.

  • Ensure all methods of SmartObjects that utilize non-SmartBox Service Objects work before configuring them for usage in the Event Bus.

  • Start small with Custom Events. Register a single method with a few simple parameters and output the parameters to the console to get started.

  • Ensure that your Types can be resolved between the context data represented in the Object Browser and the Action Parameters of the Custom Event or the e-mail fields of a Notification.

  • Test the code that you expect to raise an event outside of the context of the Event Bus. For example, write a Windows application to make sure that the FileSystemWatcher class is raising the Created event for the file filter you've configured.

  • Test your mapping classes to ensure the Provider and Resolver are processing context data as you expect.

  • Test your workflow processes by using Management Console in K2 workspace to load process data fields and start a new process — ensure that the process completes without errors.

  • Enable the Journal option for the "eventbus" and "eventbus error" public queues in MSMQ. Although the data on the queue is not very usable, every event successfully raised via the Generic Client Event Recorder will make an entry in the journal.

  • Monitor the ClientEventRecorderError table in the EventBus database for any errors that may occur with your custom recorders.

  • Monitor the Event Bus logging information by running K2 blackpearl server in console mode. The Event Bus messages are the ones with Category=14 in the MessageList section of the C:Program FilesK2 blackpearlHost ServerinHostServerLogging.config file. See Chapter 19 for more information on configuring K2 blackpearl server for console mode.

  • Enable your code for debugging in Visual Studio by attaching to the K2HostServer.exe process. See the K2 blackpearl Developer Reference for more information on configuring Visual Studio to debug K2 Host Server.

Walkthrough: Event Bus SMTP Sample

Let's walk through a sample of creating a new custom event based on the arrival of mail in a SMTP folder. The scenario in this example involves a process in which:

  • A user sends an e-mail to a specific address with a SharePoint search term as the Subject.

  • The Event Bus Recorder creates an event with context data from the e-mail and adds it to the queue.

  • The Event Bus creates a new instance of a SharePoint Search process which queries a SharePoint site and sends the user a list of results that match their query.

We must build several components to surface and process the event of receiving an e-mail with the Event Bus. Figure 21-11 shows how these components fit in the overall solution.

Figure 21-11

Figure 21.11. Figure 21-11

The provided solution contains three projects related to the registration, configuration, and processing of an e-mail received event and the associated context data from the e-mail. The solution also contains two projects for custom action that will be taken once the e-mail is received, namely the execution of a workflow process.

The five projects are:

  • SourceCode.EventBus.Samples.SMTPEventRecorder: Implements the IEventRecorder interface. The Start method utilizes the FileSystemWatcher .NET Framework classes to monitor the SearchSharePoint mailbox and parse the e-mails received for the From address (this will become the search Requestor) and the Subject (this will become the search Keyword).

  • Once the e-mail is parsed and context data is serialized, Generic Client Event Recorder (ClientRecorder) is used to put the event and context data on the queue:

    RaiseEvent((object)context, "C2815731-5997-4A9F-9837-EBCE48C6FF3F", "SMTP",
    "OnMailReceived");
  • SourceCode.EventBus.Samples.GenericXmlMapping: Contains the XmlDataProvider class to serialize the context data (From and Subject fields) and a XmlDataResolver class to deserialize the context data.

  • SourceCode.EventBus.Samples.SMTPObjectBrowser: Implements the IObjectBrowser interface. The ObjectBrowser class provides the user interface components necessary to allow users to use K2 Workspace to configure Notifications or Custom Events (discussed later in this chapter) for the SMTP Event Recorder.

  • SourceCode.EventBus.Samples.SearchSharePointEvent: Contains the static method SearchSharePointForDocuments that is responsible for starting a workflow process and mapping the context data of the event to process data fields.

    SearchSharePointForDocuments(string keyword, string requestor)
  • SearchSharePoint: Contains the SearchResults workflow process that executes a search across document libraries in SharePoint for documents matching the keyword and returns the results in an e-mail to the requestor.

The following steps will help you get the SMTP Event Bus Sample running on your system.

This example assumes that Visual Studio is installed on the same machine as the K2 server.

  1. Download and open the example solution SourceCode.EventBus.Samples.SMTP.sln.

    The example assumes that the solution folder has been extracted to the root of the C drive.

    All project files and references are configured for K2 blackpearl installed in the default C:Program FilesK2blackpearl directory. If your directory is different, you will need to change the following:

    • All project References

    • All Build Output directories on the projects

    • All configuration file links in the Solution Items folder

    • All XML configuration file values listed below

    The example assumes that there is an e-mail account SearchSharePoint with an SMTP drop at C:InetpubmailrootMailboxdenallix.comP3_SearchSharePoint.mbx. Change this value in the SourceCode.EventBus.Samples.SMTPEventRecorder.dll.config if necessary.

    The sample assumes that the files in the Sample Documents directory are loaded into the Shared Documents library on the http://portal.denallix.com/sites/sales. Reconfigure the SearchSharePoint workflow project to change this location.

    Although the projects are configured to deploy the assemblies to the correct locations automatically, the step to copy the assembly to the appropriate location is listed here for reference.

  2. Deploy the SMTP Event Recorder.

    • Build the SourceCode.EventBus.Samples.SMTPEventRecorder project.

    • Copy the assembly to C:Program FilesK2 blackpearlHost ServerBinSourceCode.EventBus.Samples.SMTPEventRecorder.dll.

    • Add a Recorder to the <eventrecorders> section of C:Program FilesK2 blackpearlHost ServerBinSourceCode.EventBus.Server.config to let the Host Server know about the new recorder. Insert this section above <mappings> if it doesn't exist.

      <eventrecorders>
      <recorder name="SMTP Event Recorder"
      assembly="SourceCode.EventBus.Samples.SMTPEventRecorder "
      type="SourceCode.EventBus.Samples.SMTPEventRecorder.Recorder"></recorder>
      </eventrecorders>
  3. Deploy the Generic XML Mapper.

    • Build the SourceCode.EventBus.Samples.GenericXmlMapping project.

    • Copy the assembly to C:Program FilesK2 blackpearlBin SourceCode.EventBus.Samples.GenericXmlMapping.dll.

    • Add a Mapping to the <mappings> section of C:Program FilesK2 blackpearlHost ServerBinSourceCode.EventBus.Server.config.

      <mapping guid="B6477085-403F-4D65-8C58-81A015BE63C0" assemblyfullname="C:Program
      FilesK2 blackpearlBinSourceCode.EventBus.Samples.GenericXmlMapping.dll"
      assemblytyperesolver="SourceCode.EventBus.Samples.GenericXmlMapping.XmlDataResolver"
      assemblytypeprovider="SourceCode.EventBus.Samples.GenericXmlMapping.XmlDataProvider" />
    • Add a Resolver to the <resolvers> section of C:Program FilesK2 blackpearlHost ServerBinSourceCode.EventBus.Mapping.dll.config.

      <resolver id="B6477085-403F-4D65-8C58-81A015BE63C0" assembly="C:Program FilesK2
      blackpearlBinSourceCode.EventBus.Samples.GenericXmlMapping.dll"
      assemblytype="SourceCode.EventBus.Samples.GenericXmlMapping.XmlDataResolver" />
  4. Deploy the Object Browser.

    • Build the SourceCode.EventBus.Samples.SMTPObjectBrowser project.

    • Copy the assembly to C:Program FilesK2 blackpearlBin SourceCode.EventBus.Samples.SMTPObjectBrowser.dll.

    • Add an ObjectBrowser to the <eventbusobjectbrowsers> section of C:Program FilesK2 blackpearlWorkSpaceSiteweb.config.

      <objectbrowser id="C2815731-5997-4A9F-9837-EBCE48C6FF3F" displayname="SMTP Object
      Browser" assemblyfullname="C:Program FilesK2
      blackpearlBinSourceCode.EventBus.Samples.SMTPObjectBrowser.dll"
      assemblytypeprovider="SourceCode.EventBus.Samples.SMTPObjectBrowser.ObjectBrowser"
      imageclosed="images/OB/folder_closed.gif" imageopen="images/OB/folder_open.gif"
      connectionstring="" />
  5. Deploy the Custom Action Event.

    • Build the SoureCode.EventBus.Samples.SearchSharePointEvent project.

    • Copy the assembly to C:Program FilesK2 blackpearlHost ServerBin SourceCode.EventBus.Samples.SearchSharePointEvent.dll.

    • Add an Assembly (for custom notification) to the <assemblies> section of C:Program FilesK2 blackpearlHost ServerBinSourceCode.EventBus.Assemblies.config.

      <assembly displayname="Search SharePoint Process" fullname="C:Program FilesK2
      blackpearlHost ServerBinSourceCode.EventBus.Samples.SearchSharePointEvent.dll" />
  6. Deploy the SearchSharePointSearchResults workflow process shown in Figure 21-12.

    Figure 21-12

    Figure 21.12. Figure 21-12

Once the previous steps are completed, you should execute an IISRESET and restart the K2 blackpearl server in console mode. You will see the SMTP Event Recorder load (see Figure 21-13).

Figure 21-13

Figure 21.13. Figure 21-13

The final steps in this sample involve configuring the new SMTP event to start the workflow process.

  1. Within K2 Workspace, navigate to Notification Events

    Figure 21-13
  2. Provide a Name and Description and select a Location (see Figure 21-14), and then click Next.

    Figure 21-14

    Figure 21.14. Figure 21-14

  3. Select the event raised by the SMTP Event Recorder by selecting SMTP Object Browser

    Figure 21-14
    Figure 21-15

    Figure 21.15. Figure 21-15

  4. Configure the Custom Action by clicking Add Action (see Figure 21-16).

    Figure 21-16

    Figure 21.16. Figure 21-16

  5. Click Search, select Search SharePoint Process from the list of Available Assemblies (see Figure 21-17), and then click Next.

    Figure 21-17

    Figure 21.17. Figure 21-17

  6. Select SourceCode.EventBus.Samples.SearchSharePointEvent.StartProcess (see Figure 21-18), and then click Next.

    Figure 21-18

    Figure 21.18. Figure 21-18

  7. Select SearchSharePointForDocuments (see Figure 21-19), and then click Finish.

    Figure 21-19

    Figure 21.19. Figure 21-19

  8. Select the From field in the Object Browser on the left, and drag-and-drop it to the requestor field in the Action Parameters section in the lower right (see Figure 21-20). Drag-and-drop the Subject field to the keyword Action Parameter, and then click Finish.

    Figure 21-20

    Figure 21.20. Figure 21-20

  9. Click Return to landing.

The configured custom event will now appear in the list (see Figure 21-21).

Figure 21-21

Figure 21.21. Figure 21-21

The sample is now fully configured. You can verify that everything is working by sending an e-mail with "xbox" in the subject to the SearchSharePoint e-mail address (see Figure 21-22).

Figure 21-22

Figure 21.22. Figure 21-22

This will cause an event to be raised to the Event Bus and the SearchResults workflow process to execute sending the e-mail shown in Figure 21-23.

Figure 21-23

Figure 21.23. Figure 21-23

The SMTP Event Bus Sample is a great example of the extensibility and power of the K2 blackpearl platform. The Event Bus allowed us to easily monitor an external system for events and execute a workflow process, using the contextual data of the event. The application of this concept in the enterprise is very exciting.

Summary

The Event Bus is a powerful addition to the K2 platform. It serves as a mechanism to allow external LOB system events to affect the K2 platform, to send custom notifications designed in the K2 Workspace, to launch processes based on custom events and data contained within those events, and to schedule recurring events. The Event Bus is a critical component that brings reliable, message-based event processing to the K2 platform. In the next chapter we'll look at how to take advantage of some of the advanced features of K2 blackpearl as well as some advanced process scenarios.

Notes

[21]



[21] "Event-Driven Business Process Management" by Rainer von Ammon, et al. 8.dis.uniroma1.it/pdf/fa-ammohttp://debs08.dis.uniroma1.it/pdf/fa-ammon.pdf

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset