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 OnMessageExceptionHandlerCalled()
        {
            var invalidQueueName = "nonexistentqueuename";
            var exceptionReceivedHandlerCalled = false;

            await using var client = CreateClient();
            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-existent 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.CloseAsync();

            Assert.That(
                async() => await processor.StartProcessingAsync(),
                Throws.InstanceOf <ObjectDisposedException>());
        }
Beispiel #3
0
        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");
            }
        }
Beispiel #4
0
        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 ReceiveMessagesAsync()
 {
     // Register the function that will process messages
     _serviceBusProcessor.ProcessMessageAsync += ProcessMessagesAsync;
     _serviceBusProcessor.ProcessErrorAsync   += ProcessErrorsAsync;
     await _serviceBusProcessor.StartProcessingAsync();
 }
Beispiel #6
0
        public async Task CannotStartProcessorWhenConnectionIsClosed()
        {
            var connectionClosed    = false;
            var mockTransportClient = new Mock <TransportClient>();
            var mockConnection      = new Mock <ServiceBusConnection>("not.real.com", Mock.Of <TokenCredential>(), new ServiceBusClientOptions())
            {
                CallBase = true
            };

            mockTransportClient
            .SetupGet(client => client.IsClosed)
            .Returns(() => connectionClosed);

            mockConnection
            .Setup(connection => connection.CreateTransportClient(
                       It.IsAny <ServiceBusTokenCredential>(),
                       It.IsAny <ServiceBusClientOptions>()))
            .Returns(mockTransportClient.Object);

            var processor = new ServiceBusProcessor(
                mockConnection.Object,
                "entityPath",
                false,
                new ServiceBusProcessorOptions());

            processor.ProcessMessageAsync += _ => Task.CompletedTask;
            processor.ProcessErrorAsync   += _ => Task.CompletedTask;

            connectionClosed = true;

            Assert.That(async() => await processor.StartProcessingAsync(),
                        Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));

            await processor.DisposeAsync();
        }
Beispiel #7
0
        public static async Task ReceiveMessagesAsync()
        {
            await using (ServiceBusClient client = new ServiceBusClient(Config.ConnectionString))
            {
                // create a processor that we can use to process the messages
                ServiceBusProcessor processor = client.CreateProcessor(Config.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();

                Thread.Sleep(Timeout.Infinite);
                //Console.WriteLine("press any key to end the processing");
                //Console.ReadKey();

                //// stop processing
                //Console.WriteLine("\nStopping the receiver...");
                //await processor.StopProcessingAsync();
                //Console.WriteLine("Stopped receiving messages");
            }
        }
        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 ReceiveSalesMessageAsync()
        {
            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");


            var client = new ServiceBusClient(ServiceBusConnectionString);

            var processorOptions = new ServiceBusProcessorOptions
            {
                MaxConcurrentCalls   = 1,
                AutoCompleteMessages = false
            };

            await using ServiceBusProcessor processor = client.CreateProcessor(QueueName, processorOptions);

            processor.ProcessMessageAsync += MessageHandler;
            processor.ProcessErrorAsync   += ErrorHandler;


            await processor.StartProcessingAsync();

            Console.Read();

            await processor.CloseAsync();
        }
Beispiel #10
0
        static async Task ReceiveMessageAsync()
        {
            Console.WriteLine("=========================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("=========================================================");
            var options = new ServiceBusProcessorOptions {
                AutoCompleteMessages = false
            };

            await using ServiceBusProcessor processor = string.IsNullOrWhiteSpace(SubscriptionName) ?
                                                        srv.CreateProcessor(QueueOrTopicName, options) :
                                                        srv.CreateProcessor(QueueOrTopicName, SubscriptionName, options);
            processor.ProcessMessageAsync += async(arg) => {
                Console.WriteLine($"Received message: SequenceNumber: {arg.Message.SequenceNumber} Body: {Encoding.UTF8.GetString(arg.Message.Body)}");
                // Console.WriteLine($"Received message: SequenceNumber: {arg.Message.SequenceNumber} Body: {arg.Message.As<Item>().ToString()}");
                if (AbandonarMultiplosDe > 0 && arg.Message.SequenceNumber % AbandonarMultiplosDe == 0)
                {
                    await arg.AbandonMessageAsync(arg.Message);
                }
                else
                {
                    await arg.CompleteMessageAsync(arg.Message);
                }
            };
            processor.ProcessErrorAsync += ExceptionReceivedHandler;
            await processor.StartProcessingAsync();

            Console.Read();
            Console.WriteLine("Exit processor...");
        }
        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();
            }
        }
Beispiel #12
0
        public async Task StopProcessingExceptionLogsEvents()
        {
            var mockLogger            = new Mock <ServiceBusEventSource>();
            var mockTransportReceiver = new Mock <TransportReceiver>();
            var mockConnection        = GetMockConnection(mockTransportReceiver);

            mockTransportReceiver.Setup(
                transportReceiver => transportReceiver.ReceiveBatchAsync(
                    1,
                    It.IsAny <TimeSpan?>(),
                    It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult((IList <ServiceBusReceivedMessage>)
                                     new List <ServiceBusReceivedMessage>
            {
                new ServiceBusReceivedMessage
                {
                    LockTokenGuid = Guid.NewGuid()
                }
            }));
            var processor = new ServiceBusProcessor(mockConnection.Object, "queueName", false, 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);

                throw new TestException();
            }

            await processor.StartProcessingAsync();

            var cts = new CancellationTokenSource();

            cts.Cancel();
            Assert.That(
                async() => await processor.StopProcessingAsync(cts.Token),
                Throws.InstanceOf <TaskCanceledException>());

            mockLogger
            .Verify(
                log => log.StopProcessingStart(
                    processor.Identifier),
                Times.Once);
            mockLogger
            .Verify(
                log => log.StopProcessingException(
                    processor.Identifier,
                    It.IsAny <string>()),
                Times.Once);
        }
Beispiel #13
0
        //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();
            }
        }
        /// <summary>
        /// Subscriber to message queue.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>Task.</returns>
        public virtual Task SubscribeToMessageBusAsync(CancellationToken cancellationToken = default)
        {
            _serviceBusClient = new ServiceBusClient(_option.ConnectionString);

            // create the options to use for configuring the processor
            var options = new ServiceBusProcessorOptions
            {
                // By default or when AutoCompleteMessages is set to true, the processor will complete the message after executing the message handler
                // Set AutoCompleteMessages to false to [settle messages](https://docs.microsoft.com/en-us/azure/service-bus-messaging/message-transfers-locks-settlement#peeklock) on your own.
                // In both cases, if the message handler throws an exception without settling the message, the processor will abandon the message.
                AutoCompleteMessages = false,
                // I can also allow for multi-threading
                MaxConcurrentCalls = 2,
                ReceiveMode        = ServiceBusReceiveMode.PeekLock
            };

            // create a processor that we can use to process the messages
            _serviceBusProcessor = _serviceBusClient.CreateProcessor(_option.QueueName, options);

            // configure the message and error handler to use
            _serviceBusProcessor.ProcessMessageAsync += MessageHandlerAsync;
            _serviceBusProcessor.ProcessErrorAsync   += ErrorHandlerAsync;

            // start processing
            return(_serviceBusProcessor.StartProcessingAsync(cancellationToken));
        }
Beispiel #15
0
        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;
            }
        }
Beispiel #16
0
        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 void StartProcessingExceptionLogsEvents()
        {
            var mockLogger     = new Mock <ServiceBusEventSource>();
            var mockConnection = new Mock <ServiceBusConnection>();

            mockConnection.Setup(
                connection => connection.RetryOptions)
            .Returns(new ServiceBusRetryOptions());
            var processor = new ServiceBusProcessor(mockConnection.Object, "queueName", false, new ServiceBusPlugin[] { }, new ServiceBusProcessorOptions
            {
                AutoComplete = false,
                MaxAutoLockRenewalDuration = TimeSpan.Zero
            })
            {
                Logger = mockLogger.Object
            };

            Assert.That(
                async() => await processor.StartProcessingAsync(),
                Throws.InstanceOf <InvalidOperationException>());

            mockLogger
            .Verify(
                log => log.StartProcessingStart(
                    processor.Identifier),
                Times.Once);
            mockLogger
            .Verify(
                log => log.StartProcessingException(
                    processor.Identifier,
                    It.IsAny <string>()),
                Times.Once);
        }
        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();
                }
            }
        }
Beispiel #19
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _orderPaymentRequestedProcessor.ProcessMessageAsync += ProcessMessageAsync;
            _orderPaymentRequestedProcessor.ProcessErrorAsync   += ErrorHandler;

            await _orderPaymentRequestedProcessor.StartProcessingAsync();
        }
        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);
            };
        }
Beispiel #21
0
        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();
        }
Beispiel #22
0
        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");
        }
    }
Beispiel #24
0
        public async Task SubscribeAsync(
            Func <string, DateTimeOffset, Task> messageHandler,
            Func <Exception, Task> errorHandler,
            CancellationToken cancellationToken)
        {
            // add handler to process messages
            processor.ProcessMessageAsync += async args =>
            {
                using var operation = telemetry.StartOperation <RequestTelemetry>(this, args.Message.CorrelationId);

                var messageProcessingStartDelay = DateTimeOffset.UtcNow - args.Message.EnqueuedTime;
                telemetry.RecordMetric(
                    "StartMessageProcessing-Delay",
                    (long)messageProcessingStartDelay.TotalSeconds);

                await messageHandler(args.Message.Body.ToString(), args.Message.EnqueuedTime);

                // delete the message
                await args.CompleteMessageAsync(args.Message, cancellationToken);
            };

            // add handler to process any errors
            processor.ProcessErrorAsync += async args => { await errorHandler(args.Exception); };

            // start processing
            await processor.StartProcessingAsync(cancellationToken);
        }
        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);
        }
Beispiel #26
0
        private async Task RegisterSubscriptionClientMessageHandlerAsync()
        {
            _serviceBusReceiver.ProcessMessageAsync += MessageHandler;

            _serviceBusReceiver.ProcessErrorAsync += ErrorHandler;

            await _serviceBusReceiver.StartProcessingAsync();
        }
 async Task StartMessageListener()
 {
     processor = client.CreateProcessor(this.TopicName, this.SubscriptionName);
     processor.ProcessMessageAsync += Processor_ProcessMessageAsync;
     processor.ProcessErrorAsync   += Processor_ProcessErrorAsync;
     StartTime = DateTime.UtcNow;
     await processor.StartProcessingAsync();
 }
Beispiel #28
0
 public async Task StartReadAsync(Func <ProcessMessageEventArgs, Task> onMessage, Func <ProcessErrorEventArgs, Task> onError, CancellationToken cancellationToken = default)
 {
     OnMessage = onMessage;
     OnError   = onError;
     ClientReader.ProcessMessageAsync += OnMessage;
     ClientReader.ProcessErrorAsync   += OnError;
     await ClientReader.StartProcessingAsync(cancellationToken).NoContext();
 }
Beispiel #29
0
 public Task StartProcessingAsync(CancellationToken cancellationToken = default)
 {
     return(_serviceBusProcessorAsObject switch
     {
         ServiceBusProcessor serviceBusProcessor => serviceBusProcessor.StartProcessingAsync(cancellationToken),
         ServiceBusSessionProcessor serviceBusSessionProcessor => serviceBusSessionProcessor.StartProcessingAsync(cancellationToken),
         _ => Task.CompletedTask
     });
Beispiel #30
0
        private static Task ReceiveMessages(string queueName, CancellationToken cancellationToken)
        {
            var doneReceiving             = new TaskCompletionSource <bool>();
            ServiceBusProcessor processor = _client.CreateProcessor(queueName);

            // close the receiver and factory when the CancellationToken fires
            cancellationToken.Register(
                async() =>
            {
                await processor.CloseAsync();
                doneReceiving.SetResult(true);
            });

            processor.ProcessMessageAsync += async args =>
            {
                ServiceBusReceivedMessage message = args.Message;
                // If the message holds JSON data and the label is set to "Scientist",
                // we accept the message and print it.
                if (message.Subject != null &&
                    message.ContentType != null &&
                    message.Subject.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) &&
                    message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                {
                    var body = message.Body;

                    // System.Text.JSON does not currently support deserializing to dynamic
                    Dictionary <string, string> scientist = body.ToObjectFromJson <Dictionary <string, string> >();

                    lock (Console.Out)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine(
                            "\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}," +
                            " \n\t\t\t\t\t\tEnqueuedTime = {2}," + "\n\t\t\t\t\t\tExpiresAt = {4}, \n\t\t\t\t\t\tContentType = \"{3}\"," +
                            " \n\t\t\t\t\t\tContent: [ firstName = {5}, name = {6} ]",
                            message.MessageId,
                            message.SequenceNumber,
                            message.EnqueuedTime,
                            message.ContentType,
                            message.ExpiresAt,
                            scientist["firstName"],
                            scientist["name"]);
                        Console.ResetColor();
                    }

                    await args.CompleteMessageAsync(message, args.CancellationToken);
                }
                else
                {
                    // if the messages doesn't fit the criteria above, we deadletter it
                    await args.DeadLetterMessageAsync(message, cancellationToken : args.CancellationToken);
                }
            };

            processor.ProcessErrorAsync += LogMessageHandlerException;
            _ = processor.StartProcessingAsync(cancellationToken);
            return(doneReceiving.Task);
        }