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

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:

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

1mkdir azureservicebus.amqp.console

2. Create the project


1cd azureservicebus.amqp.console
2dotnet 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):

1{
2    "ServiceBus": {
3        "NamespaceUrl": "[The namespace url (i.e. codeityourself.servicebus.windows.net)]",
4        "PolicyName": "[The policy name]",
5        "Key": "[The SAS key]"
6    }
7}

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.

 1{
 2  "version": "1.0.0-*",
 3  "buildOptions": {
 4    "debugType": "portable",
 5    "emitEntryPoint": true,
 6     "copyToOutput": {
 7      "include": "appsettings.json"
 8    }
 9  },
10  "dependencies": {
11    "Microsoft.Extensions.Configuration": "1.0.0",
12    "Microsoft.Extensions.Configuration.Json": "1.0.0",
13    "AMQPNetLite": "1.2.0",
14    "System.Net.Http": "4.1.0",
15    "System.Xml.XmlDocument": "4.0.1",
16    "System.Runtime.Serialization.Xml": "4.1.1"
17  },
18  "frameworks": {
19    "netcoreapp1.0": {
20      "dependencies": {
21        "Microsoft.NETCore.App": {
22          "type": "platform",
23          "version": "1.0.0"
24        }
25      },
26      "imports": "dnxcore50"
27    }
28  }
29}

5. Restore packages


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

1dotnet restore

6. Modify Program.cs


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

  1namespace ConsoleApplication
  2{
  3    using System;
  4    using System.IO;
  5    using System.Net;
  6    using System.Xml;
  7    using Amqp;
  8    using Amqp.Framing;
  9    using Microsoft.Extensions.Configuration;
 10
 11    public class Program
 12    {
 13        public static void Main(string[] args)
 14        {
 15            // Enable to app to read json setting files
 16            var builder = new ConfigurationBuilder()
 17                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
 18
 19            // build the configuration
 20            var configuration = builder.Build();
 21
 22            // Azure service bus SAS key
 23            var policyName = WebUtility.UrlEncode(configuration["ServiceBus:PolicyName"]);
 24            var key = WebUtility.UrlEncode(configuration["ServiceBus:Key"]);
 25
 26            // Azure service bus namespace
 27            var namespaceUrl = configuration["ServiceBus:NamespaceUrl"];
 28
 29            // Create the AMQP connection string
 30            var connnectionString = $"amqps://{policyName}:{key}@{namespaceUrl}/";
 31
 32            // Create the AMQP connection
 33            var connection = new Connection(new Address(connnectionString));
 34
 35            // Create the AMQP session
 36            var amqpSession = new Session(connection);
 37
 38            // Give a name to the sender
 39            var senderSubscriptionId = "codeityourself.amqp.sender";
 40            // Give a name to the receiver
 41            var receiverSubscriptionId = "codeityourself.amqp.receiver";
 42
 43            // Name of the topic you will be sending messages
 44            var topic = "codeityourself";
 45
 46            // Name of the subscription you will receive messages from
 47            var subscription = "codeityourself.listener";
 48
 49            // Create the AMQP sender
 50            var sender = new SenderLink(amqpSession, senderSubscriptionId, topic);
 51
 52            for (var i = 0; i < 10; i++)
 53            {
 54                // Create message
 55                var message = new Message($"Received message {i}");
 56
 57                // Add a meesage id
 58                message.Properties = new Properties() { MessageId = Guid.NewGuid().ToString() };
 59
 60                // Add some message properties
 61                message.ApplicationProperties = new ApplicationProperties();
 62                message.ApplicationProperties["Message.Type.FullName"] = typeof(string).FullName;
 63
 64                // Send message
 65                sender.Send(message);
 66            }
 67
 68            // Create the AMQP consumer
 69            var consumer = new ReceiverLink(amqpSession, receiverSubscriptionId, $"{topic}/Subscriptions/{subscription}");
 70
 71            // Start listening
 72            consumer.Start(5, OnMessageCallback);
 73
 74            // Wait for a key to close the program
 75            Console.Read();
 76        }
 77
 78        /// <summary>
 79        /// Method that will be called every time a message is received.
 80        /// </summary>
 81        /// 
 82        /// 
 83        static void OnMessageCallback(ReceiverLink receiver, Message message)
 84        {
 85            try
 86            {
 87                // You can read the custom property
 88                var messageType = message.ApplicationProperties["Message.Type.FullName"];
 89
 90                // Variable to save the body of the message.
 91                string body = string.Empty;
 92
 93                // Get the body
 94                var rawBody = message.GetBody<object>();
 95  
 96                  // If the body is byte[] assume it was sent as a BrokeredMessage  
 97                  // and deserialize it using a XmlDictionaryReader
 98                  if (rawBody is byte[])
 99                  {
100                      using (var reader = XmlDictionaryReader.CreateBinaryReader(
101                          new MemoryStream(rawBody as byte[]),
102                          null,
103                          XmlDictionaryReaderQuotas.Max))
104                      {
105                          var doc = new XmlDocument();
106                          doc.Load(reader);
107                          body = doc.InnerText;
108                      }
109                  }
110                  else // Asume the body is a string
111                  {
112                      body = rawBody.ToString();
113                  }
114  
115                  // Write the body to the Console.
116                  Console.WriteLine(body);
117  
118                  // Accept the messsage.
119                  receiver.Accept(message);
120              }
121              catch (Exception ex)
122              {
123                  receiver.Reject(message);
124                  Console.WriteLine(ex);
125              }
126          }
127      }
128  }

8. Build


Build the application with the following command

1dotnet build

9. Run


You are good to go so run the application

1dotnet run

You can get the code here

Hope it helps!


Step by step: .NET Core and Entity Framework Core
Step by step: Entity Framework Core and Shadow Properties
comments powered by Disqus