public static async Task StartAsync()
        {
            _subscriptionName = await CreateSubscriptionAsync();

            //create a processor that will be used to process the messages
            _sbProcessor = _sbClient.CreateProcessor(_topicName, _subscriptionName, new ServiceBusProcessorOptions());

            // add handler to process messages
            _sbProcessor.ProcessMessageAsync += MessageHandler;

            // add handler to process any errors
            _sbProcessor.ProcessErrorAsync += ErrorHandler;

            //start processing
            await _sbProcessor.StartProcessingAsync();
        }
示例#2
0
 public ServiceBusIntegration(ServiceBusConfiguration configuration, ServiceBusOptions options)
 {
     Configuration = configuration;
     if (!string.IsNullOrWhiteSpace(options.AccessKey))
     {
         ServiceBusClient client = new(options.ConnectionString);
         this.Client       = client.CreateSender(configuration.Name);
         this.ClientReader = client.CreateProcessor(configuration.Name, options.Options);
     }
     else
     {
         ServiceBusClient client = new(options.FullyQualifiedName, new DefaultAzureCredential());
         this.Client       = client.CreateSender(configuration.Name);
         this.ClientReader = client.CreateProcessor(configuration.Name, options.Options);
     }
 }
示例#3
0
        public async Task RecevoirMessagesAsync()
        {
            var client = new ServiceBusClient(_chaineConnexion);

            // create a processor that we can use to process the messages
            processor = client.CreateProcessor(_nomTopic, _nomSouscription, new ServiceBusProcessorOptions());

            processor.ProcessMessageAsync += ActionSuccesReception;

            processor.ProcessErrorAsync += ActionErreurReception;

            // Commence à écouter le topic
            await processor.StartProcessingAsync();

            Console.WriteLine("En attente de message sur le topic {0} - souscription {1} ...", _nomTopic, _nomSouscription);
        }
示例#4
0
        public async Task CanDisposeClosedProcessor()
        {
            var processor = new ServiceBusProcessor(
                GetMockedReceiverConnection(),
                "entityPath",
                false,
                new ServiceBusProcessorOptions());

            processor.ProcessMessageAsync += _ => Task.CompletedTask;
            processor.ProcessErrorAsync   += _ => Task.CompletedTask;
            await processor.StartProcessingAsync().ConfigureAwait(false);

            await processor.CloseAsync();

            await processor.DisposeAsync();
        }
示例#5
0
        public AzureServiceBusConsumer(IProcessPayment processPayment, IConfiguration configuration, IMessageBus messageBus)
        {
            _processPayment = processPayment;
            _configuration  = configuration;
            _messageBus     = messageBus;

            serviceBusConnectionString    = _configuration.GetValue <string>("ServiceBusConnectionString");
            subscriptionPayment           = _configuration.GetValue <string>("OrderPaymentProcessSubscription");
            orderupdatepaymentresulttopic = _configuration.GetValue <string>("OrderUpdatePaymentResultTopic");
            orderPaymentProcessTopic      = _configuration.GetValue <string>("OrderPaymentProcessTopics");


            var client = new ServiceBusClient(serviceBusConnectionString);

            orderPaymentProcessor = client.CreateProcessor(orderPaymentProcessTopic, subscriptionPayment);
        }
示例#6
0
        public void Setup()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);
            _client       = new ServiceBusClient(_testConnection);
            ServiceBusProcessorOptions processorOptions = new ServiceBusProcessorOptions();
            ServiceBusProcessor        messageProcessor = _client.CreateProcessor(_entityPath);
            ServiceBusReceiver         receiver         = _client.CreateReceiver(_entityPath);

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageProcessor);
            var configuration = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>(_connection, _testConnection));

            _serviceBusOptions = new ServiceBusOptions();
            _mockProvider      = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));
            _mockClientFactory = new Mock <ServiceBusClientFactory>(
                configuration,
                Mock.Of <AzureComponentFactory>(),
                _mockProvider.Object,
                new AzureEventSourceLogForwarder(new NullLoggerFactory()),
                new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));

            _mockProvider
            .Setup(p => p.CreateMessageProcessor(_client, _entityPath, It.IsAny <ServiceBusProcessorOptions>()))
            .Returns(_mockMessageProcessor.Object);

            _mockProvider
            .Setup(p => p.CreateClient(_testConnection, It.IsAny <ServiceBusClientOptions>()))
            .Returns(_client);

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

            _listener = new ServiceBusListener(
                _functionId,
                ServiceBusEntityType.Queue,
                _entityPath,
                false,
                _mockExecutor.Object,
                _serviceBusOptions,
                _connection,
                _mockProvider.Object,
                _loggerFactory,
                false,
                _mockClientFactory.Object);

            _scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor();
        }
        public async Task StartReceiveMessageFromSubscriptionAsync(Action <ProcessMessageEventArgs> processMessageFunc)
        {
            if (string.IsNullOrWhiteSpace(_subscriptionName))
            {
                throw new ArgumentNullException("Parameter SubscriptionName");
            }
            await using (ServiceBusClient client = new ServiceBusClient(_connectionString))
            {
                // create a processor that we can use to process the messages
                processor = client.CreateProcessor(_topicName, _subscriptionName);

                //processor.ProcessMessageAsync += processMessageFunc;
                processor.ProcessErrorAsync += ErrorHandler;

                await processor.StartProcessingAsync();
            }
        }
示例#8
0
 public AzureServiceBusEventBus(EventBusConfiguration eventBusConfiguration,
                                IServiceProvider serviceProvider,
                                IEventBusSubscriptionsManager subscriptionManager,
                                ILogger <AzureServiceBusEventBus> logger,
                                ServiceBusSender serviceBusSender,
                                ServiceBusProcessor serviceBusReceiver,
                                ServiceBusAdministrationClient serviceBusAdministrationClient)
 {
     _eventBusConfiguration = eventBusConfiguration ?? throw new ArgumentNullException(nameof(eventBusConfiguration));
     _serviceProvider       = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _subscriptionManager   = subscriptionManager ?? throw new ArgumentNullException(nameof(subscriptionManager));
     _logger                         = logger ?? throw new ArgumentNullException(nameof(logger));
     _serviceBusSender               = serviceBusSender ?? throw new ArgumentNullException(nameof(serviceBusSender));
     _serviceBusReceiver             = serviceBusReceiver ?? throw new ArgumentNullException(nameof(serviceBusReceiver));
     _serviceBusAdministrationClient = serviceBusAdministrationClient
                                       ?? throw new ArgumentNullException(nameof(serviceBusAdministrationClient));
 }
        public ServiceBusSubscriber(IServiceBusProcessorFactory processorFactory,
                                    IMessageParser messageParser,
                                    IMessageProcessor messageProcessor,
                                    ILogger <ServiceBusSubscriber <TM> > logger)
        {
            if (processorFactory == null)
            {
                throw new ArgumentNullException(nameof(processorFactory));
            }
            _logger           = logger ?? throw new ArgumentNullException(nameof(logger));
            _messageParser    = messageParser ?? throw new ArgumentNullException(nameof(messageParser));
            _messageProcessor = messageProcessor ?? throw new ArgumentNullException(nameof(messageProcessor));

            _processor = processorFactory.Create <TM>();
            _processor.ProcessMessageAsync += MessageHandler;
            _processor.ProcessErrorAsync   += ErrorHandler;
        }
示例#10
0
        public ServiceBusSubscriber(IQueueReferenceFactory queueReferenceFactory,
                                    ServiceBusClient serviceBusClient,
                                    ITransportSerializer messageParser,
                                    IMessageProcessor messageProcessor,
                                    ILogger <ServiceBusSubscriber <TM> > logger, SystemInfo systemInfo)
        {
            _logger           = logger ?? throw new ArgumentNullException(nameof(logger));
            _messageParser    = messageParser ?? throw new ArgumentNullException(nameof(messageParser));
            _messageProcessor = messageProcessor ?? throw new ArgumentNullException(nameof(messageProcessor));
            _systemInfo       = systemInfo ?? throw new ArgumentNullException(nameof(systemInfo));

            var references = queueReferenceFactory.Create <TM>();

            _processor = serviceBusClient.CreateProcessor(references.TopicName, references.SubscriptionName);
            _processor.ProcessMessageAsync += MessageHandler;
            _processor.ProcessErrorAsync   += ProcessErrorAsync;
        }
示例#11
0
        private async Task OpenNewMessageReceiverAsync()
        {
            _messageProcessor = await Settings.CreateMessageProcessorAsync();

            Namespace = _messageProcessor.FullyQualifiedNamespace;

            /* TODO: we can't support Azure Service Bus plug-ins yet because the new Azure SDK doesn't yet support this:
             *       https://github.com/arcus-azure/arcus.messaging/issues/176 */

            RegisterClientInformation(JobId, _messageProcessor.EntityPath);

            Logger.LogTrace("Starting message pump '{JobId}' on entity path '{EntityPath}' in namespace '{Namespace}'", JobId, EntityPath, Namespace);
            _messageProcessor.ProcessErrorAsync   += ProcessErrorAsync;
            _messageProcessor.ProcessMessageAsync += ProcessMessageAsync;
            await _messageProcessor.StartProcessingAsync();

            Logger.LogInformation("Message pump '{JobId}' on entity path '{EntityPath}' in namespace '{Namespace}' started", JobId, EntityPath, Namespace);
        }
示例#12
0
    public EventBusServiceBus(IServiceBusPersisterConnection serviceBusPersisterConnection,
                              ILogger <EventBusServiceBus> logger, IEventBusSubscriptionsManager subsManager, ILifetimeScope autofac, string subscriptionClientName)
    {
        _serviceBusPersisterConnection = serviceBusPersisterConnection;
        _logger           = logger ?? throw new ArgumentNullException(nameof(logger));
        _subsManager      = subsManager ?? new InMemoryEventBusSubscriptionsManager();
        _autofac          = autofac;
        _subscriptionName = subscriptionClientName;
        _sender           = _serviceBusPersisterConnection.TopicClient.CreateSender(_topicName);
        ServiceBusProcessorOptions options = new ServiceBusProcessorOptions {
            MaxConcurrentCalls = 10, AutoCompleteMessages = false
        };

        _processor = _serviceBusPersisterConnection.TopicClient.CreateProcessor(_topicName, _subscriptionName, options);

        RemoveDefaultRule();
        RegisterSubscriptionClientMessageHandlerAsync().GetAwaiter().GetResult();
    }
示例#13
0
 public BasicConsumer(ServiceBusClient client, int?index, ILogger logger, Func <ReadOnlyMemory <byte>, Task> procmessage, Action stop)
 {
     _logger      = logger ?? throw new ArgumentNullException(nameof(logger));
     _procmessage = procmessage ?? throw new ArgumentNullException(nameof(procmessage));
     _stop        = stop ?? throw new ArgumentNullException(nameof(stop));
     _logger.Info("New ServiceBusProcessor starting...");
     _queueName = ModelBuilder.GetQueueName <TMessage>(index).ToLower();
     _processor = client.CreateProcessor(_queueName, new ServiceBusProcessorOptions
     {
         AutoCompleteMessages = false,
         PrefetchCount        = 1, //Only one task at the same time
         MaxConcurrentCalls   = 1,
         ReceiveMode          = ServiceBusReceiveMode.PeekLock
     });
     _processor.ProcessMessageAsync += _processor_ProcessMessageAsync;
     _processor.ProcessErrorAsync   += _processor_ProcessErrorAsync;
     _logger.Info("New ServiceBusProcessor started");
 }
示例#14
0
        public async Task CannotStartProcessorWhenProcessorIsDisposed()
        {
            var mockConnection = GetMockedReceiverConnection();

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

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

            await processor.DisposeAsync();

            Assert.That(async() => await processor.StartProcessingAsync(),
                        Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusProcessor)));
        }
示例#15
0
        public AzureServiceBusConsumer(OrderRepository orderRepository, IConfiguration configuration, IMessageBus messageBus)
        {
            _orderRepository = orderRepository;
            _configuration   = configuration;
            _messageBus      = messageBus;

            serviceBusConnectionString    = _configuration.GetValue <string>("ServiceBusConnectionString");
            subscriptionCheckOut          = _configuration.GetValue <string>("SubscriptionCheckOut");
            checkoutMessageTopic          = _configuration.GetValue <string>("CheckoutMessageTopic");
            orderPaymentProcessTopic      = _configuration.GetValue <string>("OrderPaymentProcessTopics");
            orderUpdatePaymentResultTopic = _configuration.GetValue <string>("OrderUpdatePaymentResultTopic");


            var client = new ServiceBusClient(serviceBusConnectionString);

            checkOutProcessor = client.CreateProcessor(checkoutMessageTopic);
            orderUpdatePaymentStatusProcessor = client.CreateProcessor(orderUpdatePaymentResultTopic, subscriptionCheckOut);
        }
        public ServiceBusMessagingClient(IDistributedSearchConfiguration demoCredential)
        {
            this.configuration = demoCredential;

            this.serviceBusClient = new ServiceBusClient(
                connectionString: demoCredential.ServiceBusConnectionString);

            this.topicClient = this.serviceBusClient.CreateSender(
                queueOrTopicName: demoCredential.ServiceBusTopicNameRequests);

            this.subscriptionClient = this.serviceBusClient.CreateProcessor(
                topicName: demoCredential.ServiceBusTopicNameRequests,
                subscriptionName: demoCredential.ProviderName,
                options: new ServiceBusProcessorOptions
            {
                ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete,
            });
        }
示例#17
0
        public async Task RetrieveMessageAsync(string connectionString, string queueName)
        {
            await using (ServiceBusClient client = new ServiceBusClient(connectionString))
            {
                ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());
                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");
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

            _logger.LogInformation("connection string " + _appSettings.AzureServiceBusSettings.ConnectionString);
            _logger.LogInformation("Topics " + _appSettings.AzureServiceBusSettings.TopicName);
            _logger.LogInformation("Subscription " + _appSettings.AzureServiceBusSettings.Subscription);

            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());

                _logger.LogInformation("ServiceBusProcessor running at: {time}", DateTimeOffset.Now);

                // add handler to process messages
                processor.ProcessMessageAsync += ObjectMessageHandler;

                _logger.LogInformation("ProcessMessageAsync running at: {time}", DateTimeOffset.Now);

                // add handler to process any errors
                processor.ProcessErrorAsync += ObjectErrorHandler;

                _logger.LogInformation("ProcessErrorAsync running at: {time}", DateTimeOffset.Now);

                // start processing
                await processor.StartProcessingAsync();

                _logger.LogInformation("StartProcessingAsync running at: {time}", DateTimeOffset.Now);

                while (!stoppingToken.IsCancellationRequested)
                {
                    if (stopProcess)
                    {
                        _logger.LogInformation("StopProcessingAsync");
                        await processor.StopProcessingAsync();

                        await this.StopAsync(stoppingToken);
                    }
                    //await processor.StopProcessingAsync();
                    //await Task.Delay(1000, stoppingToken);
                }
            }
        }
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            var client = new ServiceBusClient(_testConnection);
            ServiceBusProcessor processor = client.CreateProcessor(_entityPath);
            ServiceBusReceiver  receiver  = client.CreateReceiver(_entityPath);
            var configuration             = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>("connection", _testConnection));

            ServiceBusOptions config = new ServiceBusOptions
            {
                ExceptionHandler = ExceptionReceivedHandler
            };

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

            _mockMessagingProvider = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(config));
            _mockClientFactory     = new Mock <ServiceBusClientFactory>(configuration, Mock.Of <AzureComponentFactory>(), _mockMessagingProvider.Object, new AzureEventSourceLogForwarder(new NullLoggerFactory()), new OptionsWrapper <ServiceBusOptions>(new ServiceBusOptions()));
            _mockMessagingProvider
            .Setup(p => p.CreateMessageProcessor(It.IsAny <ServiceBusClient>(), _entityPath, It.IsAny <ServiceBusProcessorOptions>()))
            .Returns(_mockMessageProcessor.Object);

            _mockMessagingProvider
            .Setup(p => p.CreateBatchMessageReceiver(It.IsAny <ServiceBusClient>(), _entityPath, default))
            .Returns(receiver);

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

            _listener = new ServiceBusListener(
                _functionId,
                ServiceBusEntityType.Queue,
                _entityPath,
                false,
                config.AutoCompleteMessages,
                _mockExecutor.Object,
                config,
                "connection",
                _mockMessagingProvider.Object,
                _loggerFactory,
                false,
                _mockClientFactory.Object);
        }
示例#20
0
        static async Task Main()
        {
            // The Service Bus client types are safe to cache and use as a singleton for the lifetime
            // of the application, which is best practice when messages are being published or read
            // regularly.
            //

            // Create the client object that will be used to create sender and receiver objects
            client = new ServiceBusClient(connectionString);

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

            try
            {
                // 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");
            }
            finally
            {
                // Calling DisposeAsync on client types is required to ensure that network
                // resources and other unmanaged objects are properly cleaned up.
                await processor.DisposeAsync();

                await client.DisposeAsync();
            }
        }
示例#21
0
        public async Task StartReceiveMessagesFromSubscriptionAsync(Action <FileModelReceive> processMessageFunc)
        {
            if (string.IsNullOrWhiteSpace(_subscriptionName))
            {
                throw new ArgumentNullException("Parameter SubscriptionName cannot be null or empty");
            }

            ServiceBusClient client = new ServiceBusClient(_connectionString);

            processor = client.CreateProcessor(_topicName, _subscriptionName, new ServiceBusProcessorOptions());
            processor.ProcessMessageAsync += async args =>
            {
                string body    = args.Message.Body.ToString();
                var    message = JsonSerializer.Deserialize <FileModelReceive>(body);
                processMessageFunc.Invoke(message);
                await args.CompleteMessageAsync(args.Message);
            };
            processor.ProcessErrorAsync += ErrorHandler;
            await processor.StartProcessingAsync();
        }
示例#22
0
        static async Task ReceiveMessagesAsync()
        {
            await using (ServiceBusClient client = new ServiceBusClient(connectionString))
            {
                ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());

                processor.ProcessMessageAsync += MessageHandler;

                processor.ProcessErrorAsync += ErrorHandler;

                await processor.StartProcessingAsync();

                Console.WriteLine("Aguarde um minuto ou então pressione alguma tecla para sair da execução");
                Console.ReadKey();

                await processor.StopProcessingAsync();

                Console.WriteLine("Fim processamento de mensagens");
            }
        }
示例#23
0
文件: Bot.cs 项目: moiph/ub3r-b0t
        /// <summary>
        /// Creates a ServiceBusClient for azure service bus to listen for notifications.
        /// </summary>
        private async Task StartServiceBusListener()
        {
            await using var client = new ServiceBusClient(this.Config.ServiceBusConnectionString);
            var options = new ServiceBusProcessorOptions
            {
                ReceiveMode = ServiceBusReceiveMode.PeekLock,
            };

            await using ServiceBusProcessor processor = client.CreateProcessor(this.queueName, options);
            processor.ProcessMessageAsync            += ServiceBusMessageHandler;
            processor.ProcessErrorAsync += (ProcessErrorEventArgs args) =>
            {
                Log.Error(args.Exception, $"ServiceBus message handler failure. Source: {args.ErrorSource}; Namespace: {args.FullyQualifiedNamespace}; EntityPath: {args.EntityPath}");
                return(Task.CompletedTask);
            };

            await processor.StartProcessingAsync();

            await Task.Delay(-1);
        }
        public static async Task InitializeAsync(ServiceBusConfiguration config, ServiceBusClient client)
        {
            ServiceBusProcessor processor = client.CreateProcessor(config.Queue);

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

            Task MessageHandler(ProcessMessageEventArgs args)
            {
                _receivedMessages.Add($"MessageId:{args.Message.MessageId}, Seq#:{args.Message.SequenceNumber}, data:{args.Message.Body}");
                return(Task.CompletedTask);
            }

            Task ErrorHandler(ProcessErrorEventArgs args)
            {
                _receivedMessages.Add($"Exception: \"{args.Exception.Message}\" {args.EntityPath}");
                return(Task.CompletedTask);
            }

            await processor.StartProcessingAsync();
        }
示例#25
0
        public void CannotRemoveHandlerThatHasNotBeenAdded()
        {
            var processor = new ServiceBusProcessor(
                GetMockedConnection(),
                "entityPath",
                false,
                new ServiceBusProcessorOptions());

            // First scenario: no handler has been set.

            Assert.That(() => processor.ProcessMessageAsync -= eventArgs => Task.CompletedTask, Throws.InstanceOf <ArgumentException>());
            Assert.That(() => processor.ProcessErrorAsync   -= eventArgs => Task.CompletedTask, Throws.InstanceOf <ArgumentException>());

            // Second scenario: there is a handler set, but it's not the one we are trying to remove.

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

            Assert.That(() => processor.ProcessMessageAsync -= eventArgs => Task.CompletedTask, Throws.InstanceOf <ArgumentException>());
            Assert.That(() => processor.ProcessErrorAsync   -= eventArgs => Task.CompletedTask, Throws.InstanceOf <ArgumentException>());
        }
        /// <summary>
        /// Creates an <see cref="ServiceBusProcessor"/> instance based on the provided settings.
        /// </summary>
        internal async Task <ServiceBusProcessor> CreateMessageProcessorAsync()
        {
            if (_tokenCredential is null)
            {
                string rawConnectionString = await GetConnectionStringAsync();

                string entityPath = DetermineEntityPath(rawConnectionString);

                var client = new ServiceBusClient(rawConnectionString);
                return(CreateProcessor(client, entityPath, SubscriptionName));
            }
            else
            {
                var client = new ServiceBusClient(FullyQualifiedNamespace, _tokenCredential);

                string entityPath             = DetermineEntityPath();
                ServiceBusProcessor processor = CreateProcessor(client, entityPath, SubscriptionName);

                return(processor);
            }
        }
示例#27
0
        static async Task ReceiveMessageAsync()
        {
            // create a Service Bus receiver client
            await using (ServiceBusClient client = new ServiceBusClient(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
                };

                // create a processor that we can use to process the messages
                //ServiceBusProcessor processor = client.CreateProcessor(queueName, subscriptionName, new ServiceBusProcessorOptions());
                //https://docs.microsoft.com/en-us/dotnet/api/overview/azure/messaging.servicebus-readme-pre#send-and-receive-a-message
                ServiceBusProcessor processor = client.CreateProcessor(queueName, options);

                // configure/add message and error handler to use
                processor.ProcessMessageAsync += MessageHandler;
                processor.ProcessErrorAsync   += ErrorHandler;

                // start processing
                await processor.StartProcessingAsync();

                Console.WriteLine("Wait for a minute and then press any key to end the processing");
                Console.Read();

                // stop processing
                Console.WriteLine("\nStopping the receiver...");
                await processor.StopProcessingAsync();

                Console.WriteLine("Stopped receiving messages");
            }
        }
示例#28
0
        public NotificationDispatcher(
            IServiceScopeFactory serviceScopeFactory,
            ServiceBusClient serviceBusClient,
            IOptions <NotificationsOptions> notificationsOptions,
            ILogger <NotificationDispatcher> logger)
        {
            this.serviceScopeFactory  = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory));
            this.serviceBusClient     = serviceBusClient ?? throw new ArgumentNullException(nameof(serviceBusClient));
            this.notificationsOptions = notificationsOptions ?? throw new ArgumentNullException(nameof(notificationsOptions));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            queueName = notificationsOptions.Value.Scheduler.AzureServiceBus.QueueName;

            if (string.IsNullOrWhiteSpace(queueName))
            {
                throw new ArgumentException($"Queue name '{queueName}' is not allowed");
            }

            serviceBusProcessor = serviceBusClient.CreateProcessor(queueName);
            serviceBusProcessor.ProcessMessageAsync += ProcessMessageAsync;
            serviceBusProcessor.ProcessErrorAsync   += ProcessErrorAsync;
        }
示例#29
0
        public void CanRemoveHandlerThatHasBeenAdded()
        {
            var processor = new ServiceBusProcessor(
                GetMockedConnection(),
                "entityPath",
                false,
                new ServiceBusProcessorOptions());

            Func <ProcessMessageEventArgs, Task> eventHandler = eventArgs => Task.CompletedTask;
            Func <ProcessErrorEventArgs, Task>   errorHandler = eventArgs => Task.CompletedTask;

            processor.ProcessMessageAsync += eventHandler;
            processor.ProcessErrorAsync   += errorHandler;

            Assert.That(() => processor.ProcessMessageAsync -= eventHandler, Throws.Nothing);
            Assert.That(() => processor.ProcessErrorAsync   -= errorHandler, Throws.Nothing);

            // Assert that handlers can be added again.

            Assert.That(() => processor.ProcessMessageAsync += eventHandler, Throws.Nothing);
            Assert.That(() => processor.ProcessErrorAsync   += errorHandler, Throws.Nothing);
        }
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            IHostBuilder host = Host.CreateDefaultBuilder(args)
                                .ConfigureServices((hostContext, services) =>
            {
                services.AddLogging();

                services.AddApplicationInsightsTelemetryWorkerService(o =>
                {
                    o.EnableAdaptiveSampling = false;
                    o.DeveloperMode          = true;
                });
                services.AddApplicationInsightsTelemetryProcessor <CustomTelemetryProcessor>();
                services.AddSingleton <ITelemetryInitializer, CustomTelemetryInitializer>();

                services.AddSingleton <ServiceBusProcessor>(_ =>
                {
                    ServiceBusClient client       = new ServiceBusClient(hostContext.Configuration.GetValue <string>("AzureServiceBus_ConnectionString"));
                    ServiceBusProcessor processor = client.CreateProcessor(
                        hostContext.Configuration.GetValue <string>("AzureServiceBus_TopicName"),
                        hostContext.Configuration.GetValue <string>("AzureServiceBus_SubscriptionName"),
                        new ServiceBusProcessorOptions()
                    {
                        AutoCompleteMessages = false,
                        MaxConcurrentCalls   = hostContext.Configuration.GetValue <int>("AzureServiceBus_MaxConcurrentCalls")
                    });
                    return(processor);
                });

                services.AddHostedService <Worker>();
            })
                                .ConfigureLogging((hostContext, builder) =>
            {
                builder.AddConsole();
                builder.AddApplicationInsights();
            });

            return(host);
        }