Exemplo n.º 1
0
        private async Task ProcessPayments(ProcessMessageEventArgs args)
        {
            var message = args.Message;
            var body    = Encoding.UTF8.GetString(message.Body);

            PaymentRequestMessage paymentRequestMessage = JsonConvert.DeserializeObject <PaymentRequestMessage>(body);

            var result = _processPayment.PaymentProcessor();

            UpdatePaymentResultMessage updatePaymentResultMessage = new()
            {
                Status  = result,
                OrderId = paymentRequestMessage.OrderId,
                Email   = paymentRequestMessage.Email
            };


            try
            {
                await _messageBus.PublishMessage(updatePaymentResultMessage, orderupdatepaymentresulttopic);

                await args.CompleteMessageAsync(args.Message);
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
        private async Task MessageHandlerAsync(ProcessMessageEventArgs arg)
        {
            var message = arg.Message;
            var body    = Encoding.UTF8.GetString(message.Body.ToArray());
            var data    = JsonSerializer.Deserialize <TEntity>(body, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

            if (ValidateMessage(data))
            {
                if (await ProcessDataAsync(data).ConfigureAwait(false))
                {
                    // Now that we're done with "processing" the message, we tell the broker about that being the
                    // case. The MessageReceiver.CompleteAsync operation will settle the message transfer with
                    // the broker and remove it from the broker.
                    await arg.CompleteMessageAsync(message)
                    .ConfigureAwait(false);
                }
                else
                {
                    // If the message does not meet our processing criteria, we will dead letter it, meaning
                    // it is put into a special queue for handling defective messages. The broker will automatically
                    // dead letter the message, if delivery has been attempted too many times.
                    await arg.DeadLetterMessageAsync(message)
                    .ConfigureAwait(false);
                }
            }
        }
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body = args.Message.Body.ToString();

            Console.WriteLine($"Received: {body}");
            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 4
0
        private static async Task MessageHandler(ProcessMessageEventArgs args, string subscription)
        {
            var message = args.Message;

            Console.WriteLine($"Received: {message.Body}, id {message.MessageId}, subscription {subscription}");
            await args.CompleteMessageAsync(message);
        }
    private async Task Processor_ProcessMessageAsync(ProcessMessageEventArgs arg)
    {
        try
        {
            var message = arg.Message.Body.ToObjectFromJson <AzureInvalidationMessage>(EntityJsonContext.FullJsonSerializerOptions);

            if (message.CreationDate < StartTime)
            {
                return;
            }

            if (message.OriginMachineName == Environment.MachineName &&
                message.OriginApplicationName == Schema.Current.ApplicationName)
            {
                return;
            }

            Receive?.Invoke(message.MethodName, message.Argument);

            await arg.CompleteMessageAsync(arg.Message);
        }catch (Exception ex)
        {
            ex.LogException(ex => ex.ControllerName = nameof(AzureServiceBusBroadcast));
        }
    }
Exemplo n.º 6
0
        public Task onMessage(ProcessMessageEventArgs arg)
        {
            string body    = arg.Message.Body.ToString();
            var    message = JsonTool.Deserialize <PubSubMessage>(body);

            switch (message.ContentType)
            {
            case ContentType.NMS_UPDATE: { var obj = JsonTool.Deserialize <ModelUpdateEvent>(message.Content); Handle(obj, null); break; }

            case ContentType.SCADA_UPDATE: { var obj = JsonTool.Deserialize <ScadaUpdateEvent>(message.Content); Handle(obj, null); break; }

            case ContentType.SCADA_HISTORY: { var obj = JsonTool.Deserialize <HistoryUpdateEvent>(message.Content); Handle(obj, null); break; }

            case ContentType.SCADA_DOM: { var obj = JsonTool.Deserialize <DomUpdateEvent>(message.Content); Handle(obj, null); break; }

            case ContentType.SCADA_HISTORY_GRAPH: { var obj = JsonTool.Deserialize <HistoryGraphicalEvent>(message.Content); Handle(obj, null); break; }

            case ContentType.CE_UPDATE: { var obj = JsonTool.Deserialize <CeUpdateEvent>(message.Content); Handle(obj, null); break; }

            case ContentType.CE_HISTORY_GRAPH: { var obj = JsonTool.Deserialize <CeGraphicalEvent>(message.Content); Handle(obj, null); break; }

            default: break;
            }
            return(arg.CompleteMessageAsync(arg.Message));
        }
Exemplo n.º 7
0
        private async Task MessageHandler(ProcessMessageEventArgs arg)
        {
            var eventName = arg.Message.Subject;

            if (_subscriptionManager.HasSubscriptionsForEvent(eventName))
            {
                var subscriptions = _subscriptionManager.GetHandlersForEvent(eventName);
                foreach (var subscription in subscriptions)
                {
                    var handler = _serviceProvider.GetService(subscription.HandlerType);
                    if (handler == null)
                    {
                        continue;
                    }

                    var eventType   = _subscriptionManager.GetEventTypeByName(eventName);
                    var messageData = Encoding.UTF8.GetString(arg.Message.Body);

                    var integrationEvent = JsonSerializer.Deserialize(messageData, eventType);
                    var concreteType     = typeof(IIntegrationEventHandler <>).MakeGenericType(eventType);
                    await(Task) concreteType.GetMethod("HandleAsync").Invoke(handler, new object[] { integrationEvent });
                    await arg.CompleteMessageAsync(arg.Message);
                }
            }
        }
Exemplo n.º 8
0
        private async Task ProcessMessageAsync(ProcessMessageEventArgs args)
        {
            var eventTypeName = args.Message.ApplicationProperties["event-type"].ToString();

            var(eventType, eventHandlerTypes) =
                _eventHandlerTypesMap.FirstOrDefault(mapper => mapper.Key.FullName == eventTypeName);

            if (eventHandlerTypes != null && eventHandlerTypes.Count > 0)
            {
                var taskSelect = eventHandlerTypes.Select(eventHandlerType =>
                {
                    using var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME);

                    var eventHandler = scope.ResolveOptional(eventHandlerType);
                    if (eventHandler == null)
                    {
                        return(Task.CompletedTask);
                    }

                    var integrationEvent = JsonConvert.DeserializeObject(args.Message.Body.ToString(), eventType);
                    var concreteType     = typeof(IIntegrationEventHandler <>).MakeGenericType(eventType);

                    return((Task)concreteType.GetMethod("HandleAsync")
                           ?.Invoke(eventHandler, new object[] { integrationEvent }));
                });

                await Task.WhenAll(taskSelect);
            }

            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 9
0
        private async Task MessageHandler(ProcessMessageEventArgs args)
        {
            try
            {
                _logger.LogInformation($"client '{_systemInfo.ClientId}' received message '{args.Message.MessageId}'. Processing...");

                var message = await _messageParser.DeserializeAsync <TM>(args.Message.Body);

                await _messageProcessor.ProcessAsync((dynamic)message, args.CancellationToken);

                await args.CompleteMessageAsync(args.Message).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"an error has occurred while processing message '{args.Message.MessageId}': {ex.Message}");
                if (args.Message.DeliveryCount > 3)
                {
                    await args.DeadLetterMessageAsync(args.Message).ConfigureAwait(false);
                }
                else
                {
                    await args.AbandonMessageAsync(args.Message).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 10
0
        public async Task UserSettledPropertySetCorrectly()
        {
            var msg  = new ServiceBusReceivedMessage();
            var args = new ProcessMessageEventArgs(
                msg,
                new Mock <ServiceBusReceiver>().Object,
                CancellationToken.None);

            Assert.IsFalse(msg.IsSettled);

            msg.IsSettled = false;
            await args.AbandonMessageAsync(msg);

            Assert.IsTrue(msg.IsSettled);

            await args.CompleteMessageAsync(msg);

            Assert.IsTrue(msg.IsSettled);

            msg.IsSettled = false;
            await args.DeadLetterMessageAsync(msg);

            Assert.IsTrue(msg.IsSettled);

            msg.IsSettled = false;
            await args.DeadLetterMessageAsync(msg, "reason");

            Assert.IsTrue(msg.IsSettled);

            msg.IsSettled = false;
            await args.DeferMessageAsync(msg);

            Assert.IsTrue(msg.IsSettled);
        }
        private async Task HandleMessageAsync(ProcessMessageEventArgs processMessageEventArgs)
        {
            try
            {
                var rawMessageBody = Encoding.UTF8.GetString(processMessageEventArgs.Message.Body.ToBytes().ToArray());
                Logger.LogInformation("Received message {MessageId} with body {MessageBody}",
                                      processMessageEventArgs.Message.MessageId, rawMessageBody);

                var order = JsonConvert.DeserializeObject <TMessage>(rawMessageBody);
                if (order != null)
                {
                    await ProcessMessage(order, processMessageEventArgs.Message.MessageId,
                                         processMessageEventArgs.Message.ApplicationProperties,
                                         processMessageEventArgs.CancellationToken);
                }
                else
                {
                    Logger.LogError(
                        "Unable to deserialize to message contract {ContractName} for message {MessageBody}",
                        typeof(TMessage), rawMessageBody);
                }

                Logger.LogInformation("Message {MessageId} processed", processMessageEventArgs.Message.MessageId);

                await processMessageEventArgs.CompleteMessageAsync(processMessageEventArgs.Message);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Unable to handle message");
            }
        }
    private async Task ProcessMessagesAsync(ProcessMessageEventArgs args)
    {
        var message     = args.Message;
        var messageText = message.Body.ToString();

        Console.WriteLine($"Received message: {messageText}, delivery count: {message.DeliveryCount}");

        /*
         *  Note: Un-commenting below line will cause message to be 'abandoned' immediately.
         *  Message delivery will be retried if max delivery count has not been exceeded.
         */
        // throw new Exception("thrown deliberately");

        /*
         *  Note: un-commenting below line will cause message to be 'abandoned' immediately.
         *  Message delivery will be retried if max delivery count has not been exceeded.
         */
        // await args.AbandonMessageAsync(message);

        /*
         *  Note: un-commenting below line will cause message to be 'deadlettered' immediately.
         *  Message delivery will NOT be retried (irrespective of whether the message delivery count
         *  has been exceeded or not).
         */
        // await args.DeadLetterMessageAsync(message);

        /*
         *  Note: un-commenting below line will cause message to be marked 'completed' immediately.
         *  Technically this is not required since MessageHandlerOptions's 'autoComplete' is set to true by default.
         */
        await args.CompleteMessageAsync(message);
    }
Exemplo n.º 13
0
        private async Task MessageHandler(ProcessMessageEventArgs e)
        {
            string data = e.Message.Body.ToString();

            mensajes.Add(data);
            //DEBEMOS IR ELIMINANDO LOS MENSAJES DE LA COLA COMO LEIDOS/PROCESADOS
            await e.CompleteMessageAsync(e.Message);
        }
        private async Task MessageHandlerAsync(ProcessMessageEventArgs args)
        {
            var messageAsString = args.Message.Body.ToString();

            await _messageHandler(messageAsString);

            await args.CompleteMessageAsync(args.Message);
        }
        // handle received messages
        async Task MessageHandler(ProcessMessageEventArgs args)
        {
            var body = args.Message.Body.ToString();

            _cacheContainerService.RefreshCache(body);
            // complete the message. messages is deleted from the subscription.
            await args.CompleteMessageAsync(args.Message);
        }
        private async Task OnMessageReceivedAsync <TEvent, TConsumer>(EventRegistration ereg, EventConsumerRegistration creg, ProcessMessageEventArgs args)
            where TEvent : class
            where TConsumer : IEventConsumer <TEvent>
        {
            var message           = args.Message;
            var messageId         = message.MessageId;
            var cancellationToken = args.CancellationToken;

            message.ApplicationProperties.TryGetValue(AttributeNames.ActivityId, out var parentActivityId);

            using var log_scope = Logger.BeginScopeForConsume(id: messageId,
                                                              correlationId: message.CorrelationId,
                                                              sequenceNumber: message.SequenceNumber,
                                                              extras: new Dictionary <string, string>
            {
                ["EnqueuedSequenceNumber"] = message.EnqueuedSequenceNumber.ToString(),
            });

            // Instrumentation
            using var activity = EventBusActivitySource.StartActivity(ActivityNames.Consume, ActivityKind.Consumer, parentActivityId?.ToString());
            activity?.AddTag(ActivityTagNames.EventBusEventType, typeof(TEvent).FullName);
            activity?.AddTag(ActivityTagNames.EventBusConsumerType, typeof(TConsumer).FullName);
            activity?.AddTag(ActivityTagNames.MessagingSystem, Name);
            var destination = TransportOptions.UseBasicTier || ereg.UseQueueInsteadOfTopic() ? ereg.EventName : creg.ConsumerName;

            activity?.AddTag(ActivityTagNames.MessagingDestination, destination); // name of the queue/subscription
            activity?.AddTag(ActivityTagNames.MessagingDestinationKind, "queue"); // the spec does not know subscription so we can only use queue for both

            try
            {
                Logger.LogDebug("Processing '{MessageId}'", messageId);
                using var scope = CreateScope();
                using var ms    = message.Body.ToStream();
                var contentType = new ContentType(message.ContentType);
                var context     = await DeserializeAsync <TEvent>(body : ms,
                                                                  contentType : contentType,
                                                                  registration : ereg,
                                                                  scope : scope,
                                                                  cancellationToken : cancellationToken);

                Logger.LogInformation("Received message: '{MessageId}' containing Event '{Id}'",
                                      messageId,
                                      context.Id);

                await ConsumeAsync <TEvent, TConsumer>(@event : context,
                                                       scope : scope,
                                                       cancellationToken : cancellationToken);

                // Complete the message
                Logger.LogDebug("Completing message: {MessageId}.", messageId);
                await args.CompleteMessageAsync(message : message, cancellationToken : cancellationToken);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Event processing failed. Moving to deadletter.");
                await args.DeadLetterMessageAsync(message : message, cancellationToken : cancellationToken);
            }
        }
Exemplo n.º 17
0
            static async Task MessageHandler(ProcessMessageEventArgs args)
            {
                var body = args.Message.Body.ToString();

                Console.WriteLine($"Received Message: { body }");

                // we can evaluate application logic and use that to determine how to settle the message.
                await args.CompleteMessageAsync(args.Message);
            }
        private static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            var result = args.Message.Body.ToObjectFromJson <MessageTest <MyClass> >();

            Console.WriteLine($"Received: {result}");

            // complete the message. messages is deleted from the queue.
            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 19
0
        // handle received messages
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body = args.Message.Body.ToString();

            _nomes.Add(body);

            // complete the message. messages is deleted from the queue.
            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 20
0
        // handle received messages
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body = args.Message.Body.ToString();

            Console.WriteLine($"Received: {body}");

            // complete the message. messages is deleted from the queue.
            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 21
0
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            var body = args.Message.Body.ToString();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Received: {body}");

            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 22
0
        static async Task ProcessMessagesAsync(ProcessMessageEventArgs args)
        {
            // Process the message.
            Console.WriteLine($"Received message: SequenceNumber:{args.Message.SequenceNumber} Body:{Encoding.UTF8.GetString(args.Message.Body)}");

            // Complete the message so that it is not received again.
            // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default).
            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 23
0
        private async Task ProcessQueueMessageAsync(ProcessMessageEventArgs arg)
        {
            string body = arg.Message.Body.ToString();

            QueueMessageModel queueMessageModel = JsonConvert.DeserializeObject <QueueMessageModel>(body);

            System.Console.WriteLine($"The queue message body is {queueMessageModel.TransactionId}");

            await arg.CompleteMessageAsync(arg.Message);
        }
Exemplo n.º 24
0
        private async Task MessageHandler(ProcessMessageEventArgs args)
        {
            var eventName   = $"{args.Message.Subject}{INTEGRATION_EVENT_SUFFIX}";
            var messageData = Encoding.UTF8.GetString(args.Message.Body.ToArray());

            // Complete the message so that it is not received again.
            if (await ProcessEvent(eventName, messageData))
            {
                await args.CompleteMessageAsync(args.Message);
            }
        }
Exemplo n.º 25
0
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body    = args.Message.Body.ToString();
            var    payload = JsonConvert.DeserializeObject <Notification>(body);

            Console.WriteLine("Received notification");

            //Update table
            await getTable(payload.Url);

            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 26
0
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body = args.Message.Body.ToString();

            Console.WriteLine($"Received: {body}");

            var signUpCourse = JsonConvert.DeserializeObject <SignUpToCourseDto>(body);

            //process the msg and verify if the student is able to enter the course based in some rules as capacity of the course, etc.

            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Handles service bus messages.
        /// </summary>
        private async Task ServiceBusMessageHandler(ProcessMessageEventArgs args)
        {
            string           body             = args.Message.Body.ToString();
            NotificationData notificationData = null;

            try
            {
                notificationData = JsonConvert.DeserializeObject <NotificationData>(body);
            }
            catch (JsonSerializationException ex)
            {
                Log.Warning(ex, "Failed to deserialize notification");
            }

            if (notificationData != null)
            {
                // If it's a system notification, handle it directly, otherwise pass it along
                if (notificationData.Type == NotificationType.System)
                {
                    switch (notificationData.SubType)
                    {
                    case SubType.SettingsUpdate:
                        await this.UpdateSettingsAsync();

                        break;

                    case SubType.Shutdown:
                        Log.Information("Shutdown notification received");
                        this.exitCode = (int)ExitCode.ExpectedShutdown;
                        break;

                    default:
                        Log.Error($"Error processing notification, unrecognized subtype: {notificationData.SubType}");
                        break;
                    }
                }
                else
                {
                    try
                    {
                        await this.SendNotification(notificationData);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error processing notification");
                    }
                }
            }

            // For now, no retries. Regardless of notification send success, complete it.
            await args.CompleteMessageAsync(args.Message);
        }
        private async Task OnOrderPaymentUpdateReceived(ProcessMessageEventArgs args)
        {
            var messageBody = Encoding.UTF8.GetString(args.Message.Body);
            var orderPaymentUpdateMessage = JsonConvert.DeserializeObject <OrderPaymentUpdateMessage>(messageBody);

            await using var _orderDbContext = new OrderDbContext(_options);
            var order = await _orderDbContext.Orders.FindAsync(orderPaymentUpdateMessage.OrderId);

            order.OrderPaid = orderPaymentUpdateMessage.PaymentSuccess;
            await _orderDbContext.SaveChangesAsync();

            await args.CompleteMessageAsync(args.Message);
        }
Exemplo n.º 29
0
        static async Task ActionSuccesReception(ProcessMessageEventArgs consommateur)
        {
            string contenuMessage = consommateur.Message.Body.ToString();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Message recu : " + contenuMessage);
            Console.ForegroundColor = ConsoleColor.White;

            await consommateur.CompleteMessageAsync(consommateur.Message);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Confirmation de traitement Envoyée  : " + contenuMessage);
            Console.ForegroundColor = ConsoleColor.White;
        }
Exemplo n.º 30
0
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body             = args.Message.Body.ToString();
            var    receivingPayload = JsonConvert.DeserializeObject <ReceptionPayload>(body);
            string rec_load         = JsonConvert.SerializeObject(receivingPayload);

            var sendingPayload = JsonConvert.DeserializeObject <SendingPayload>(rec_load);

            File.WriteAllBytes(@"current.json", Convert.FromBase64String(receivingPayload.ContextImageJpg));

            await CheckPreviousMatch();

            await using (FileStream my_stream = new FileStream("current.json", FileMode.Open, FileAccess.Read)) {
                sendingPayload.ContextImageReference = await Problem3.UploadImage(@"current.json", my_stream);
            }

            Console.WriteLine("Current time: {0:HH:mm:ss.fff}", DateTime.Now);
            Console.WriteLine(receivingPayload.LicensePlate);
            Console.WriteLine("[{0}]", string.Join(", ", Table.table));


            if (checkMatch(receivingPayload.LicensePlate))
            {
                sendingPayload.LicensePlate = matched;

                string sen_load = JsonConvert.SerializeObject(sendingPayload);
                Console.WriteLine(sen_load);
                var response = await client.PostAsync(uri, new StringContent(sen_load, Encoding.UTF8, "application/json"));

                Console.WriteLine("Sent data to server, response : " + response);
                Console.WriteLine("Found match !");
            }
            else
            {
                var result = await Problem5.MakeRequest(sendingPayload.ContextImageReference);

                string sendingPayloadString = JsonConvert.SerializeObject(sendingPayload);
                var    waitingPayload       = JsonConvert.DeserializeObject <WaitingPayload>(sendingPayloadString);
                waitingPayload.Id = result;
                queue.Enqueue(waitingPayload);
                Console.WriteLine("No match, sending to Azure recognition");
            }
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            // complete the message. messages is deleted from the queue.
            await args.CompleteMessageAsync(args.Message);
        }