Event Based Solution with Azure Event Grid & Logic Apps.

Event Based Solution with Azure Event Grid & Logic Apps.

Introduction

Event grid is new app-service in azure that connect applications together so that applications talk to each other in distributed environment. This way of working decouple application components, which enables more scalability, maintainability, and extensibility.

At the basic level it’s similar to a message queue service, like Azure Service Bus Topics, that enables a publish / subscribe model.

Azure Event Grid is a different kind of messaging service that’s built to enable event-based architectures like those use with Microservices architectures to be built more easily.

Azure Event Grid can be described as an event broker that has one of more event publishers and subscribers. Event publishers are currently Azure blob storage, resource groups, subscriptions, event hubs and custom events etc.  Subsequently, there are consumers of events (subscribers) like Azure Functions, Logic Apps, and WebHooks.

E1.jpg

 

Employee On boarding System Example:

Let’s take employee boarding system example which is very common and essential process to every organizations. So whenever new employees hired then there are some hiring formalities like save employee details in company database (azure database,on premises Database etc) and send and welcome email to employee to notified about joining dates and other formalities  and also send calendar invites for both parties (employee and HR) to remind the joining date.

There may be some other parties may include in this process like transport department,IT department etc to set up all the necessary things at the time of employee on boarding.

So employee information is common to all parties and on the basis of this information the have to execute some set of  actions  like email creation,Id card issue,IT assets arrangement and seat allocation,so there should be a mechanism that can broadcast the same information to all interested parties.

Here Azure event grid comes in picture and help us to solve this problem in very efficient manner and  logic apps removes all hurdles to integrate all external integrations like mail client,database base logic etc without much coding part.

Process Flow:

E3.jpg

There are below important sections to developed above solution:

  1. Mvc application to submit employee details.
  2. Setup azure event grid in azure
  3. setup logic apps in azure
  4. Add logic apps as subscriber to event grid
  5. Integrate all together from step 1 to step 4.

 

1 ) Create Employee On-boarding Portal (Mvc Application)

Primarily web application will receive all employee details from end-users and generate a json formatted message and send to azure event grid topic instead of directly inserted in azure database.Later this message broadcast to all its subscribers and processed.In our case logic app is topic subscriber hence message received by logic app and start processing and executing related actions like send mail,send calendar invite so on.

Here i am taking simple mvc application for demonstration with simple form.

e9.jpg

2 ) Setup azure event grid in azure

Login on azure portal and select new and search for event grid topic.Fill all the mandatory details like name,subscription,region and resource group.

e4.jpg

once we finish with event grid configuration then we will navigate to below user interface where we have to set up event subscriptions.In our case logic apps will be our event listener and need to map here but we will setup later in next steps.

e5.jpg

3 ) Setup Logic App Service:

Logic Apps helps us build, schedule, and automate processes as workflows so we can integrate apps, data, systems, and services across enterprises or organizations. Logic Apps simplifies how we design and create scalable solutions for app integration, data integration, system integration, enterprise application integration (EAI).

Choose “logic app ” service from available service in azure portal and fill all required information.

e6

e7

Now press create button and fill all required details like logic app name,resource group,region etc. logic app name should be unique throughout the globally and azure portal automatically suggest whether name is unique or not.

e8.jpg

now navigate to logic app and start designing process flow with logic app connector.Below is complete designed logic app flow and we will talk about each connector step by step.

e10.jpg

Let’s talk about each connector in details.

  • EventGrid Connector: logic apps have connector called event grid connector that able to connect with event grid and received all broadcast messages.Here it will received employee details that is json formatted messages  submitted by mvc application to event grid.

 e11.jpg

  • Parse Json Connector: This connector parse the message that received from event grid on the basis of provided message schema.Here output from event grid connector will become input for parse json connector.If message parse successfully than same message passed to next step that responsible to insert data in database

 e12.jpg

  • Sqlserver Connector: Sql connector enable us make communication with database.by using valid database credential we can make connection with database and select target tables in which message details need to store.

 E13.jpg

Once connection establish successfully with server then we can see all tables of that server.here we need to map our message properties with table columns to store message in sql tables.

when we will click on each property then message properties selection area enable to choose right property from all available.Below we can see there are multiple properties showing to select and we may select one or more properties to store in particular column,here i select employeeId to store in employeeid column.

e15.jpg

E14.jpg

  • Google Calender & Gmail Calender Connectors: we have successfully configured event grid ,message parsing and database connection.Now we have to set up two important task like send Calender invite and send emails.here we are adding both connectors as parallel branch so that execute simultaneously once message save successfully in database.

first we have to click on (+) symbol and choose “add parallel branch” and then select google Calender connector and again repeat above thing select Gmail connector.

         e16.jpg

Now we have to provide all required information like valid Gmail email id and other massage details.

E17.jpg

Now our logic app completely ready to use but one small integration still pending that is an integration of azure event grid logic apps.

4 ) Add logic apps as subscriber to event grid: Till above step we have created event grid, mvc application and logic apps.Now we have to add our logic apps as a subscriber to event grid so that every message can be broadcast to logic apps and trigger it.let’s see below steps:

  • go to newly created event grid topic from azure portal and click on “Event Subscription” button on top of the expanded view in event grid and some mandatory details as per below .

E18

To find subscriber endpoint,go to back our logic app.there is a option called “CalledBackUrl” and this is actual logic app calling end-point.we need to copied it and paste on above form.

e19.jpg

once we add logic app as a subscriber,it will showing in event grid subscriber’s list as per below:

e20.jpg

Great..our integration done till this step.Now little bit C# code need to add at our controller level to convert employee joining details in json message and send to event grid. let’s see how can we do it.

5 ) Mvc Application & Event Grid Integration:

Here mvc application works as message initiator and send employee details to event grid. by calling event grid topic  end-point as a service.once this message send to event grid then event grid broadcast same message to its subscriber,here logic app is our subscriber so logic app trigger and start executing it’s all components like save data in db and send mails to employee email id.

we can find event-grid endpoint from event grid detail page as per below

e21.jpg

look at the mvc controller from where application call event grid and sent message:

EmployeeController.cs


<span class="mceItemHidden">public class <span class="mceItemHidden"><span class="hiddenSpellError">EmployeeController</span></span> : Controller</span>
 {
 // GET: Employee
<span class="mceItemHidden"> public <span class="mceItemHidden"><span class="hiddenSpellError">ActionResult</span></span> Index()</span>
 {
 return View();
 }
<span class="mceItemHidden"> [<span class="mceItemHidden"><span class="hiddenSpellError">HttpPost</span></span>]</span>
<span class="mceItemHidden"> public <span class="mceItemHidden"><span class="hiddenSpellError">ActionResult</span></span> Index(<span class="hiddenSpellError">EmployeeModel</span> <span class="hiddenSpellError">employeeModel</span>)</span>
 {
<span class="mceItemHidden"> <span class="mceItemHidden"><span class="hiddenSpellError">TimeSpan</span></span> hours = new System.TimeSpan(0, 9, 0, 0);</span>
 employeeModel.DateOfJoining.Add(hours);

employeeModel.DateOfJoining = employeeModel.DateOfJoining.ToUniversalTime();
<span class="mceItemHidden"> <span class="mceItemHidden"><span class="hiddenSpellError">EventGridModel</span></span> <span class="hiddenSpellError">evmModel</span> = new EventGridModel();</span>
<span class="mceItemHidden"> <span class="mceItemHidden"><span class="hiddenSpellError">evmModel</span></span>.id = new Guid().<span class="hiddenSpellError">ToString</span>();</span>
 evmModel.eventType = "NewPost";
 evmModel.subject = "blog/posts";
 evmModel.eventTime = "2017-08-20T23:14:22+1000";
 evmModel.data = employeeModel;

<span class="mceItemHidden">List<span class="mceItemHidden"><span class="hiddenSpellError">egmList</span></span> = new List();</span>
 egmList.Add(evmModel);
<span class="mceItemHidden"> <span class="mceItemHidden"><span class="hiddenSpellError">SendMessageToEventGrid</span></span>(egmList);</span>
 return View();
 }

Here private method “SendMessageToEventGrid” called and in this method we have use event grid end-point to post json message.let’s look at implementation.

E22.jpg

Till now we have set up each component and now let’s see how things works when details submitted by mvc applcation.we will once details submitted successfully than message broadcast to all subscriber by event grid and logic app trigger and send Calender invite and email to employee.

Mvc application with employee details:

E23.jpg

Once we press create button,message send to event grid and event grid triggers logic app.below is logic app running status where we can see all connector execute successfully ( click on highlighted details and See green sign on each connector).

we can see the complete process took only 5 second to execute including all connector.

E24.jpg

Logic app running status in expend view:

E25.jpg

Below is email and calender invite from my inbox where we can see email successfully sent by logic apps.

E26

Calender Invite:

E27

 

I hope you like this..keep learning and sharing.

 

 

 

 

 

 

Filtered Subscriptions with Azure Service Bus Topics

Filtered Subscriptions with Azure Service Bus Topics

Download Complete Project: AzureTopicSubscriptionfilters

Azure Service Bus topics allow multiple subscribers to receive the same messages. So if we post an message to a topic, then one subscriber might send an order confirmation email, while another subscriber to the same event might handle payments.

The way this is done is that you create multiple “subscriptions” on the topic, and then you can listen for messages on those subscriptions, in the same way that you would listen for messages on a regular queue.

But what if your subscription is only interested in a subset of messages that are posted to that topic? Well, this is where filters come in. When we create a subscription, we can specify the properties of the messages we are interested in.

What is Rule Filter

As the filter’s type implies, it allows for defining a SQL92 standard expression in its constructor that will govern what messages are filtered out.

There are following types of filters :

  1.  SQLFilter – The filter that a number of other filters derive from such TrueFilter and FalseFilter
  2. TrueFilter – This 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.
  3. FalseFilter – The antithesis of a TrueFilter that generates a SQL92 expression of 1=0; a subscription with this filter will never subscript to any messages of the associated topic.
  4. CorrelationFilter – This filter subscribes the subscription to all messages of a particular CorrelationId property of the message.
    Note:Be aware that the comparison values in your SQL expression are case-sensitive, while the property names are not (e.g. “Zone= ‘East’” is not the same as “zone= ‘east’”)

In earlier post we have seen how default rules works and how same message broadcast to all subscriptions. Now we will see how custom rules works and how specific message subscribe by the subscriber with custom filtering rules.

Example:

Let’s consider order processing system where some orders need to publish to topics and some region wise subscriptions are also setup in the topic.Instead of broadcast all orders to all subscriptions,only region wise orders will broadcast to specific subscriptions.

In our case orders belongs to two regions (East and North) and two subscriptions are setup to subscribe these messages,i.e East Subscription only receives east region orders and north subscription receives north region orders.

T18

Adding rules to the subscriptions:

Subscriptions are not limited to one rule however. We can add additional rules to an existing subscription.


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(60),
};
var zone = subsription.Replace("Subscription", "");

// Rule for EastSubsrciption to recieve those message that belongs to specific zones.
RuleDescription ruleDescForSubscriptions = new RuleDescription("ZoneFilter", new SqlFilter("Zone='" + zone + "'"));

nameSpaceManager.CreateSubscription(subscriptionDesc,ruleDescForSubscriptions);
var ss = SubscriptionClient.FormatDeadLetterPath(TopicName, subsription);
}
}

}

Here RuleDescription class is used to create a filter rules. Above code will add two filter rules  in  subscriptions which are  “Zone=’East’ and “Zone=’North'”.

An additional properties also need to send with broker message along with creating filter rules.


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);
brokerMessage.Properties.Add("Zone", order.Zone);
topicClient.Send(brokerMessage);
Console.Write(Displaytext);

}

See the “Zone” property set in broker message.

Complete Code For Message Publisher:


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

namespace MessageSender
{
class Publisher
{
static NamespaceManager nameSpaceManager;

static void Main()
{
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(60),
};
var zone = subsription.Replace("Subscription", "");

// Rule for EastSubsrciption to recieve those message that belongs to specific zones.
RuleDescription ruleDescForSubscriptions = new RuleDescription("ZoneFilter", new SqlFilter("Zone='" + zone + "'"));

nameSpaceManager.CreateSubscription(subscriptionDesc,ruleDescForSubscriptions);
var ss = SubscriptionClient.FormatDeadLetterPath(TopicName, subsription);
}
}

}
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);
brokerMessage.Properties.Add("Zone", order.Zone);
topicClient.Send(brokerMessage);
Console.Write(Displaytext);

}
}
}

Complete code for message receiver:


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");
Console.ReadLine();
}

public static void ReadMessageFromSubscription(string TopicName)
{

foreach (SubscriptionDescription description in nameSpaceManager.GetSubscriptions(TopicName))
{
SubscriptionClient sClient = SubscriptionClient.CreateFromConnectionString(TopicConfigurations.Namespace,"OrderTopic", description.Name);

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("=======================================");
Console.WriteLine("---Order Recieving From [" + description.Name + "]---");
Console.WriteLine("=======================================");
while (true)
{
BrokeredMessage bmessgage = sClient.Receive(TimeSpan.FromSeconds(2));

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();
}
else
{
break;
}
}
sClient.Close();
}

}
}
}

Once the messages are sent to Topic, the subscriber should start showing the appropriate message count. In our case if we send a message with East and North as Zone, as per the rules set, EastSubscriber should receive only 2 message which is East region messages and Northsubscriber should receive also 2 messages as north region has 2  messages.

Let’s run complete application and then talk about the output.

Here we can see there are 4 orders publish to order topic,there are 2 orders that belongs to East region and 2 orders for North reagion.Important thing that this time all 4 messages has not broadcast to both subscriptions because we have created 2 filters rule for both regions.

t19

Take a look on azure portal , here we can see each subscriptions received 2 messages according to their filter rule.

t20.jpg

Now see topic & subscription details with azure service bus explorer.We can see custom filters with name “ZoneFilter” has created in both subscripiton with filter rule.

t21.jpg

Of course, you can get away without using filters at all, if you just set up plain subscriptions and only respond to messages of interest in your handlers. But using the filters will reduce network traffic and save unnecessary work processing messages that aren’t of interest.

Read more about service bus explorer :Link

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

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.