Step 1: Create a Custom Event Handler

In this step, you create a custom event handler that generates an advance shipping notice (ASN) message in XML format.

You perform the following procedures in this step.

Procedure Description

To create an event handler class

This procedure has instructions to create a custom event handler class that derives from the RfidEventHandlerBase class.

To implement the GetEventHandlerMetadata method

This procedure has instructions to implement the GetEventHandlerMetadata method to support parameters for the event handler.

To implement the Init method

This procedure has instructions to implement the Init method to support initialization of the event handler.

To implement the ProcessTagReadEvent method

This procedure has instructions to implement the ProcessTagReadEvent method to support processing an event.

To build the event handler assembly

This procedure has instructions to build the event handler assembly (myeventhandler.dll).

  1. Click Start, point to All Programs, point to Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

  2. In Visual Studio, click File, point to New, and then click Project.

  3. In Project Types, select Visual C#.

  4. In Visual Studio Installed Templates, select Class Library.

  5. For Location, type c:\rfidtutorial.

  6. For Name, type MyEventHandler.

  7. Clear the Create directory for solution option.

  8. Click OK to close the New Project dialog box.

  9. In the Solution Explorer window, right-click Class1.cs, and then click Rename.

  10. Type MyEventHandler.cs, and then press ENTER.

  11. Confirm that the name of the class is changed from Class1 to MyEventHandler in the editor.

  12. In the Solution Explorer window, right-click References, and then click Add Reference.

  13. Click the Browse tab.

  14. Navigate to the bin subdirectory (C:\Program Files\Microsoft BizTalk RFID\bin) of the BizTalk RFID installation directory.

  15. Select Microsoft.Rfid.Design.dll, and then click OK.

  16. Repeat instructions 12, 13 and 14 to add references to the Microsoft.Rfid.SpiSdk.dll and Microsoft.Rfid.util.dll assemblies.

    Dd352454.note(en-us,BTS.70).gifNote
    You can also multiple-select the assemblies by pressing CTRL and the assembly names.

  17. If the MyEventHandler.cs file is not open in the editor, double-click MyEventHandler.cs in the Solution Explorer window to open it.

  18. Add the following statements at the beginning of the file after the existing using statements:

    using Microsoft.SensorServices.Rfid;
    using Microsoft.SensorServices.Rfid.Utilities;
    
  19. Modify the MyEventHandler class to derive from the RfidEventHandlerBase class:

    public class MyEventHandler : RfidEventHandlerBase
    

  1. Add a public static method named GetEventHandlerMetadata to the MyEventHandler class as shown in the following code fragment:

        public static RfidEventHandlerMetadata GetEventHandlerMetadata(bool vendorextensionalso)
        {
        }
    
    Dd352454.note(en-us,BTS.70).gifNote
    A custom event handler class must implement a public static method named GetEventHandlerMetadata to support configuration of an event handler. The signature of the method must be the same as the one shown in the preceding code fragment. RFID Manager invokes this method to obtain metadata about the event handlers and populate the property grid.

  2. Add the following code to the GetEventHandlerMetadata method to support two parameters—LogRequirement and ASNOutputFolder. When LogRequirement is set to true, the event handler logs information to the process log file. The event handler generates an advance shipment notice (ASN) to the ASNOutputFolder folder.

            RfidEventHandlerMetadata metadata;
            Dictionary<string, RfidEventHandlerParameterMetadata>    parameters = new Dictionary<string,   RfidEventHandlerParameterMetadata>();
            parameters.Add("LogRequirement", new   RfidEventHandlerParameterMetadata(typeof(bool), "Logging Required", true, false));
            parameters.Add("ASNOutputFolder", new   RfidEventHandlerParameterMetadata(typeof(string), "Advance Shipping Notice Output Folder", null, true));
            metadata = new RfidEventHandlerMetadata("MyEventHandler",   parameters);
            return metadata;
    
    Dd352454.note(en-us,BTS.70).gifNote
    The RfidEventHandlerMetadata object in the preceding code maps the name of the event handler to a parameter dictionary. The parameter dictionary in the preceding code contains two keys—LogRequirement and ASNOutputFolder. The values for these keys in the dictionary are parameter metadata describing the type of the parameter, default value for the parameter, and so on.

  1. Right-click RfidEventHandlerBase in the editor, and then click Implement Abstract Class. You should see the Init method added to the MyEventHandler class.

    public override void Init(Dictionary<string, object> parameters, RfidProcessContext container)
    {
         throw new Exception("The method or operation is not implemented.");
    } 
    
  2. Remove the statement that throws an exception from the Init method.

    public override void Init(Dictionary<string, object> parameters, RfidProcessContext container)
    {
    }
    
    Dd352454.note(en-us,BTS.70).gifNote
    You should use the Init method to initialize an event handler. In this scenario, you could use the Init method to extract the values for the LogRequirement and ASNOutputFolder parameters that are set at design time by using RFID Manager.

  3. Add two private member variables to the class to hold the values of the LogRequirement and ASNOutputFolder parameters of the event handler as shown in the following code:

        private bool logRequired;
        private string ASNOutputFolder;
    
  4. Add the following code to the Init method to initialize these member variables with the values of the parameters LogRequirement and ASNOutputFolder.

            if (parameters == null)
                return;
            if (parameters.ContainsKey("LogRequirement"))
                logRequired = (bool)parameters["LogRequirement"];
            if (parameters.ContainsKey("ASNOutputFolder"))
                ASNOutputFolder = (string)parameters["ASNOutputFolder"]; 
    
    Dd352454.note(en-us,BTS.70).gifNote
    The first parameter that BizTalk RFID passes to the Init method is a dictionary of parameters to the event handler and their values.

  5. Based on the value of the LogRequirement parameter, you may want to initialize a logger object that you can use to log information to the process log file. Add the following method and declare two variables as shown in the following code fragment to support logging:

        private Level logLevel;
        private static ILogger myLogger;
    
  6. Add a method named InitializeLog as shown in the following code fragment:

        internal void InitializeLog(RfidProcessContext container)
        {
            if (myLogger != null)
                return;
            string loggerName = this.GetType().Name;
            myLogger = RfidProcessContext.GetLogger(loggerName);
            //inherit log level from the process
            myLogger.CurrentLevel = RfidProcessContext.GetLogger(container.ProcessName).CurrentLevel;
            logLevel = myLogger.CurrentLevel;
            myLogger.Info("starting logging for {0}", loggerName);
        } 
    
    Dd352454.note(en-us,BTS.70).gifNote
    An event handler should use the logger object returned by the GetLogger method of the RfidProcessContext object to log any information. This causes all the information logged by any event handler in the same process to be in one log file.

    Dd352454.note(en-us,BTS.70).gifNote
    An event handler should use the logging level configured by the user to determine the type of information to log to its log file. The preceding code uses the logging level of the process.

  7. Add a statement to invoke the InitializeLog method from the Init method as shown in the following code fragment:

        if (logRequired)
            InitializeLog(container); 
    
    Dd352454.note(en-us,BTS.70).gifNote
    BizTalk RFID passes the RfidProcessContext object as a second parameter to the Init method. The Init method then passes the RfidProcessContext object to the InitializeLog method as a parameter.

  1. Add an event handler method to the class as shown in the following code fragment:

        [RfidEventHandlerMethod]
        public TagReadEvent ProcessTagReadEvent(TagReadEvent tagReadEvent)
        {
        } 
    
    Dd352454.note(en-us,BTS.70).gifNote
    An event handler method must be annotated with the RfidEventHandlerMethod attribute.

    Dd352454.note(en-us,BTS.70).gifNote
    The ProcessTagReadEvent method in the preceding code takes a TagReadEvent as an input parameter, processes it, and returns a TagReadEvent as an output parameter for the next event handler in the event handler pipeline to process the event.

  2. Add the following code to the ProcessTagReadEvent code to generate an advance shipment notice (ASN) message:

            if (logRequired) myLogger.Log(String.Format("At the beginning of the ProcessTagReadEvent method. Event is: {0}", tagReadEvent), logLevel);
    
            try
            {
                //Generate ASN, and drop it to the output folder
                XmlDocument doc = new XmlDocument();
                string PONum = (string)tagReadEvent.VendorSpecificData["PONumber"];
                string ItemID = (string)tagReadEvent.VendorSpecificData["ItemID"];
                string ASNXml = "<ASN><PONumber>" + PONum + "</PONumber><ItemID>" + ItemID + "</ItemID><ShippedDate>" + DateTime.Now.ToString() + "</ShippedDate></ASN>";
                doc.LoadXml(ASNXml);
                doc.Save(ASNOutputFolder + "\\ASN_" + System.Guid.NewGuid().ToString() + ".xml");
            }
            catch (Exception ex)
            {
                if (logRequired) myLogger.Log(String.Format("exception {0}", ex), Level.Error);
               }
    
            if (logRequired) myLogger.Log(String.Format("At the end of the ProcessTagReadEvent method. Event is: {0}", tagReadEvent), logLevel);
    
        return tagReadEvent;
    
    Dd352454.note(en-us,BTS.70).gifNote
    The preceding code uses the values of ItemID and PONumber in the vendor-specific data of the tag-read event posted to the process to generate an advance shipment notice (ASN) message.

  3. Add the following statement at the beginning of the file after the existing using statements:

    using System.Xml; 
    
  4. Add another event handler method that takes an array of RfidEventBase as a parameter, and add the code to the method as shown in the following code fragment:

        [RfidEventHandlerMethod]
        public TagReadEvent ProcessTagReadEvent(RfidEventBase[] tagReadEvents)
        {
            TagReadEvent tagReadEvent = (TagReadEvent) tagReadEvents[0];
            return ProcessTagReadEvent(tagReadEvent);
            // Handles only the first tagRead event in the array, the other events in the array are ignored.
        }
    
    Dd352454.note(en-us,BTS.70).gifNote
      In the later steps, you will be using a RuleEnginePolicyExecutor event handler ahead of this component in the event handler pipeline. The output type of the RuleEnginePolicyExecutor must match the input type of at least one of the event handlers of this class. That is the reason why you are creating this method that takes an array of RfidEventBase objects as a parameter.

  1. In the Solution Explorer window, right-click MyEventHandler, and then click Build.

  2. Resolve any build errors by verifying the code in your event handler against the code in the instructions of this step.

Dd352454.note(en-us,BTS.70).gifNote
In the next step, you will copy the myeventhandler.dll assembly to the processes\TutorialProcess\bin directory in your BizTalk RFID installation directory so that you can use the event handler in the TutorialProcess process.

The following comments apply to this step:

  • The name of an event handler method can be any valid method name. This custom event handler uses the name HandleTagReadEvent to make its function obvious.

  • When you deploy an event handler, you can also initiate a custom installation action that is required for the event handler to function. For example, deploying a custom event handler might create a SQL Server database or a table within a database to store the data needed by the event handler. To deploy an event handler, you call the Deploy method. Likewise, to remove an event handler, you call the Undeploy method. For more information, see Event Handler Deployment.

  • The Event Handler Template sample ships with a Visual Studio template that you can use to create an event handler. To develop an event handler component using the template, you need to create a new project using the template and implement the methods in the RfidEventHandlerBase class. For more information, see the readme document shipped with the Event Handler Template sample.

Now that you have completed this step, perform Step 2: Modify the Process to Use the Custom Event Handler, which gives you step-by-step instructions for configuring the process to use the custom event handler you created in this step.

Show: