Skip to content

Commit 81030a8

Browse files
Merge pull request #312921 from alexwolfmsft/passwordless-update
Update .NET code to use passwordless auth
2 parents 7cac013 + 72fc3e3 commit 81030a8

2 files changed

Lines changed: 302 additions & 3 deletions

File tree

articles/service-bus-messaging/service-bus-filter-examples.md

Lines changed: 258 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
title: Set subscriptions filters in Azure Service Bus | Microsoft Docs
33
description: This article provides examples for defining filters and actions on Azure Service Bus topic subscriptions.
44
ms.topic: how-to
5-
ms.date: 05/28/2025
5+
ms.date: 03/10/2026
66
ms.devlang: csharp
77
ms.custom:
88
- devx-track-dotnet
9-
- sfi-ropc-nochange
9+
- passwordless-dotnet
1010
---
1111

1212
# Set subscription filters (Azure Service Bus)
@@ -123,6 +123,7 @@ It's equivalent to: `sys.ReplyTo = '[email protected]' AND sys.Label = 'Import
123123

124124

125125
## .NET example for creating subscription filters
126+
126127
Here's a .NET C# example that creates the following Service Bus entities:
127128

128129
- Service Bus topic named `topicfiltersampletopic`
@@ -133,6 +134,93 @@ Here's a .NET C# example that creates the following Service Bus entities:
133134

134135
For more information, see the inline code comments.
135136

137+
### [Passwordless](#tab/passwordless)
138+
139+
```csharp
140+
namespace CreateTopicsAndSubscriptionsWithFilters
141+
{
142+
using Azure.Identity;
143+
using Azure.Messaging.ServiceBus.Administration;
144+
using System;
145+
using System.Threading.Tasks;
146+
147+
public class Program
148+
{
149+
// Service Bus Administration Client object to create topics and subscriptions
150+
static ServiceBusAdministrationClient adminClient;
151+
152+
// fully qualified namespace for the Service Bus
153+
static readonly string fullyQualifiedNamespace = "<YOUR SERVICE BUS NAMESPACE>.servicebus.windows.net";
154+
155+
// name of the Service Bus topic
156+
static readonly string topicName = "topicfiltersampletopic";
157+
158+
// names of subscriptions to the topic
159+
static readonly string subscriptionAllOrders = "AllOrders";
160+
static readonly string subscriptionColorBlueSize10Orders = "ColorBlueSize10Orders";
161+
static readonly string subscriptionColorRed = "ColorRed";
162+
static readonly string subscriptionHighPriorityRedOrders = "HighPriorityRedOrders";
163+
164+
public static async Task Main()
165+
{
166+
try
167+
{
168+
169+
Console.WriteLine("Creating the Service Bus Administration Client object");
170+
adminClient = new ServiceBusAdministrationClient(fullyQualifiedNamespace, new DefaultAzureCredential());
171+
172+
Console.WriteLine($"Creating the topic {topicName}");
173+
await adminClient.CreateTopicAsync(topicName);
174+
175+
Console.WriteLine($"Creating the subscription {subscriptionAllOrders} for the topic with a True filter ");
176+
// Create a True Rule filter with an expression that always evaluates to true
177+
// It's equivalent to using SQL rule filter with 1=1 as the expression
178+
await adminClient.CreateSubscriptionAsync(
179+
new CreateSubscriptionOptions(topicName, subscriptionAllOrders),
180+
new CreateRuleOptions("AllOrders", new TrueRuleFilter()));
181+
182+
183+
Console.WriteLine($"Creating the subscription {subscriptionColorBlueSize10Orders} with a SQL filter");
184+
// Create a SQL filter with color set to blue and quantity to 10
185+
await adminClient.CreateSubscriptionAsync(
186+
new CreateSubscriptionOptions(topicName, subscriptionColorBlueSize10Orders),
187+
new CreateRuleOptions("BlueSize10Orders", new SqlRuleFilter("color='blue' AND quantity=10")));
188+
189+
Console.WriteLine($"Creating the subscription {subscriptionColorRed} with a SQL filter");
190+
// Create a SQL filter with color equals to red and a SQL action with a set of statements
191+
await adminClient.CreateSubscriptionAsync(topicName, subscriptionColorRed);
192+
// remove the $Default rule
193+
await adminClient.DeleteRuleAsync(topicName, subscriptionColorRed, "$Default");
194+
// now create the new rule. notice that user. prefix is used for the user/application property
195+
await adminClient.CreateRuleAsync(topicName, subscriptionColorRed, new CreateRuleOptions
196+
{
197+
Name = "RedOrdersWithAction",
198+
Filter = new SqlRuleFilter("user.color='red'"),
199+
Action = new SqlRuleAction("SET quantity = quantity / 2; REMOVE priority;SET sys.CorrelationId = 'low';")
200+
201+
}
202+
);
203+
204+
Console.WriteLine($"Creating the subscription {subscriptionHighPriorityRedOrders} with a correlation filter");
205+
// Create a correlation filter with color set to Red and priority set to High
206+
await adminClient.CreateSubscriptionAsync(
207+
new CreateSubscriptionOptions(topicName, subscriptionHighPriorityRedOrders),
208+
new CreateRuleOptions("HighPriorityRedOrders", new CorrelationRuleFilter() {Subject = "red", CorrelationId = "high"} ));
209+
210+
// delete resources
211+
//await adminClient.DeleteTopicAsync(topicName);
212+
}
213+
catch (Exception e)
214+
{
215+
Console.WriteLine(e.ToString());
216+
}
217+
}
218+
}
219+
}
220+
```
221+
222+
### [Connection String](#tab/connection-string)
223+
136224
```csharp
137225
namespace CreateTopicsAndSubscriptionsWithFilters
138226
{
@@ -215,8 +303,174 @@ namespace CreateTopicsAndSubscriptionsWithFilters
215303
}
216304
```
217305

306+
---
307+
218308
## .NET example for sending receiving messages
219309

310+
### [Passwordless](#tab/passwordless)
311+
312+
```csharp
313+
namespace SendAndReceiveMessages
314+
{
315+
using System;
316+
using System.Text;
317+
using System.Threading.Tasks;
318+
using Azure.Identity;
319+
using Azure.Messaging.ServiceBus;
320+
using Newtonsoft.Json;
321+
322+
public class Program
323+
{
324+
const string TopicName = "TopicFilterSampleTopic";
325+
const string SubscriptionAllMessages = "AllOrders";
326+
const string SubscriptionColorBlueSize10Orders = "ColorBlueSize10Orders";
327+
const string SubscriptionColorRed = "ColorRed";
328+
const string SubscriptionHighPriorityOrders = "HighPriorityRedOrders";
329+
330+
// fully qualified namespace for the Service Bus
331+
static string fullyQualifiedNamespace = "<YOUR SERVICE BUS NAMESPACE>.servicebus.windows.net";
332+
333+
// the client that owns the connection and can be used to create senders and receivers
334+
static ServiceBusClient client;
335+
336+
// the sender used to publish messages to the topic
337+
static ServiceBusSender sender;
338+
339+
// the receiver used to receive messages from the subscription
340+
static ServiceBusReceiver receiver;
341+
342+
public async Task SendAndReceiveTestsAsync(string fullyQualifiedNamespace)
343+
{
344+
// This sample demonstrates how to use advanced filters with ServiceBus topics and subscriptions.
345+
// The sample creates a topic and 3 subscriptions with different filter definitions.
346+
// Each receiver will receive matching messages depending on the filter associated with a subscription.
347+
348+
// Send sample messages.
349+
await this.SendMessagesToTopicAsync(fullyQualifiedNamespace);
350+
351+
// Receive messages from subscriptions.
352+
await this.ReceiveAllMessageFromSubscription(SubscriptionAllMessages);
353+
await this.ReceiveAllMessageFromSubscription(SubscriptionColorBlueSize10Orders);
354+
await this.ReceiveAllMessageFromSubscription(SubscriptionColorRed);
355+
await this.ReceiveAllMessageFromSubscription(SubscriptionHighPriorityOrders);
356+
}
357+
358+
359+
async Task SendMessagesToTopicAsync(string fullyQualifiedNamespace)
360+
{
361+
// Create the clients that we'll use for sending and processing messages.
362+
client = new ServiceBusClient(fullyQualifiedNamespace, new DefaultAzureCredential());
363+
sender = client.CreateSender(TopicName);
364+
365+
Console.WriteLine("\nSending orders to topic.");
366+
367+
// Now we can start sending orders.
368+
await Task.WhenAll(
369+
SendOrder(sender, new Order()),
370+
SendOrder(sender, new Order { Color = "blue", Quantity = 5, Priority = "low" }),
371+
SendOrder(sender, new Order { Color = "red", Quantity = 10, Priority = "high" }),
372+
SendOrder(sender, new Order { Color = "yellow", Quantity = 5, Priority = "low" }),
373+
SendOrder(sender, new Order { Color = "blue", Quantity = 10, Priority = "low" }),
374+
SendOrder(sender, new Order { Color = "blue", Quantity = 5, Priority = "high" }),
375+
SendOrder(sender, new Order { Color = "blue", Quantity = 10, Priority = "low" }),
376+
SendOrder(sender, new Order { Color = "red", Quantity = 5, Priority = "low" }),
377+
SendOrder(sender, new Order { Color = "red", Quantity = 10, Priority = "low" }),
378+
SendOrder(sender, new Order { Color = "red", Quantity = 5, Priority = "low" }),
379+
SendOrder(sender, new Order { Color = "yellow", Quantity = 10, Priority = "high" }),
380+
SendOrder(sender, new Order { Color = "yellow", Quantity = 5, Priority = "low" }),
381+
SendOrder(sender, new Order { Color = "yellow", Quantity = 10, Priority = "low" })
382+
);
383+
384+
Console.WriteLine("All messages sent.");
385+
}
386+
387+
async Task SendOrder(ServiceBusSender sender, Order order)
388+
{
389+
var message = new ServiceBusMessage(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(order)))
390+
{
391+
CorrelationId = order.Priority,
392+
Subject = order.Color,
393+
ApplicationProperties =
394+
{
395+
{ "color", order.Color },
396+
{ "quantity", order.Quantity },
397+
{ "priority", order.Priority }
398+
}
399+
};
400+
await sender.SendMessageAsync(message);
401+
402+
Console.WriteLine("Sent order with Color={0}, Quantity={1}, Priority={2}", order.Color, order.Quantity, order.Priority);
403+
}
404+
405+
async Task ReceiveAllMessageFromSubscription(string subsName)
406+
{
407+
var receivedMessages = 0;
408+
409+
receiver = client.CreateReceiver(TopicName, subsName, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete } );
410+
411+
// Create a receiver from the subscription client and receive all messages.
412+
Console.WriteLine("\nReceiving messages from subscription {0}.", subsName);
413+
414+
while (true)
415+
{
416+
var receivedMessage = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(10));
417+
if (receivedMessage != null)
418+
{
419+
foreach (var prop in receivedMessage.ApplicationProperties)
420+
{
421+
Console.Write("{0}={1},", prop.Key, prop.Value);
422+
}
423+
Console.WriteLine("CorrelationId={0}", receivedMessage.CorrelationId);
424+
receivedMessages++;
425+
}
426+
else
427+
{
428+
// No more messages to receive.
429+
break;
430+
}
431+
}
432+
Console.WriteLine("Received {0} messages from subscription {1}.", receivedMessages, subsName);
433+
}
434+
435+
public static async Task Main()
436+
{
437+
try
438+
{
439+
Program app = new Program();
440+
await app.SendAndReceiveTestsAsync(fullyQualifiedNamespace);
441+
}
442+
catch (Exception e)
443+
{
444+
Console.WriteLine(e.ToString());
445+
}
446+
}
447+
}
448+
449+
class Order
450+
{
451+
public string Color
452+
{
453+
get;
454+
set;
455+
}
456+
457+
public int Quantity
458+
{
459+
get;
460+
set;
461+
}
462+
463+
public string Priority
464+
{
465+
get;
466+
set;
467+
}
468+
}
469+
}
470+
```
471+
472+
### [Connection String](#tab/connection-string)
473+
220474
```csharp
221475
namespace SendAndReceiveMessages
222476
{
@@ -376,6 +630,8 @@ namespace SendAndReceiveMessages
376630
}
377631
```
378632

633+
---
634+
379635

380636
## Next steps
381637
See the following samples:

articles/service-bus-messaging/topic-filters.md

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Azure Service Bus Topic Filters Overview
33
description: This article explains how subscribers can define which messages they want to receive from a topic by specifying filters.
44
#customer intent: As a developer, I want to understand how to use SQL filters in Azure Service Bus so that I can filter messages based on specific conditions.
55
ms.topic: conceptual
6-
ms.date: 02/10/2026
6+
ms.date: 03/10/2026
77
ms.custom: sfi-ropc-nochange
88
---
99

@@ -36,6 +36,28 @@ A **SqlFilter** holds a SQL-like conditional expression that the broker evaluate
3636

3737
Here's a .NET example for defining a SQL filter:
3838

39+
#### [Passwordless](#tab/passwordless)
40+
41+
```csharp
42+
adminClient = new ServiceBusAdministrationClient(fullyQualifiedNamespace, new DefaultAzureCredential());
43+
44+
// Create a SQL filter with color set to blue and quantity to 10
45+
await adminClient.CreateSubscriptionAsync(
46+
new CreateSubscriptionOptions(topicName, "ColorBlueSize10Orders"),
47+
new CreateRuleOptions("BlueSize10Orders", new SqlRuleFilter("color='blue' AND quantity=10")));
48+
49+
// Create a SQL filter with color set to red
50+
// Action is defined to set the quantity to half if the color is red
51+
await adminClient.CreateRuleAsync(topicName, "ColorRed", new CreateRuleOptions
52+
{
53+
Name = "RedOrdersWithAction",
54+
Filter = new SqlRuleFilter("user.color='red'"),
55+
Action = new SqlRuleAction("SET quantity = quantity / 2;")
56+
}
57+
```
58+
59+
#### [Connection String](#tab/connection-string)
60+
3961
```csharp
4062
adminClient = new ServiceBusAdministrationClient(connectionString);
4163

@@ -53,6 +75,8 @@ await adminClient.CreateRuleAsync(topicName, "ColorRed", new CreateRuleOptions
5375
Action = new SqlRuleAction("SET quantity = quantity / 2;")
5476
}
5577
```
78+
79+
---
5680
### Boolean filters
5781
The **TrueFilter** and **FalseFilter** work as boolean filters. The **TrueFilter** selects all arriving messages for the subscription, and the **FalseFilter** selects none of the arriving messages. These two filters derive from the SQL filter.
5882

@@ -110,6 +134,23 @@ By using SQL filter conditions, you can define an action that annotates the mess
110134

111135
Here's a .NET example that creates a SQL rule with an action to update the quantity when the color is Red.
112136

137+
#### [Passwordless](#tab/passwordless)
138+
139+
```csharp
140+
adminClient = new ServiceBusAdministrationClient(fullyQualifiedNamespace, new DefaultAzureCredential());
141+
142+
// Create a SQL filter with color set to red
143+
// Action is defined to set the quantity to half if the color is red
144+
await adminClient.CreateRuleAsync(topicName, "ColorRed", new CreateRuleOptions
145+
{
146+
Name = "RedOrdersWithAction",
147+
Filter = new SqlRuleFilter("user.color='red'"),
148+
Action = new SqlRuleAction("SET quantity = quantity / 2;")
149+
}
150+
```
151+
152+
#### [Connection String](#tab/connection-string)
153+
113154
```csharp
114155
adminClient = new ServiceBusAdministrationClient(connectionString);
115156

@@ -123,6 +164,8 @@ await adminClient.CreateRuleAsync(topicName, "ColorRed", new CreateRuleOptions
123164
}
124165
```
125166

167+
---
168+
126169
> [!IMPORTANT]
127170
> When you update system properties through rule actions, you might change the expected behavior. Some properties are only evaluated when a message is received in a queue or a topic. Therefore, when you update these properties in a rule action and then deliver them in a subscription, they're ignored. Although when autoforwarding to another queue or topic, they're reevaluated.
128171
>

0 commit comments

Comments
 (0)