Showing posts with label ServiceBus. Show all posts
Showing posts with label ServiceBus. Show all posts

Saturday, January 10, 2015

Slides from Calgary Azure Dev Camp

On January 10, 2015 I had the opportunity to speak about the Azure Service Bus.  This was an introductory presentation on the subject, but I  was able to sneak in a more complex demo at the end that includes Azure Mobile Services and BizTalk.  I have uploaded the slides to slideshare below.  If you want to see a video of the the final demo you can view that on Channel 9.


Sunday, June 2, 2013

Introducing Windows Azure BizTalk Services Preview –Part 1

 

On Monday, June 3rd Microsoft announced the Preview of Windows Azure BizTalk Services (aka WABS or just BizTalk Services).  Windows Azure BizTalk Services is a managed service provided by Microsoft.  More specifically you can think of BizTalk Services as a Platform as a Service (PaaS) offering.  Recently, I had an opportunity to work with this platform as I was involved in an NDA event in New York City.  While I was preparing for that presentation I took the opportunity to document some of my learnings so that I could share them when the content was no longer considered NDA.  With the TechEd announcement this information is now considered public hence the timing of this blog post.

The purpose of this offering is to provide customers a way to execute integration scenarios in a cloud based environment.  The idea is that you would design and build your interfaces locally within Visual Studio and then deploy your interface to the cloud where it is executed.

Conceptually we can think of a Windows Azure BizTalk Services much like any other interface that utilizes an Integration platform.  We have source systems, an intermediary where we can perform functions like Message Validation, Enrich, Transformation and Enrich (aka VETE).  We then have the ability Route our message to the appropriate destination system.  The difference with this platform is that the “heavy lifting” is occurring in the Windows Azure cloud as opposed to our On-Premise BizTalk Servers.

image

 

There are some subtle differences between Windows Azure BizTalk Services and BizTalk Server 2013 (On-Premise) solutions.  I say subtle because for an experienced BizTalk person these new concepts are not that big of a leap.  Below is s diagram containing some of the key artifacts and components that make up a BizTalk Service solution.

image

Bridges

The term that jumps out at you is probably Bridges. What is a Bridge? A Bridge is a message processing entity.  Probably the closest BizTalk construct that you can relate a Bridge to is an Orchestration but there are differences.  The reason why Orchestration is “kinda close” is that it groups a series of action or processes together within one logical container.

image

Bridges include Sources, Pipelines and Destinations.  Currently within the Windows Azure BizTalk Services Preview we have 3 types of Bridges:

  • Xml One-Way Bridge
  • Xml Request-Reply Bridge
  • Pass-Through Bridge (for message transport)

Within a Pipeline we can call transformations, perform validations, encode, decode or enrich messages.

We also have 3 types Source types:

  • FTP/S
  • HTTP
  • SFTP

and 9 Destination types:

  • FTP
  • One-Way External Service Endpoint (No Service Bus connectivity)
  • One-Way Relay Endpoint (Service Bus connectivity)
  • Service Bus Queue
  • Service Bus Topic
  • SFTP Destination
  • Two-Way External Service Endpoint
  • Two-Way Relay Endpoint (Service Bus connectivity)

Technically this Destination list is not fully complete.  We also have the ability to communicate with On-Premise LOB systems which I will go through in another Blog Post.

SDK Installation

Even though our BizTalk Services run in the cloud, we still perform our development activities within Visual Studio.  Currently Visual Studio does not ship with the appropriate templates that allow us to build BizTalk Services solutions.  However, we can get these templates from the Windows Azure BizTalk Services SDK.

The installation is pretty straight forward and I have included some screen shots below.

Note: On 64 bit machines only need to install the 64 bit SDK

 

image

 

image

image

image

image

 

Visual Studio Experience

When we launch Visual Studio 2012 we will discover a new C# templates under the BizTalk Services node:

image

If we choose BizTalk Service we see a blank diagram that allows us to drop a Bridge and Source or Destination endpoints onto it.

image

If we choose BizTalk Service Artifacts we will see a new project that does not include a bridge but a Transformation (map) and two sample schemas.

image

If we choose the BizTalk Service Project template we have more capabilities as we can drop any of the following Artifacts/Actions onto our canvas.

image

 

In the image below I have modeled a scenario just to visualize what building an interface in BizTalk Services may look like.  In this scenario we are a company that specializes in managing Request For Information (RFI) processes. Organizations that have projects that they would like vendor responses to will send us these requests and we will publish this information to our trusted vendor network that allow them to be informed of these opportunities. 

In this scenario I have an XML One-Way Bridge which will expose an HTTP(s) Endpoint.  Within this bridge we will perform an transformation from the message type that was sent by our customer requesting RFI information into a message type that all of our Vendor partners are expecting. Once we have transformed this message, we need to drop it on a Service Bus topic. 

image

Much like a BizTalk Server project we will start with our schemas.  This schema editor is very similar, if not the same, as the BizTalk Server schema editor. The first schema that we will build represents our client request.

 

image

Next we will create a schema that we use with our strategic vendors who subscribe to our service. You will notice that there are more fields in the partner schema.  This is where the value of our firm comes from as we have direct communication with client and have some additional insight into their project about whether the project is likely to proceed and will also expose the name of the customer.  Typically these values would be looked up from a CRM system but for now we will keep it simple and include it in the map.

image

Next we will add a Transformation(or Map) to our solution that will allow us to transform our CustomerRequest into a PartnerRequest message.

Getting deep into the mapper is outside the scope of this post but you will see some new “functoids” or what are now being called Message Operations.  Some of these new capabilities include ForEach, MapEach, If-Then-Else, List Operations and YES you can call custom code.

image

Once we have defined our Schemas and Maps we can now configure our XML Bridge.  Within this bridge we will specify our message type that we will be receiving (CustomerRequest).  We will also specify our Xml Transform (Map).  Since we are not dealing with flat files and do not have any Validation requirements we will leave those stages in their defaulted stage.

image

We now need to wire up the output of our Bridge to our Destination endpoint which is a Service Bus Topic.  We will do so by selecting a Connector operation and then connect the dots(kinda like in Viso) between our Bridge and Topic endpoint.

 

image

Now remember that we can perform message routing in BizTalk Services.  To set our Routing patch we will need to click on the line that we drew from our Bridge to our Topic.

image

We now need to click on the Filter Condition.  In this case we are not going to restrict any messages from continuing to our topic so we will select Match All but we do have the ability to create a filter based upon message content.

image

Next we will change our focus to the Service Bus Topic.  We need to configure this endpoint by clicking on it and then modifying the PartnerTopic.config (filename will vary) file for it.  Within this config file we will specify our Service Bus namespace, topic name,Issuer Name and Key.  Please note that these are production Service Bus entities and have nothing to do with the BizTalk Services Preview environment.

image

We also want to rename our XMLOneWayBridge so that we are not using the default name since this name will makeup part of our URI. 

image

Lastly we want to specify our endpoint where our Bridge can be contacted. To do this click on any empty space on the canvas and then modify the Deployment Endpoint.  (Note the endpoint below is fictitious).

image

At this point we can now deploy our solution to Windows Azure BizTalk Services.  We can do so by right mouse clicking on our Visual Studio Solution and selecting Deploy Solution. Here is where we want to specify our BizTalk Services environment configuration.  You cannot use your Production Windows Azure credentials here.

image

The deployment only takes a few seconds and when it is completed we should see a message like the following:

image

Testing

Part of the SDK that we just installed includes utilities that can be used when Sending and Receiving messages to/from BizTalk Services.  We are going to go ahead and leverage the MessageSender application.

The Message Sender Application is a command line tool that is expecting the following inputs:

  • ACS Namespace (for BizTalk Services environment)
  • Issuer Name
  • Issuer Key
  • Bridge Endpoint Address
  • File location to message you want to send
  • Content Type

image

The result is that our message has been sent to our bridge successfully.

image

If we go to the Windows Azure Production portal we will discover that we have a message within our Subscription.

image

Conclusion

If some of this looks familiar it is because it is!.  This is the evolution of what use to be called Windows Azure EAI/EDI Labs.  It is now being branded underneath the “BizTalk” brand which makes sense on a few levels in my opinion.  For instance the team that is working on this new service is the same team responsible for the BizTalk Server product.  One thing you will hear the product team speak to is that there is “ONE BIZTALK”. One platform with many capabilities including BizTalk Server On-Premise, BizTalk Server running as Infrastructure as a Service (IaaS) and now BizTalk Services which is running as a Platform as a Service offering.

There is another huge aspect to BizTalk Services that has been neglected from this post as I just am not familiar with it but EDI in the cloud also makes up a substantial part of this offering and arguably provides the greatest area of opportunity.

I am just getting started with blogging about BizTalk Services.  Stay tuned for my next post on how to integrate On-Premise Line of Business Applications(SAP)  with BizTalk Services.

Wednesday, May 8, 2013

Presentation from recent talks

In the past week I have had the opportunity to speak at two events.  On May 1st I spoke at the Phoenix Connected Systems User Group and on May 6th I gave two presentations at the BizTalk Bootcamp in Charlotte.

It was a lot of fun putting these demos together and I received a lot of good feedback so hopefully you will also benefit from them.  You can find the slide deck here: http://sdrv.ms/12fBU53

Note: Some of the Service Bus slides were borrowed from Clemens Vasters’ deck which he has made freely available here.

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.