public void StartStopMultipleTimes() { var invalidQueueName = "nonexistentqueuename"; var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusProcessor processor = client.CreateProcessor(invalidQueueName); TaskCompletionSource <bool> taskCompletionSource = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); processor.ProcessMessageAsync += eventArgs => Task.CompletedTask; processor.ProcessErrorAsync += eventArgs => Task.CompletedTask; var startTasks = new List <Task> { processor.StartProcessingAsync(), processor.StartProcessingAsync() }; Assert.That( async() => await Task.WhenAll(startTasks), Throws.InstanceOf <InvalidOperationException>()); var stopTasks = new List <Task>() { processor.StopProcessingAsync(), processor.StopProcessingAsync() }; Assert.That( async() => await Task.WhenAll(stopTasks), Throws.InstanceOf <InvalidOperationException>()); }
public async Task StopProcessingExceptionLogsEvents() { var mockLogger = new Mock <ServiceBusEventSource>(); var mockTransportReceiver = new Mock <TransportReceiver>(); var mockConnection = GetMockConnection(mockTransportReceiver); mockTransportReceiver.Setup( transportReceiver => transportReceiver.ReceiveMessagesAsync( 1, It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult((IReadOnlyList <ServiceBusReceivedMessage>) new List <ServiceBusReceivedMessage> { new ServiceBusReceivedMessage { LockTokenGuid = Guid.NewGuid() } })); var processor = new ServiceBusProcessor(mockConnection.Object, "queueName", false, new ServiceBusPlugin[] { }, new ServiceBusProcessorOptions { AutoComplete = false, MaxAutoLockRenewalDuration = TimeSpan.Zero }) { Logger = mockLogger.Object }; processor.ProcessErrorAsync += ExceptionHandler; processor.ProcessMessageAsync += MessageHandler; async Task MessageHandler(ProcessMessageEventArgs arg) { // simulate IO await Task.Delay(1000); } await processor.StartProcessingAsync(); await processor.StopProcessingAsync(); Assert.That( async() => await processor.StopProcessingAsync(), Throws.InstanceOf <InvalidOperationException>()); mockLogger .Verify( log => log.StopProcessingStart( processor.Identifier), Times.Once); mockLogger .Verify( log => log.StopProcessingException( processor.Identifier, It.IsAny <string>()), Times.Once); }
public static async Task ReceiveMessagesFromSubscriptionAsync() { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "dGVhbTAyOi1BTU1wc25oW251T3IxcFM="); //UNCOMMENT !! await getTable(baseUrl); //COMMENT !! //await Table.readFile(); await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a processor that we can use to process the messages ServiceBusProcessor processor = client.CreateProcessor(topicName, subscriptionName, new ServiceBusProcessorOptions()); // add handler to process messages processor.ProcessMessageAsync += MessageHandler; // add handler to process any errors processor.ProcessErrorAsync += ErrorHandler; // start processing await processor.StartProcessingAsync(); Console.WriteLine("Wait for a minute and then press any key to end the processing"); Console.ReadKey(); // stop processing Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } }
public static async Task ReceiveMessagesFromSubscriptionAsync(string subscriptionName) { await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a processor that we can use to process the messages ServiceBusProcessor processor = client.CreateProcessor(topicName, subscriptionName, new ServiceBusProcessorOptions()); // add handler to process messages processor.ProcessMessageAsync += args => MessageHandler(args, subscriptionName); // add handler to process any errors processor.ProcessErrorAsync += ErrorHandler; // start processing await processor.StartProcessingAsync(); Console.ReadKey(); // stop processing Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } }
public async Task Stop(CancellationToken cancellationToken) { _logger.LogInformationIfEnabled("Stopping event processing at {StartedAt} UTC", DateTime.UtcNow); await _processor.StopProcessingAsync(cancellationToken); _logger.LogInformationIfEnabled("Event processing stopped at {StartedAt} UTC", DateTime.UtcNow); }
public async Task StopReceiveMessageFromSubscriptionAsync() { if (processor != null) { await processor.StopProcessingAsync(); } }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { await using ServiceBusProcessor processor = _serviceBusClient.CreateProcessor(_settings.ServiceBusQueueName, new ServiceBusProcessorOptions { AutoCompleteMessages = true, }); processor.ProcessMessageAsync += ProcessMessageAsync; processor.ProcessErrorAsync += ProcessErrorAsync; await processor.StartProcessingAsync(cancellationToken); try { await Task.Delay(Timeout.Infinite, cancellationToken); } catch (TaskCanceledException) { } try { await processor.StopProcessingAsync(); } finally { processor.ProcessMessageAsync -= ProcessMessageAsync; processor.ProcessErrorAsync -= ProcessErrorAsync; } }
static async Task Main() { client = new ServiceBusClient(connectionString); processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions()); try { processor.ProcessMessageAsync += MessageHandler; processor.ProcessErrorAsync += ErrorHandler; await processor.StartProcessingAsync(); Console.WriteLine("Wait for a minute and then press any key to end the processing"); Console.ReadKey(); Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } finally { await processor.DisposeAsync(); await client.DisposeAsync(); } }
private async Task CloseMessageReceiverAsync() { if (_messageProcessor is null) { return; } try { Logger.LogTrace("Closing message pump '{JobId}' on entity path '{EntityPath}' in '{Namespace}'", JobId, EntityPath, Namespace); await _messageProcessor.StopProcessingAsync(); _messageProcessor.ProcessMessageAsync -= ProcessMessageAsync; _messageProcessor.ProcessErrorAsync -= ProcessErrorAsync; await _messageProcessor.CloseAsync(); Logger.LogInformation("Message pump '{JobId}' on entity path '{EntityPath}' in '{Namespace}' closed : {Time}", JobId, EntityPath, Namespace, DateTimeOffset.UtcNow); } catch (TaskCanceledException) { // Ignore. } catch (Exception exception) { Logger.LogWarning(exception, "Cannot correctly close the message pump '{JobId}' on entity path '{EntityPath}' in '{Namespace}': {Message}", JobId, EntityPath, Namespace, exception.Message); } }
//private static string _subscriptionName = "demosubscription2"; static async Task Main(string[] args) { var connStr = ""; var topicName = "demotopic1"; _topicClient = new ServiceBusClient(connStr); _processor = _topicClient.CreateProcessor(topicName, _subscriptionName, new ServiceBusProcessorOptions()); try { _processor.ProcessMessageAsync += MessageHandler; _processor.ProcessErrorAsync += ErrorHandler; await _processor.StartProcessingAsync(); Console.WriteLine("Wait for a minute and then press any key to end the processing"); Console.ReadKey(); Console.WriteLine("Stopping"); await _processor.StopProcessingAsync(); Console.WriteLine("Stopped"); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } finally { await _processor.DisposeAsync(); await _topicClient.DisposeAsync(); } }
static async Task ReceiveMessagesAsync() { await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a processor that we can use to process the messages ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions()); // add handler to process messages processor.ProcessMessageAsync += MessageHandler; // add handler to process any errors processor.ProcessErrorAsync += ErrorHandler; // start processing await processor.StartProcessingAsync(); Console.WriteLine("Wait for a minute and then press any key to end the processing"); Console.ReadKey(); // stop processing Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } }
public async Task ReceiveMessageAsync(string connectionString, string queueName) { try { await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock }); processor.ProcessMessageAsync += ProcessQueueMessageAsync; processor.ProcessErrorAsync += ProcessErrorMessageAsync; await processor.StartProcessingAsync(); Console.WriteLine("Wait for a minute and then press any key to end the processing"); Console.ReadKey(); // stop processing Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } } catch (System.Exception) { throw; } }
private static async Task Main(string[] args) { ServiceBusProcessor _editorialMessagesProcessor = null; try { ServiceBusClient serviceBusClient = new ServiceBusClient(ConnectionString); _editorialMessagesProcessor = serviceBusClient.CreateProcessor(TopicName, SubscriptionName); //SPIEGA _editorialMessagesProcessor.ProcessMessageAsync += PizzaItemMessageHandler; _editorialMessagesProcessor.ProcessErrorAsync += PizzaItemErrorHandler; await _editorialMessagesProcessor.StartProcessingAsync(); Console.WriteLine("Waiting for pizza orders"); Console.ReadKey(); } catch (Exception) { throw; } finally { if (_editorialMessagesProcessor != null) { await _editorialMessagesProcessor.StopProcessingAsync(); } } }
public async Task ProcessorActivities() { ClientDiagnosticListener.ProducedLink[] messageActivities = null; int messageProcessedCt = 0; bool callbackExecuted = false; _listener = new ClientDiagnosticListener( EntityScopeFactory.DiagnosticNamespace, scopeStartCallback: scope => { if (scope.Name == DiagnosticProperty.ProcessMessageActivityName) { Assert.IsNotNull(messageActivities); Assert.AreEqual( messageActivities[messageProcessedCt], scope.Links.Single()); callbackExecuted = true; } }); await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusSender sender = client.CreateSender(scope.QueueName); var messageCt = 2; var msgs = ServiceBusTestUtilities.GetMessages(messageCt); await sender.SendMessagesAsync(msgs); Activity[] sendActivities = AssertSendActivities(false, sender, msgs); messageActivities = sendActivities.Select(a => new ClientDiagnosticListener.ProducedLink(a.ParentId, a.TraceStateString)).ToArray(); ServiceBusProcessor processor = client.CreateProcessor(scope.QueueName, new ServiceBusProcessorOptions { AutoCompleteMessages = false, MaxReceiveWaitTime = TimeSpan.FromSeconds(10), MaxConcurrentCalls = 1 }); TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>(); processor.ProcessMessageAsync += args => { if (++messageProcessedCt == messageCt) { tcs.SetResult(true); } return(Task.CompletedTask); }; processor.ProcessErrorAsync += ServiceBusTestUtilities.ExceptionHandler; await processor.StartProcessingAsync(); await tcs.Task; await processor.StopProcessingAsync(); for (int i = 0; i < messageCt; i++) { _listener.AssertAndRemoveScope(DiagnosticProperty.ReceiveActivityName); var processScope = _listener.AssertAndRemoveScope(DiagnosticProperty.ProcessMessageActivityName); AssertCommonTags(processScope.Activity, processor.EntityPath, processor.FullyQualifiedNamespace); } Assert.IsTrue(callbackExecuted); }; }
static async Task MainAsync() { serviceBusClient = new ServiceBusClient(ServiceBusConnectionString); serviceBusProcessor = serviceBusClient.CreateProcessor(TopicName, SubscriptionName, RegisterOptions()); //serviceBusProcessor = serviceBusClient.CreateProcessor(QueueName, RegisterOptions()); serviceBusProcessor.ProcessErrorAsync += ExceptionReceivedHandler; serviceBusProcessor.ProcessMessageAsync += ProcessMessagesAsync; Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register the queue message handler and receive messages in a loop try { serviceBusProcessor.StartProcessingAsync(); } catch (ServiceBusException e) { System.Console.WriteLine("OH SNAP!: " + e.Message); } Console.ReadLine(); await serviceBusProcessor.StopProcessingAsync(); await serviceBusProcessor.CloseAsync(); await serviceBusClient.DisposeAsync(); }
public async Task UpdateWantedList() { await using (ServiceBusClient client = new ServiceBusClient(_connectionString)) { // create a processor that we can use to process the messages ServiceBusProcessor processor = client.CreateProcessor(_wantedTopic, _subscriptionKey, new ServiceBusProcessorOptions()); // add handler to process messages processor.ProcessMessageAsync += MessageHandler; // add handler to process any errors processor.ProcessErrorAsync += ErrorHandler; // start processing await processor.StartProcessingAsync(); Console.WriteLine("Waiting for updates..."); Console.ReadKey(); // stop processing Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } }
public static async Task ReceiveMessagesAsync() { string connectionString = "Endpoint=sb://demobusk8.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Xpmhbbn6TwtKl0agPsIeqCX6z2ZI29UAcWzx7zwxaWk="; string queueName = "queuecityworksnet"; await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a processor that we can use to process the messages ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions()); // add handler to process messages processor.ProcessMessageAsync += MessageHandler; // add handler to process any errors processor.ProcessErrorAsync += ErrorHandler; // start processing await processor.StartProcessingAsync(); Console.WriteLine("Wait for a minute and then press any key to end the processing"); Thread.Sleep(5000000); // stop processing Console.WriteLine("\nStopping the receiver..."); await processor.StopProcessingAsync(); Console.WriteLine("Stopped receiving messages"); } }
public async Task StopReadAsync(CancellationToken cancellationToken = default) { await ClientReader.StopProcessingAsync(cancellationToken).NoContext(); ClientReader.ProcessMessageAsync -= OnMessage; ClientReader.ProcessErrorAsync -= OnError; }
protected virtual async Task DisposeInternal() { // Hmmm... why does StopProcessingAsync take so long? _ = Task.Run(() => { try { _processor.StopProcessingAsync().Wait(); } catch { } }); try { await DeleteSubscription(_connectionString, _topic, _subscription); } catch { } try { await _client.DisposeAsync().AsTask(); } catch { } }
public async Task StartStopProcessingLogsEvents() { var mockLogger = new Mock <ServiceBusEventSource>(); var mockTransportReceiver = new Mock <TransportReceiver>(); var mockConnection = GetMockConnection(mockTransportReceiver); mockTransportReceiver.Setup( transportReceiver => transportReceiver.ReceiveMessagesAsync( 1, It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult((IList <ServiceBusReceivedMessage>) new List <ServiceBusReceivedMessage>() { new ServiceBusReceivedMessage() })); var processor = new ServiceBusProcessor(mockConnection.Object, "queueName", false, new ServiceBusPlugin[] { }, new ServiceBusProcessorOptions { MaxAutoLockRenewalDuration = TimeSpan.Zero, AutoComplete = false }) { Logger = mockLogger.Object }; processor.ProcessErrorAsync += ExceptionHandler; processor.ProcessMessageAsync += MessageHandler; async Task MessageHandler(ProcessMessageEventArgs arg) { // simulate IO await Task.Delay(1000); } await processor.StartProcessingAsync(); mockLogger .Verify( log => log.StartProcessingStart( processor.Identifier), Times.Once); mockLogger .Verify( log => log.StartProcessingComplete( processor.Identifier), Times.Once); await processor.StopProcessingAsync(); mockLogger .Verify( log => log.StopProcessingStart( processor.Identifier), Times.Once); mockLogger .Verify( log => log.StopProcessingComplete( processor.Identifier), Times.Once); }
public override async Task StopAsync(CancellationToken cancellationToken) { await _processor.StopProcessingAsync(cancellationToken); _logger.LogInformation("ServiceBus EventHandler Service Stop."); await base.StopAsync(cancellationToken); }
public async Task ArreterReceptionMessages() { Console.ReadKey(); Console.WriteLine("\nArrêt du souscripteur..."); await processor.StopProcessingAsync(); Console.WriteLine("Le souscripteur a arreté de recevoir les messages"); }
public async Task OnMessageExceptionHandlerCalledTest() { var invalidQueueName = "nonexistentqueuename"; var exceptionReceivedHandlerCalled = false; var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusProcessor processor = client.GetProcessor(invalidQueueName); processor.ProcessMessageAsync += ProcessMessage; processor.ProcessErrorAsync += ProcessErrors; Task ProcessMessage(ProcessMessageEventArgs args) { Assert.Fail("Unexpected exception: Did not expect messages here"); return(Task.CompletedTask); } Task ProcessErrors(ProcessErrorEventArgs args) { Assert.NotNull(args); Assert.NotNull(args.Exception); Assert.AreEqual(processor.FullyQualifiedNamespace, args.FullyQualifiedNamespace); Assert.AreEqual(ExceptionReceivedEventArgsAction.Receive, args.Action); Assert.AreEqual(processor.EntityPath, args.EntityPath); if (args.Exception is ServiceBusException sbException) { if (sbException.Reason == ServiceBusException.FailureReason.MessagingEntityNotFound) { exceptionReceivedHandlerCalled = true; return(Task.CompletedTask); } } Assert.Fail($"Unexpected exception: {args.Exception}"); return(Task.CompletedTask); } try { await processor.StartProcessingAsync(); var stopwatch = Stopwatch.StartNew(); while (stopwatch.Elapsed.TotalSeconds <= 10) { if (exceptionReceivedHandlerCalled) { break; } await Task.Delay(TimeSpan.FromSeconds(1)); } Assert.True(exceptionReceivedHandlerCalled); } finally { await processor.StopProcessingAsync(); } }
public async Task CloseConnectionAsync() { await _serviceBusProcessor.StopProcessingAsync(); await _serviceBusProcessor.CloseAsync(); await _serviceBusClient.DisposeAsync(); Console.WriteLine("Client connection closed"); }
public async Task Stop() { await checkOutProcessor.StopProcessingAsync(); await checkOutProcessor.DisposeAsync(); await orderUpdatePaymentStatusProcessor.StopProcessingAsync(); await orderUpdatePaymentStatusProcessor.DisposeAsync(); }
public async void Dispose() { // stop processing await processor.StopProcessingAsync(); await processor.DisposeAsync(); await sender.DisposeAsync(); await serviceBusClient.DisposeAsync(); }
public async Task ProcessorActivities() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { using var listener = new TestDiagnosticListener(EntityScopeFactory.DiagnosticNamespace); var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusSender sender = client.CreateSender(scope.QueueName); var messageCt = 2; var msgs = GetMessages(messageCt); await sender.SendMessagesAsync(msgs); Activity[] sendActivities = AssertSendActivities(false, sender, msgs, listener); ServiceBusProcessor processor = client.CreateProcessor(scope.QueueName, new ServiceBusProcessorOptions { AutoComplete = false, MaxReceiveWaitTime = TimeSpan.FromSeconds(10), MaxConcurrentCalls = 1 }); TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>(); int messageProcessedCt = 0; processor.ProcessMessageAsync += args => { messageProcessedCt++; if (messageProcessedCt == messageCt) { tcs.SetResult(true); } return(Task.CompletedTask); }; processor.ProcessErrorAsync += ExceptionHandler; await processor.StartProcessingAsync(); await tcs.Task; await processor.StopProcessingAsync(); for (int i = 0; i < messageCt; i++) { (string Key, object Value, DiagnosticListener)receiveStart = listener.Events.Dequeue(); (string Key, object Value, DiagnosticListener)receiveStop = listener.Events.Dequeue(); (string Key, object Value, DiagnosticListener)processStart = listener.Events.Dequeue(); Assert.AreEqual(DiagnosticProperty.ProcessMessageActivityName + ".Start", processStart.Key); Activity processActivity = (Activity)processStart.Value; AssertCommonTags(processActivity, processor.EntityPath, processor.FullyQualifiedNamespace); CollectionAssert.Contains( processActivity.Tags, new KeyValuePair <string, string>( DiagnosticProperty.MessageIdAttribute, msgs[i].MessageId)); (string Key, object Value, DiagnosticListener)processStop = listener.Events.Dequeue(); Assert.AreEqual(DiagnosticProperty.ProcessMessageActivityName + ".Stop", processStop.Key); } }; }
//ServiceBusProcessor.StopProcessingAsync currently has a bug when using the AMQP protocol that prevents it from gracefully shutting down in a timely manner //it will timeout after 1 min and eventually shutdown but we don't want to wait for that so do all shutdown waiting in an async void method. private async void Stop() { await using (_sender) await using (_processor) { await _processor.StopProcessingAsync(); await _processor.CloseAsync(); await _sender.CloseAsync(); } }
public async Task Stop(bool initializedByAzureServiceBus) { _logger.Info($"ServiceBusProcessor for queue {_queueName} is stoping..."); if (initializedByAzureServiceBus) { _stop(); } await _processor.StopProcessingAsync(); await _processor.DisposeAsync(); }
public async Task OnMessageExceptionHandlerCalled() { var invalidQueueName = "nonexistentqueuename"; var exceptionReceivedHandlerCalled = false; var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusProcessor processor = client.CreateProcessor(invalidQueueName); TaskCompletionSource <bool> taskCompletionSource = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); processor.ProcessMessageAsync += ProcessMessage; processor.ProcessErrorAsync += ProcessErrors; Task ProcessMessage(ProcessMessageEventArgs args) { Assert.Fail("Unexpected exception: Did not expect messages here"); return(Task.CompletedTask); } Task ProcessErrors(ProcessErrorEventArgs args) { Assert.NotNull(args); Assert.NotNull(args.Exception); Assert.AreEqual(processor.FullyQualifiedNamespace, args.FullyQualifiedNamespace); Assert.AreEqual(ServiceBusErrorSource.Receive, args.ErrorSource); Assert.AreEqual(processor.EntityPath, args.EntityPath); if (args.Exception is ServiceBusException sbException) { if (sbException.Reason == ServiceBusFailureReason.MessagingEntityNotFound || // There is a race condition wherein the service closes the connection when getting // the request for the non-existant queue. If the connection is closed by the time // our exception handling kicks in, we throw it as a ServiceCommunicationProblem // as we cannot be sure the error wasn't due to the connection being closed, // as opposed to what we know is the true cause in this case, // MessagingEntityNotFound. sbException.Reason == ServiceBusFailureReason.ServiceCommunicationProblem) { exceptionReceivedHandlerCalled = true; taskCompletionSource.SetResult(true); return(Task.CompletedTask); } } Assert.Fail($"Unexpected exception: {args.Exception}"); return(Task.CompletedTask); } await processor.StartProcessingAsync(); await taskCompletionSource.Task; Assert.True(exceptionReceivedHandlerCalled); await processor.StopProcessingAsync(); }