Skip to content

Commit 858781e

Browse files
authored
Merge pull request #267861 from spelluru/sbuspeek0301
Added C# code
2 parents f1fda43 + fbe729c commit 858781e

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

articles/service-bus-messaging/message-browsing.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,70 @@ You can specify the maximum number of messages that you want the peek operation
4242

4343
Here's an example snippet for peeking all messages with the Python Service Bus SDK. The `sequence_number​` can be used to track the last peeked message and start browsing at the next message.
4444

45+
### [C#](#tab/csharp)
46+
47+
```csharp
48+
using Azure.Messaging.ServiceBus;
49+
50+
// Create a Service Bus client for your namespace
51+
ServiceBusClient client = new ServiceBusClient("NAMESPACECONNECTIONSTRING");
52+
53+
// Create Service Bus receiver for your queue in the namespace
54+
ServiceBusReceiver receiver = client.CreateReceiver("QUEUENAME");
55+
56+
// Peek operation with max count set to 5
57+
var peekedMessages = await receiver.PeekMessagesAsync(maxMessages: 5);
58+
59+
// Keep receiving while there are messages in the queue
60+
while (peekedMessages.Count > 0)
61+
{
62+
int counter = 0; // To get the sequence number of the last peeked message
63+
int countPeekedMessages = peekedMessages.Count;
64+
65+
if (countPeekedMessages > 0)
66+
{
67+
// For each peeked message, print the message body
68+
foreach (ServiceBusReceivedMessage msg in peekedMessages)
69+
{
70+
Console.WriteLine(msg.Body);
71+
counter++;
72+
}
73+
Console.WriteLine("Peek round complete");
74+
Console.WriteLine("");
75+
}
76+
77+
// Start receiving from the message after the last one
78+
var fromSeqNum = peekedMessages[counter-1].SequenceNumber + 1;
79+
peekedMessages = await receiver.PeekMessagesAsync(maxMessages: 5, fromSequenceNumber: fromSeqNum);
80+
}
81+
```
82+
83+
The following sample output is from peeking a queue with 13 messages in it.
84+
85+
```bash
86+
Message 1
87+
Message 2
88+
Message 3
89+
Message 4
90+
Message 5
91+
Peek round complete
92+
93+
Message 6
94+
Message 7
95+
Message 8
96+
Message 9
97+
Message 10
98+
Peek round complete
99+
100+
Message 11
101+
Message 12
102+
Message 13
103+
Peek round complete
104+
```
105+
106+
107+
### [Python](#tab/python)
108+
45109
```python
46110
import os
47111
from azure.servicebus import ServiceBusClient
@@ -66,6 +130,8 @@ with servicebus_client:
66130
print("Receive is done.")
67131
```
68132

133+
---
134+
69135
## Next steps
70136
Try the samples in the language of your choice to explore Azure Service Bus features.
71137

0 commit comments

Comments
 (0)