private async Task ProcessMessageAsync(Message message, CancellationToken cancellationToken)
        {
            if (_handlers.Count == 0)
            {
                return;
            }

            string eventType   = message.UserProperties[Constants.EventTypeProperty].ToString();
            string messageBody = Encoding.UTF8.GetString(message.Body);

            System.Type messageBodyType = Type.GetType(eventType);
            object      eventObject     = JsonConvert.DeserializeObject(messageBody, messageBodyType);

            if (eventObject is TellUsEvent tellUsEvent)
            {
                if (_handlers.ContainsKey(messageBodyType))
                {
                    await _handlers[messageBodyType].Handle(tellUsEvent, message.CorrelationId, cancellationToken);
                    await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
                }
            }
            else
            {
                await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken);
            }
        }
Esempio n. 2
0
        public async Task ReceiveMessageFromTopic <T>(Func <T, MessageProcessResponse> onProcess)
        {
            MessageHandlerOptions options = new MessageHandlerOptions(e =>
            {
                Trace.TraceError(e.Exception.Message);
                return(Task.CompletedTask);
            })
            {
                AutoComplete         = false,
                MaxAutoRenewDuration = TimeSpan.FromMinutes(1)
            };

            await Task.Run(() => _subscriptionClient.RegisterMessageHandler(
                               async(message, token) =>
            {
                try
                {
                    // Get message
                    string data = Encoding.UTF8.GetString(message.Body);
                    T item      = JsonConvert.DeserializeObject <T>(data);

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

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

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

                    case MessageProcessResponse.Dead:
                        await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken);
                    Trace.TraceError(ex.Message);
                }
            }, options));
        }
        private async Task HandleMessage(Message message, CancellationToken token)
        {
            var request = JsonConvert.DeserializeObject <HttpRequest>(Encoding.UTF8.GetString(message.Body));

            var requestMessage = new HttpRequestMessage();

            foreach (var header in request.Headers)
            {
                requestMessage.Headers.Add(header.Item1, header.Item2);
            }
            requestMessage.Method = request.Method switch
            {
                "get" => HttpMethod.Get,
                "head" => HttpMethod.Head,
                "post" => HttpMethod.Post,
                "put" => HttpMethod.Put,
                "delete" => HttpMethod.Delete,
                //"connect" => HttpMethod.Connect,
                "options" => HttpMethod.Options,
                "trace" => HttpMethod.Trace,
                "patch" => HttpMethod.Patch,
                _ => throw new InvalidOperationException($"invalid http method {request.Method}")
            };
            var uriBuilder = new UriBuilder();

            uriBuilder.Host           = config.GetForwardingHost();
            uriBuilder.Port           = config.GetForwardingPort();
            uriBuilder.Path           = request.Path;
            uriBuilder.Query          = request.Query;
            requestMessage.RequestUri = uriBuilder.Uri;

            HttpResponseMessage response = null;
            string log = $"{DateTime.UtcNow.ToString("u")} host={config.GetForwardingHost()} port={config.GetForwardingPort()} path={request.Path} query={request.Query}";

            try
            {
                response = await httpClient.SendAsync(requestMessage);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

                    log = $"{log} complete=true";
                }
                else
                {
                    await subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken);

                    log = $"{log} dead-letter=true";
                }
            }
            catch (Exception ex)
            {
                log = $"{log} error={ex.GetType().Name} error-correlation={message.SystemProperties.LockToken}";
                logger.LogError($"error-correlation={message.SystemProperties.LockToken} {ex.ToString()}");
            }
            finally { logger.LogInformation($"{log} status={response?.StatusCode.ToString() ?? "none"}"); }
        }
Esempio n. 4
0
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _subscriptionClient.RegisterMessageHandler(async(message, token) =>
            {
                try
                {
                    var eventString = Encoding.UTF8.GetString(message.Body);

                    var @event = JsonConvert.DeserializeObject <TEvent>(eventString);

                    await _handler.HandleAsync(@event, token);

                    await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
                }
                catch (BadRequestException e)
                {
                    Console.WriteLine(e);
                    await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken, e.Message, e.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    if (message.SystemProperties.DeliveryCount > 9)
                    {
                        await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken, e.Message, e.ToString());
                    }
                }
            }, new MessageHandlerOptions(args =>
            {
                Console.WriteLine(args.Exception.Message);
                return(Task.CompletedTask);
            })
            {
                AutoComplete       = false,
                MaxConcurrentCalls = 1
            }
                                                       );

            return(Task.CompletedTask);
        }
 static async Task ProcessMessagesAsync(Message message, CancellationToken token)
 {
     try
     {
         //throw new DivideByZeroException();
         Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
         await subClient.CompleteAsync(message.SystemProperties.LockToken);
     }
     catch (Exception ex)
     {
         await subClient.DeadLetterAsync(message.SystemProperties.LockToken, "error occured!", ex.Message);
     }
 }
Esempio n. 6
0
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var integrationEvent = JsonConvert.DeserializeObject <TEvent>(Encoding.UTF8.GetString(message.Body));

            _logger.LogInformation(
                "Event {Event} has been triggered {EventHandler}, Message: {Message}",
                typeof(TEvent).Name,
                typeof(TEventHandler).Name,
                integrationEvent?.ToJsonString());

            var isSuccess = await ProcessEventAsync(integrationEvent);

            if (isSuccess)
            {
                await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
            }
            else
            {
                await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken);
            }
        }
 public Task DeadLetterAsync(string lockToken, string deadLetterReason, string deadLetterErrorDescription = null)
 {
     return(_subscriptionClient.DeadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription));
 }