Ejemplo n.º 1
0
 public ServiceBusMessageStateHandler(IReceiverClient client, Message sbMessage, IMessageSerializer serializer, int deadLetterDeliveryLimit)
 {
     DeadLetterDeliveryLimit = deadLetterDeliveryLimit;
     _client    = client;
     _sbMessage = sbMessage;
     _message   = serializer.Deserialize <T>(Encoding.UTF8.GetString(_sbMessage.Body));
 }
Ejemplo n.º 2
0
        void AddReceiveContextPayloads(ReceiveContext receiveContext, IReceiverClient receiverClient, Message message)
        {
            MessageLockContext lockContext = new ReceiverClientMessageLockContext(receiverClient, message);

            receiveContext.GetOrAddPayload(() => lockContext);
            receiveContext.GetOrAddPayload(() => _context);
        }
        /// <summary>
        /// Receives from queue.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="targetModel">The target model.</param>
        /// <param name="handler">The handler.</param>
        /// <returns></returns>
        public bool ReceiveFromQueue <T>(T targetModel, Func <T, Task> handler)
        {
            try
            {
                ServiceBusDetails serviceBusDetails = GetServiceBusDetailsFromT(targetModel.GetType());

                if (!string.IsNullOrEmpty(serviceBusDetails.Connection))
                {
                    receiverClient = new AzureQueueReceiver(serviceBusDetails.Connection, serviceBusDetails.QueueName);
                    MessageHandlerOptions messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentCalls = 50,
                        AutoComplete       = true
                    };

                    //subscriptionClient.RegisterMessageHandler(handler, messageHandlerOptions);
                    receiverClient.RegisterMessageHandler(async(msg, token) =>
                    {
                        // Get message
                        string message      = Encoding.UTF8.GetString(msg.Body).ToBase64Decode();
                        dynamic obj         = JsonConvert.DeserializeObject(message);
                        dynamic retrunModel = JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(obj.originalvalue));
                        handler(retrunModel);
                    }, messageHandlerOptions);

                    return(true);
                }

                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 4
0
 internal MessageDispatcher(IServiceScopeFactory scopeFactory, IReceiverClient client, MessageHandlerRegistry registry, LogCorrelationHandler logCorrelationHandler)
 {
     LogCorrelationHandler = logCorrelationHandler;
     ScopeFactory          = scopeFactory;
     Client   = client;
     Registry = registry;
 }
Ejemplo n.º 5
0
        public async Task Start()
        {
            var serviceBusConnectionString = _configuration.GetConnectionString("AzureServiceBus");

            _serviceBusConfig = _configuration.GetSection(nameof(ServiceBusConfig)).Get <ServiceBusConfig>();
            var busConfig = _configuration.GetSection(nameof(BusConfig)).Get <BusConfig>();

            if (busConfig != null)
            {
                _logger.LogWarning($"{busConfig.BusType} with ConnectionString {serviceBusConnectionString.ReplaceWithStars(20)} will delay start for {busConfig.BusDelayStartInSec} ");
                await Task.Delay(busConfig.BusDelayStartInSec * 1000);

                _logger.LogWarning($"{busConfig.BusType} connecting...");
            }

            _approvedAdoProjcetMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, _serviceBusConfig.ApprovedAdoProjectsTopic, _serviceBusConfig.ApprovedAdoProjectsSub);
            _rejectedAdoProjcetMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, _serviceBusConfig.RejectedAdoProjectsTopic, _serviceBusConfig.RejectedAdoProjectsSub);
            //queueReceiverClient = new QueueClient(serviceBusConnectionString, _serviceBusConfig.QueueNameTest);

            var messageHandlerOptions = new MessageHandlerOptions(OnServiceBusException)
            {
                MaxConcurrentCalls = 5, AutoComplete = false
            };

            _approvedAdoProjcetMessageReceiverClient?.RegisterMessageHandler(OnApprovedReceived, messageHandlerOptions);
            _rejectedAdoProjcetMessageReceiverClient?.RegisterMessageHandler(OnRejectedReceived, messageHandlerOptions);
            //queueReceiverClient?.RegisterMessageHandler(ExecuteQueueMessageProcessing, messageHandlerOptions);
        }
Ejemplo n.º 6
0
        public Task SubscribeAsync(CancellationToken cancelToken)
        {
            if (cancelToken == null)
            {
                throw new ArgumentNullException(nameof(cancelToken));
            }

            if (IsClosed)
            {
                throw new InvalidOperationException("Service bus connection has already been closed.");
            }

            if ((receiverClient == null) && (cancelToken.IsCancellationRequested == false))
            {
                receiverClient = CreateReceiverClient();

                var messageHandlerOptions = new MessageHandlerOptions(HandleMessagingExceptionAsync)
                {
                    AutoComplete = false
                };

                cancelToken.Register(async() => await receiverClient.CloseAsync().ConfigureAwait(false));
                receiverClient.RegisterMessageHandler(HandleMessageAsync, messageHandlerOptions);
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 7
0
        private void InitializeClients(ChannelType channelType)
        {
            var channelName      = _configuration.GetServiceBusChannelName(channelType, _channel);
            var retryPolicy      = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), 10);
            var connectionString = _configuration.GetServiceBusConnectionString();

            switch (channelType)
            {
            case ChannelType.PublishSubscribe:
                _receiverClient = new SubscriptionClient(connectionString, channelName, _subscriptionName, retryPolicy: retryPolicy);
                _senderClient   = new TopicClient(connectionString, channelName, retryPolicy);
                break;

            case ChannelType.PointToPoint:
                var queueClient = new QueueClient(connectionString, channelName, ReceiveMode.PeekLock, retryPolicy);
                _receiverClient = queueClient;
                _senderClient   = queueClient;
                break;

            default:
                throw new Exception($"Unkown channel type {channelType}");
            }

            string deadPath = EntityNameHelper.FormatDeadLetterPath(_receiverClient.Path);

            _deadLetterQueue = new MessageReceiver(connectionString, deadPath, ReceiveMode.PeekLock);
        }
Ejemplo n.º 8
0
 public ChannelReceiver(IReceiverClient receiverClient,
                        Func <TMessage, Task> messageHandler,
                        ILogger logger)
 {
     receiverClient.RegisterMessageHandler(async(v, token) =>
     {
         try
         {
             var messageObject = JsonConvert.DeserializeObject <TMessage>(Encoding.UTF8.GetString(v.Body));
             await messageHandler(messageObject).ConfigureAwait(false);
         }
         catch (Exception ex)
         {
             logger.Exception(ex);
         }
     }, new MessageHandlerOptions(v =>
     {
         logger.Exception(v.Exception);
         return(Task.CompletedTask);
     })
     {
         AutoComplete       = true,
         MaxConcurrentCalls = 1
     });
 }
        private async Task HandleReceivedMessage(IReceiverClient receiverClient, ISenderClient senderClient,
                                                 Message message, CancellationToken token)
        {
            var eventName   = message.Label;
            var messageData = Encoding.UTF8.GetString(message.Body);

            await ProcessEvent(eventName, messageData);

            // Complete the message so that it is not received again.
            await receiverClient.CompleteAsync(message.SystemProperties.LockToken);

            var eventType = _subscriptionsManager.GetEventTypeByName(eventName);

            if (eventType != null && eventType != typeof(CompletedEvent))
            {
                var eventData = JObject.Parse(messageData);
                if (Guid.TryParse((string)eventData["Id"], out var eventId))
                {
                    var publisherId = (string)eventData["PublisherId"];

                    var completedEvent = new CompletedEvent(eventId, publisherId);
                    await PublishEventAsync(completedEvent, senderClient);
                }
            }
        }
Ejemplo n.º 10
0
        public AzureServiceBusReceiver(IReceiverClient receiverClient, ISBMessageReceiver messageReceiver, MessageHandlerOptions messageHandlerOptions)
        {
            _receiverClient        = receiverClient ?? throw new ArgumentNullException(nameof(receiverClient));
            _messageReceiver       = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver));
            _messageHandlerOptions = messageHandlerOptions ??
                                     new MessageHandlerOptions(DefaultExceptionReceiverHandler)
            {
                AutoComplete = false,


                /*
                 * In fact, what the property actually means is the maximum about of time they lock renewal will happen for internally on the subscription client.
                 * So if you set this to 24 hours e.g. Timespan.FromHours(24) and your processing was to take 12 hours, it would be renewed. However, if you set
                 * this to 12 hours using Timespan.FromHours(12) and your code ran for 24, when you went to complete the message it would give a lockLost exception
                 * (as I was getting above over shorter intervals!).
                 *
                 * in fact, Microsoft's implementation runs a background task that periodically renews the message lock until it expires.
                 */
                MaxAutoRenewDuration = TimeSpan.FromMinutes(10), //should be in fact called "max processing time"
                MaxConcurrentCalls   = 2
            };

            _autoComplete = _messageHandlerOptions.AutoComplete;

            //note: we can't use management SDK as it requires high priviledged SP in Azure
        }
Ejemplo n.º 11
0
 public QueueWorker(
     IReceiverClient messageReceiver,
     IWorkflowDispatcher workflowDispatcher,
     IOptions <AzureServiceBusOptions> options,
     Func <IReceiverClient, Task> disposeReceiverAction,
     ILogger <QueueWorker> logger) : base(messageReceiver, workflowDispatcher, options, disposeReceiverAction, logger)
 {
 }
Ejemplo n.º 12
0
 public static Task AbandonByErrorAsync(this Message message, IReceiverClient client, Exception e)
 {
     return(client.AbandonAsync(message.SystemProperties.LockToken, new Dictionary <string, object>
     {
         { "ErrorMessage", e.Message },
         { "Exception", e.ToString() }
     }));
 }
Ejemplo n.º 13
0
 public QueueWorker(
     IReceiverClient messageReceiver,
     Scoped <IWorkflowLaunchpad> workflowLaunchpad,
     IOptions <AzureServiceBusOptions> options,
     Func <IReceiverClient, Task> disposeReceiverAction,
     ILogger <QueueWorker> logger) : base(messageReceiver, workflowLaunchpad, options, disposeReceiverAction, logger)
 {
 }
Ejemplo n.º 14
0
 public TopicWorker(
     IReceiverClient receiverClient,
     Scoped <IWorkflowLaunchpad> workflowLaunchpad,
     IOptions <AzureServiceBusOptions> options,
     Func <IReceiverClient, Task> disposeReceiverAction,
     ILogger <TopicWorker> logger) : base(receiverClient, workflowLaunchpad, options, disposeReceiverAction, logger)
 {
 }
Ejemplo n.º 15
0
 public TopicWorker(
     IReceiverClient receiverClient,
     IWorkflowDispatcher workflowDispatcher,
     IOptions <AzureServiceBusOptions> options,
     Func <IReceiverClient, Task> disposeReceiverAction,
     ILogger <TopicWorker> logger) : base(receiverClient, workflowDispatcher, options, disposeReceiverAction, logger)
 {
 }
Ejemplo n.º 16
0
        public ObserverClient(ISubscriptionClient client, bool shouldRecieveOnce = true)
        {
            this.receiver = client;

            shouldOnlyReceiveOnce = shouldRecieveOnce;

            // Register QueueClient's MessageHandler and receive messages in a loop //
            RegisterOnMessageHandlerAndReceiveMessages();
        }
Ejemplo n.º 17
0
 public void SetUp()
 {
     _receiver       = A.Fake <IServiceBusMessageReceiver>();
     _factory        = A.Fake <IReceiverClientFactory>();
     _receiverClient = A.Fake <IReceiverClient>();
     A.CallTo(() => _factory.Create())
     .Returns(_receiverClient);
     _sut = new GenericServiceBusCommunicationListener(null, _factory, _receiver);
 }
Ejemplo n.º 18
0
        Task OnMessage(IReceiverClient messageReceiver, Message message, CancellationToken cancellationToken)
        {
            if (IsStopping)
            {
                return(WaitForDeliveryComplete());
            }

            return(_messageReceiver.Handle(message, cancellationToken, context => AddReceiveContextPayloads(context, messageReceiver, message)));
        }
        protected void InitializeReciever(IReceiverClient messageReciever, ILoggerFactory loggerFactory)
        {
            MessageReciever = messageReciever;

            //  _serverWaitTime = TimeSpan.FromSeconds(waitTime <= 0 ? DefaultWaitTime : waitTime);

            _loggerFactory = loggerFactory;
            _logger        = loggerFactory?.CreateLogger(nameof(BusMessageReceiverClient));
        }
Ejemplo n.º 20
0
        public ObserverClient(IReceiverClient client)
        {
            // Set the receive once flag for Queues //
            shouldOnlyReceiveOnce = true;

            this.receiver = client;

            // Register QueueClient's MessageHandler and receive messages in a loop //
            RegisterOnMessageHandlerAndReceiveMessages();
        }
Ejemplo n.º 21
0
        public PurchasingAzureServiceBusConsumer(IConfiguration config, IMessageBus messageBus)
        {
            _configuration = config;
            _messageBus    = messageBus;

            var serviceBusConnectionString = _configuration.GetValue <string>("AzureServiceBusConnectionString");

            productCreatedMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString,
                                                                         prodcutCreatedMessageTopic, subscriptionName);
        }
Ejemplo n.º 22
0
        public RequestReplySender(ISenderClient sender, IReceiverClient receiver)
        {
            _sender   = sender;
            _receiver = receiver;

            _receiver.RegisterMessageHandler(OnMessageReceived,
                                             new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                AutoComplete = false
            });
        }
        private async Task ProcessSessionMessageAsync(IReceiverClient client, IMessageSession session, Message message, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Type : {ClientType}", client.GetType());

            try
            {
                _logger.LogInformation($"Session       :{session.SessionId}");
                _logger.LogInformation($"SequenceNumber:{message.SystemProperties.SequenceNumber}");
                _logger.LogInformation($"Label         :{message.Label}");
                _logger.LogInformation($"DeliveryCount :{message.SystemProperties.DeliveryCount}");

                string body = Encoding.UTF8.GetString(message.Body);
                if (body == "1")
                {
                    await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); // simulate delay

                    _logger.LogError("Error: " + DateTime.UtcNow);
                    throw new Exception("!!!");
                }

                //if (message.Label == nameof(PersonMessage))
                //{
                //    var person = _serializer.Deserialize<PersonMessage>(message.Body);
                //    _logger.LogInformation("person = " + JsonConvert.SerializeObject(person));
                //}
                //else
                //{
                //    _logger.LogInformation("other = " + body);
                //}

                _logger.LogInformation("OK : " + body);

                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); // simulate delay

                await session.CompleteAsync(message.SystemProperties.LockToken);

                //await client.CompleteAsync(message.SystemProperties.LockToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error while Process Message with MessageId: {MessageId}", message.MessageId);
                if (!session.IsClosedOrClosing)
                {
                    var properties = new Dictionary <string, object>
                    {
                        { "uhuh", DateTime.UtcNow.ToString() }
                    };

                    await session.AbandonAsync(message.SystemProperties.LockToken, properties);

                    //await client.AbandonAsync(message.SystemProperties.LockToken);
                }
            }
        }
Ejemplo n.º 24
0
 public void PurgeServiceBusMessagesAsync(IReceiverClient receiverClient, ITestOutputHelper output)
 {
     receiverClient.RegisterMessageHandler(async(Microsoft.Azure.ServiceBus.Message message, CancellationToken token) =>
     {
         // purge message
         await receiverClient.CompleteAsync(message.SystemProperties.LockToken);
     }, new MessageHandlerOptions(async args => output.WriteLine(args.Exception.ToString()))
     {
         MaxConcurrentCalls = 1,
         AutoComplete       = false
     });
 }
        public void StartListening()
        {
            activeClient = CreateListener();

            activeClient.RegisterMessageHandler((message, handler) =>
            {
                OnMessageReceived?.Invoke(this, new OnMessageReceivedEventArgs(message));

                return(activeClient.CompleteAsync(message.SystemProperties.LockToken));
            }, new MessageHandlerOptions(x => Task.CompletedTask));

            Console.WriteLine("Started Listening for " + this.GetType().Name);
        }
        public AzureServiceBusReceiver(IReceiverClient receiverClient, bool peekLock, MessageHandlerOptions messageHandlerOptions)
        {
            _receiverClient = receiverClient ?? throw new ArgumentNullException(nameof(receiverClient));
            _peekLock       = peekLock;

            _messageHandlerOptions = messageHandlerOptions ??
                                     new MessageHandlerOptions(DefaultExceptionReceiverHandler)
            {
                AutoComplete         = false,
                MaxAutoRenewDuration = TimeSpan.FromMinutes(1),
                MaxConcurrentCalls   = 1
            };
        }
Ejemplo n.º 27
0
        async Task OnMessage(IReceiverClient messageReceiver, Message message, CancellationToken cancellationToken)
        {
            if (IsStopping)
            {
                await WaitAndAbandonMessage(messageReceiver, message).ConfigureAwait(false);

                return;
            }

            using var delivery = Tracker.BeginDelivery();

            await _messageReceiver.Handle(message, context => AddReceiveContextPayloads(context, messageReceiver, message)).ConfigureAwait(false);
        }
        public AzServiceBusConsumer(IConfiguration configuration, IMessageBus messageBus, OrderRepository orderRepository)
        {
            _configuration   = configuration;
            _orderRepository = orderRepository;
            // _logger = logger;
            _messageBus = messageBus;

            var serviceBusConnectionString = _configuration.GetValue <string>("ServiceBusConnectionString");

            checkoutMessageTopic = _configuration.GetValue <string>("CheckoutMessageTopic");

            checkoutMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, checkoutMessageTopic, subscriptionName);
        }
Ejemplo n.º 29
0
        protected async Task WaitAndAbandonMessage(IReceiverClient receiverClient, Message message)
        {
            try
            {
                await _deliveryComplete.Task.ConfigureAwait(false);

                await receiverClient.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                LogContext.Error?.Log(exception, "Abandon message faulted during shutdown: {InputAddress}", _context.InputAddress);
            }
        }
Ejemplo n.º 30
0
        protected async Task WaitAndAbandonMessage(IReceiverClient receiverClient, Message message)
        {
            try
            {
                await _deliveryComplete.Task.ConfigureAwait(false);

                await receiverClient.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Debug($"Stopping receiver, abandoned message faulted: {_context.InputAddress}", exception);
                }
            }
        }