Esempio n. 1
0
        private async Task OnMessage(Message message, QueueClient client)
        {
            var processResult = false;

            try
            {
                var dto      = JsonConvert.DeserializeObject <StateCheckMessageDto>(Encoding.UTF8.GetString(message.Body));
                var jobGrain = _orleansClient.GetGrain <IJobGrain>(dto.JobId);
                var job      = await jobGrain.GetJobAsync(true);

                if (job != null)
                {
                    if (dto.StateCheckConfig.TargetStateList.Contains(job.CurrentJobState))
                    {
                        processResult =
                            await _handlerPool.HandleStateCheckerMessageAsync(dto.StateCheckConfig.SuccessfulAction,
                                                                              dto, job);
                    }
                    else
                    {
                        processResult =
                            await _handlerPool.HandleStateCheckerMessageAsync(dto.StateCheckConfig.FailedAction, dto,
                                                                              job);
                    }
                }
                else
                {
                    await client.AbandonAsync(message.SystemProperties.LockToken, new Dictionary <string, object>()
                    {
                        { "dl_reason", $"Grain {dto.JobId} No Exist" }
                    });

                    return;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"exception in {nameof(StateChecker)}");
            }

            if (processResult)
            {
                await client.CompleteAsync(message.SystemProperties.LockToken);
            }
            else
            {
                await client.AbandonAsync(message.SystemProperties.LockToken);
            }
        }
Esempio n. 2
0
        public void Receive <T>(
            QueueClient client,
            Func <T, CancellationToken, Task <MessageProcessResponse> > onProcess,
            Action <ExceptionReceivedEventArgs> onError,
            Action <Exception> onProcessingError,
            Action onWait)
            where T : InstanceMessage
        {
            var options = new MessageHandlerOptions(e =>
            {
                onError(e);
                return(Task.CompletedTask);
            })
            {
                // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false,

                MaxAutoRenewDuration = TimeSpan.FromMinutes(1)
            };

            client.RegisterMessageHandler(
                async(message, token) =>
            {
                try
                {
                    // Get message
                    var data = Encoding.UTF8.GetString(message.Body);
                    T item   = JsonConvert.DeserializeObject <T>(data);

                    // Process message
                    var result = await onProcess(item, token);

                    if (result == MessageProcessResponse.Complete)
                    {
                        await client.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessResponse.Abandon)
                    {
                        await client.AbandonAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessResponse.Dead)
                    {
                        await client.DeadLetterAsync(message.SystemProperties.LockToken);
                    }

                    // Wait for next message
                    onWait();
                }
                catch (Exception ex)
                {
                    await client.DeadLetterAsync(message.SystemProperties.LockToken);
                    onProcessingError(ex);
                }
            }, options);
        }
Esempio n. 3
0
        private async Task ProcessMessageAsync(Message message, CancellationToken token)
        {
            try
            {
                T   item   = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(message.Body));
                var result = _processData.Process(item);

                if (result == MessageResponseEnum.Complete)
                {
                    await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
                }
                else
                if (result == MessageResponseEnum.Abandon)
                {
                    await _queueClient.AbandonAsync(message.SystemProperties.LockToken);
                }
                else
                if (result == MessageResponseEnum.Dead)
                {
                    await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Message handler encountered an exception");
                await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
            }
        }
Esempio n. 4
0
        private ValueTask <T> TryDeserialize(Message message)
        {
            try
            {
                return(new ValueTask <T>(MessagePackSerializer.Deserialize <T>(message.Body)));
            }
            catch (Exception e)
            {
                return(new ValueTask <T>(HandleException(e, message)));
            }

            async Task <T> HandleException(Exception e, Message m)
            {
                _logger.LogError(e, $"Error parsing {typeof(T).Name} from '{_queueName}'.");
                if (message.SystemProperties.DeliveryCount < 4)
                {
                    await _client.AbandonAsync(message.SystemProperties.LockToken);
                }
                else
                {
                    await _client.DeadLetterAsync(message.SystemProperties.LockToken, "Cannot parse.");
                }

                return(default(T));
            }
        }
Esempio n. 5
0
        public override async Task AbandonAsync(IQueueEntry <T> entry)
        {
            Interlocked.Increment(ref _abandonedCount);
            await _queueClient.AbandonAsync(new Guid(entry.Id)).AnyContext();

            await OnAbandonedAsync(entry).AnyContext();
        }
Esempio n. 6
0
        private async Task ProcessMessageAsync(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
        {
            QueueClient queueClient = _queueClient;

            try
            {
                if (!string.Equals(message.ContentType, "application/json"))
                {
                    throw new Exception($"Invalid content type for AMQP message: {message.ContentType}");
                }

                if (message.Body != null)
                {
                    await _messenger.ProcessMessageAsync(Address, Encoding.UTF8.GetString(message.Body)).ConfigureAwait(false);
                }
                else
                {
                    await _messenger.ProcessMessageAsync(Address, null).ConfigureAwait(false);
                }

                await queueClient.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
            }
            catch (RescheduleException)
            {
                // no log, this is "wanted"

                await queueClient.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Exception during processing AMQP message, not abandoning it for timeout (this will avoid duplicates): {exception}");
            }
        }
        private async Task OnMessage2(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
        {
            if (token.IsCancellationRequested || message == null)
            {
                return;
            }

            try
            {
                var tuple            = _converter.FromAzureMessage(message);
                var outboundMessages = new List <Message>();
                var ctx = new InvocationContext(message.Label, tuple.Item1, _invoker, outboundMessages);
                await _invoker.ProcessAsync(ctx, tuple.Item2);


                var azureMsgs = new List <Microsoft.Azure.ServiceBus.Message>();
                foreach (var outboundMessage in outboundMessages)
                {
                    var azureMsg = _converter.ToAzureMessage(outboundMessage, tuple.Item1);
                    azureMsgs.Add(azureMsg);
                }

                if (azureMsgs.Any())
                {
                    await _queueClient.SendAsync(azureMsgs);
                }
            }
            catch (Exception ex)
            {
                await _queueClient.AbandonAsync(message.SystemProperties.LockToken);

                ExceptionLogger?.OnReceiveException(new ReceiveExceptionContext(_queueClient, message, ex));
            }
        }
Esempio n. 8
0
        public override async Task AbandonAsync(IQueueEntry <T> entry)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Queue {Name}:{QueueId} abandon item: {Id}", _options.Name, QueueId, entry.Id);
            }
            if (entry.IsAbandoned || entry.IsCompleted)
            {
                throw new InvalidOperationException("Queue entry has already been completed or abandoned.");
            }

            if (entry is QueueEntry <T> val && val.Data["Pull-Strategy"].Equals(false))
            {
                await _queueClient.AbandonAsync(entry.Id).AnyContext();
            }
            else
            {
                await _messageReceiver.AbandonAsync(entry.Id).AnyContext();
            }
            Interlocked.Increment(ref _abandonedCount);
            entry.MarkAbandoned();
            await OnAbandonedAsync(entry).AnyContext();

            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace("Abandon complete: {Id}", entry.Id);
            }
        }
Esempio n. 9
0
        public override async Task AbandonAsync(string id)
        {
            Interlocked.Increment(ref _abandonedCount);
            await _queueClient.AbandonAsync(new Guid(id)).AnyContext();

            await OnAbandonedAsync(id).AnyContext();
        }
Esempio n. 10
0
        public override async Task AbandonAsync(IQueueEntry <T> entry)
        {
            await EnsureQueueCreatedAsync().AnyContext(); // Azure SB needs to call this as it populates the _queueClient field

            Interlocked.Increment(ref _abandonedCount);
            await _queueClient.AbandonAsync(new Guid(entry.Id)).AnyContext();

            await OnAbandonedAsync(entry).AnyContext();
        }
Esempio n. 11
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        NotificationItem ni = null;
                        try
                        {
                            ni = ObjectSerialization.Deserialize <NotificationItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.DeadLetter();
                            await _client.DeadLetterAsync(message.SystemProperties.LockToken);
                        }

                        await ProcessNotificationItem(ni, message.MessageId, body);
                    }
                    else
                    {
                        success = false;
                        result  = "Message body is null or empty";
                    }

                    try
                    {
                        //message.Complete();
                        await _client.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    result  = ex.ToString();

                    Logging.LogException(ex);
                    //message.Abandon();
                    await _client.AbandonAsync(message.SystemProperties.LockToken);
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Esempio n. 12
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        CqrsEvent qi = null;
                        try
                        {
                            qi = ObjectSerialization.Deserialize <CqrsEvent>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.Complete();
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }

                        success = await ProcessPaymentQueueItem(qi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    Logging.SendExceptionEmail(ex, "PaymentQueueLogic");

                    await _client.AbandonAsync(message.SystemProperties.LockToken);

                    //message.Abandon();
                    success = false;
                    result  = ex.ToString();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Esempio n. 13
0
        public void Receive(
            Func <T, MessageProcessResponse> onProcess,
            Action <Exception> onError,
            Action onWait)
        {
            var options = new MessageHandlerOptions(e =>
            {
                onError(e.Exception);
                return(Task.CompletedTask);
            })
            {
                AutoComplete         = false,
                MaxAutoRenewDuration = TimeSpan.FromMinutes(1)
            };
            var connectionString = "Endpoint=sb://chamaqueue.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=q1MKPN84/guik0UAoa4e83W6eg8z6162yFToJiKKuU4=";
            var queueName        = "SignUpQueue";

            QueueClient client = new QueueClient(connectionString, queueName, ReceiveMode.ReceiveAndDelete);

            client.RegisterMessageHandler(
                async(message, token) =>
            {
                try
                {
                    // Get message
                    var data = Encoding.UTF8.GetString(message.Body);
                    T item   = JsonConvert.DeserializeObject <T>(data);

                    // Process message
                    var result = onProcess(item);

                    if (result == MessageProcessResponse.Complete)
                    {
                        await client.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessResponse.Abandon)
                    {
                        await client.AbandonAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessResponse.Dead)
                    {
                        await client.DeadLetterAsync(message.SystemProperties.LockToken);
                    }

                    // Wait for next message
                    onWait();
                }
                catch (Exception ex)
                {
                    await client.DeadLetterAsync(message.SystemProperties.LockToken);
                    onError(ex);
                }
            }, options);
        }
Esempio n. 14
0
        public void Receive(
            Func <Message <T>, MessageProcessingStatus> onProcess,
            Action <Exception> onError,
            Action onWait)
        {
            var options = new MessageHandlerOptions(e =>
            {
                onError(e.Exception);
                return(Task.CompletedTask);
            })
            {
                AutoComplete         = false,
                MaxAutoRenewDuration = TimeSpan.FromMinutes(1)
            };

            queueClient.RegisterMessageHandler(
                async(message, token) =>
            {
                try
                {
                    // Get message
                    var data  = Encoding.UTF8.GetString(message.Body);
                    T payload = JsonConvert.DeserializeObject <T>(data);
                    var id    = message.MessageId;

                    // Process message
                    var result = onProcess(new Message <T> {
                        Id = id, Payload = payload
                    });

                    if (result == MessageProcessingStatus.Complete)
                    {
                        await queueClient.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessingStatus.Abandon)
                    {
                        await queueClient.AbandonAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessingStatus.Dead)
                    {
                        await queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                    }

                    // Wait for next message
                    onWait();
                }
                catch (Exception ex)
                {
                    await queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                    onError(ex);
                }
            }, options);
        }
Esempio n. 15
0
 static async Task ReceiveMessagesAsync(Message message, CancellationToken token)
 {
     try
     {
         Console.WriteLine($"Received message: {Encoding.UTF8.GetString(message.Body)}");
         await queueClient.CompleteAsync(message.SystemProperties.LockToken);
     }
     catch (Exception ex)
     {
         await queueClient.AbandonAsync(message.SystemProperties.LockToken);
     }
 }
Esempio n. 16
0
        static async Task TryProcessMessagesAsync(Message message, CancellationToken token)
        {
            try
            {
                await ProcessMessagesAsync(message, token);
            }
            catch
            {
                await queueClient.AbandonAsync(message.SystemProperties.LockToken);

                throw;
            }
        }
Esempio n. 17
0
        private static async Task ProcessMessagesAsync(Message message, CancellationToken arg2)
        {
            // Process the message
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

            // Complete the message so that it is not received again.
            // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default).
            await queueClient.AbandonAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
            // If queueClient has already been Closed, you may chose to not call CompleteAsync() or AbandonAsync() etc. calls
            // to avoid unnecessary exceptions.
        }
Esempio n. 18
0
        public Task StartReceivingMessages(MessageHandlerExecutor messageHandlerExecutor)
        {
            queueClient = new QueueClient(connectionString, configuration.ReceiveOptions.QueueName);
            queueClient.RegisterMessageHandler(
                async(message, cancellationToken) =>
            {
                try
                {
                    await messageHandlerExecutor.Execute(GetMessageBody(message, ReceivingMessageTypeNames),
                                                         new AzureServiceBusMessageContext(Bus, message), cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    var exception = e is System.Reflection.TargetInvocationException ? e.InnerException : e;

                    var propertiesToModify = new Dictionary <string, object>
                    {
                        { "ExceptionType", exception.GetType().Name },
                        { "ExceptionMessage", exception.Message },
                        { "ExceptionStackTrace", exception.StackTrace }
                    };

                    if (exception.InnerException != null)
                    {
                        var innerException = exception.InnerException;
                        propertiesToModify.Add("InnerExceptionType", innerException.GetType().Name);
                        propertiesToModify.Add("InnerExceptionMessage", innerException.Message);
                        propertiesToModify.Add("InnerExceptionStackTrace", innerException.StackTrace);
                    }

                    await queueClient.AbandonAsync(
                        message.SystemProperties.LockToken,
                        propertiesToModify).ConfigureAwait(false);
                }
            },
                new MessageHandlerOptions(_ => Task.CompletedTask)
            {
                MaxConcurrentCalls   = configuration.ReceiveOptions.MaxConcurrentCalls,
                MaxAutoRenewDuration = configuration.ReceiveOptions.MaxAutoRenewDuration
            });

            return(Task.CompletedTask);

            object GetMessageBody(ServiceBusMessage message, IReceivingMessageTypeNames messageTypeNames)
            {
                var messageTypeName = message.UserProperties[UserProperties.MessageTypeKey].ToString();
                var type            = messageTypeNames.GetReceivingTypeByMessageTypeName(messageTypeName);

                return(JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message.Body), type));
            }
        }
 public async Task AbandonMessage(string lockToken, bool ignoreLockLostException)
 {
     try
     {
         await _queueClient.AbandonAsync(Guid.Parse(lockToken));
     }
     catch (MessageLockLostException ex)
     {
         if (ignoreLockLostException == false)
         {
             throw ex;
         }
     }
 }
        private async Task OnMessage(Message message, QueueClient client)
        {
            var processResult = false;

            try
            {
                var msgDto     = JsonConvert.DeserializeObject <ActionMessageDto>(Encoding.UTF8.GetString(message.Body));
                var grain      = _orleansClient.GetGrain <IJobGrain>(msgDto.JobId);
                var relatedJob = await grain.GetJobAsync(true);

                if (relatedJob == null)
                {
                    await client.AbandonAsync(message.SystemProperties.LockToken, new Dictionary <string, object>()
                    {
                        { "dl_reason", $"Grain {msgDto.JobId} No Exist" }
                    });

                    return;
                }

                processResult = await _handlerPool.HandleMessageAsync(msgDto);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"exception in {nameof(_handlerPool.HandleMessageAsync)}");
            }

            if (processResult)
            {
                await client.CompleteAsync(message.SystemProperties.LockToken);
            }
            else
            {
                await client.AbandonAsync(message.SystemProperties.LockToken);
            }
        }
        public override async Task AbandonAsync(IQueueEntry <T> entry)
        {
            _logger.LogDebug("Queue {_options.Name}:{QueueId} abandon item: {entryId}", _options.Name, QueueId, entry.Id);
            if (entry.IsAbandoned || entry.IsCompleted)
            {
                throw new InvalidOperationException("Queue entry has already been completed or abandoned.");
            }

            await _queueClient.AbandonAsync(new Guid(entry.Id)).AnyContext();

            Interlocked.Increment(ref _abandonedCount);
            entry.MarkAbandoned();
            await OnAbandonedAsync(entry).AnyContext();

            _logger.LogTrace("Abandon complete: {entryId}", entry.Id);
        }
        static async Task ReceiveMessagesAsync(Message message, CancellationToken token)
        {
            try
            {
                Console.WriteLine($"Received message: {Encoding.UTF8.GetString(message.Body)}");

                //UNCOMMENT BELOW CODE TO GENERATE EXCEPTION, SO THAT MESSSAGE WILL BE ADDED IN DEAD LETTER QUEUE
                //int i = 0;
                //i = i / Convert.ToInt32(message);

                await queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }
            catch (Exception ex)
            {
                await queueClient.AbandonAsync(message.SystemProperties.LockToken);
            }
        }
Esempio n. 23
0
        public void Receive(Func <T, MessageProcessResponse> onProcess, Action <Exception> onError, Action onWait)
        {
            var options = new MessageHandlerOptions(e =>
            {
                onError(e.Exception);
                return(Task.CompletedTask);
            })
            {
                AutoComplete = false
            };

            _queueClient.RegisterMessageHandler(
                async(message, token) =>
            {
                try
                {
                    var data = Encoding.UTF8.GetString(message.Body);
                    T item   = JsonConvert.DeserializeObject <T>(data);

                    var result = onProcess(item);

                    switch (result)
                    {
                    case MessageProcessResponse.Complete:
                        await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
                        break;

                    case MessageProcessResponse.Abandon:
                        await _queueClient.AbandonAsync(message.SystemProperties.LockToken);
                        break;

                    case MessageProcessResponse.Dead:
                        await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                        break;
                    }

                    //waiting for next message
                    onWait();
                }
                catch (Exception e)
                {
                    await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                    onError(e);
                }
            }, options);
        }
Esempio n. 24
0
        public void Receive(Func <Student, MessageProcessResponse> onProcess,
                            Action <Exception> onError,
                            Action onWait)
        {
            var options = new MessageHandlerOptions(e => {
                LogError(e.Exception);
                return(Task.CompletedTask);
            })
            {
                AutoComplete         = false,
                MaxAutoRenewDuration = TimeSpan.FromMinutes(1)
            };

            _queueClient.RegisterMessageHandler(
                async(message, token) => {
                try {
                    var data = Encoding.UTF8.GetString(message.Body);

                    Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{data}");
                    var student = JsonConvert.DeserializeObject <Student>(data);

                    var result = onProcess(student);

                    if (result == MessageProcessResponse.Complete)
                    {
                        await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessResponse.Abandon)
                    {
                        await _queueClient.AbandonAsync(message.SystemProperties.LockToken);
                    }
                    else if (result == MessageProcessResponse.Dead)
                    {
                        await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                    }

                    onWait();
                } catch (Exception ex) {
                    _logger.Error($"Error: {ex.Message}");
                    await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
                    onError(ex);
                }
            }, options);
        }
Esempio n. 25
0
        private static async Task MessageHandler(Message message, CancellationToken cancellationToken)
        {
            string messageText = Encoding.UTF8.GetString(message.Body);

            Console.Write($"[DeliveryCount: {message.SystemProperties.DeliveryCount}]");
            if (messageText.Contains("abandon", StringComparison.InvariantCultureIgnoreCase))
            {
                Console.WriteLine(" - Message abandoned");
                await _queueClient.AbandonAsync(message.SystemProperties.LockToken);
            }
            else if (messageText.Contains("deadletter", StringComparison.InvariantCultureIgnoreCase))
            {
                Console.WriteLine(" - Message cannot be processed");
                await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken, "Poison Message", $"System cannot process the specified message: `{messageText}`");
            }
            else
            {
                Console.WriteLine($" - {messageText}");
                await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }
        }
Esempio n. 26
0
        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                AutoComplete = false
            };

            _queue.RegisterMessageHandler(
                async(message, token) =>
            {
                try
                {
                    throw new Exception("Test");
                }
                catch (Exception)
                {
                    await _queue.AbandonAsync(message.SystemProperties.LockToken);
                    throw;
                }
            },
                messageHandlerOptions);
        }
Esempio n. 27
0
        public async Task HandleMessage(Message msg, CancellationToken token)
        {
            var body = UTF8Encoding.UTF8.GetString(msg.Body);

            var  handler        = HandleMessageAndReturnIfSuccess;
            bool shouldComplete = false;

            if (handler != null)
            {
                shouldComplete = handler(body);
            }
            if (shouldComplete)
            {
                Console.WriteLine("Completing Message");
                await client.CompleteAsync(msg.SystemProperties.LockToken);
            }
            else
            {
                Console.WriteLine("Abandoning Message");
                await client.AbandonAsync(msg.SystemProperties.LockToken);
            }
        }
Esempio n. 28
0
        public Task Subscribe(IMessageSubscriber handler, string queue)
        {
            _Client = new QueueClient(_ConnectionString, queue, ReceiveMode.PeekLock);

            var messageHandlerOptions = new MessageHandlerOptions((e) => { return(Task.Delay(100)); })
            {
                AutoComplete       = false,
                MaxConcurrentCalls = 1
            };

            _Client.RegisterMessageHandler(async(busMessage, concurrentToken) =>
            {
                var token = busMessage.SystemProperties.LockToken;
                try
                {
                    var body = busMessage.Body;
                    if (handler != null)
                    {
                        var message = JsonConvert.DeserializeObject <BusMessage>(Encoding.UTF8.GetString(body));

                        await handler.Handle(message);
                    }

                    await _Client.CompleteAsync(token);
                }
                catch (CommandException)
                {
                    await _Client.DeadLetterAsync(token);
                }
                catch
                {
                    await _Client.AbandonAsync(token);
                }
            }, messageHandlerOptions);

            return(Task.CompletedTask);
        }
Esempio n. 29
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                MessageQueueItem mqi = null;

                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        try
                        {
                            mqi = ObjectSerialization.Deserialize <MessageQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.Complete();
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }

                        await ProcessMessageQueueItem(mqi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();

                    if (mqi != null)
                    {
                        ex.Data.Add("DepartmentId", mqi.DepartmentId);

                        if (mqi.Message != null)
                        {
                            ex.Data.Add("MessageId", mqi.Message.MessageId);
                            ex.Data.Add("SendingUserId", mqi.Message.SendingUserId);
                            ex.Data.Add("RecievingUserId", mqi.Message.ReceivingUserId);
                        }
                    }

                    ex.Data.Add("MQI", JsonConvert.SerializeObject(mqi));

                    Logging.LogException(ex);
                    await _client.AbandonAsync(message.SystemProperties.LockToken);

                    //message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Esempio n. 30
0
 public Task AbandonAsync(string id)
 {
     Interlocked.Increment(ref _abandonedCount);
     return(_queueClient.AbandonAsync(new Guid(id)));
 }