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
Utilizing Azure Regions
Tyler StelzerTyler Stelzer  |  
May 08, 2018
Often when people hear Azure, they think “cloud”. But they should be thinking “clouds”. Azure has datacenters across the world that can be thought of as independent clouds. This gives organizations multiple options when determining the best utilization of a cloud-based...
Blog Article
How to Use Azure Search Services
Steven NelsonSteven Nelson  |  
Apr 10, 2018
Azure has a unique service offering aptly named “Azure Search”. This is a search-as-a-service cloud solution that lets you add a rich search service to your apps.   The search service abstracts the complexities of document retrieval through both a REST API and a .NET SDK...
Blog Article
Microsoft Build 2017 Day 3 Recap
Brandon MartinezBrandon Martinez  |  
May 13, 2017
Day three of Microsoft Build 2017 did not have a keynote, but that doesn’t mean it ends without content to fill the day. Today will be focused on sessions, “The Hub”, and catching some of the Channel 9 Live production happening right here at the conference. Here’s a...
Blog Article
Microsoft Build 2017 Day 2 Recap
Brandon MartinezBrandon Martinez  |  
May 12, 2017
Another beautiful day in Seattle, and another amazing day at Build 2017! Today started off with another fantastic keynote followed by a wide array of awesome sessions. Here’s my recap of today’s events. Keynote Today’s keynote was heavily focused at improvements and...
Blog Article
Microsoft Build 2017 Day 1 Recap
Brandon MartinezBrandon Martinez  |  
May 11, 2017
I’m very excited to be here in Seattle, Washington to attend the Microsoft Build 2017 conference! It’s an honor to be amongst the geekiest of the geeks in the Microsoft community and to be able to absorb a ton of knowledge over the next few days. I’ll be posting daily recaps of...