Beispiel #1
0
        private async Task HandleMessageAsync(Message message, CancellationToken cancellationToken)
        {
            var formatter = new BinaryFormatter();

            if (message.Body == null)
            {
                await _subClient.AbandonAsync(message.SystemProperties.LockToken);

                return;
            }

            var objectStream = new MemoryStream(message.Body);
            var updateEvent  = (ContentPageChangeEventArgs)formatter.Deserialize(objectStream);

            if (updateEvent.Title == null)
            {
                _logger.LogWarning($"Changeset {updateEvent.ChangesetId} has null title");
                await _subClient.CompleteAsync(message.SystemProperties.LockToken);

                return;
            }

            var prevMeta = _cache.GetPageMetadata(updateEvent.Title);

            if (prevMeta != null && prevMeta.ChangeSetId > updateEvent.ChangesetId)
            {
                _logger.LogWarning($"Update to page {updateEvent.Title} has higher local rev, {prevMeta.ChangeSetId} > {updateEvent.ChangesetId}");
                await _subClient.CompleteAsync(message.SystemProperties.LockToken);

                return;
            }

            try
            {
                var(meta, page) = await _apiClient.GetPageAsync(updateEvent.Title, updateEvent.ChangesetId);

                if (meta != null && page != null)
                {
                    _cache.PutPageContent(updateEvent.Title, meta, page);
                    await _subClient.CompleteAsync(message.SystemProperties.LockToken);

                    _logger.LogInformation($"Updated page {updateEvent.Title} to rev {updateEvent.ChangesetId}");
                }
            }
            catch (Exception exc)
            {
                _logger.LogError(exc, "MW getting update failed");
            }
        }
 public async Task CompleteMessage(Message message)
 {
     // We have turned off auto complete, and must complete the message when everything is ok.
     // This must be done within 30 seconds, otherwise other clients of the subscription might handle the message.
     // Because of this, ProcessFile should never take more than 30 seconds, or should be asynchronous
     await _client.CompleteAsync(message.SystemProperties.LockToken);
 }
        void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Register the function that processes messages.
            _subscriptionClient.RegisterMessageHandler((message, token) =>
            {
                string json = Encoding.UTF8.GetString(message.Body);
                CartItemsReceiverDetails cartItems = JsonConvert.DeserializeObject <CartItemsReceiverDetails>(json);
                int quantityDifference             = 1;

                bool result = _searchRepository.UpdateQuantitiesForMenuOfRestaurant(cartItems.RestaurantId, cartItems.MenuId, cartItems.Quantity,
                                                                                    out quantityDifference);

                //if (quantityDifference < 1 && result)
                //{
                //    cartItems.Quantity = quantityDifference;
                //    string jsonForOrderService = JsonConvert.SerializeObject(cartItems);
                //    SendMessageAsync(jsonForOrderService);
                //}
                Console.WriteLine($"{cartItems.Quantity} plates of Menu {cartItems.MenuId} ordered from Restaurant {cartItems.RestaurantId}");

                return(_subscriptionClient.CompleteAsync(message.SystemProperties.LockToken));
            }, new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                AutoComplete       = false,
                MaxConcurrentCalls = 1
            });
        }
Beispiel #4
0
            static async Task ProcessInvoiceMessagesAsync(Message message, CancellationToken token)
            {
                var json  = EncodingService.Base64Decode(message.Body);
                var trans = EncodingService.DecodeJson <OnlineTransaction>(json);

                // Random delay of at least a second
                var rnd = new Random(Environment.TickCount);
                await Task.Delay((int)(1000 + 1000 * rnd.NextDouble()));

                // Process the message.
                //Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{json}");
                Console.WriteLine(DateTime.Now.ToString() + ": Invoice Received");

                // Process the invoice
                trans.ProcessedTimeUTC = DateTime.UtcNow;
                trans.Processed        = true;
                // Persist to SQL
                await SaveTransactionAsync(trans, json);

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

                // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
                // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
                // to avoid unnecessary exceptions.
            }
Beispiel #5
0
        static async Task ProcessMessagesAsync(Message message, System.Threading.CancellationToken token)
        {
            // Process the message
            Console.WriteLine($"Received message: Sequence Number:{message.SystemProperties.SequenceNumber} \t Body:{Encoding.UTF8.GetString(message.Body)}");

            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
Beispiel #6
0
        private static async Task ProcessMessagesAsync2(Message message, CancellationToken token)
        {
            Console.WriteLine($"ProcessMessagesAsync2:::: {Encoding.UTF8.GetString(message.Body)} with LockToken: {message.SystemProperties.LockToken}");
            await Task.Delay(5000, token);

            await _subscriptionClient2.CompleteAsync(message.SystemProperties.LockToken);
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var messageBody = Encoding.UTF8.GetString(message.Body);

            Console.WriteLine($"Message Received from Subscription '{SubscriptionName}' : '{messageBody}'");
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); // Because autocomplete is false
        }
Beispiel #8
0
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            if (IsThisMessageForMe(message))
            {
                try
                {
                    var deserialisedMessage = JsonSerializer.Deserialize <MessageModel>(Encoding.UTF8.GetString(message.Body));

                    var authorsCollection = cosmosDatabase.GetCollection <ExternalApiAuthor>(writerCosmosDbConfig.AuthorsCollectionId);
                    var booksCollection   = cosmosDatabase.GetCollection <ExternalApiBook>(writerCosmosDbConfig.BooksCollectionId);

                    // Save it on Cosmos DB
                    await authorsCollection.InsertOneAsync(deserialisedMessage.Author, cancellationToken : token).ConfigureAwait(false);

                    await booksCollection.InsertManyAsync(deserialisedMessage.Books, cancellationToken : token).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            //TODO: Not sure whether we need to complete the msg if it wasn't for this subscriptor ....
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
 private async Task ProcessMessagesAsync(Message message, CancellationToken token)
 {
     _logger.LogInformation($"[{_subscription} | Nova mensagem] " +
                            Encoding.UTF8.GetString(message.Body));
     await _client.CompleteAsync(
         message.SystemProperties.LockToken);
 }
Beispiel #10
0
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message.
            Console.WriteLine($"Received message: CorrelationId: {message.CorrelationId} SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

            var activity = message.ExtractActivity();

            using (var operation = telemetry.StartOperation <RequestTelemetry>("Processiong Message", activity.RootId, activity.ParentId))
            {
                try
                {
                    telemetry.TrackTrace($"Received message: Activity ParentId: {activity.ParentId} SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
                    await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
                }catch (Exception ex)
                {
                    telemetry.TrackException(ex);
                    operation.Telemetry.Success = false;
                    throw;
                }
                Console.WriteLine($"Completed message: CorrelationId: {message.CorrelationId} 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 subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default).


            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
        private static async Task ProcessMessageAsync(Message msg, CancellationToken token)
        {
            string data = Encoding.UTF8.GetString(msg.Body);

            msgList.Add(data);

            await subscriptionClient.CompleteAsync(msg.SystemProperties.LockToken);

            if (msgList.Count == 4)
            {
                stockInfo = _searchRepository.ItemInStock(int.Parse(msgList[0]), int.Parse(msgList[1]));

                if (stockInfo.quantity >= Int16.Parse(msgList[3]))
                {
                    ItemValue = "ItemInStock";
                }
                else if (stockInfo.quantity < Int16.Parse(msgList[3]))
                {
                    ItemValue = "ItemOutOfStock";
                }
                msg = new Message(Encoding.UTF8.GetBytes(ItemValue));
                await topicClient.SendAsync(msg);

                msgList = new List <string>();
            }
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message
            //Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
            var messageString = Encoding.UTF8.GetString(message.Body);

            Blockchain receivedBlockchain = JsonConvert.DeserializeObject <Blockchain>(messageString);

            if (receivedBlockchain.IsValid() && receivedBlockchain.Chain.Count > Program.blockchain.Chain.Count)
            {
                List <Transaction> newTransactions = new List <Transaction>();
                newTransactions.AddRange(receivedBlockchain.PendingTransactions);
                newTransactions.AddRange(Program.blockchain.PendingTransactions);

                receivedBlockchain.PendingTransactions = newTransactions;
                Program.blockchain = receivedBlockchain;
            }
            if (!blockchainSynced)
            {
                //Send(JsonConvert.SerializeObject(Program.blockchain));
                blockchainSynced = true;
            }

            // Complete the message so that it is not received again.
            // This can be done only if the subscriptionClient is opened in ReceiveMode.PeekLock mode (which is default).
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        private async Task OnMessage(Message messageToHandle, CancellationToken lockToken)
        {
            try {
                string groupId = messageToHandle.UserProperties["CollectionId"].ToString();
                if (_messageHolder.TryAdd(groupId, new HashSet <string>()))
                {
                    _processedMessagesHolder.TryAdd(groupId, new ConcurrentDictionary <string, string>());
                }

                string dataJSON = Encoding.UTF8.GetString(messageToHandle.Body);

                int totalMessagesCount = int.Parse(messageToHandle.UserProperties["Count"].ToString());

                string updatedMessage = await ProcessMessage(messageToHandle, dataJSON);

                if (!updatedMessage.Equals("", StringComparison.InvariantCultureIgnoreCase))
                {
                    _processedMessagesHolder[groupId].TryAdd(messageToHandle.MessageId, updatedMessage);
                }

                await subscriptionClient.CompleteAsync(messageToHandle.SystemProperties.LockToken);

                _messageHolder[groupId].Add(dataJSON);

                int processedMessagesCount = _messageHolder[groupId].Count;

                if (processedMessagesCount == totalMessagesCount)
                {
                    // --- Get original messages list
                    HashSet <string> removed = new HashSet <string>();
                    _messageHolder.TryRemove(groupId, out removed);
                    IList <string> messagesList = removed.ToList();

                    // --- Get processed messages list
                    ConcurrentDictionary <string, string> removedDictionary = new ConcurrentDictionary <string, string>();
                    _processedMessagesHolder.TryRemove(groupId, out removedDictionary);
                    IList <string> processedMessagesList = null;
                    if (removedDictionary.Count > 0)
                    {
                        processedMessagesList = removedDictionary.Values.ToList();
                    }
                    if (!(logger is null))
                    {
                        logger.LogInformation(String.Format("====== PROCESSING GROUP OF {0} MESSAGES FOR {1} ======", totalMessagesCount.ToString(), messageToHandle.UserProperties["CollectionId"].ToString()));
                    }
                    await ProcessMessagesWhenLastReceived(messagesList, messageToHandle, processedMessagesList);
                }

                if (!(logger is null))
                {
                    logger.LogInformation(String.Format("----- Processed message {0} of {1} for {2} -----", processedMessagesCount.ToString(), totalMessagesCount.ToString(), messageToHandle.UserProperties["CollectionId"].ToString()));
                }
            } catch (Exception ex) {
                await subscriptionClient.AbandonAsync(messageToHandle.SystemProperties.LockToken);

                //logger.LogError(ex.Message + ex.StackTrace);
                //throw new ApplicationException(ex.Message + ex.StackTrace);
                throw ex;
            }
        }
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message.
            _logger.LogInformation($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

            await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        static async Task ProcessMessageAsync(Message message, CancellationToken token)
        {
            var taskStatusEvent = GetTaskStatusEvent(message);

            #region Dump object to console
            var messageBody = Encoding.UTF8.GetString(message.Body);
            Log.Debug($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber}");
            Log.Debug("");
            Log.Debug($"Message Body:");
            Log.Debug(Dump(messageBody));
            Log.Debug("");
            Log.Debug($"Inner Message body:");
            Log.Debug(Dump(taskStatusEvent));
            Log.Debug($"Posting the message body TaskStatusEvent body to Fenetre Test Harness");
            Log.Debug("");
            Log.Debug("----------------------------------------------------------------------");
            #endregion

            await PostTaskStatusEvent(taskStatusEvent);

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

            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
Beispiel #16
0
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            _logger.LogInformation($"Received the following message: {Encoding.UTF8.GetString(message.Body)}");

            // Complete the message so that it is not received again.
            await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
Beispiel #17
0
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var messageBody = Encoding.UTF8.GetString(message.Body);

            _messageHandler.HandleMessage(messageBody);
            await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
Beispiel #18
0
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message.
            string s = Encoding.UTF8.GetString(message.Body);

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

            if (listOfMessagesfromQueue.Count == 2)
            {
                StockDeails             = _searchRepository.GetStockDetails(int.Parse(listOfMessagesfromQueue[0]), int.Parse(listOfMessagesfromQueue[1]));
                CallBackMessagetoBeSent = StockDeails.quantity.ToString();
                message = new Message(Encoding.UTF8.GetBytes(CallBackMessagetoBeSent));



                // Send the message to the topic
                await topicClient.SendAsync(message);

                listOfMessagesfromQueue = new List <string>();
            }
            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
Beispiel #19
0
        static async Task ProcessAppControlMessagesAsync(Message message, CancellationToken token)
        {
            string strBody = Encoding.UTF8.GetString(message.Body);

            try
            {
                AppControlMessage controlObject = JsonConvert.DeserializeObject <AppControlMessage>(strBody);
                if (0 == controlObject.AppName.CompareTo("hoho"))
                {
                }
            }
            catch (Exception ex)
            {
                string se = ex.Message;
            }

            // Complete the message so that it is not received again.
            // This can be done only if the subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default).
            if (!token.IsCancellationRequested)
            {
                await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
            }

            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Display the message.
            Console.WriteLine($"Received sale performance message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
Beispiel #21
0
        async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            string msg = Encoding.UTF8.GetString(message.Body);

            _customerBusiness.UpdateFromReceivedMessage(msg);
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            string dados = Encoding.UTF8.GetString(message.Body);

            _logger.Information($"Mensagem recebida: {dados}");

            var acao = JsonSerializer.Deserialize <Acao>(dados,
                                                         new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            var validationResult = new AcaoValidator().Validate(acao);

            if (validationResult.IsValid)
            {
                acao.UltimaAtualizacao = DateTime.Now;
                var dbRedis = _conexaoRedis.GetDatabase();
                dbRedis.StringSet(
                    "ACAO-" + acao.Codigo,
                    JsonSerializer.Serialize(acao),
                    expiry: null);

                _logger.Information("Ação registrada com sucesso!");
            }
            else
            {
                _logger.Error("Dados inválidos para a Ação");
            }

            await _subscriptionClient.CompleteAsync(
                message.SystemProperties.LockToken);
        }
        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);
            }
        }
Beispiel #24
0
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            string dados = Encoding.UTF8.GetString(message.Body);

            _logger.Information($"Mensagem recebida: {dados}");

            var acao = JsonSerializer.Deserialize <Acao>(dados,
                                                         new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            var validationResult = new AcaoValidator().Validate(acao);

            if (validationResult.IsValid)
            {
                _repository.Save(acao);
                _logger.Information("Ação registrada com sucesso!");
            }
            else
            {
                _logger.Error("Dados inválidos para a Ação");
            }

            await _subscriptionClient.CompleteAsync(
                message.SystemProperties.LockToken);
        }
        async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message.
            var messageBody    = Encoding.UTF8.GetString(message.Body);
            var sequenceNumber = message.SystemProperties.SequenceNumber;
            var messageId      = message.MessageId;

            if (MessageReceivedCounter == 0) // Set MessageSentTimeStamp on the first message that we send
            {
                MessageReceivedTimeStamp = DateTime.UtcNow;
            }

            MessageReceivedCounter++;

            // Console.WriteLine($"Received message: MessageId:{messageId}, SequenceNumber:{sequenceNumber} Body:{messageBody}");

            var r = _onMessageReceived(messageBody, message.MessageId, sequenceNumber);

            if (r)
            {
                // Complete the message so that it is not received again.
                // This can be done only if the subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default).
                await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
            }
            else
            {
                // Release message so it can be processed again
                await _subscriptionClient.AbandonAsync(message.SystemProperties.LockToken);
            }
            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            string dados = Encoding.UTF8.GetString(message.Body);

            _logger.Information($"Mensagem recebida: {dados}");

            var cotacao = JsonSerializer.Deserialize <CotacaoMoeda>(dados,
                                                                    new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            var validationResult = new CotacaoMoedaValidator().Validate(cotacao);

            if (validationResult.IsValid)
            {
                cotacao.UltimaAtualizacao = DateTime.Now;
                var dbRedis = _conexaoRedis.GetDatabase();
                dbRedis.StringSet(
                    "COTACAO-" + cotacao.Sigla,
                    JsonSerializer.Serialize(cotacao),
                    expiry: null);

                _logger.Information("Cotação registrada com sucesso!");

                using (var clientLogicAppSlack = new HttpClient())
                {
                    clientLogicAppSlack.BaseAddress = new Uri(
                        _configuration["UrlLogicAppAlerta"]);
                    clientLogicAppSlack.DefaultRequestHeaders.Accept.Clear();
                    clientLogicAppSlack.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestMessage =
                        new HttpRequestMessage(HttpMethod.Post, String.Empty);

                    requestMessage.Content = new StringContent(
                        JsonSerializer.Serialize(new
                    {
                        moeda = cotacao.Sigla,
                        valor = cotacao.Valor,
                    }), Encoding.UTF8, "application/json");

                    var respLogicApp = clientLogicAppSlack
                                       .SendAsync(requestMessage).Result;
                    respLogicApp.EnsureSuccessStatusCode();

                    _logger.Information(
                        "Envio de alerta para Logic App de integração com o Slack");
                }
            }
            else
            {
                _logger.Error("Dados inválidos para a Cotação");
            }

            await _subscriptionClient.CompleteAsync(
                message.SystemProperties.LockToken);
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // 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.
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        private static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var jsonString = Encoding.UTF8.GetString(message.Body);

            Console.WriteLine(jsonString);

            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
Beispiel #29
0
        static async Task ProcessCreateOrderMessagesAsync(Message message, CancellationToken token)
        {
            dynamic order = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message.Body));

            Console.WriteLine($"{DateTime.UtcNow.ToString("HH:mm:ss.fff")} - Topic: \"CreateOrderTopic\" received Order with Id: {order.Id} and Status: {order.Status}");

            await _createOrderSubscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        private async Task ProcessMessageAsync(Message messsage, CancellationToken cancellationToken)
        {
            string body   = Encoding.UTF8.GetString(messsage.Body);
            var    person = JsonConvert.DeserializeObject <Person>(body);

            Console.WriteLine($"Person Received, Name: {person.Name}, Age: {person.Age}");
            await subscriptionClient.CompleteAsync(messsage.SystemProperties.LockToken);
        }