{"id":10011,"date":"2023-07-27T18:24:22","date_gmt":"2023-07-27T18:24:22","guid":{"rendered":"https:\/\/putridparrot.com\/blog\/?p=10011"},"modified":"2023-07-27T18:24:22","modified_gmt":"2023-07-27T18:24:22","slug":"creating-and-using-the-azure-service-bus","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/creating-and-using-the-azure-service-bus\/","title":{"rendered":"Creating and using the Azure Service Bus"},"content":{"rendered":"<p>The Azure Service Bus is not much different to every other service bus out there, i.e. we send messages to it and other applications or services receive those messages by pulling the messages off the bus or monitoring it.<\/p>\n<p>Let&#8217;s set up an Azure Service bus. <\/p>\n<p>We&#8217;ll use the Azure Dashboard (the instructions below are correct as per the Dashboard at the time of writing).<\/p>\n<ul>\n<li>Type <em>Service Bus<\/em> into the search bar of the dashboard or locate the <em>Service Bus<\/em> from the dashboard buttons etc. if available<\/li>\n<li>Click <em>Create<\/em> then either give the resource group a name (or select an existing). I&#8217;ll <em>create new<\/em> and mine&#8217;s going to be called <em>test-app<\/em>. Create a namespace, mine&#8217;s <em>test-app-bus<\/em> and set the location pricing tier etc. as you wish.<\/li>\n<li>Click the <em>Review + create<\/em> button.<\/li>\n<li>Review your settings then if you&#8217;re happy, click the <em>Create<\/em> button<\/li>\n<\/ul>\n<p>If all went well, you&#8217;ll see the deployment in progress. When completed, we need to set up a queue&#8230;<\/p>\n<ul>\n<li>Click the <em>Go to resource<\/em> button from the deployment page<\/li>\n<li>Click the <em>Queue<\/em> button<\/li>\n<li>The queue name needs to be unique within the namespace, I&#8217;ve chosen test-app-queue, although it&#8217;s more likely you&#8217;ll want to choose a name that really reflects what the purpose of the queue is, for example trades, appointments, orders are some real world names you might prefer to use<\/li>\n<li>I&#8217;m going to leave all queue options as the default for this example<\/li>\n<li>Click the <em>Create<\/em> button and in a few seconds the queue should be created.<\/li>\n<\/ul>\n<p>In the dashboard for the <em>Service Bus Namespace<\/em> you&#8217;ll see the queues listed at the bottom of the page. This pages also shows requests count, message count etc.<\/p>\n<p>We&#8217;ve not completed everything yet. We need to create a SAS policy for accessing the service bus&#8230;<\/p>\n<ul>\n<li>From the <em>Service Bus Namespace<\/em> dashboard, select <em>Entities | Queues<\/em> select the queue to view the dashboard page <em>Service Bus Queue<\/em><\/li>\n<li>From here select <em>Settings | Shard access policies<\/em><\/li>\n<li>Click the <em>Add<\/em> button<\/li>\n<li>We&#8217;re going to set the policy up for applications sending messages, so give the policy an appropriate name, such as <em>SenderPolicy<\/em> and ensure the <em>Send<\/em> checkbox is checked<\/li>\n<li>Finally, click the <em>Create<\/em> button<\/li>\n<\/ul>\n<p>If you now click on the policy it will show keys and connection strings. We&#8217;ll need the <em>Primary Connection String<\/em> for our test application. <\/p>\n<p><em>Note: Obviously these keys need to be kept secure otherwise anyone could interact with your service bus queues.<\/em><\/p>\n<p><strong>Creating a test app to send messages<\/strong><\/p>\n<p>This is all well and good, but let&#8217;s now create a little C# test app to send messages to our queue.<\/p>\n<ul>\n<li>From Visual Studio create a new project, we&#8217;ll just create a Console application for now<\/li>\n<li>Add a NuGet reference to Azure.Messaging.ServiceBus<\/li>\n<\/ul>\n<p>In Program.cs simply copy\/paste the following<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing Azure.Messaging.ServiceBus;\r\n\r\nconst string connectionString = &quot;the-send-primary-connection-string&quot;;\r\nconst string queueName = &quot;test-app-queue&quot;;\r\n\r\nvar serviceBusClient = new ServiceBusClient(connectionString);\r\nvar serviceBusSender = serviceBusClient.CreateSender(queueName);\r\n\r\ntry\r\n{\r\n    using var messageBatch = await serviceBusSender.CreateMessageBatchAsync();\r\n\r\n    for (var i = 1; i &lt;= 10; i++)\r\n    {\r\n        if (!messageBatch.TryAddMessage(new ServiceBusMessage($&quot;Message {i}&quot;)))\r\n        {\r\n            throw new Exception($&quot;The message {i} is too large to fit in the batch&quot;);\r\n        }\r\n    }\r\n\r\n    await serviceBusSender.SendMessagesAsync(messageBatch);\r\n    Console.ReadLine();\r\n}\r\nfinally\r\n{\r\n    await serviceBusSender.DisposeAsync();\r\n    await serviceBusClient.DisposeAsync();\r\n}\r\n\r\n<\/pre>\n<p><strong>Creating a test app to receive messages<\/strong><\/p>\n<p>Obviously we will want to receive messages from our service bus, so let&#8217;s create another C# console application and copy\/paste the following into Program.cs<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing Azure.Messaging.ServiceBus;\r\n\r\nasync Task MessageHandler(ProcessMessageEventArgs args)\r\n{\r\n    var body = args.Message.Body.ToString();\r\n    Console.WriteLine($&quot;Received: {body}&quot;);\r\n    await args.CompleteMessageAsync(args.Message);\r\n}\r\n\r\nTask ErrorHandler(ProcessErrorEventArgs args)\r\n{\r\n    Console.WriteLine(args.Exception.ToString());\r\n    return Task.CompletedTask;\r\n}\r\n\r\nconst string connectionString = &quot;the-listen-primary-connection-string&quot;;\r\nconst string queueName = &quot;test-app-queue&quot;;\r\n\r\nvar serviceBusClient = new ServiceBusClient(connectionString);\r\nvar serviceBusProcessor = serviceBusClient.CreateProcessor(queueName, new ServiceBusProcessorOptions());\r\n\r\ntry\r\n{\r\n    serviceBusProcessor.ProcessMessageAsync += MessageHandler;\r\n    serviceBusProcessor.ProcessErrorAsync += ErrorHandler;\r\n\r\n    await serviceBusProcessor.StartProcessingAsync();\r\n\r\n    Console.ReadKey();\r\n\r\n    await serviceBusProcessor.StopProcessingAsync();\r\n}\r\nfinally\r\n{\r\n    await serviceBusProcessor.DisposeAsync();\r\n    await serviceBusClient.DisposeAsync();\r\n}\r\n<\/pre>\n<p>Before this will work we also need to go back to the Azure Dashboard, go to the Queues section and click on <em>Shared access policies<\/em>. Along side our <em>SenderPolicy<\/em> add a new policy, we&#8217;ll call it <em>ListenPolicy<\/em> and check the Listen checkbox. Copy the <em>Primary Connection String<\/em> to the code above.<\/p>\n<p>This code will listen for messages but in some cases you may wish to just get a single message, in which case you could use this code<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing Azure.Messaging.ServiceBus;\r\n\r\nconst string connectionString = &quot;the-listen-primary-connection-string&quot;;\r\nconst string queueName = &quot;test-app-queue&quot;;\r\n\r\nawait using var client = new ServiceBusClient(connectionString);\r\n\r\nvar receiver = client.CreateReceiver(queueName);\r\nvar message = await receiver.ReceiveMessageAsync();\r\nvar body = message.Body.ToString();\r\n\r\nConsole.WriteLine(body);\r\n\r\nawait receiver.CompleteMessageAsync(message);\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>The Azure Service Bus is not much different to every other service bus out there, i.e. we send messages to it and other applications or services receive those messages by pulling the messages off the bus or monitoring it. Let&#8217;s set up an Azure Service bus. We&#8217;ll use the Azure Dashboard (the instructions below are [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[96,3],"tags":[],"class_list":["post-10011","post","type-post","status-publish","format-standard","hentry","category-azure-2","category-c"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/10011","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=10011"}],"version-history":[{"count":5,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/10011\/revisions"}],"predecessor-version":[{"id":10037,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/10011\/revisions\/10037"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=10011"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=10011"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=10011"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}