protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await using var client = new ServiceBusClient(connectionString);

            var options = new ServiceBusProcessorOptions
            {
                AutoCompleteMessages = false
            };

            await using var queueProcessor      = client.CreateProcessor(config.Queue, options);
            queueProcessor.ProcessMessageAsync += MessageHandler;
            queueProcessor.ProcessErrorAsync   += ErrorHandler;


            await using var subscriptionProcessor      = client.CreateProcessor(config.Topic, config.Subscription, options);
            subscriptionProcessor.ProcessMessageAsync += MessageHandler;
            subscriptionProcessor.ProcessErrorAsync   += ErrorHandler;

            await queueProcessor.StartProcessingAsync();

            await subscriptionProcessor.StartProcessingAsync();

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(1);
            }
        }
예제 #2
0
        public async Task Test()
        {
            await using var sender = _bus.CreateSender("orders");
            var publisher = new Publisher(sender);

            await _admin.Setup("orders", "ServiceA", "CreateOrder");

            await _bus
            .CreateProcessor("orders", "ServiceA")
            .Hookup(new ServiceA(publisher))
            .StartProcessingAsync();

            await _admin.Setup("orders", "test", "OrderCreated");

            var test = new Subscriber <OrderCreated>();
            await _bus
            .CreateProcessor("orders", "test")
            .Hookup(test)
            .StartProcessingAsync();

            var order = Generator.NewOrder();
            await publisher.Publish("CreateOrder", order, DateTimeOffset.UtcNow);

            await test.Assert(x => x.Should().BeEquivalentTo(order), TimeSpan.FromSeconds(10));
        }
예제 #3
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...");
        }
예제 #4
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);
        }
        private ServiceBusProcessor CreateProcessor(ServiceBusClient client, string entityName, string subscriptionName)
        {
            ServiceBusProcessorOptions options = DetermineMessageProcessorOptions();

            if (string.IsNullOrWhiteSpace(subscriptionName))
            {
                return(client.CreateProcessor(entityName, options));
            }

            return(client.CreateProcessor(entityName, subscriptionName, options));
        }
        public AzServiceBusConsumer(IConfiguration configuration, DbContextOptions <OrderDbContext> options, IMessageBus messageBus)
        {
            _client     = new ServiceBusClient(configuration["ServiceBusConnectionString"]);
            _options    = options;
            _messageBus = messageBus;

            _checkoutMessageTopic            = configuration.GetValue <string>("CheckoutMessageTopic");
            _orderPaymentRequestMessageTopic = configuration.GetValue <string>("OrderPaymentRequestMessageTopic");
            _orderPaymentUpdatedMessageTopic = configuration.GetValue <string>("OrderPaymentUpdatedMessageTopic");

            _checkoutMessageProcessor     = _client.CreateProcessor(_checkoutMessageTopic, _subscriptionName, new ServiceBusProcessorOptions());
            _orderPaymentUpdatedProcessor = _client.CreateProcessor(_orderPaymentUpdatedMessageTopic, _subscriptionName, new ServiceBusProcessorOptions());
        }
예제 #7
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");
            }
        }
예제 #8
0
        public async Task PluginsCanAlterMessageUsingProcessor()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(
                             enablePartitioning: false,
                             enableSession: false))
            {
                var plugin  = new SendReceivePlugin();
                var options = new ServiceBusClientOptions();
                options.AddPlugin(plugin);
                var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
                var sender = client.CreateSender(scope.QueueName);
                await sender.SendMessageAsync(GetMessage());

                Assert.True(plugin.WasCalled);

                var processor = client.CreateProcessor(scope.QueueName);
                processor.ProcessErrorAsync += ExceptionHandler;
                var tcs = new TaskCompletionSource <bool>();
                processor.ProcessMessageAsync += args =>
                {
                    Assert.AreEqual("received", args.Message.Body.ToString());
                    tcs.SetResult(true);
                    return(Task.CompletedTask);
                };
                await processor.StartProcessingAsync();

                await tcs.Task;
                await processor.StopProcessingAsync();
            }
        }
    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");
        }
    }
예제 #10
0
        public void ProcessorOptionsSetOnClient()
        {
            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 options    = new ServiceBusProcessorOptions
            {
                AutoComplete               = false,
                MaxConcurrentCalls         = 10,
                PrefetchCount              = 5,
                ReceiveMode                = ReceiveMode.ReceiveAndDelete,
                MaxAutoLockRenewalDuration = TimeSpan.FromSeconds(60),
                MaxReceiveWaitTime         = TimeSpan.FromSeconds(10)
            };
            var processor = client.CreateProcessor("queueName", options);

            Assert.AreEqual(options.AutoComplete, processor.AutoComplete);
            Assert.AreEqual(options.MaxConcurrentCalls, processor.MaxConcurrentCalls);
            Assert.AreEqual(options.PrefetchCount, processor.PrefetchCount);
            Assert.AreEqual(options.ReceiveMode, processor.ReceiveMode);
            Assert.AreEqual(options.MaxAutoLockRenewalDuration, processor.MaxAutoLockRenewalDuration);
            Assert.AreEqual(fullyQualifiedNamespace, processor.FullyQualifiedNamespace);
            Assert.IsFalse(processor.IsClosed);
            Assert.IsFalse(processor.IsProcessing);
        }
        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;
            }
        }
        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);
            };
        }
        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>());
        }
예제 #14
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();
            }
        }
예제 #15
0
        private static async Task ReceiveTextMessage()
        {
            const string queueName = "sbq-text-message";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(queueName);
            }

            Console.WriteLine($"Receiving messages for {nameof(ReceiveTextMessage)}...");

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            // get the options to use for configuring the processor
            var options = new ServiceBusProcessorOptions
            {
                // By default after the message handler returns, the processor will complete the message
                // If we want more fine-grained control over settlement, we can set this to false.
                AutoCompleteMessages = false,

                // I can also allow for multi-threading
                MaxConcurrentCalls = 2
            };

            // create a processor that we can use to process the messages
            var processor = client.CreateProcessor(queueName, options);

            processor.ProcessMessageAsync += MessageHandler;
            processor.ProcessErrorAsync   += ErrorHandler;
예제 #16
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");
            }
        }
예제 #17
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");
            }
        }
예제 #18
0
        private async Task Process(CancellationToken cancellationToken)
        {
            var options = new ServiceBusProcessorOptions()
            {
                MaxConcurrentCalls = Options.MaxConcurrentCalls
            };

            await using var processor = ServiceBusClient.CreateProcessor(QueueName);

            try
            {
                processor.ProcessMessageAsync += MessageHandler;
                processor.ProcessErrorAsync   += ErrorHandler;
                await processor.StartProcessingAsync(cancellationToken);

                // Block until token is cancelled
                await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
            }
            catch (OperationCanceledException)
            {
            }
            finally
            {
                // Do not flow cancellationToken since we always want to wait for processing to finish
                await processor.StopProcessingAsync();

                processor.ProcessMessageAsync -= MessageHandler;
                processor.ProcessErrorAsync   -= ErrorHandler;
            }
        }
예제 #19
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");
            }
        }
예제 #20
0
        public async Task SetupOrderUpdateTopicListener(Func <OrderResult, Task> action)
        {
            var processor = _client.CreateProcessor(_PurchaseUpdateTopic, _PurchaseUpdateTopicSubscription);

            async Task handleMessage(ProcessMessageEventArgs args)
            {
                var orderResult = JsonSerializer.Deserialize <OrderResult>(args.Message.Body.ToString());

                await action(orderResult);

                await args.CompleteMessageAsync(args.Message);
            }

            Task handleError(ProcessErrorEventArgs args)
            {
                _logger.LogError(args.Exception.ToString());
                return(Task.CompletedTask);
            }

            processor.ProcessMessageAsync += handleMessage;
            processor.ProcessErrorAsync   += handleError;

            // start processing
            await processor.StartProcessingAsync();
        }
예제 #21
0
        public Worker(
            string queueOrTopic,
            string?subscription,
            string tag,
            ServiceBusClient serviceBusClient,
            ServiceBusAdministrationClient administrationClient,
            IClock clock,
            IServiceScopeFactory serviceScopeFactory,
            IOptions <AzureServiceBusOptions> options,
            ILogger <Worker> logger)
        {
            QueueOrTopic          = queueOrTopic;
            Subscription          = subscription == "" ? null : subscription;
            Tag                   = tag;
            ServiceBusClient      = serviceBusClient;
            _administrationClient = administrationClient;
            _clock                = clock;
            _serviceScopeFactory  = serviceScopeFactory;
            _logger               = logger;

            var processorOptions = new ServiceBusProcessorOptions
            {
                MaxConcurrentCalls = options.Value.MaxConcurrentCalls
            };

            _processor = subscription == null?serviceBusClient.CreateProcessor(queueOrTopic, processorOptions) : serviceBusClient.CreateProcessor(queueOrTopic, subscription, processorOptions);

            _processor.ProcessMessageAsync += OnMessageReceivedAsync;
            _processor.ProcessErrorAsync   += OnErrorAsync;
        }
        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();
            }
        }
예제 #23
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();
        }
        /// <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));
        }
예제 #25
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 ServiceBusWaitAndCheck(string connectionString, string topic, string subscription, string filter, Func <Task <bool> > check, int timeout = 60000)
        {
            CheckIsNotNullOrWhitespace(nameof(connectionString), connectionString);
            CheckIsNotNullOrWhitespace(nameof(topic), topic);
            CheckIsNotNullOrWhitespace(nameof(subscription), subscription);
            CheckIsNotNull(nameof(check), check);
            CheckIsNotLessThanOrEqualTo(nameof(timeout), timeout, 0);

            _topic        = topic;
            _subscription = subscription;
            _filter       = filter;

            _wait             = new AsyncManualResetEvent(false);
            _timeout          = timeout;
            _connectionString = connectionString;
            _check            = check;

            _client = new ServiceBusClient(_connectionString);
            CreateSubscription(_connectionString, _topic, _subscription, _filter).Wait();

            _processor = _client.CreateProcessor(topic, subscription, new ServiceBusProcessorOptions());

            _processor.ProcessMessageAsync += _processor_ProcessMessageAsync;
            _processor.ProcessErrorAsync   += _processor_ProcessErrorAsync;
        }
        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();
                }
            }
        }
        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();
        }
        public void Setup()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);
            var client = new ServiceBusClient(_testConnection);
            ServiceBusProcessorOptions processorOptions = new ServiceBusProcessorOptions();
            ServiceBusProcessor        messageProcessor = client.CreateProcessor(_entityPath);

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageProcessor);

            _serviceBusOptions     = new ServiceBusOptions();
            _mockMessagingProvider = new Mock <MessagingProvider>(MockBehavior.Strict, new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));

            _mockMessagingProvider
            .Setup(p => p.CreateMessageProcessor(_entityPath, _testConnection))
            .Returns(_mockMessageProcessor.Object);

            _mockServiceBusAccount = new Mock <ServiceBusAccount>(MockBehavior.Strict);
            _mockServiceBusAccount.Setup(a => a.ConnectionString).Returns(_testConnection);

            _loggerFactory  = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            _listener = new ServiceBusListener(_functionId, EntityType.Queue, _entityPath, false, _mockExecutor.Object, _serviceBusOptions, _mockServiceBusAccount.Object,
                                               _mockMessagingProvider.Object, _loggerFactory, false);
            _scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor();
        }
예제 #30
0
        public void ConcurrencyUpdateManager_UpdatesProcessorConcurrency()
        {
            var concurrencyOptions = new OptionsWrapper <ConcurrencyOptions>(new ConcurrencyOptions {
                DynamicConcurrencyEnabled = true
            });
            var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, _mockConcurrencyThrottleManager.Object);

            _mockConcurrencyThrottleManager.Setup(p => p.GetStatus()).Returns(new ConcurrencyThrottleAggregateStatus {
                State = ThrottleState.Disabled
            });
            ServiceBusProcessor     processor        = _client.CreateProcessor(_entityPath);
            Lazy <MessageProcessor> messageProcessor = new Lazy <MessageProcessor>(() => new MessageProcessor(processor));
            ILogger logger = _loggerFactory.CreateLogger("test");

            ServiceBusListener.ConcurrencyUpdateManager concurrencyUpdateManager = new ServiceBusListener.ConcurrencyUpdateManager(concurrencyManager, messageProcessor, null, false, _functionId, logger);

            // when no messages are being processed, concurrency is not adjusted
            Assert.AreEqual(1, processor.MaxConcurrentCalls);
            SetFunctionCurrentConcurrency(concurrencyManager, _functionId, 10);
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(1, processor.MaxConcurrentCalls);

            // ensure processor concurrency is adjusted up
            concurrencyUpdateManager.MessageProcessed();
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(10, processor.MaxConcurrentCalls);

            // ensure processor concurrency is adjusted down
            SetFunctionCurrentConcurrency(concurrencyManager, _functionId, 5);
            concurrencyUpdateManager.MessageProcessed();
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(5, processor.MaxConcurrentCalls);
        }