Tuesday, February 5, 2013

Service Bus Notification Hubs-Part 4 The Solution

It has been fun discovering Service Bus Notifications. I have received some good feedback over Twitter recently and have also shown my demo to some colleagues over the past week with some great responses.

In my last post we discussed the solution at a high level.  Within this post we are going focus on the actual implementation.  I will warn you in advance that this post will be fairly lengthy so buckle up.  If you find the walkthrough too long, be sure to check the video at the end of the post that will show this solution live in action.

I am going to break this post up into 5 Sections:

  1. Creating Service Bus Queues
  2. Creating Customer Power Outage Application
  3. Creating PLT Application
  4. Creating BizTalk Application
  5. Testing/Demo

Section 1: Creating Service Bus Queues

The area that we are going to focus on in this section is highlighted below in green.  In total we are going to create 3 Queues.

image

The 3 Queues are called:

  • customerqueue
  • createworkorder
  • updateworkorder

The Queues were created from the WindowsAzure.com portal using the default settings.

image

 

Section 2: Creating Customer Application

Moving on, we are going to focus on the Customer facing application.  In this case I am running the application on the SurfaceRT but you certainly do not require a SurfaceRT to run it.  In my case I just needed to ensure that my app is being compiled for ARM as opposed to x64.

I will also caution that I am by no means a Windows 8 store app expert.  So if you are looking for a fancy UI or UX you aren’t going to find it here.  I approaching this blog post from an integration perspective.

image

In order to build this sample you will need a Windows Store development account.  If you have an MSDN account you already have some entitlements so it won’t cost you extra.  Otherwise you can expect to pay some money(it may vary by country so I will just leave it there).

Let’s get started:

  • Open Visual Studio and create a new Windows Store Application.  We need to select Grid App (XAML) in this case.

image

  • If you open the GroupItemsPage.xaml you will discover a GridView that contains many repeating Items.  To simplify our app, we will just delete this markup and create something a little simpler.
  • Drag some text boxes and labels onto the design canvas.  Don’t worry about the Current Weather and Weather Warnings images.  Those are simply static images used to improve the user experience.  If you are following along, here are the actual names of the text fields, labels, checkboxes and button that were used:
    • txtSiteId
    • txtName
    • txtAddress
    • listCity
    • chkETR
    • chkConfirmPowerOn
    • btsSubmitOutage

image

  • With our GUI now set, lets double click on the btsSubmitOutage button to create a click event handler.  Within this handler we will have the following code:

private void btsSubmitOutage_Click(object sender, RoutedEventArgs e)
{
     txtStatus.Text = "";
     CustomerPowerOutage cust = new CustomerPowerOutage();
     cust.SiteID = txtSiteId.Text;
     cust.CustomerName = txtName.Text;
     cust.Address = txtAddress.Text;
    
     ListBoxItem selected =(ListBoxItem) listCity.SelectedItem;
     cust.City = selected.Content.ToString();

     bool requestETR = (bool) chkETR.IsChecked;
     bool requestPowerOnConfirmation = (bool) chkConfirmPowerOn.IsChecked;

     SendMessageToQueue(cust,requestETR,requestPowerOnConfirmation);
    
}

  • You may have noticed that there are a couple things missing: what is this CustomerPowerOutage object and where is the code listing for the SendMessageToQueue? 
  • The CustomerPowerOutage is just a class that we will use to capture/store this data from the form.  This object will get serialized so that it can be processed by BizTalk as an XML document.

namespace CustomerPowerOutageApp
{
    public class CustomerPowerOutage
    {
        public string SiteID { get; set; }
        public string CustomerName { get; set; }
        public string Address {get;set;}
        public string City { get; set; }
    }
}

  • The SendMessageToQueue method’s code is listed below.  This method is responsible for communicating with the customer queue that we created in the previous section.  A pre-requisite for this function is a library, or dll, that will allow us to communicate with Service Bus.  In this case we can’t use the typical Microsoft.ServiceBus.dll that is available in Nuget.  Instead we need to get the Service Bus WinRT Managed SDK which is available here.   In order to use this functionality provide the following reference: using Microsoft.WindowsAzure.Messaging;.
  • You will notice in this code that we are going to set some message properties.  We can think of these properties to be much like brokered messaging properties but since we are not explicitly using the BrokeredMessaging object I won’t call them that.  Another thing to note is that we are using the async model in this case which is different from some of the console app style samples that you may be use to.

private async void SendMessageToQueue(CustomerPowerOutage cust,bool requestETR, bool requestPowerOnConfirmation)
    {
       
        Message m = new Message(cust, new DataContractSerializer(typeof(CustomerPowerOutage)));
        m.Properties.Add("RequestETR", requestETR);
        m.Properties.Add("RequestPowerOnConfirmation", requestPowerOnConfirmation);
        await CustomerQueue.SendAsync(m);
        txtStatus.Text  = "Power Outage Ticket has been successfully received.";
    }

  • The next question is probably: I haven’t created a connection yet so how can I send this message?  Very true, this is something that we need to do and can be done in the constructor of this class:

private Queue CustomerQueue = null;
    public GroupedItemsPage()
    {
        this.InitializeComponent();
        CustomerQueue = new Queue("CustomerQueue", "Endpoint=sb://<your_namespace>.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=<your_key>");
   
    }

At this point we have built the GUI, created a contract that we can use to exchange data with BizTalk, and sent a message to Service Bus Queue.  What is missing though is that our Customer Power Outage Application will receive Service Bus Notifications (Toast Notifications). This is represented as step 11 in the Solution Overview images.  Since we are in this application, lets do this now.

  • Right click on our project and select Store –> Associate with App Store…
  • Sign In with your app store credentials
  • Click the Reserve Name link

image

  • Give your App a unique name

image

  • Provide a unique name.  Theoretically, your app could end up in the App Store so this is why you need a unique name and can’t use the name that has been used in this blog post.

image

  • Click Save  to reserve this app name.

image

  • Next we want to click on the Advanced features link.  This is where we are going to enroll our application to support receiving push notifications.
image
  • Click on the Push notifications and Live Connect services info link

image

  • Click on the Authenticating your service link

image

  • Make a note of both the Package Security Identifier (SID) and Client secret. We will need both of these values when we create our Service Bus Notification Hub in the Windows Azure portal.

image

  • Now we do need to move over to the WindowsAzure.com portal where we will create our Notification Hub.  Log into the portal, select Service Bus, then the namespace that you want to use, followed by click on Notification Hubs.

image

  • Click the New button and then App Services –>Service Bus Notification Hub –> Quick Create and then provide a unique Notification Hub Name.

image

  • We now need to double click on our newly created Hub Notification and then click on the Configure link.

image

  • We now want to provide the Package SID and Client Secret that we previously generated.  If we have a an Apple Certificate thumbprint we could put it here but Apple is out of scope for this blog post.

image

  • In order receive Toast Notifications, we need to enable our application to accept them.  In order allow this we need to double click on the Package.appxmanifest file and then set Toast capable to Yes.

image

At this point we have finished our configuration for Service Bus Notification Hubs.  We now need to wire up some code within our application in order to take advantage of this configuration.

  • In our App.xaml.cs file we need to include the following references.

using Microsoft.WindowsAzure.Messaging;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

  • Next we want to create a class level variable called notificationHub.

NotificationHub notificationHub;

  • Within our class constructor we need to provide our connection details.

     /// <summary>
     /// Initializes the singleton Application object.  This is the first line of authored code
     /// executed, and as such is the logical equivalent of main() or WinMain().
     /// </summary>
     public App()
     {
         var cn =
         ConnectionString.CreateUsingSharedAccessSecretWithListenAccess(
         "sb://<your_namespace>.servicebus.windows.net/ ",
         "<your_NotificationHubCredentials>);
         notificationHub = new NotificationHub("PowerOutageNotificationhub", cn);

         this.InitializeComponent();
         this.Suspending += OnSuspending;
     }

  • Note: the Notification Hub Credentials are different than your typical Service Bus credentials.  New credential “modes” have been introduced as part of Notification Hubs.  There are credentials that allow Listen access and credentials that allow for Full access (Publish and Read). To access these credentials go into the Notification Hub portion of the Windows Azure Portal and click on the View SAS Key label.

image

  • In this particular case we want the key that provides Listen rights.  In the BizTalk code later we will use the key that possesses Listen, Manage, Send rights.

image

  • Within the OnLaunched method we want to initialize our Notification registration.

protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {

            await InitializeNotificationsAsync();

……

  • We also want to initialize our Notification registration within the OnActivated method.

protected async override void OnActivated(IActivatedEventArgs args)
     {
         base.OnActivated(args);
         await InitializeNotificationsAsync();
     }

  • Next we need to actually create the InitializeNotificationAsync method.  Within this method we are going to check to see if our registration exists, if it does not we are going to create it.  If we do need to create it then there are a few things that we need to provide in the CreateTemplateRegistrationForApplicationAsync call. The first is the Toast Template that we want to call.  In this case we will use a helper method which will be described shortly.  Next, we need to provide a name for this registration.  Finally we are going to create what is called a Tag. A Tag is basically criteria that we would like to subscribe on.  In this case we will only create one, but it does accept an array of strings if we wanted more.  The value that is being specified here is the customer’s SiteID.  If you go back to the previous GUI screen you should see this value is populated.  In a production system, I would envision a customer going through an enrollment process where they would provide their SiteID.  Then from this method we would simply load it from a configuration store.  This is very important to our scenario though.  When the PLT updates a work order, this SiteID is actually pushed up to the Service Bus Notification Hub and that is how this client will receive a Toast Notification since we are looking for Tags that contain this value.

    async Task InitializeNotificationsAsync()
       {
           await notificationHub.RefreshRegistrationsAsync();

           if (!await notificationHub.RegistrationExistsForApplicationAsync(
                                                            "PowerOutageAppToastReg"))
           {

           await notificationHub.CreateTemplateRegistrationForApplicationAsync(
               BuildTextToastTemplate(), "PowerOutageAppToastReg", new string[] {"0090123456789"});   //Our Customer Site ID
                                                                              
       }
   }

  • Toast Templates are a very important part of the user experience for Service Bus Notifications.  For the purpose of this blog post I am going to keep things short but I suggest checking out this video by Clemens Vasters who can provide this topic more justice.  For the purpose of this blog post we will use the ToastTemplateType.ToastText02 template.  This will allow us to to pass two “parameters” that can be used in our Toast Notification. 

 

XmlDocument BuildTextToastTemplate()
{
     var template =
         ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
     var textNode = template.SelectSingleNode("//text[@id='1']") as XmlElement;
     if (textNode != null)
     {
         textNode.InnerText = "$(msg)";
     }

     var textNode2 = template.SelectSingleNode("//text[@id='2']") as XmlElement;
     if (textNode2 != null)
     {
         textNode2.InnerText = "$(msg2)";
     }

     return template;
}

  • At this point we are done with our Customer Power Outage application.  If we want to perform an initial test we can run our application and submit a message to our Service Bus Queue to ensure it works properly.  To submit a message we simply click Create Power Outage.

image

  • If we navigate to our Windows Azure portal we should see that our CustomerQueue Queue Length Property has a value of 1

image

Section 3: Creating PLT Application

Note: There are aspects of this application that are very similar to the Customer Power Outage scenario so those parts will not be duplicated.  I will try to do a good job of communicating when this happens.

The purpose of this application is that we will have a Power Line Technician (PLT) that will receive a notification indicating that he/she has work to do.  When the PLT is in their application, they will be able to retrieve their order from the Service Bus queue.  As they update the order or close it the information will be sent back to the Service Bus and subsequent Notifications will be sent to the Customer who logged the Power Outage.

image

  • Once again we need to create a Windows Store Application.  We also need to select Grid App (XAML) the project type.
  • Once again I recommend creating your GUI first.  In this case we want to create the following controls:
    • txtSiteID
    • txtName
    • txtAddress
    • txtCity
    • btnRetrieveNextOrder
    • lblETR (hidden)
    • lblETR2 (hidden)
    • txtETR (hidden)
    • btnUpdateETR (hidden)
    • lblPowerRestored (hidden)
    • txtPowerRestored (hidden)
    • lblETR2_Copy (hidden)
    • btnCloseOrder (hidden)
    • txtStatus (hidden)
    • imgMap (hidden – added for effect)

image

  • If we double click on the btnRetrieveNextOrder button, an event handler will be created. Within this event handler we are simply going to call a method called ReceiveMessageFromQueue that will pull a message off of the CreateWorkOrder Queue

    private void btnRetrieveNextOrder_Click(object sender, RoutedEventArgs e)
      {

          ReceiveMessageFromQueue();
      }

  • Within the ReceiveMessageFromQueue method we are going to retrieve a message off of the Queue.  We are going to use a Data Contract Serializer so that we can use a typed message to populate the various text controls that exist on the screen.

private async void ReceiveMessageFromQueue()
{

    var message = await cwo.ReceiveAsync<Message>(new System.TimeSpan(0,0,5));

    var data = message.GetBody<UpdateOrder>(new DataContractSerializer(typeof(UpdateOrder)));

    txtAddress.Text = data.Address;
    txtSiteID.Text = data.SiteID;
    txtName.Text = data.CustomerName;
    txtCity.Text = data.City;

 

    //Retrieve the BrokeredMessaging Properties so that we can later be used by BizTalk to determine whether or not Notifications should be send

    isETRRequired =(bool) message.Properties["RequestETR"];
    isPowerRestoreRequired = (bool) message.Properties["RequestPowerOnConfirmation"];

    //display controls
    lblETR.Visibility = Windows.UI.Xaml.Visibility.Visible;
    lblETR2.Visibility = Windows.UI.Xaml.Visibility.Visible;
    txtETR.Visibility = Windows.UI.Xaml.Visibility.Visible;
    btnUpdateETR.Visibility = Windows.UI.Xaml.Visibility.Visible;

    lblPowerRestored.Visibility = Windows.UI.Xaml.Visibility.Visible;
    txtPowerRestored.Visibility = Windows.UI.Xaml.Visibility.Visible;
    lblETR2_Copy.Visibility = Windows.UI.Xaml.Visibility.Visible;
    btnCloseOrder.Visibility = Windows.UI.Xaml.Visibility.Visible;
    imgMap.Visibility = Windows.UI.Xaml.Visibility.Visible;
    txtStatus.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
     
}

  • Below is the UpdateOrder type that is used to represent a Trouble Order that has been received from a Customer.

namespace PowerLineTechnicianApp
{
   public class UpdateOrder
    {
        public string SiteID { get; set; }
        public string CustomerName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public double ETR { get; set; }
        public double PowerOutDuration { get; set; }
        public string OrderAction { get; set; }
        public bool NotifyETR { get; set; }
        public bool NotifyPowerRestored { get; set; }
    }
}

 

  • When the btnRetrieveNextOrder is pressed and subsequently the order is downloaded.  Some additional controls will be added to the screen.  This includes two buttons that allow us to update the Trouble Order.  The point of the update is to notify the Outage Management System, via BizTalk, of the update.  What we will soon discover is that while this is happening that We can also send messages from BizTalk to a Service Bus Notification Hub.  More on this later.

image

  • In order to update an order we need to wire an Event Handler for the  btnUpdateETR button.  Within here we will populate the UpdateOrder message and send it to the UpdateWorkOrder Service Bus Queue.

private void btnUpdateETR_Click(object sender, RoutedEventArgs e)
  {

      UpdateOrder uo = new UpdateOrder();

      uo.Address = txtAddress.Text;
      uo.City= txtCity.Text;
      uo.CustomerName = txtName.Text;
      uo.SiteID = txtSiteID.Text;
      uo.OrderAction = "UPDATE";
      uo.ETR = System.Convert.ToDouble(txtETR.Text);
      uo.NotifyETR = isETRRequired;
      uo.NotifyPowerRestored = isPowerRestoreRequired;

      SendMessageToQueue(uo);

 
  }

  • The SendMessageToQueue method is not all that different than the method that was written in the Customer Power Outage Application.

    private async void SendMessageToQueue(UpdateOrder  uo )
    {

        Message m = new Message(uo, new DataContractSerializer(typeof(UpdateOrder)));
      

    //Send message Asynchronously
        await uwo.SendAsync(m);
        txtStatus.Visibility = Windows.UI.Xaml.Visibility.Visible;
        txtStatus.Text = "Update Successfully Sent to Outage Management System";

        txtETR.Text = "";
        txtPowerRestored.Text = "";
    }

  • Similar to the btnUpdateETR event handler we will provide similar functionality for the Close button.  The difference is really the OrderAction property.  For the Update process we will set it to UPDATE but for closing the Order we will set it to CLOSED.

private void btnCloseOrder_Click(object sender, RoutedEventArgs e)
{

    txtETR.Text = "";
    txtStatus.Text = "";

    UpdateOrder uo = new UpdateOrder();

    uo.Address = txtAddress.Text;
    uo.City = txtCity.Text;
    uo.CustomerName = txtName.Text;
    uo.SiteID = txtSiteID.Text;
    uo.OrderAction = "CLOSED";
    uo.PowerOutDuration = System.Convert.ToDouble(txtPowerRestored.Text);
    uo.NotifyETR = isETRRequired;
    uo.NotifyPowerRestored = isPowerRestoreRequired;

    SendMessageToQueue(uo);


}

  • Much like the Customer Power Outage Application we need to provide connection strings for this communication to the Service Bus to occur.  We will create these connections within the Constructor of the GroupedItemsPage()

Queue cwo;  //Create Work Order Queue
Queue uwo; //Update Work Order Queue
bool isETRRequired = false; //Used to store the value coming from the Brokered Message Property
bool isPowerRestoreRequired = false; //Used to store the value coming from the Brokered Message Property

//Constructor
public GroupedItemsPage()
{
     cwo = new Queue("CreateWorkOrder", "Endpoint=sb://<your_namespace>.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=<your_key>");

     uwo = new Queue("UpdateWorkOrder", "Endpoint=sb://<your_namespace>.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=<your_key>");

    this.InitializeComponent();
}

  • We have now covered the ability for a PLT to retrieve a message from the Customer Queue and then provide the ability to update or close a work order.  There is still a core missing piece of functionality and that is the Notification Hub capabilities.  Much like the Customer Power Outage Application we need to go through the same steps of:
    • Adding Reference to Microsoft.WindowsAzure.Messaging.dll from the Service Bus WinRT Preview SDK.  By the way, this package includes assemblies for ARM, x86 and x64 so you are covered even if you aren’t using a Surface.
    • Associating App with App Store and allowing for Windows Notification Services
    • Enabling Toast Notifications in the Package.appmanifest
    • Creating another Notification Hub called workorderhub
    • Configuring Notification Hub to use the Windows Notification Service Package SID and Client Secret.
  • Once we have finished our Windows Notification Services and Service Bus Notification Hubs configuration we can create our Notification Hub Registrations within the App.xaml.cs  file.  The following steps need to be completed in order for the application to function properly.
  • Add the following references

using Microsoft.WindowsAzure.Messaging;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
using System.Threading.Tasks;

  • Add the following class level variable and then populate the constructor

sealed partial class App : Application
{

    NotificationHub notificationHub;

    /// <summary>
    /// Initializes the singleton Application object.  This is the first line of authored code
    /// executed, and as such is the logical equivalent of main() or WinMain().
    /// </summary>
    public App()
    {
        var cn =
ConnectionString.CreateUsingSharedAccessSecretWithListenAccess(
"sb://<your_namespace>.servicebus.windows.net/ ",
"<your_listenkey>");
        notificationHub = new NotificationHub("workorderhub", cn);

        this.InitializeComponent();
        this.Suspending += OnSuspending;
    }

  • In the OnLaunched method add the following method call

protected override async void OnLaunched(LaunchActivatedEventArgs args)
      {
          await InitializeNotificationsAsync();

……..

  • Create the following OnActivated method.  Much like before we will check to see if a Notification already exists.  In this case we are looking for a registration called WorkOrderAppToastReg.  If it doesn’t exist then we will create a new registration and include the tag called Airdrie.  In case you are wondering Airdrie is a small city north of Calgary in Alberta.  In this case this PLT is responsible for the city of Airdrie.  When BizTalk publishes a notification that contains the tag of Airdrie, this PLT will receive it.  Once again in a prod system, pulling this value from configuration makes more sense. 

protected async override void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);
            await InitializeNotificationsAsync();
        }

        async Task InitializeNotificationsAsync()
        {
            await notificationHub.RefreshRegistrationsAsync();

            if (!await notificationHub.RegistrationExistsForApplicationAsync(
                                                             "WorkOrderAppToastReg"))
            {

                await notificationHub.CreateTemplateRegistrationForApplicationAsync(
                    BuildTextToastTemplate(), "WorkOrderAppToastReg", new string[] { "Airdrie" });

            }
        }

  • At this point we will want to make sure our application can compile and run.  In this case we will not have a message to retrieve because BizTalk is the system that will place the message on the Service Bus Queue that we are going to pull from.

Section 4: Creating  BizTalk Application

BizTalk is the ‘glue’ that is used to tie this all together.  BizTalk will perform the following functions:

  • Pull the Customer Power Outage message off of the Customer Service Bus Queue
  • Transform this message into a Work Order and place it on the Work Order Create Service Bus Queue
  • Publish a notification to the Service Bus Notification Hub that will contain the Tag of Airdrie.  The PLT that is responsible for Airdrie will receive a Toast Notification. He/She can then click the toast notification and the PLT application will launch.
  • Upon launch the PLT can click the Retrieve Message button and the Work Order will be pulled off of the Service Bus Queue.
  • The PLT can now update the work and click the Update or Close Work Order buttons.  The result is that a message will flow to the Work Order Update Service Bus Queue that BizTalk will be watching.  When a message does arrive in the Queue, BizTalk will pick it up and send it to the Outage Management System (a file drop in this scenario). BizTalk will also use the information that exists within the Work Order message to push a notification to the Service Bus Notification Hub.  Included in this Notification will be a tag that represents a Customer’s SiteID (Customer ID).  Any subscriber that has registered that tag will receive a Notification that their Work Order has been updated and an Estimated Time of Restore exists or that their Work Order has been closed that their Power has been restored.

image

  • Much like any BizTalk project, we will start with creating a few schemas:
    • Within the Customer Application a class exists called CustomerPowerOutage. From a BizTalk perspective we will generate a schema based on a sample XML file of this class.  We will use the same technique that was described in a previous post.  The end result is that we will have a BizTalk schema that looks like this:

image

  • We will also distinguish a few fields to make our lives simpler when sending Service Bus Notification messages.  These fields include:
    • Address
    • City
    • SiteID
  • The next schemas that we need to create is the PLTWorkOrder schema that is based on the class that was discussed in the PLT application.  We will also distinguish several fields to make our lives easier in Expression shapes.  Once again we will generate a schema based upon a technique found in this post.

image

  • The last schema that we are going to create is a PropertySchema.  This PropertySchema will be used to capture the “Brokered” Message properties that are being send from the Customer Power Outage application.  We will see this schema being used later in the BizTalk Administration console.  In this case both fields are of type boolean.

image

  • We will now start with the Orchestrations.  The first one is called ProcessCustomerOutage.odx.

image

  • Within this Orchestration we will receive our CustomerPowerOutage message and then transform it into an instance of a PLTWorkOrder using a map called CustomerOutage_to_PLTWorkOrder.btm

image

  • Since we want to ensure that are “Brokered” Message Properties are carried forth to our PLT application we will want to copy them within a MessageAssignment shape.

image

  • We will now send our instance of the PLTWorkOrder to the logical Send Port.
  • Finally, we will send our Service Bus Notification Hub message from an Expression shape.

image

  • We can dig into this code more by opening the OutageMangementHelper project. Within this project we will discover a helper class called OMSHelper that contains our method called SendWorkOrderNotifcations.  In order to use this code we will need to reference a Nuget Package called Microsoft.ServiceBusPreview and then provide the following using statements:

using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Notifications;

  • The code itself is pretty similar to the code in the client applications.  A core difference is that we need to use the Full Access key instead of the Listen key that was used in the client applications.  Something else that you may notice is; this is where we are providing our 2 “Toast Notification” parameters that will be displayed within our Toast Notification.

public static void SendWorkOrderNotifications(string City, string Address)
{

    var cn = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSecretWithFullAccess(
"<your_namespace>", "<Full_AccessKey”>);
    var hubClient = NotificationHubClient.CreateClientFromConnectionString(cn, "workorderhub");
    hubClient.SendTemplateNotification(new Dictionary<string, string>
                                    {
                                        {"msg", "New Power Outage has been reported"},
                                        {"msg2","Location of outage is: " + Address + ", " + City}
                                    }, "Estimated Time Of Restore", City);

}

  • The next, and last, Orchestration that we are going to dive into is called ProcessWorkOrderUpdate.odx.  The purpose of this Orchestrations is to process Work Order Updates or Work Order Closes and send them to Outage Management System.

image

  • Once the message has been sent to the Logical Send Port we will detect whether or not the Work Order is an Update or a Close message based upon the content within the message and send the appropriate message to Service Bus Notification Hub.  For the purpose of these Toast Notifications we will use the same Notification Hub but we will change our message to our Customer.
  • In order to facilitate these Notification Hub messages, two methods have been created within the OutageManagementSystemHelper project called SendEstimatedTimeOfRestore and SendPowerOutageComplete. In both instances we will be specifying a tag of SiteID.  This will allow our Customer Power Outage app to receive these messages.  What this also ensures is that other Customers who currently have power will not receive these messages since the SiteID is a unique ID for customers. The code listing for both of these methods are below.

 

public static void SendEstimatedTimeOfRestore(string SiteID,DateTime etr)
{

    var cn = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSecretWithFullAccess(
"<your_namespace>", "<Full_AccessKey");
    var hubClient = NotificationHubClient.CreateClientFromConnectionString(cn, "PowerOutageNotificationhub");
    hubClient.SendTemplateNotification(new Dictionary<string, string>
                                    {
                                        {"msg", "Power Outage Estimated Time of Restore"},
                                        {"msg2","Your estimated time of restore is: " + etr.ToString()}
                                    }, "Estimated Time Of Restore", SiteID);

}


public static void SendPowerOutageComplete(string SiteID, double duration)
{

    var cn = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSecretWithFullAccess(
"<your_namespace>", "<Full_AccessKey");
    var hubClient = NotificationHubClient.CreateClientFromConnectionString(cn, "PowerOutageNotificationhub");
    hubClient.SendTemplateNotification(new Dictionary<string, string>
                                    {
                                        {"msg", "Power Outage has been resolved"},
                                        {"msg2","Your total outage time was: " + duration +" hours"}
                                    }, "Estimated Time Of Restore", SiteID);

}

  • We can now deploy our BizTalk Application and configure it.  Don’t forget to GAC your helper assembly!
  • Our first Receive Location is used to retrieve messages off of the Customer Queue.  In the General tab we need to specify our Service Bus Namespace and Queue Name.

image

  • Within the Authentication tab we need to provide appropriate Service Bus credentials.
  • Since our Customer Power Outage App is supplying “Brokered” Message Properties we need to specify the namespace of the Property Schema that we previously created.

image

  • The next Receive Location is used to retrieve messages from the Work Order Queue and is pretty straight forward in the sense that we need to provide our Service Bus Namespace and Queue name.

image

  • Moving onto our Send Ports we also have two.  The first is a Send Port that will use the SB-Messaging Adapter that will send a new Work Order message that will be retrieved by the PLT application.

image

  • Finally we need to create a FILE based Send Port that will send the updated or closed Work Orders to the Outage Management System.

image

Testing: Since there are a lot of moving parts I am going to try something new and record the interactions between these systems.  You can view the video below:

Service Bus Notification Hubs + BizTalk Server 2013 Beta

Conclusion

Overall I am very happy with the way that this solution works.  The funny thing is that about 1.5 years ago at my previous organization we were thinking about doing this exact scenario and supporting mobile devices.  Unfortunately that project never came to fruition but now the Service Bus Notification Hubs are out it makes it a lot easier.

Another important takeaway is that there can be some very important information that is moving through BizTalk.  I hope I have demonstrated that it isn’t to hard to use this information to generate Toast Notifications.  This concept isn’t all that new when you thing of BAM Alerting.  The difference is that we are now longer bound to just emails and can tailor an even better user experience through Toast Notifications.  Another opportunity that was not explored in this post(but maybe a future post) is that we can also update Live Tiles through this same mechanism which will only enhance this user experience.

I hope you have enjoyed this post as much as I have enjoyed putting it together.

2 comments:

Unknown said...

awesome effort guys. must have taken up a few hours but was certainly worth it in the end from the looks of things.

Kent Weare said...

Thanks Adam