How to add filters to Topic's subscription in Azure Service Bus

Ankit Raonka picture Ankit Raonka · Jun 26, 2018 · Viewed 7.8k times · Source

i want add filter for subscription so that different actions are performed on different types of event.

How do i add filters to it. Should it be added before sending to topic or it can be done in azure portal?

Answer

Bruce Chen picture Bruce Chen · Jun 28, 2018

How do i add filters to it. Should it be added before sending to topic or it can be done in azure portal?

AFAIK, Azure Portal does not provide the feature for you to create a subscription under the specific Service Bus Topic along with the filter expression.

Per my experience, you may need to use the Service Bus client library for your development language to create your subscription with the filter expression. For C#, you may follow the code snippet below to create the subscription and retrieve the messages:

var namespaceManager = SB.NamespaceManager.CreateFromConnectionString("{connectionString}");

//create a subscription with the filter expression
if (!namespaceManager.SubscriptionExists("{your-topic-name}", "{your-subscription-name}"))
{
    namespaceManager.CreateSubscription("{your-topic-name}", "{your-subscription-name}", new SqlFilter("sys.Label='important' or MessageId<0"));
}

//send topic message(s)
var msg= new BrokeredMessage("Hello World");
msg.Properties["From"] = "Bruce Chen";
msg.Label = "important";
msg.Properties["MessageId"] = 1;
var client = TopicClient.CreateFromConnectionString("{connectionString}", "{your-topic-name}");
client.Send(msg);

//subscription receives message(s)
var subClient =SubscriptionClient.CreateFromConnectionString(connectionString, "{your-topic-name}", "{your-subscription-name}");
subClient .OnMessage(m =>
{
    Console.WriteLine(m.GetBody<string>() + "," + m.Label + "," + m.Properties["From"] + "," + m.Properties["MessageId"]);
});
Console.ReadLine();

Moreover, the SQLFilter syntax only applies on the public property of the BrokeredMessage class or the key of the BrokeredMessage class dictionary (e.g. BrokeredMessage.Properties).