Step by step: .NET Core, Azure Service Bus and AMQP

by Carlos Mendible on 17 Jul 2016 » Azure, dotNetCore

Today I’ll show you how to create a small console application with a Step by step: .NET Core, Azure Service Bus and AMQP example.

First be aware of the following prerequisites:

**OS** **Prerequisites**
Windows Windows: You must have .NET Core SDK for Windows or both Visual Studio 2015 Update 3* and .NET Core 1.0 for Visual Studio installed.
linux, mac or docker checkout .NET Core

You will also need an Azure Service Bus namespace, topic and subscription with the correct set of credentials. (Start here: How to use Service Bus topics and subscriptions if you don’t know how to configure the Service Bus)

Now let’s start:

1. Create a folder for your new project


Open a command promt an run

mkdir azureservicebus.amqp.console

2. Create the project


cd azureservicebus.amqp.console
dotnet new

3. Create a settings file


Create an appsettings.json file to hold your service bus connection information (remember to replace the values with those from your Service Bus configuration):

{
    "ServiceBus": {
        "NamespaceUrl": "[The namespace url (i.e. codeityourself.servicebus.windows.net)]",
        "PolicyName": "[The policy name]",
        "Key": "[The SAS key]"
    }
}

4. Modify the project file


Modify the project.json to add the AMQPNetLite dependencies and also specify that the appsettings.json file must be copied to the output (buildOptions section) so it becomes available to the application once you build it.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true,
     "copyToOutput": {
      "include": "appsettings.json"
    }
  },
  "dependencies": {
    "Microsoft.Extensions.Configuration": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "AMQPNetLite": "1.2.0",
    "System.Net.Http": "4.1.0",
    "System.Xml.XmlDocument": "4.0.1",
    "System.Runtime.Serialization.Xml": "4.1.1"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

5. Restore packages


You just modified the project.json file with new dependencies so please restore the packages with the following command:

dotnet restore

6. Modify Program.cs


Replace the contents of the Program.cs file with the following code

namespace ConsoleApplication
{
    using System;
    using System.IO;
    using System.Net;
    using System.Xml;
    using Amqp;
    using Amqp.Framing;
    using Microsoft.Extensions.Configuration;

    public class Program
    {
        public static void Main(string[] args)
        {
            // Enable to app to read json setting files
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            // build the configuration
            var configuration = builder.Build();

            // Azure service bus SAS key
            var policyName = WebUtility.UrlEncode(configuration["ServiceBus:PolicyName"]);
            var key = WebUtility.UrlEncode(configuration["ServiceBus:Key"]);

            // Azure service bus namespace
            var namespaceUrl = configuration["ServiceBus:NamespaceUrl"];

            // Create the AMQP connection string
            var connnectionString = $"amqps://{policyName}:{key}@{namespaceUrl}/";

            // Create the AMQP connection
            var connection = new Connection(new Address(connnectionString));

            // Create the AMQP session
            var amqpSession = new Session(connection);

            // Give a name to the sender
            var senderSubscriptionId = "codeityourself.amqp.sender";
            // Give a name to the receiver
            var receiverSubscriptionId = "codeityourself.amqp.receiver";

            // Name of the topic you will be sending messages
            var topic = "codeityourself";

            // Name of the subscription you will receive messages from
            var subscription = "codeityourself.listener";

            // Create the AMQP sender
            var sender = new SenderLink(amqpSession, senderSubscriptionId, topic);

            for (var i = 0; i < 10; i++)
            {
                // Create message
                var message = new Message($"Received message {i}");

                // Add a meesage id
                message.Properties = new Properties() { MessageId = Guid.NewGuid().ToString() };

                // Add some message properties
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["Message.Type.FullName"] = typeof(string).FullName;

                // Send message
                sender.Send(message);
            }

            // Create the AMQP consumer
            var consumer = new ReceiverLink(amqpSession, receiverSubscriptionId, $"{topic}/Subscriptions/{subscription}");

            // Start listening
            consumer.Start(5, OnMessageCallback);

            // Wait for a key to close the program
            Console.Read();
        }

        /// <summary>
        /// Method that will be called every time a message is received.
        /// </summary>
        /// 
        /// 
        static void OnMessageCallback(ReceiverLink receiver, Message message)
        {
            try
            {
                // You can read the custom property
                var messageType = message.ApplicationProperties["Message.Type.FullName"];

                // Variable to save the body of the message.
                string body = string.Empty;

                // Get the body
                var rawBody = message.GetBody<object>();
  
                  // If the body is byte[] assume it was sent as a BrokeredMessage  
                  // and deserialize it using a XmlDictionaryReader
                  if (rawBody is byte[])
                  {
                      using (var reader = XmlDictionaryReader.CreateBinaryReader(
                          new MemoryStream(rawBody as byte[]),
                          null,
                          XmlDictionaryReaderQuotas.Max))
                      {
                          var doc = new XmlDocument();
                          doc.Load(reader);
                          body = doc.InnerText;
                      }
                  }
                  else // Asume the body is a string
                  {
                      body = rawBody.ToString();
                  }
  
                  // Write the body to the Console.
                  Console.WriteLine(body);
  
                  // Accept the messsage.
                  receiver.Accept(message);
              }
              catch (Exception ex)
              {
                  receiver.Reject(message);
                  Console.WriteLine(ex);
              }
          }
      }
  }

8. Build


Build the application with the following command

dotnet build

9. Run


You are good to go so run the application

dotnet run

You can get the code here: https://github.com/cmendible/dotnetcore.samples/tree/master/azureservicebus.amqp.console

Hope it helps!