Back to List

Santa’s Big Delivery – A Quick Azure Service Bus Tutorial

Erin Draheim Erin Draheim  |  
Dec 15, 2016
 
Azure Service Bus is a reliable and flexible way to deliver data to a variety of consumers. If all of Santa’s Helpers could send Christmas wishes to the North Pole with Service Bus, Santa could be sure every present is built and delivered to the right house with ease. This quick tutorial will show you how to setup an Azure Service Bus namespace, Service Bus topic and subscriptions.  This tutorial also makes use of Service Bus Explorer to view the topics and subscriptions.

Setup your Service Bus namespace in Azure and the rest can be done in code.  In the Azure portal, choose to create a new Service Bus namespace. We are naming this one “northpole” and choosing Standard pricing tier



You can either use the default Shared Access Key or create your own depending on the access needed by clients.  For demo purposes, I’ve created a key called GiftAccess with full Manage, Send and Listen rights. This will allow clients to create their own subscriptions on the fly.  Copy the endpoint to use in your code below.



In VS2015, install the WindowsAzure.ServiceBus Nuget package.  This has all the necessary libraries for communicating with the service bus. 



Create a C# Windows Console Project.  The code below will create the “workshop” topic.  Santa’s helpers can send out request for gifts right away and each request will go to the workshop to get built and added to Santa’s route.  

Simple Main program to keep everything together.  Each method could be run in its own program.  Methods to send and receive messages can run in completely different applications and do not even need to be online at the same time.

private static string connectionString =
  "Endpoint=sb://northpole.servicebus.windows.net;SharedAccessKeyName=GiftAccess;SharedAccessKey=[key]";
private static string topicName = "workshop";
 
static void Main(string[] args)
{
       Console.WriteLine($"Choose (1)Santa's Helper, (2)Build it or (3)Map it?");
       int option = int.Parse(Console.ReadLine());
 
       switch (option)
       {
              case 1:
                      SantasHelper();
                      break;
              case 2:
                      BuildIt();
                      break;
              default:
                      MapIt();
                      break;
       }
}

  
SantasHelper method creates the workshop topic that will route all the messages.  

private static void SantasHelper()
{
       var topicDescription = new TopicDescription(topicName);
       topicDescription.MaxSizeInMegabytes = 5120;
       topicDescription.DefaultMessageTimeToLive = new TimeSpan(1, 0, 0);
 
       CreateTopic(topicDescription);
 
       do
       {
              Console.WriteLine($"What's your name?");
              string name = Console.ReadLine();
              Console.WriteLine($"What type of present do you want?");
              string present = Console.ReadLine();
 
              var client = TopicClient.CreateFromConnectionString(connectionString, topicDescription.Path);
 
              string msgTime = DateTime.Now.ToString();
              var message = new BrokeredMessage($"{name}");
              message.Properties["type"] = present;
              client.Send(message);
              Console.WriteLine($"{msgTime} - Sending request for {name}'s {present}");
 
       } while (true);
}

 
CreateTopic() does the work to create the Service Bus topic.
 
private static void CreateTopic(TopicDescription topicDescription)
{
       var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
       if (!namespaceManager.TopicExists(topicDescription.Path))
       {
              topicDescription = namespaceManager.CreateTopic(topicDescription);
              Console.WriteLine($"{topicDescription.Path} topic created");
       }
       else
       {
              Console.WriteLine($"{topicDescription.Path} topic already exists");
       }
}

 
Running the application and choosing 1 to run “Santa’s Helper” will create the topic.  The console window shows that the topic is created. 



A view of Service Bus Explorer also shows that the topic is created. 


Without any subscriptions setup to receive the messages, they don’t have anywhere to go yet. Messages sent now will be throw out.  Let’s continue with creating some subscriptions to handle the messages. 

BuildIt() and MapIt() will create 2 subscriptions that each do something different with the same message.  BuildIt() takes the message and builds the toy.  MapIt() adds that house and toy to the route so Santa can make sure all the toys get delivered to the right spot.  Ok, these methods don’t really do anything but print out some console messages, but let’s use some imagination, it is Christmas after all.

private static void BuildIt()
{
       var subscriptionName = "build-it";
       CreateSubscription(subscriptionName);
 
       SubscriptionClient subscriptionClient =
SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName);
 
       Console.WriteLine($"Workshop is open and ready to build toys");
       BrokeredMessage message;
       while ((message = subscriptionClient.Receive()) != null)
       {
              string present = (string)message.Properties["type"];
              string msgBody = message.GetBody<string>();
              Console.WriteLine($"{DateTime.Now} {msgBody}'s request was received.");
              Thread.Sleep(2000); //Simulate processing time
              Console.WriteLine($"{DateTime.Now} Done making the {present}");
              Console.WriteLine($"Waiting for more...");
              message.Complete();
       }
}
 
private static void MapIt()
{
       var subscriptionName = "map-it";
       CreateSubscription(subscriptionName);
 
       SubscriptionClient subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName);
 
       Console.WriteLine($"Ready to plan Santa's route");
       BrokeredMessage message;
       while ((message = subscriptionClient.Receive()) != null)
       {
              string present = (string)message.Properties["type"];
              string msgBody = message.GetBody<string>();
              Console.WriteLine($"{DateTime.Now} {msgBody}'s request was received.");
              Thread.Sleep(2000); //Simulate processing time
              Console.WriteLine($"{msgBody} is added to the route");
              Console.WriteLine($"Waiting for more...");
              message.Complete();
       }
}


CreateSubscription does the work to create the subscription on the workshop topic.

private static void CreateSubscription(string subscriptionName)
{
       var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
       if (!namespaceManager.SubscriptionExists(topicName, subscriptionName))
       {
              // Make sure the subscription exists so there is somewhere to send this message
              namespaceManager.CreateSubscription(topicName, subscriptionName);
              Console.WriteLine($"{subscriptionName} subscription created ");
       }
       else
       {
              Console.WriteLine($"{subscriptionName} subscription already exists ");
       }
}


Running the program, one for each option, will send and receive messages.  Santa’s helper will send out messages.  Build it and Map It will each handle the messages to take care of getting those toys build and sent out for Christmas delivery.



The topic and subscriptions can also be viewed in Service Bus explorer.  Message counts are 0 because all messages have been handled – built and added to the route for Santa to deliver.



This tutorial shows how quickly and easily Service Bus topics and subscription can be setup to send and handle messages.  This flexible information delivery system has many uses, beyond getting all of those gifts out by Christmas Day! 
 
Azure

 

Love our Blogs?

Sign up to get notified of new Skyline posts.

 


Related Content


Blog Article
Machine Monitoring IoT Solution with Azure Services and Power BI
Eric SaltzmannEric Saltzmann  |  
Jun 11, 2019
We often hear organizations ask how they can drive more insights out of their connected devices. Though the Internet of Things (IoT) has been a buzzword for the last few years, many organizations are still struggling through the headache of implementing an IoT pilot or solution. Most of the...
Blog Article
Azure Tips & Tricks: Application Insights Snapshot Debugger
Todd TaylorTodd Taylor  |  
May 21, 2019
A painful memory that is burned into my developer-brain is a production support issue for a .NET web API that I wrote years ago. I worked for a large retailer at the time, and the bug was preventing electronic pricing signs from displaying the most up-to-date price for hundreds of products at...
Blog Article
Azure Tips & Tricks: Moving Operations in API Management
Todd TaylorTodd Taylor  |  
May 07, 2019
Azure API Management (APIM) helps developers save a lot of time by doing most of the heavy lifting involved in creating an API gateway and developer portal. However, the APIM administrative UI is missing a few minor times-saving features, such as the ability to move API operations between APIs...
Blog Article
How to Implement a Cloud-based Business Continuity Plan
Skyline Technologies  |  
Apr 23, 2019
First and foremost, you need to clarify your definitions. Make sure your team, your IT team, your business leaders, and your organization understand the definitions of RPO and RTO. Also make sure they understand how those impact their business and their business continuity plan.   Case...
Blog Article
Advantages of a Cloud-based Business Continuity Plan
Skyline Technologies  |  
Apr 09, 2019
One of the concerns we hear from customers is how much control is given up when moving to the cloud – especially in business continuity. That’s understandable, so we’re going to break down the advantages of an Azure Cloud Cold Site and Hot Site.   Azure Cloud Cold Site...