To receive messages from a topic queue, you would create a subscription. A subscription resembles a virtual queue that receives a copy of the message sent to a topic queue.
In some scenarios, it would be helpful to filter message properties and only receive messages that satisfy the filter condition. Currently, if a subscriber creates a subscription to a topic, all messages arriving at that topic are made available to the subscriber. This is because the default filter MatchAll
is applied when no filters are specified on the creation of a subscription.
Azure Service Bus has the concept of subscription rules, which allows you to define filters and actions that are applied to a Topic.
More information on creating subscriptions from Microsoft can be found at: http://msdn.microsoft.com/en-us/library/microsoft.servicebus.namespacemanager.createsubscription.aspx.
A filter is an expression in the form of a SQL 92 style predicate, for example, "StoreLocation = 'Auckland'"
. These filters are applied to either system or user-defined application properties that are available in the BrokeredMessage
class.
The actual code to create a filter and subscription will look like the following example:
//create the filter SqlFilter cityFilter = new SqlFilter("StoreLocation = 'Wellington'");
This will forward all messages to the subscription named SouthernRegion
if the StoreLocation
name equals Wellington
.
Remember that the filter expression is based on the SQL 92 syntax, which will allow you to add more filtering options in the syntax. Here is an example:
SqlFilter highValuecityFilter = new SqlFilter("StoreLocation = 'Wellington' OR StoreLocation = 'Levin' AND SalesValue > 5000");
The filter is then added to the namespace instance and topic, using the CreateSubscription
method, as shown here:
//create a filtered subscription nsManager.CreateSubscription("SalesTopicQueue", "SouthernRegion", cityFilter);
A rule can also define an action using the RuleDescription
object. With actions, you can modify the value of an existing property when the filter condition evaluates to true
. The following code demonstrates how to set the value of a user-defined application property named Priority
when the filtered condition evaluates to true
, using the SQL 92 syntax:
var ruleLowPrice = new RuleDescription() { Filter = new SqlFilter("SalesValue < 1000") Action = new SqlRuleAction("set Priority='Low'"), }; var ruleHighPrice = new RuleDescription() { Filter = new SqlFilter("SalesValue >= 1000") Action = new SqlRuleAction("set Priority ='High'"), };
Once the filter and actions have been defined, they can be added to the namespace manager, as before:
nsManager.CreateSubscription("SalesTopicQueue","AccountsLow", ruleLowPrice); nsManager.CreateSubscription("SalesTopicQueue","AccountsHigh", ruleHighPrice);