async Task ProcessMessagesAsync(Message message, CancellationToken token) { if (_queueClient.IsClosedOrClosing) { Logger.Log("Queue is closing, abandoning message."); await _queueClient.AbandonAsync(message.SystemProperties.LockToken); return; } string videoUrl = ""; try { // Process the message. Logger.Log($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}"); string json = Encoding.UTF8.GetString(message.Body); videoUrl = QueueMessageParser.GetUrl(json); Logger.Log($"Received this videoUrl: {videoUrl}"); if (videoUrl.EndsWith("test.MP4")) { throw new ApplicationException("Something broke, fail safe for testing exceptions!"); } SkiVideoProcessor processor = new SkiVideoProcessor(videoUrl); await processor.ProcessAsync(); await _queueClient.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception e) { if (message.SystemProperties.DeliveryCount <= 2) { Logger.Log($"Abandoned message.", e); // abandon and allow another to try in case of transient errors await _queueClient.AbandonAsync(message.SystemProperties.LockToken); } else { Logger.Log($"Dead lettering message.", e); await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken, e.Message, e.InnerException?.Message); } } finally { Logger.Log($"Message handler completed for {videoUrl}."); if (Completed != null) { Completed(this, null); } } }
private async Task ProcessMessagesAsync(Message message, CancellationToken token) { try { var messageBody = message.Body; var statusObject = JsonConvert.DeserializeObject( System.Text.Encoding.UTF8.GetString(messageBody), typeof(ServiceStatus)); ServiceStatus status = (ServiceStatus)statusObject; SaveServiceStatus(status); Console.WriteLine($"{status.Address}: {status.Code} - {status.Description} - {message.SystemProperties.EnqueuedTimeUtc}"); } catch (SerializationException e) { throw new MessageCorruptedException("Message corrupted.", e); } if (token.IsCancellationRequested) { await _queueClient.AbandonAsync(message.SystemProperties.LockToken); } else { await _queueClient.CompleteAsync(message.SystemProperties.LockToken); } }
public async Task <string> GetMessageByCorrelationId(string correlationId) { _logger.Log($"GetMessageByCorrelationId: {correlationId}"); var tcs = new TaskCompletionSource <Message>(); string returnMessageBody = string.Empty; var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false }; _responseQueueClient.RegisterMessageHandler(async(message, cancellationToken) => { _logger.Log($"Received Message: {message.CorrelationId}, To: {message.To}, ReplyTo: {message.ReplyTo}"); if (message.CorrelationId == correlationId) { returnMessageBody = Encoding.UTF8.GetString(message.Body, 0, message.Body.Length); await _responseQueueClient.CompleteAsync(message.SystemProperties.LockToken); _logger.Log($"Accepted Message: {returnMessageBody}"); tcs.TrySetResult(message); } else { await _responseQueueClient.AbandonAsync(message.SystemProperties.LockToken); } }, messageHandlerOptions); await tcs.Task; return(returnMessageBody); }
public async Task HandleWeatherUpdate([ServiceBusTrigger("weatherDataEventQueue", Connection = "SERVICE_BUS_CONNECTION")] Message message, ILogger log) { try { var stringValue = Encoding.UTF8.GetString(message.Body, 0, message.Body.Length); var weatherUpdateEvent = JsonConvert.DeserializeObject <WeatherUpdateTriggerEvent>(stringValue); log.LogInformation($"WeatherCollectionRequestedHandler for Zip {weatherUpdateEvent.ZipCode} triggered at {DateTime.UtcNow}"); var command = new UpdateZipForecast.Command { WeatherUpdateEvent = weatherUpdateEvent }; await mediator.Send(command); } catch (JsonException jsonException) { await queueClient.DeadLetterAsync(message.SystemProperties.LockToken); log.LogError($"Error occured when parsing message."); } catch (Exception e) { await queueClient.AbandonAsync(message.SystemProperties.LockToken); log.LogError(e.StackTrace); } }
private async Task ProcessMessagesAsync(Message message, CancellationToken token) { // Process the message Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}"); if (message.Label == "Request") { // 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.CompleteAsync(message.SystemProperties.LockToken); object result = null; if (_marconiIsBusy) { } else { _marconiIsBusy = true; try { var start = DateTime.UtcNow; string query = Encoding.UTF8.GetString(message.Body); ResolverEntry aEntry = new ResolverEntry(_doc, aRevitTask); result = await aEntry.GetResultAsync(JObject.Parse(query)); } catch (Exception e) { } _marconiIsBusy = false; } var responseMessage = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result))) { ContentType = "application/json", Label = "Response", CorrelationId = message.MessageId, MessageId = Guid.NewGuid().ToString(), TimeToLive = TimeSpan.FromMinutes(5) }; // Send the message to the queue IQueueClient queueResponseClient = new QueueClient(ServiceBusConnectionStringBuilder); await queueClient.SendAsync(responseMessage); } else { 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. }
static async Task ProcessMessagesAsync(Message message, CancellationToken token) { Console.WriteLine($"Received message!" + $"SequenceNumber: {message.SystemProperties.SequenceNumber} " + $"DeliveryCount: {message.SystemProperties.DeliveryCount} " + $"Body: {Encoding.UTF8.GetString(message.Body)}"); //await Task.Delay(TimeSpan.FromSeconds(5)); await _queue.AbandonAsync(message.SystemProperties.LockToken); }
static async Task ProcessMessagesAndAbandonAsync(Message message, CancellationToken token) { // Process the message Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber}, Delivery Count: {message.SystemProperties.DeliveryCount} 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. }
async Task ProcessMessagesAsync(Message message, CancellationToken token) { try { await this.HandleAsync(JsonConvert.DeserializeObject <TMessage>(Encoding.UTF8.GetString(message.Body)), Guid.Parse(message.CorrelationId)); } catch (Exception ex) { _logger.LogError(ex, $"Azure ServiceBus subscriber failed processing message {typeof(TMessage).FullName}"); await _queueClient.AbandonAsync(message.SystemProperties.LockToken); } await _queueClient.CompleteAsync(message.SystemProperties.LockToken); }
static async Task ProcessMessagesAsync(Message message, CancellationToken token) { try { // Process the message var body = Encoding.UTF8.GetString(message.Body); dynamic obj = Newtonsoft.Json.Linq.JObject.Parse(body); var orderId = obj.order.ToString(); var orderObject = new { OrderId = orderId }; var orderMessage = Newtonsoft.Json.JsonConvert.SerializeObject(orderObject); var eventTelemetry = new EventTelemetry(); eventTelemetry.Name = $"ServiceBusListener"; eventTelemetry.Properties.Add("team", TeamName); eventTelemetry.Properties.Add("sequence", "3"); eventTelemetry.Properties.Add("type", "servicebus"); eventTelemetry.Properties.Add("service", "servicebuslistener"); eventTelemetry.Properties.Add("orderId", orderId); var result = await SendRequest(orderMessage); if (result) { Console.WriteLine($"Send order to fulfillment {orderId}"); eventTelemetry.Properties.Add("status", "sent to fulfillment service"); // 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.CompleteAsync(message.SystemProperties.LockToken); } else { eventTelemetry.Properties.Add("status", "failed to send to fulfillment service"); // This will make the message available again for processing await queueClient.AbandonAsync(message.SystemProperties.LockToken); } trackEvent(eventTelemetry); // 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. } catch (Exception ex) { Console.WriteLine(ex.Message); telemetryClient.TrackException(ex); } }
private static async Task HandleMessage(Message message, CancellationToken token) { try { bool isDeadLetterMessage = message.UserProperties.Keys.FirstOrDefault(k => k.Equals("DeadLetterReason")) != null; bool hasSessionId = !string.IsNullOrEmpty(message.SessionId); Console.WriteLine("Message Received!"); var smsMessage = JsonConvert.DeserializeObject <SmsMessage>(Encoding.UTF8.GetString(message.Body)); Console.WriteLine("Content: " + smsMessage.Content); Console.WriteLine("Destination: " + smsMessage.Destination); Console.WriteLine("Is DLQ: " + isDeadLetterMessage); // Writing messages with not null sessionId's to session disabled queues is not forbidden. // In fact, if you write messages with sessionId to a queue where sessions are disabled, // you will still get messages FIFO. Console.WriteLine("Has session ID: " + hasSessionId); if (hasSessionId) { Console.WriteLine("Session ID: " + message.SessionId); } // 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). if (isDeadLetterMessage) { await _dlqReceiver.CompleteAsync(message.SystemProperties.LockToken); } else { await _queueClient.CompleteAsync(message.SystemProperties.LockToken); } Console.WriteLine("***********************\n"); } catch { Console.WriteLine("Received exception while handling the message, abandoning..."); await _queueClient.AbandonAsync(message.SystemProperties.LockToken); } }
private async Task ProcessMessagesAsync(Message message, CancellationToken token) { try { var messageBody = message.Body; if (!ValidateMondatoryFields(message)) { throw new MessageCorruptedException("Message metadata not found."); } var sequence = GetMessageMetadata <string>("Sequence", message); var positionNumber = GetMessageMetadata <int>("Position", message); var partsNumber = GetMessageMetadata <int>("Size", message); var constructedFile = GetConstructedFile(sequence, partsNumber); var constructed = constructedFile.AppendFilePart(messageBody, positionNumber); if (constructed) { SaveCostructedFile(constructedFile); _constructedFiles.Remove(sequence); } Console.WriteLine(positionNumber); } catch (SerializationException e) { throw new MessageCorruptedException("Message corrupted.", e); } if (token.IsCancellationRequested) { await _queueClient.AbandonAsync(message.SystemProperties.LockToken); } else { // 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). // 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. await _queueClient.CompleteAsync(message.SystemProperties.LockToken); } }
public static Task ReceiveMessage(Message message, CancellationToken cancellation) { lock (Console.Out) { var content = Encoding.UTF8.GetString(message.Body); Console.WriteLine("Message received:"); Console.WriteLine(content); var notification = JsonConvert.DeserializeObject <Commons.Message>(content); if (notification == null || notification.Receipient.Contains("@test.pl")) { return(queueClient.AbandonAsync(message.SystemProperties.LockToken)); } } return(queueClient.CompleteAsync(message.SystemProperties.LockToken)); }
public async Task ReceiveMessageFromQueue <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(() => _queueClient.RegisterMessageHandler( async(message, token) => { try { string data = Encoding.UTF8.GetString(message.Body); T item = JsonConvert.DeserializeObject <T>(data); MessageProcessResponse 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; } } catch (Exception ex) { await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken); Trace.TraceError(ex.Message); } }, options)); }
static async Task ProcessMessagesAsync(Message message, CancellationToken token) { Random random = new Random(); int DeadLetter = random.Next(1, 3); if (DeadLetter == 1) { Console.WriteLine($"Purposefully Dead-Lettering."); await queueClient.AbandonAsync(message.SystemProperties.LockToken); } else { // Process the message StudentInfo.StudentInfo newStudent = JsonConvert.DeserializeObject <StudentInfo.StudentInfo>(Encoding.UTF8.GetString(message.Body)); Console.WriteLine($"New Student Recieved: {newStudent.Name}"); await queueClient.CompleteAsync(message.SystemProperties.LockToken); } }
private async Task ProcessMessagesAsync(Message message, CancellationToken token) { try { // Deserialize message, send mail via smtp client, and complete message string messageBody = Encoding.UTF8.GetString(message.Body); EmailMessage emailMessage = JsonConvert.DeserializeObject <EmailMessage>(messageBody); await _mailer.SendMailAsync(emailMessage); await _queueClient.CompleteAsync(message.SystemProperties.LockToken); _logger.LogInformation($"Processed message: SequenceNumber:{message.SystemProperties.SequenceNumber}"); } catch (Exception ex) { // failed to process message, mark as Abandoned _logger.LogError(ex, $"Error processing message: SequenceNumber:{message.SystemProperties.SequenceNumber}"); await _queueClient.AbandonAsync(message.SystemProperties.LockToken); } }
public void StartListening(string identityKeyName) { var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 1, AutoComplete = false }; queueClient.RegisterMessageHandler(async(Message msg, CancellationToken ct) => { var messageListeners = registeredListeners.Where(r => r.MessageType == msg.Label); if (!messageListeners.Any()) { Console.WriteLine($"No listeners for Message Type {msg.Label}."); return; } messageListeners = registeredListeners.Where(r => r.Id == msg.UserProperties[identityKeyName] as string); if (messageListeners.Any()) { foreach (var messageListener in messageListeners) { Console.WriteLine($"Notifying listener for '{msg.UserProperties[identityKeyName]}."); bool processed = messageListener.Notify(msg); if (processed) { Console.WriteLine($"Processed '{msg.UserProperties[identityKeyName]}."); await queueClient.CompleteAsync(msg.SystemProperties.LockToken); } } } else { Console.WriteLine($"No listeners for '{msg.UserProperties[identityKeyName]}."); await queueClient.AbandonAsync(msg.SystemProperties.LockToken); } }, messageHandlerOptions); }
static async Task ProcessMessagesAsync(Message message, CancellationToken token) { // Process the message //YJYGlobal.LogLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber}"); try { var posToClose = Serialization.ByteArrayToObject(message.Body) as PosToClose; YJYGlobal.LogLine( $"Received: {posToClose.Id} {posToClose.closeType} {posToClose.closePx} {posToClose.closePxTime}"); var autoClosePosition = PositionService.AutoClosePosition(posToClose); var checkAndCloseFollowPositions = PositionService.CheckAndCloseFollowPositions(autoClosePosition.Id); MessageService.AddAutoCloseMessage(autoClosePosition); MessageService.AddAutoCloseMessages(checkAndCloseFollowPositions); YJYGlobal.LogLine( $"pos closed: {autoClosePosition.Id} type:{autoClosePosition.CloseType} pl:{autoClosePosition.PL}"); // 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.CompleteAsync(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. } catch (Exception e) { YJYGlobal.LogException(e); await queueClient.AbandonAsync(message.SystemProperties.LockToken); } }
private static async Task ProcessMessagesAsync(Message message, CancellationToken token) { // Process the message var messageBody = Encoding.UTF8.GetString(message.Body); Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{messageBody}"); var sendCoinsMessage = JsonConvert.DeserializeObject <SendCoinsMessage>(messageBody); if (sendCoinsMessage == null) { throw new UnknownMessageContentException("Content: " + messageBody); } var presaleInfo = await dataManager.GetPresaleInfoByIdAsync(sendCoinsMessage.PresaleId); if (presaleInfo == null) { Console.WriteLine("Given presale ID not found - something went really wrong :("); Console.ReadLine(); } // wait until wallet is ready to send the coins out var walletBalance = await rpcClient.GetBalanceAsync(); if (walletBalance == null) { presaleInfo.AdditionalData = $"get balance error - retry in the next cycle (message will be requeued)"; Console.WriteLine(presaleInfo.AdditionalData); await dataManager.SaveOrUpdatePresaleInfoAsync(presaleInfo); await Task.Delay(30000); await queueClient.AbandonAsync(message.SystemProperties.LockToken); return; } if (presaleInfo.SentToTargetTimestamp != null) { presaleInfo.AdditionalData = $"coins were already sent - don't send them multiple times - drop message from queue"; Console.WriteLine(presaleInfo.AdditionalData); await dataManager.SaveOrUpdatePresaleInfoAsync(presaleInfo); await queueClient.CompleteAsync(message.SystemProperties.LockToken); return; } // greater since we have to pay a tx fee if (walletBalance.Value > presaleInfo.NrOfCoins + 1) { var validateAddressResult = await rpcClient.ValidateAddressAsync(presaleInfo.TargetAddressCoins); if (validateAddressResult != null) { // set target address state presaleInfo.TargetAddressValid = validateAddressResult.IsValid; if (!validateAddressResult.IsValid) { presaleInfo.AdditionalData = "target address invalid - check manually"; Console.WriteLine(presaleInfo.AdditionalData); await dataManager.SaveOrUpdatePresaleInfoAsync(presaleInfo); await queueClient.CompleteAsync(message.SystemProperties.LockToken); return; } var transactionResult = await rpcClient.SendToAddressAsync(presaleInfo.TargetAddressCoins, presaleInfo.NrOfCoins, "coin presale " + presaleInfo.Id, sendCoinsMessage.PresaleId.ToString()); // if the result is invalid, try again (requeue) if (transactionResult != null) { presaleInfo.SentToTargetTxId = transactionResult; presaleInfo.SentToTargetTimestamp = DateTime.UtcNow; presaleInfo.AdditionalData = "coins sent"; Console.WriteLine(presaleInfo.AdditionalData); } else { presaleInfo.AdditionalData = $"send to address error: transactionResult null -> please send {presaleInfo.NrOfCoins} coins manually"; Console.WriteLine(presaleInfo.AdditionalData); } await dataManager.SaveOrUpdatePresaleInfoAsync(presaleInfo); await queueClient.CompleteAsync(message.SystemProperties.LockToken); } else { presaleInfo.AdditionalData = "address check error: validateAddressResult null"; Console.WriteLine(presaleInfo.AdditionalData); await dataManager.SaveOrUpdatePresaleInfoAsync(presaleInfo); await Task.Delay(30000); await queueClient.AbandonAsync(message.SystemProperties.LockToken); } } else { presaleInfo.AdditionalData = $"balance error - not enough coins available -> requeue"; Console.WriteLine(presaleInfo.AdditionalData); await dataManager.SaveOrUpdatePresaleInfoAsync(presaleInfo); await Task.Delay(30000); await queueClient.AbandonAsync(message.SystemProperties.LockToken); } }
public async Task Abandon() { // TODO: Logging here await _queueClient.AbandonAsync(this._message.SystemProperties.LockToken); }
public void Nack() { _client.AbandonAsync(_lockTag).Wait(); }
public async Task AbandonAsync(Message message) { await _serviceBusClient.AbandonAsync(message.SystemProperties.LockToken); }