public async Task GetChildClientFromClosedParentClientThrows(bool useSessions) { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: useSessions)) { var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); var sender = client.CreateSender(scope.QueueName); var message = GetMessage(useSessions ? "sessionId" : null); await sender.SendAsync(message); await sender.DisposeAsync(); ServiceBusReceiver receiver; if (!useSessions) { receiver = client.CreateReceiver(scope.QueueName); } else { receiver = await client.CreateSessionReceiverAsync(scope.QueueName); } var receivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(receivedMessage.Body.ToArray()) == Encoding.UTF8.GetString(message.Body.ToArray())); await client.DisposeAsync(); if (!useSessions) { Assert.Throws <ObjectDisposedException>(() => client.CreateReceiver(scope.QueueName)); Assert.Throws <ObjectDisposedException>(() => client.CreateReceiver(scope.QueueName, scope.QueueName)); Assert.Throws <ObjectDisposedException>(() => client.CreateSender(scope.QueueName)); } else { Assert.ThrowsAsync <ObjectDisposedException>(async() => await client.CreateSessionReceiverAsync(scope.QueueName)); Assert.ThrowsAsync <ObjectDisposedException>(async() => await client.CreateSessionReceiverAsync(scope.QueueName, sessionId: scope.QueueName)); } Assert.Throws <ObjectDisposedException>(() => client.CreateProcessor(scope.QueueName)); } }
public async Task GetChildClientFromParentSucceedsOnOpenConnection(bool useSessions) { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: useSessions)) { var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); var sender = client.CreateSender(scope.QueueName); var message = GetMessage(useSessions ? "sessionId" : null); await sender.SendAsync(message); await sender.DisposeAsync(); ServiceBusReceiver receiver; if (!useSessions) { receiver = client.CreateReceiver(scope.QueueName); } else { receiver = await client.CreateSessionReceiverAsync(scope.QueueName); } var receivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.AreEqual(message.Body.AsString(), receivedMessage.Body.AsString()); if (!useSessions) { client.CreateReceiver(scope.QueueName); client.CreateReceiver(scope.QueueName, scope.QueueName); client.CreateSender(scope.QueueName); } else { // close old receiver so we can get session lock await receiver.DisposeAsync(); await client.CreateSessionReceiverAsync(scope.QueueName); } client.CreateProcessor(scope.QueueName); } }
public static async Task Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); IConfigurationRoot Configuration = builder.Build(); var publisherConnectionString = Configuration.GetConnectionString("SubscriberConnectionString"); var topicName = Configuration["TopicName"]; Console.WriteLine(topicName); var serviceBusPubClient = new ServiceBusClient(publisherConnectionString); var serviceBusReceiverOptions = new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete }; var subNameA = "sub-a"; var subNameB = "sub-b"; ServiceBusReceiver serviceBusReceiverSubA = serviceBusPubClient.CreateReceiver(topicName, subNameA, serviceBusReceiverOptions); ServiceBusReceiver serviceBusReceiverSubB = serviceBusPubClient.CreateReceiver(topicName, subNameB, serviceBusReceiverOptions); IList <Task> receivers = new List <Task>(); receivers.Add(ReceivedMessagesAsync(serviceBusReceiverSubA, subNameA)); receivers.Add(ReceivedMessagesAsync(serviceBusReceiverSubB, subNameB)); await Task.WhenAll(receivers); await serviceBusReceiverSubA.CloseAsync(); await serviceBusReceiverSubB.CloseAsync(); Console.WriteLine("All messages received"); Console.ReadLine(); }
public SenderReceiverTest(TOptions options) : base(options) { var queue = Environment.GetEnvironmentVariable("SERVICEBUS_QUEUE"); if (string.IsNullOrEmpty(queue)) { throw new InvalidOperationException("Undefined environment variable SERVICEBUS_QUEUE"); } ServiceBusSender = ServiceBusClient.CreateSender(queue); ServiceBusReceiver = ServiceBusClient.CreateReceiver(queue); }
private async Task ProcessMessages(CancellationToken stoppingToken) { ServiceBusReceiver receiver = _sBusClient.CreateReceiver(queueName); await foreach (var message in receiver.ReceiveMessagesAsync(stoppingToken)) { _logger.LogInformation("Message received"); _logger.LogInformation($"Message ID=> {message.MessageId}"); _logger.LogInformation($"Message Body=> {message.Body.ToString()}"); await receiver.CompleteMessageAsync(message, stoppingToken); } }
public void Setup() { _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict); _client = new ServiceBusClient(_testConnection); ServiceBusProcessorOptions processorOptions = new ServiceBusProcessorOptions(); ServiceBusProcessor messageProcessor = _client.CreateProcessor(_entityPath); ServiceBusReceiver receiver = _client.CreateReceiver(_entityPath); _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageProcessor); var configuration = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>(_connection, _testConnection)); _serviceBusOptions = new ServiceBusOptions(); _mockProvider = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions)); _mockClientFactory = new Mock <ServiceBusClientFactory>( configuration, Mock.Of <AzureComponentFactory>(), _mockProvider.Object, new AzureEventSourceLogForwarder(new NullLoggerFactory()), new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions)); _mockProvider .Setup(p => p.CreateMessageProcessor(_client, _entityPath, It.IsAny <ServiceBusProcessorOptions>())) .Returns(_mockMessageProcessor.Object); _mockProvider .Setup(p => p.CreateClient(_testConnection, It.IsAny <ServiceBusClientOptions>())) .Returns(_client); _loggerFactory = new LoggerFactory(); _loggerProvider = new TestLoggerProvider(); _loggerFactory.AddProvider(_loggerProvider); var concurrencyOptions = new OptionsWrapper <ConcurrencyOptions>(new ConcurrencyOptions()); var mockConcurrencyThrottleManager = new Mock <IConcurrencyThrottleManager>(MockBehavior.Strict); var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, mockConcurrencyThrottleManager.Object); _listener = new ServiceBusListener( _functionId, ServiceBusEntityType.Queue, _entityPath, false, _serviceBusOptions.AutoCompleteMessages, _mockExecutor.Object, _serviceBusOptions, _connection, _mockProvider.Object, _loggerFactory, false, _mockClientFactory.Object, concurrencyManager); _scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor(); }
public static async Task DeadLetterMessageAsync(string connectionString, string queueName) { await using var client = new ServiceBusClient(connectionString); // create a receiver that we can use to receive the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // dead-letter the message, thereby preventing the message from being received again without receiving from the dead letter queue. await receiver.DeadLetterMessageAsync(receivedMessage); }
private async Task ProcessMessages(string platform, CancellationToken stoppingToken) { await using ServiceBusReceiver receiver = _sBusClient.CreateReceiver(topicName, platform); await foreach (var message in receiver.ReceiveMessagesAsync(stoppingToken)) { _logger.LogInformation("New show message received for {Platform}", platform); _logger.LogInformation($"Show Message ID=> {message.MessageId}"); _logger.LogInformation($"Show Message Body=> {message.Body.ToString()}"); await receiver.CompleteMessageAsync(message, stoppingToken); } }
protected override ServiceBusReceiver CreateServiceBusReceiver(SubscriptionProperties entity, ServiceBusClient client, bool purgeDeadLetterQueueInstead) { return(client.CreateReceiver( entity.TopicName, entity.SubscriptionName, new ServiceBusReceiverOptions { PrefetchCount = 50, ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete, SubQueue = purgeDeadLetterQueueInstead ? SubQueue.DeadLetter : SubQueue.None })); }
private static async Task ReadMessages() { var receiver = _client.CreateReceiver(_queueName, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete }); Console.WriteLine("Receiving messages from queue"); var messages = await receiver.ReceiveMessagesAsync(16) .ConfigureAwait(false); Console.WriteLine("Printing messages:"); foreach (var item in messages) { Console.Write($"Body: {item.Body} - "); } Console.WriteLine($"Message count: {messages.Count}"); Console.WriteLine("Receiving messages from queue done"); }
public async Task CrossEntityTransaction() { await using var queueA = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var queueB = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var topicC = await ServiceBusScope.CreateWithTopic(enablePartitioning : false, enableSession : false); #region Snippet:ServiceBusCrossEntityTransaction #if SNIPPET string connectionString = "<connection_string>"; var options = new ServiceBusClientOptions { EnableCrossEntityTransactions = true }; await using var client = new ServiceBusClient(connectionString, options); ServiceBusReceiver receiverA = client.CreateReceiver("queueA"); ServiceBusSender senderB = client.CreateSender("queueB"); ServiceBusSender senderC = client.CreateSender("topicC"); #else await using var client = new ServiceBusClient( TestEnvironment.ServiceBusConnectionString, new ServiceBusClientOptions { EnableCrossEntityTransactions = true }); ServiceBusSender senderA = client.CreateSender(queueA.QueueName); await senderA.SendMessageAsync(new ServiceBusMessage()); ServiceBusReceiver receiverA = client.CreateReceiver(queueA.QueueName); ServiceBusSender senderB = client.CreateSender(queueB.QueueName); ServiceBusSender senderC = client.CreateSender(topicC.TopicName); #endif ServiceBusReceivedMessage receivedMessage = await receiverA.ReceiveMessageAsync(); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await receiverA.CompleteMessageAsync(receivedMessage); await senderB.SendMessageAsync(new ServiceBusMessage()); await senderC.SendMessageAsync(new ServiceBusMessage()); ts.Complete(); } #endregion receivedMessage = await receiverA.ReceiveMessageAsync(TimeSpan.FromSeconds(5)); Assert.IsNull(receivedMessage); }
public static async Task <ServiceBusReceivedMessage> GetDeadLetterMessageAsync(string connectionString, string queueName) { await using var client = new ServiceBusClient(connectionString); // receive the dead lettered message with receiver scoped to the dead letter queue. ServiceBusReceiver receiver = client.CreateReceiver(queueName, new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }); // the received message is a different type as it contains some service set properties return(await receiver.ReceiveMessageAsync()); }
public override async Task GlobalSetupAsync() { await base.GlobalSetupAsync().ConfigureAwait(false); QueueScope = await ServiceBusScope.CreateWithQueue( enablePartitioning : false, enableSession : _useSessions, lockDuration : TimeSpan.FromMinutes(5)); Client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); Sender = Client.CreateSender(QueueScope.QueueName); Receiver = Client.CreateReceiver(QueueScope.QueueName); }
public ServiceBusListenerTests() { _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict); _client = new ServiceBusClient(_testConnection); ServiceBusProcessor processor = _client.CreateProcessor(_entityPath); ServiceBusReceiver receiver = _client.CreateReceiver(_entityPath); var configuration = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>("connection", _testConnection)); ServiceBusOptions config = new ServiceBusOptions { ProcessErrorAsync = ExceptionReceivedHandler }; _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, processor); _mockMessagingProvider = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(config)); _mockClientFactory = new Mock <ServiceBusClientFactory>(configuration, Mock.Of <AzureComponentFactory>(), _mockMessagingProvider.Object, new AzureEventSourceLogForwarder(new NullLoggerFactory()), new OptionsWrapper <ServiceBusOptions>(new ServiceBusOptions())); _mockMessagingProvider .Setup(p => p.CreateMessageProcessor(It.IsAny <ServiceBusClient>(), _entityPath, It.IsAny <ServiceBusProcessorOptions>())) .Returns(_mockMessageProcessor.Object); _mockMessagingProvider .Setup(p => p.CreateBatchMessageReceiver(It.IsAny <ServiceBusClient>(), _entityPath, default)) .Returns(receiver); _loggerFactory = new LoggerFactory(); _loggerProvider = new TestLoggerProvider(); _loggerFactory.AddProvider(_loggerProvider); var concurrencyOptions = new OptionsWrapper <ConcurrencyOptions>(new ConcurrencyOptions()); _mockConcurrencyThrottleManager = new Mock <IConcurrencyThrottleManager>(MockBehavior.Strict); var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, _mockConcurrencyThrottleManager.Object); _listener = new ServiceBusListener( _functionId, ServiceBusEntityType.Queue, _entityPath, false, config.AutoCompleteMessages, _mockExecutor.Object, config, "connection", _mockMessagingProvider.Object, _loggerFactory, false, _mockClientFactory.Object, concurrencyManager); _listener.Started = true; }
public async Task DeadLetterMessage() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { string connectionString = TestEnvironment.ServiceBusConnectionString; string queueName = scope.QueueName; // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); // create the sender ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage("Hello world!"); // send the message await sender.SendMessageAsync(message); // create a receiver that we can use to receive and settle the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); #region Snippet:ServiceBusDeadLetterMessage ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // dead-letter the message, thereby preventing the message from being received again without receiving from the dead letter queue. await receiver.DeadLetterMessageAsync(receivedMessage); // receive the dead lettered message with receiver scoped to the dead letter queue. ServiceBusReceiver dlqReceiver = client.CreateReceiver(queueName, new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }); ServiceBusReceivedMessage dlqMessage = await dlqReceiver.ReceiveMessageAsync(); #endregion Assert.IsNotNull(dlqMessage); } }
protected internal override MessageProcessor CreateMessageProcessor(ServiceBusClient client, string entityPath, ServiceBusProcessorOptions options) { // override the options computed from ServiceBusOptions options.MaxConcurrentCalls = 3; options.MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(MaxAutoRenewDurationMin); var processor = client.CreateProcessor(entityPath, options); var receiver = client.CreateReceiver(entityPath); // TODO decide whether it makes sense to still default error handler when there is a custom provider // currently user needs to set it. processor.ProcessErrorAsync += args => Task.CompletedTask; return(new CustomMessageProcessor(processor, _logger)); }
public void CompleteProcessingMessageAsync_Failure_PropagatesException() { ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(); var functionException = new InvalidOperationException("Kaboom!"); FunctionResult result = new FunctionResult(functionException); var client = new ServiceBusClient("Endpoint = sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=abc123="); var actions = new ServiceBusMessageActions(client.CreateReceiver("test-entity")); var ex = Assert.ThrowsAsync <InvalidOperationException>(async() => { await _processor.CompleteProcessingMessageAsync(actions, message, result, CancellationToken.None); }); Assert.AreSame(functionException, ex); }
public async Task AbandonMessages() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); var messageCount = 10; ServiceBusSender sender = client.CreateSender(scope.QueueName); using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync(); IEnumerable <ServiceBusMessage> messages = AddMessages(batch, messageCount).AsEnumerable <ServiceBusMessage>(); await sender.SendMessagesAsync(batch); var receiver = client.CreateReceiver(scope.QueueName); var messageEnum = messages.GetEnumerator(); var remainingMessages = messageCount; IList <ServiceBusReceivedMessage> receivedMessages = new List <ServiceBusReceivedMessage>(); while (remainingMessages > 0) { foreach (var msg in await receiver.ReceiveMessagesAsync(remainingMessages)) { remainingMessages--; messageEnum.MoveNext(); Assert.AreEqual(messageEnum.Current.MessageId, msg.MessageId); receivedMessages.Add(msg); Assert.AreEqual(msg.DeliveryCount, 1); } } Assert.AreEqual(0, remainingMessages); // don't abandon in the receive loop // as this would make the message available to be immediately received again foreach (var msg in receivedMessages) { await receiver.AbandonMessageAsync(msg); } messageEnum.Reset(); var receivedMessageCount = 0; foreach (var item in await receiver.PeekMessagesAsync(messageCount)) { receivedMessageCount++; messageEnum.MoveNext(); Assert.AreEqual(messageEnum.Current.MessageId, item.MessageId); } Assert.AreEqual(messageCount, receivedMessageCount); } }
private async Task ReceiveMessages(string subscription) { await using var client = new ServiceBusClient(ServiceBusConnectionString); ServiceBusReceiver receiver = client.CreateReceiver(TopicName, subscription); // In reality you would not break out of the loop like in this example but would keep looping. The receiver keeps the connection open // to the broker for the specified amount of seconds and the broker returns messages as soon as they arrive. The client then initiates // a new connection. So in reality you would not want to break out of the loop. // Also note that the code shows how to batch receive, which you would do for performance reasons. For convenience you can also always // use the regular receive pump which we show in our Quick Start and in other github samples. while (true) { try { //IList<Message> messages = await receiver.ReceiveAsync(10, TimeSpan.FromSeconds(2)); // Note the extension class which is serializing an deserializing messages and testing messages is null or 0. // If you think you did not receive all messages, just press M and receive again via the menu. IReadOnlyList <ServiceBusReceivedMessage> messages = await receiver.ReceiveMessagesAsync(maxMessages : 100); if (messages.Any()) { foreach (ServiceBusReceivedMessage message in messages) { lock (Console.Out) { Item item = message.As <Item>(); IReadOnlyDictionary <string, object> myUserProperties = message.ApplicationProperties; Console.WriteLine($"StoreId={myUserProperties["StoreId"]}"); if (message.Subject != null) { Console.WriteLine($"Subject={message.Subject}"); } Console.WriteLine( $"Item data: Price={item.GetPrice()}, Color={item.GetColor()}, Category={item.GetItemCategory()}"); } await receiver.CompleteMessageAsync(message); } } else { break; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } }
public async Task Capture_Transaction_When_Receive_From_Queue() { await using var scope = await QueueScope.CreateWithQueue(_adminClient); var sender = _client.CreateSender(scope.QueueName); var receiver = _client.CreateReceiver(scope.QueueName); await sender.SendMessageAsync( new ServiceBusMessage("test message")).ConfigureAwait(false); await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); if (!_sender.WaitForTransactions(TimeSpan.FromMinutes(2))) { throw new Exception("No transaction received in timeout"); } _sender.Transactions.Should().HaveCount(1); var transaction = _sender.FirstTransaction; transaction.Name.Should().Be($"{ServiceBus.SegmentName} RECEIVE from {scope.QueueName}"); transaction.Type.Should().Be(ApiConstants.TypeMessaging); }
public async Task DeferMessages() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); var messageCount = 10; ServiceBusSender sender = client.CreateSender(scope.QueueName); using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync(); IEnumerable <ServiceBusMessage> messages = AddMessages(batch, messageCount).AsEnumerable <ServiceBusMessage>(); await sender.SendMessagesAsync(batch); var receiver = client.CreateReceiver(scope.QueueName); var messageEnum = messages.GetEnumerator(); IList <long> sequenceNumbers = new List <long>(); var remainingMessages = messageCount; while (remainingMessages > 0) { foreach (var item in await receiver.ReceiveMessagesAsync(remainingMessages)) { remainingMessages--; messageEnum.MoveNext(); Assert.AreEqual(messageEnum.Current.MessageId, item.MessageId); sequenceNumbers.Add(item.SequenceNumber); await receiver.DeferMessageAsync(item.LockToken); } } Assert.AreEqual(0, remainingMessages); IReadOnlyList <ServiceBusReceivedMessage> deferredMessages = await receiver.ReceiveDeferredMessagesAsync(sequenceNumbers); var messageList = messages.ToList(); Assert.AreEqual(messageList.Count, deferredMessages.Count); for (int i = 0; i < messageList.Count; i++) { Assert.AreEqual(messageList[i].MessageId, deferredMessages[i].MessageId); Assert.AreEqual(messageList[i].Body.ToBytes().ToArray(), deferredMessages[i].Body.ToBytes().ToArray()); } // verify that looking up a non-existent sequence number will throw sequenceNumbers.Add(45); Assert.That( async() => await receiver.ReceiveDeferredMessagesAsync(sequenceNumbers), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessageNotFound)); } }
public async Task CanSendReceivedMessage() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { var client = new ServiceBusClient( TestEnvironment.FullyQualifiedNamespace, GetTokenCredential()); await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName); using ServiceBusMessageBatch batch = await sender.CreateBatchAsync(); var messageCt = 10; IEnumerable <ServiceBusMessage> messages = AddMessages(batch, messageCt).AsEnumerable <ServiceBusMessage>(); await sender.SendBatchAsync(batch); var receiver = client.CreateReceiver(scope.QueueName, new ServiceBusReceiverOptions() { ReceiveMode = ReceiveMode.ReceiveAndDelete }); var remainingMessages = messageCt; IList <ServiceBusReceivedMessage> receivedMessages = new List <ServiceBusReceivedMessage>(); while (remainingMessages > 0) { foreach (var msg in await receiver.ReceiveBatchAsync(messageCt)) { remainingMessages--; receivedMessages.Add(msg); } } foreach (ServiceBusReceivedMessage msg in receivedMessages) { await sender.SendAsync(ServiceBusMessage.CreateFrom(msg)); } var messageEnum = receivedMessages.GetEnumerator(); remainingMessages = messageCt; while (remainingMessages > 0) { foreach (var msg in await receiver.ReceiveBatchAsync(remainingMessages)) { remainingMessages--; messageEnum.MoveNext(); Assert.AreEqual(messageEnum.Current.MessageId, msg.MessageId); } } Assert.AreEqual(0, remainingMessages); } }
public async Task TransactionGroup() { await using var client = new ServiceBusClient( TestEnvironment.ServiceBusConnectionString, new ServiceBusClientOptions { EnableCrossEntityTransactions = true }); await using var queueA = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var queueB = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var topicC = await ServiceBusScope.CreateWithTopic(enablePartitioning : false, enableSession : false); // The first sender won't be part of our transaction and is // used only to populate the queue. ServiceBusSender senderA = client.CreateSender(queueA.QueueName); await senderA.SendMessageAsync(new ServiceBusMessage()); ServiceBusReceiver receiverA = client.CreateReceiver(queueA.QueueName); ServiceBusSender senderB = client.CreateSender(queueB.QueueName); ServiceBusSender senderC = client.CreateSender(topicC.TopicName); #region Snippet:ServiceBusTransactionGroup //@@ var options = new ServiceBusClientOptions { EnableCrossEntityTransactions = true }; //@@ await using var client = new ServiceBusClient(connectionString, options); //@@ ServiceBusReceiver receiverA = client.CreateReceiver("queueA"); //@@ ServiceBusSender senderB = client.CreateSender("queueB"); //@@ ServiceBusSender senderC = client.CreateSender("topicC"); ServiceBusReceivedMessage receivedMessage = await receiverA.ReceiveMessageAsync(); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await receiverA.CompleteMessageAsync(receivedMessage); await senderB.SendMessageAsync(new ServiceBusMessage()); await senderC.SendMessageAsync(new ServiceBusMessage()); ts.Complete(); } #endregion receivedMessage = await receiverA.ReceiveMessageAsync(); Assert.IsNull(receivedMessage); }
public async Task SendAndReceiveMessageBatch() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { #region Snippet:ServiceBusInitializeSend #if SNIPPET string connectionString = "<connection_string>"; string queueName = "<queue_name>"; #else string connectionString = TestEnvironment.ServiceBusConnectionString; string queueName = scope.QueueName; #endif // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); // create the sender ServiceBusSender sender = client.CreateSender(queueName); #region Snippet:ServiceBusSendAndReceiveBatch IList <ServiceBusMessage> messages = new List <ServiceBusMessage>(); messages.Add(new ServiceBusMessage("First")); messages.Add(new ServiceBusMessage("Second")); // send the messages await sender.SendMessagesAsync(messages); #endregion #endregion #region Snippet:ServiceBusReceiveBatch // create a receiver that we can use to receive the messages ServiceBusReceiver receiver = client.CreateReceiver(queueName); // the received message is a different type as it contains some service set properties IReadOnlyList <ServiceBusReceivedMessage> receivedMessages = await receiver.ReceiveMessagesAsync(maxMessages : 2); foreach (ServiceBusReceivedMessage receivedMessage in receivedMessages) { // get the message body as a string string body = receivedMessage.Body.ToString(); Console.WriteLine(body); } #endregion var sentMessagesEnum = messages.GetEnumerator(); foreach (ServiceBusReceivedMessage receivedMessage in receivedMessages) { sentMessagesEnum.MoveNext(); Assert.AreEqual(sentMessagesEnum.Current.Body.ToString(), receivedMessage.Body.ToString()); } } }
private static async Task <int> Main(string[] args) { if (args.Length == 0) { Console.Error.WriteLine("An Azure Service Bus connection string must be passed as the first argument"); return(1); } Agent.Subscribe(new AzureMessagingServiceBusDiagnosticsSubscriber()); var connectionString = args[0]; var adminClient = new ServiceBusAdministrationClient(connectionString); var client = new ServiceBusClient(connectionString); var queueName = Guid.NewGuid().ToString("D"); Console.WriteLine($"Creating queue {queueName}"); var response = await adminClient.CreateQueueAsync(queueName).ConfigureAwait(false); var sender = client.CreateSender(queueName); Console.WriteLine("Sending messages to queue"); await Agent.Tracer.CaptureTransaction("Send AzureServiceBus Messages", "messaging", async() => { for (var i = 0; i < 10; i++) { await sender.SendMessageAsync(new ServiceBusMessage($"test message {i}")).ConfigureAwait(false); } }); var receiver = client.CreateReceiver(queueName); Console.WriteLine("Receiving messages from queue"); var messages = await receiver.ReceiveMessagesAsync(9) .ConfigureAwait(false); Console.WriteLine("Receiving message from queue"); var message = await receiver.ReceiveMessageAsync() .ConfigureAwait(false); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return(0); }
public static async Task <long> DeferMessageAsync(string connectionString, string queueName) { await using var client = new ServiceBusClient(connectionString); // create a receiver that we can use to receive the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // defer the message, thereby preventing the message from being received again without using // the received deferred message API. await receiver.DeferMessageAsync(receivedMessage); return(receivedMessage.SequenceNumber); }
public async Task ReceiverThrowsWhenUsingSessionEntity() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true)) { await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusSender sender = client.CreateSender(scope.QueueName); ServiceBusMessage sentMessage = GetMessage("sessionId"); await sender.SendMessageAsync(sentMessage); var receiver = client.CreateReceiver(scope.QueueName); Assert.That( async() => await receiver.ReceiveMessageAsync(), Throws.InstanceOf <InvalidOperationException>()); } }
public void ReceiveValidatesMaxMessageCount() { var account = Encoding.Default.GetString(GetRandomBuffer(12)); var fullyQualifiedNamespace = new UriBuilder($"{account}.servicebus.windows.net/").Host; var connString = $"Endpoint=sb://{fullyQualifiedNamespace};SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey={Encoding.Default.GetString(GetRandomBuffer(64))}"; var client = new ServiceBusClient(connString); var receiver = client.CreateReceiver("queueName"); Assert.That( async() => await receiver.ReceiveMessagesAsync(0), Throws.InstanceOf <ArgumentOutOfRangeException>()); Assert.That( async() => await receiver.ReceiveMessagesAsync(-1), Throws.InstanceOf <ArgumentOutOfRangeException>()); }
public async Task DeferMessagesArray() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); var messageCount = 10; ServiceBusSender sender = client.CreateSender(scope.QueueName); using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync(); IEnumerable <ServiceBusMessage> messages = AddMessages(batch, messageCount).AsEnumerable <ServiceBusMessage>(); await sender.SendMessagesAsync(batch); var receiver = client.CreateReceiver(scope.QueueName); var messageEnum = messages.GetEnumerator(); long[] sequenceNumbers = new long[messageCount]; var remainingMessages = messageCount; int idx = 0; while (remainingMessages > 0) { foreach (var item in await receiver.ReceiveMessagesAsync(remainingMessages)) { remainingMessages--; messageEnum.MoveNext(); Assert.AreEqual(messageEnum.Current.MessageId, item.MessageId); sequenceNumbers[idx++] = item.SequenceNumber; await receiver.DeferMessageAsync(item.LockToken); } } Assert.AreEqual(0, remainingMessages); IReadOnlyList <ServiceBusReceivedMessage> deferredMessages = await receiver.ReceiveDeferredMessagesAsync(sequenceNumbers); var messageList = messages.ToList(); Assert.AreEqual(messageList.Count, deferredMessages.Count); for (int i = 0; i < messageList.Count; i++) { Assert.AreEqual(messageList[i].MessageId, deferredMessages[i].MessageId); Assert.AreEqual(messageList[i].Body.ToArray(), deferredMessages[i].Body.ToArray()); } // verify that an empty array can be passed deferredMessages = await receiver.ReceiveDeferredMessagesAsync(Array.Empty <long>()); Assert.IsEmpty(deferredMessages); } }
public async Task SendSessionMessageToNonSessionfulEntityShouldNotThrow() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); var sender = client.CreateSender(scope.QueueName); // this is apparently supported. The session is ignored by the service but can be used // as additional app data. Not recommended. await sender.SendMessageAsync(GetMessage("sessionId")); var receiver = client.CreateReceiver(scope.QueueName); var msg = await receiver.ReceiveMessageAsync(); Assert.AreEqual("sessionId", msg.SessionId); } }