Microsoft Azure: Service Bus Topic & Subscription With Default Filtering Rule.

Download complete project : AzureTopicSubscription

In contrast to queues, in which each message is processed by a single consumer,topics and subscriptions provide a one-to-many form of communication, in publish and subscribe pattern.

Useful for scaling to very large numbers of recipients, each published message is made available to each subscription registered with the topic. Messages are sent to a topic (and delivered to one or more associated subscriptions) and received from subscriptions. Filter rules can also be set on a per-subscription basis.

t1

Default Filters in topic:

When the subscriptions were created in the topic, no filter was defined for them, and they subscribe to all messages that are sent to the topic.

True Filter  is the default filter provided through the default rule that is generated for us when a rule or filter is not explicitly provided when creating a subscription.  Ultimately, this generates the SQL92 expression 1=1 and subscribes to receive all messages of the associated topic.

Default Rule Name:  “$Default”

Default Filter Name : “True Filter”

Default Sql Expression=”Filter=1=1″

There are multiple ways to create topic and subscription in Azure service bus.

  1. Azure Portal
  2. PowerShell
  3. language specific SDK. ex: C# azure sdk

1. Create Topic & Subscription Through Azure Portal

login to azure portal and choose “New” option from left menu.

t2

once you navigate to service bus navigation pane then fill all required information like service bus name (should be unique across the global),choose appropriate price tire ,Resource group (new or existing created group) and location.

t3

Once you press create button,your newly created service bus list down in your resource list and you can go inside it for further configuration.

for this demonstration i have created service bus with name “Rakesh-ServiceBus”.As we can see below there are two options  available ,one for Queue and another is Topic.

t4

Click on “Topic option” from top menu and enter few details like topic name,topic max size( default size is 1 GB) and define number of days to message live etc.

t5

2. Create Topic & Subscription Through C# Azure Sdk:

let’s say you have already created service bus in azure account and now you have to create topics and subscriptions through C#.

Here’s a simple example of how to achieve this with C# programming.

Creating Topics:

Topic creation is straight forward approach and below are the code to create .


nameSpaceManager = NamespaceManager.CreateFromConnectionString(TopicConfigurations.Namespace);

var TopicName = "OrderTopic";
//Create Topic
if (!nameSpaceManager.TopicExists(TopicName))
{
nameSpaceManager.CreateTopic(TopicName);
}

Creating Subscriptions:

Here two subscriptions (NorthSubscription and East Subscription) will created under the topic name “OrderTopic” .


//CreateSubscription
if (!nameSpaceManager.SubscriptionExists(TopicName, "NorthSubscription"))
{
nameSpaceManager.CreateSubscription(TopicName, "NorthSubscription");
}
if (!nameSpaceManager.SubscriptionExists(topicPath: TopicName, name: "EastSubscription"))
{
nameSpaceManager.CreateSubscription(TopicName, "EastSubscription");
}

Deleting a Topic:


var TopicName = "OrderTopic";
//Create Topic
if (nameSpaceManager.TopicExists(TopicName))
{
nameSpaceManager.DeleteTopic(TopicName);
}

Deleting a Subscription:


//Delete a subscription
if (nameSpaceManager.SubscriptionExists(TopicName, "NorthSubscription"))
{
nameSpaceManager.DeleteSubscription(TopicName, "NorthSubscription");
}

Putting all together with publisher scenario:

Taking simple order processing example where publisher send the order details to the specific topic and there are multiple subscriber (receiver) that reads order details from the topic.

As i already mentioned that default filter 1=1 applied to topic and subscription then same message will sent to both subscription because we have not defined any specific filter (will see in next article in details).

t6

Sending Order Details to Topic:

A console application  named as “MessageSender” is created to send order details to azure topic.Below are the code to send message. I will show code in parts but you can download complete sample project.


using Common;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Threading;

namespace MessageSender
{
class Publisher
{
static NamespaceManager nameSpaceManager;

static void Main()
{
Thread.Sleep(1000);
nameSpaceManager = NamespaceManager.CreateFromConnectionString(TopicConfigurations.Namespace);
CreateTopicUnderServiceBus();

TopicClient tClient = TopicClient.CreateFromConnectionString(TopicConfigurations.Namespace, "OrderTopic");

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("======================================================");
Console.WriteLine("-----------Publishing Start---------------------------");
Console.WriteLine("======================================================");

Console.ForegroundColor = ConsoleColor.Green;
PublishOrder(tClient, new Order()
{
OrderId = 5656,
CustomerName = "Vivek Jadon",
ProductName = "Iphone6",
DeliveryAddress = "MG Road Gurgaon",
Zone = "East"
});
PublishOrder(tClient, new Order()
{
OrderId = 5657,
CustomerName = "Rakesh ",
ProductName = "Samsung S8",
DeliveryAddress = "12/3 Ring Road Delhi",
Zone = "East",
});
PublishOrder(tClient, new Order()
{
OrderId = 5658,
CustomerName = "Prakash Nayal",
ProductName = "OnePlus 5T",
DeliveryAddress = "12/3 Ring Road Delhi",
Zone = "North",
});
PublishOrder(tClient, new Order()
{
OrderId = 5659,
CustomerName = "Gautom Anand",
ProductName = "Samsung S8",
DeliveryAddress = "12/3 Ring Road Delhi",
Zone = "North",
});

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("-----------Publishing End---------------------------");
Console.ReadLine();
}

public static void CreateTopicUnderServiceBus()
{
var TopicName = "OrderTopic";
string[] arrSubsription = new string[] { "NorthSubscription", "EastSubscription" };

//Create Topic
if (!nameSpaceManager.TopicExists(TopicName))
{
nameSpaceManager.CreateTopic(TopicName);
}

//CreateSubscription
foreach (string subsription in arrSubsription)
{
if (!nameSpaceManager.SubscriptionExists(TopicName, subsription))
{
SubscriptionDescription subscriptionDesc = new SubscriptionDescription(TopicName, subsription)
{
EnableDeadLetteringOnMessageExpiration = true,
EnableDeadLetteringOnFilterEvaluationExceptions = true,
DefaultMessageTimeToLive = TimeSpan.FromMinutes(5),
LockDuration = TimeSpan.FromSeconds(30)
};

nameSpaceManager.CreateSubscription(subscriptionDesc);
}
}
}

public static void PublishOrder(TopicClient topicClient, Order order)
{

String Displaytext = string.Format("Order : orderId={0},customerName={1},ProductName={2},DeliveryAddress={3},Zone={4} " +
" Sent To Topic Successfully \n\n",
order.OrderId, order.CustomerName, order.ProductName, order.DeliveryAddress, order.Zone);

//Create broker message for order
BrokeredMessage brokerMessage = new BrokeredMessage(order);
topicClient.Send(brokerMessage);
Console.Write(Displaytext);

}

}
}

Let’s run the message sender console application only (not executing any messaging receiving application) and see what type of resources and activity happens on azure portal.

Few things captured before executing sender application,you will see there is no topic and subscription created in service bus “Rakesh-Service Bus”.

T10.jpg

Now Execute message sender application and  see what happens.

  • As you see in below snapshot ,order details successfully publish to azure topic.

t11.jpg

  • go to azure portal and you find an topic with name “OrderTopic” with two subscription “EastSubscription” and “NorthSusbcription” created successfully and one thing also noticed that both subscriptions received both 4 order details because we have created subscriptions without and filter rules and if you not create any rule then default rule (1=1) applied.

t12.jpg

let’s see more in-depth by using azure service bus explorer.Service explorer provide rich user interface to know more details about messages as compare to azure portal.we can see message state weather in active state or in dead letter queue.Create and modify filter rules.

T17.jpg

 

Subscribe message from topic:

subscribers never directly connected with azure topics.Any subscriber wants to receive the message from topic then first they have to subscribe any subscription under the same topic and read messages from these subscriptions.

Putting all together with Subscriber scenario:

Again taking console application and install necessary nuget packages to support azure service bus SDK.


using Common;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System;

namespace MessageReciever
{
class Subscriber
{
static NamespaceManager nameSpaceManager;

static void Main()
{
nameSpaceManager = NamespaceManager.CreateFromConnectionString(TopicConfigurations.Namespace);
ReadMessageFromSubscription("OrderTopic");
}

public static void ReadMessageFromSubscription(string TopicName)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("======================================================");
Console.WriteLine("-----------Order Recieving Start---------------------------");
Console.WriteLine("======================================================");
foreach (SubscriptionDescription description in nameSpaceManager.GetSubscriptions(TopicName))
{
SubscriptionClient sClient = SubscriptionClient.CreateFromConnectionString(TopicConfigurations.Namespace,"OrderTopic", description.Name);
while (true)
{
BrokeredMessage bmessgage = sClient.Receive();
if (bmessgage != null)
{
Order order = bmessgage.GetBody<order>();
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(" Request Recieved, ProductName: {0},Zone : {1},CustomerName: {2},DeliveryAddress: {3} \n\n",
order.ProductName, order.Zone,order.CustomerName,order.DeliveryAddress);

Console.ForegroundColor = ConsoleColor.Yellow;
bmessgage.Complete();
}
}
}
Console.WriteLine("-----------Publishing End---------------------------");
}
}
}

Now execute sender and  receiver applications together and you find that sender start publishing messages to topic and receiver application start reading those message from both subscriptions.

T15.jpg

 

We’ve learned that two of the most powerful features in Topics and Subscriptions is the ability to distribute messages to multiple interested parties (subscriptions) and those parties are able to filter out what messages they are specifically interested in.  There is still a good bit to cover on the topic of Azure Service Bus.

A full code example attached with this and you can find link at top of the blog.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s