Home > AppFabric, Azure, Queue > AppFabric Apps (June 2011 CTP) Simple Service Bus Queue App

AppFabric Apps (June 2011 CTP) Simple Service Bus Queue App


In this post we are going to be discussing a simple app and how this app can communicate with a Service Bus Queue.

Service Bus Queues and Topics(will save this for a future post) were introduced in the May 2011 Service Bus CTP.  While Queuing is far from a new topic, the idea of providing a durable Queue in the cloud is a relatively new topic.

Why Queues?

Queues offer a few benefits in the areas of:

  • Throttling messages to downstream systems.  Some downstream applications may not be able to handle load during burst scenarios so we have an intermediary that can basically store this information in the interim while the downstream system can process the messages at their leisure.  Having the elasticity of the cloud, this becomes a compelling solution knowing that the cloud can scale during burst scenarios even if a client application cannot.
  • Disconnected client scenarios.  A producer may be publishing messages based upon specific events occurring in its system.  In a point-to-point integration scenario, the producer is expecting the consumer to be online so that the consumer can process this message.  The problem with this is that you cannot expect consuming systems to always be available. This becomes extremely relevant in mobile scenarios where people may lose Cellular connectivity.  It also becomes relevant when integrating with trading partners.  Since you cannot control what is happening with the 3rd party system, it is nice to know that you can fulfill your responsibilities and deliver a message to a durable store instead of constantly retrying the messages to the client that’s system is not available.
  • Distribution of workload/Load balancing. We can also use a queue as a central point or “collection” for messages and then use multiple clients pulling data from this queue in a round robin type fashion to distribute the load across multiple worker processes.

Now that we have introduced Queues, lets walk through implementing a simple Queue solution using an AppFabric Application.  The premise behind this simple application is we are running a power company and we want our customers to be able to tell us about power outages using their Mobile Phones.  No we are not going to build a Mobile Phone app, but for this fictitious scenario we will have them fill out a simple web page that they can access from their phone.

When creating a new Visual Studio solution, we want to make sure that we have selected an AppFabric Application

 

image

 

Once in our AppFabric Application we are going to have a blank Design View Canvas.  The first service that we want to add is a ASP.Net Web App.  To do this we will click on the Add New Service label.

image

Then we want to select ASP.Net.

image

 

We now want to add our actual Service Bus Queue

image

With our Web App and Service Bus Queue created, we now want to add a reference from our Web App to our Service Bus Queue.  We can do so by clicking on the Service References Dropdown and selecting the default service called Import1.

image

 

Since a reference called Import1 is not very meaningful we can pull this same drop down and select Import1.  With this value selected we should the property page update and we can rename this value to something more appropriate.

image

With our reference being set, we can jump into the Web application and add some controls to the Default.aspx page.  We want to add two text boxes and a button that will be used to submit the page.

 

image

In the code behind for the Default.aspx page we want to add an event handler for this submit button.

 

protected void btnSubmit_Click(object sender, EventArgs e)
{
   //Create a Queue Client
    QueueClient qc =  ServiceReferences.CreateSimpleSBQueue();

    //Create Message Sender
    MessageSender ms = qc.CreateSender();

    //Created BrokeredMessage
    BrokeredMessage bm = BrokeredMessage.CreateMessage(txtAddress.Text + " " + txtCity.Text);
 
    //Send Message
    ms.Send(bm);
   
    //Close Message Sender
    ms.Close();

    //Close Queue Client
    qc.Close();

}

 

At this point we have all of the code that we need to populate a Service Bus Queue.  Note that we have not written any code to actually create the queue.  The Queue will be provisioned when we publish and deploy our application to the cloud(or local Dev Fabric).  One item that still remains is the Service Bus Queue requires some configuration information in the form of the URI, issuer key and issuer name.

image

 

Having the ability to write to a Queue is great but not very valuable if we cannot retrieve messages from this queue.  We have a few options when it comes to retrieving messages from this queue.  We could write a quick little console application that will pull messages down in an on-premise scenario.  This console could sit within the boundaries of our corporate firewall(s) and make a connection to this Service Bus queue deployed in the cloud.  Since Alan Smith has covered this scenario in one of his web casts I don’t see much of a point in reproducing his steps here.

Instead, we are going to add another “Service Type” to our AppFabric Application.  This service is called a Code Service.  What is a Code Service?  A Code Service is a background worker process that can be used in polling-like scenarios.  You can kind of think of it like as an endless loop that keeps asking it self “do I have any work to do”?  A good example of using a code service may include sending emails out to customers who have just purchased an item off your website.  While sending the email is important to customers it usually does not have to be sent the second that the order has been processed.  Instead you may decide to send out emails every 10 minutes instead of in real time. 

Another good example of using a code service is to pull messages off of a queue.  Perhaps you want to de-queue a message and then update a database or even call a workflow service.  I will leave deciding what to do with this message once it has been de-queued up to the reader but if you followed an earlier post you know that it is not difficult to route messages to a Workflow service. For the purpose of this post, we are simply going to de-queue this message and then write a Trace event that will prove we have retrieved the message from the queue.

To add a Code Service to our project we need to head back to our Design View canvas and click on the Add Service  label.  From the dialog that will appear, we now want to select Code.

image

Since we want to connect to our Service Bus Queue, we need to add a reference to this service much like we had to do from our Web Application.

 

image

 

In our Code Service that was added to our solution we will see a method called Run that will automatically be executed.  This means that we do not need to invoke this code.

By default, a while loop is included that will execute as long as a cancellation request has not been received.  Also, we will find a Sleep statement that will pause for 5 seconds when this line of code is hit. 

image

Within this Run method we will add our own code to retrieve our messages from the queue.

public void Run(CancellationToken cancelToken)
       {
           //Create Queue Client
           QueueClient qc = ServiceReferences.CreateSimpleSBQueue();

           //Create Message Receiver
           MessageReceiver mr = qc.CreateReceiver();

           //Create Brokered Message
           BrokeredMessage br;

           while (!cancelToken.IsCancellationRequested)
           {
               while (mr.TryReceive(new TimeSpan(hours: 0, minutes: 0, seconds: 5), out br))
               {
                   System.Diagnostics.Trace.TraceInformation(string.Format("Message received: ID= {0}, Body= {1}", br.MessageId, br.GetBody<string>()));
                   br.Complete();
               }

               // Add your code here
               Thread.Sleep(5 * 1000);
           }

           mr.Close();
           qc.Close();
       }

The code itself looks a lot like the code to add messages to a Queue.  However there are a few lines worth mentioning. 

mr.TryReceive(new TimeSpan(hours: 0, minutes: 0, seconds: 5), out br))

The TryReceive method will attempt to retrieve a message from the Queue.  The parameters include a TimeSpan that will determine our server wait time and a reference to a Brokered Message where the message will be stored.

The other notable line is br.Complete();  This method confirms the receipt of the message and provides instructions that the message has been processed and can be deleted.

Testing

For the purposes of this post we are going to test our app in our local Dev Fabric.  We can run our app by click on CRTL + F5.  Once our app has been deployed to our local Dev Fabric we will notice a line in our Output window providing a link to our Trace Log.  We will use this log once we have submitted some messages to the queue to validate that we are in fact retrieving them from the Queue.

image

With our application deployed to the Local Dev Fabric, our ASP.Net Web App should appear.  We now need to populate some test data and click the Submit Outage button.

 

image

If we no navigate to our Trace Log, we should see our test message being pulled from the Queue.

image

 

Trace Logs are also available in when running applications in the cloud.  I was using the Dev Fabric for simple convenience reasons.

About these ads
Categories: AppFabric, Azure, Queue Tags:

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: