Set up a subscription for messages with no matching filter in Azure Service Bus (on-premise)
-
24-12-2019 - |
Question
I'm using Azure Service Bus 1.1 (the on premise version)
I'm trying to set up a subscription that will receive messages that have not been filtered into any other existing subscription.
I have 3 console apps, one that creates topics and subscriptions, one that sends messages to the topic, and one that receives messages from a subscription.
I'm also using the Service Bus Explorer (V2.1) to see what is happening with my console apps.
I have tried setting up the topic as described on this page and this page which uses a MatchNoneFilterExpression
but the example code does not compile(?) ie the FilterAction and FilterExpression properties are not in the RuleDescription class
RuleDescription matchNoneRule = new RuleDescription()
{
FilterAction = new SqlFilterAction("set defer = 'yes';"),
FilterExpression = new MatchNoneFilterExpression()
};
The RuleDescription class I'm using is in v2.1.0.0 of the Microsoft.ServiceBus.dll It has the following properties available,
How do I send a message that matches no other filters to a particular subscription?
Solution
From this page which suggests setting the EnableFilteringMessagesBeforePublishing
property on the topic.
It then suggests that on sending a message to this topic a message will trigger the NoMatchingSubscriptionException
I'm creating my topic with this code
var myTopic = new TopicDescription(topicName)
{
EnableFilteringMessagesBeforePublishing = true
};
namespaceManager.CreateTopic(myTopic);
I'm sending a message to the topic that doesn't match any filters and I can catch the exception and potentially resend the message with a property that does match a filter, e.g.:
try
{
topicClient.Send(message);
Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
}
catch (NoMatchingSubscriptionException ex)
{
string messageBody = message.GetBody<string>();
BrokeredMessage msg = new BrokeredMessage(messageBody);
msg.Properties.Add("Filter", "NoMatch");
foreach (var prop in message.Properties)
{
msg.Properties.Add(prop.Key, prop.Value);
}
topicClient.Send(msg);
Console.WriteLine("\n NoMatchingSubscriptionException - message resent to NoMatchingSubscription");
Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", msg.MessageId, msg.GetBody<string>()));
}