public void Requeue() { _cancellationTokenSource.Cancel(); _message.Abandon(); _completed = true; }
private void Listen(ReceiveMode receiveMode) { var mr = _messagingFactory.CreateMessageReceiver(_subscription.FullPath, receiveMode); while (_isListening) { BrokeredMessage message = null; try { message = mr.Receive(); } catch (TimeoutException) { ListeningTimedOut?.Invoke(); continue; } catch (OperationCanceledException) //When Cancel() is called on client or factory { return; } catch (Exception ex) { ExceptionOccured?.Invoke(message, ex); return; } if (message == null) { continue; } try { var isMessageHandled = HandleMessage(message); if (receiveMode == ReceiveMode.PeekLock) { if (isMessageHandled) { message.Complete(); } else { message.Abandon(); } } } catch (Exception ex) { if (receiveMode == ReceiveMode.PeekLock) { message.Abandon(); } ExceptionOccured?.Invoke(message, ex); } Thread.Sleep(50); } }
private void Listen() { BrokeredMessage receivedMessage = null; while (!this.isStopped) { try { receivedMessage = this.client.Receive(); this.ReceiveMessage(receivedMessage); } catch (MessagingException e) { // Transient problem, like network busy, or whatever. if (!e.IsTransient) { try { receivedMessage.Abandon(); } catch (Exception ex) { // Okay, NOW we have a problem. exceptionList.Add(ex); } } // wait, and try again. Thread.Sleep(10000); } catch (OperationCanceledException e) { if (!this.isStopped) { try { receivedMessage.Abandon(); } catch (Exception ex) { exceptionList.Add(ex); } exceptionList.Add(e); } } catch (Exception e) { try { receivedMessage.Abandon(); } catch (Exception ex) { exceptionList.Add(ex); } exceptionList.Add(e); } } }
private async Task RunAsync() { BrokeredMessage receivedMessage = null; while (!IsStopped) { try { // Receive the message receivedMessage = SubClient.Receive(); if (receivedMessage != null) { Order orderDetails = receivedMessage.GetBody <Order>(); Order order = new Order(); order.CustomerName = orderDetails.CustomerName; order.EmailId = orderDetails.EmailId; order.ProductOrderDetailsList = orderDetails.ProductOrderDetailsList; order.OrderDate = orderDetails.OrderDate; order.TotalDue = orderDetails.TotalDue; order.orderStatus = "Processed"; // Remove message from subscription receivedMessage.Complete(); order.OrderId = Guid.NewGuid(); await azureDocDBHelper.AddDocument(order, "OrderDetails"); receivedMessage = null; } } catch (MessagingException e) { if (null != receivedMessage) { //unlock message in subscription receivedMessage.Abandon(); } if (!e.IsTransient) { Trace.WriteLine(e.Message); throw; } Thread.Sleep(10000); } catch (Exception ex) { // unlock message in subscription receivedMessage.Abandon(); Trace.WriteLine(ex.Message); } } }
async static void ProcessReceivedMessage(Task <BrokeredMessage> t) { EventHubProcessor processor = new EventHubProcessor(); BrokeredMessage message = t.Result; if (message != null) { var messagestring = message.GetBody <String>(); try { processor.ProcessMessage(JsonConvert.DeserializeObject <Request>(messagestring)); //var a = 0; //var i = 1 / a; count = count + 1; Console.WriteLine("Total Count :- {0}", count); message.CompleteAsync(); } catch (Exception ex) { Console.WriteLine("Error :- {0} - {1}", ex.Message, ex.InnerException); message.Abandon(); } } }
/// <summary> /// Listens for numMessages consecutive messages /// </summary> /// <param name="numMessages">Number of messages to listen to</param> /// <returns>The last received message</returns> public virtual T Listen <T>(int numMessages) { int messages = numMessages; T messageBody = default(T); // Continuously process messages received from the HighMessages subscription while (messages > 0) { BrokeredMessage message = SubClient.Receive(TimeSpan.FromSeconds(15)); messages--; if (message != null) { try { messageBody = message.GetBody <T>(); Console.WriteLine(string.Format("Message {0}: {1}", message.Properties["MessageNumber"], messageBody)); // Remove message from subscription message.Complete(); } catch (Exception) { // Indicate a problem, unlock message in subscription message.Abandon(); } } } return(messageBody); }
public override void Run() { Trace.TraceInformation("Signupsworker is running"); while (true) { QueueClient qc = QueueClient.CreateFromConnectionString(ConnectionString, qname); BrokeredMessage msg = qc.Receive(); if (msg != null) { try { Trace.WriteLine("New Signup processed: " + msg.Properties["email"]); msg.Complete(); // Log to table storage SaveToStorage(msg.Properties["email"].ToString()); } catch (Exception) { // Indicate a problem, unlock the queue msg.Abandon(); } } } }
private static void ReceiveMessage() { // You can receive messages in one of two ways:- // 1. ReceiveAndDelete - get the message in one shot and remove it from the queue - messages are lost if the receiver crashes. // 2. PeekLock - two stage process where a message is locked, processed and released once it's completed. // The 3rd parameter on the QueueClient sets the mode (PeekLock by default). QueueClient client = QueueClient.CreateFromConnectionString(connectionString, queueName, ReceiveMode.PeekLock); // Continuously process messages sent to the queue while (true) { Console.WriteLine("Waiting..."); BrokeredMessage message = client.Receive(); if (message != null) { try { Console.WriteLine("Body: " + message.GetBody <string>()); Console.WriteLine("MessageID: " + message.MessageId); Console.WriteLine("Test Property: " + message.Properties["TestProperty"]); // Remove message from queue message.Complete(); break; } catch (Exception) { // Indicate a problem, unlock message in queue message.Abandon(); } } } }
public static async Task Run([ServiceBusTrigger("%DEVICE_LIFECYCLE_QUEUE_NAME%", AccessRights.Listen, Connection = "DEVICE_LIFECYCLE_CONNECTION_STRING")] BrokeredMessage message, TraceWriter log) { log.Info(String.Format("Starting to create/remove device in Loriot")); Stream stream = message.GetBody <Stream>(); StreamReader reader = new StreamReader(stream); dynamic queueItem = JObject.Parse(reader.ReadToEnd()); try { if (message.Properties["opType"].Equals("createDeviceIdentity")) { log.Info(String.Format("Register device {0}", queueItem.deviceId)); var results = await LoriotClient.RegisterNewDevice(queueItem, log); } else if (message.Properties["opType"].Equals("deleteDeviceIdentity")) { log.Info(String.Format("Remove device {0}", queueItem.deviceId)); var results = await LoriotClient.DeleteDevice(queueItem, log); } log.Info(String.Format("Action completed")); await message.CompleteAsync(); } catch (HttpRequestException httpRequestEx) { message.Abandon(); log.Error(httpRequestEx.Message, httpRequestEx); throw; } }
void sbqReceiver_OnMessageRecevied(BrokeredMessage brokeredMessage) { try { // Process the message Trace.WriteLine("Processing Service Bus message: " + brokeredMessage.SequenceNumber); var driverWorkstate = JsonConvert.DeserializeObject <DriverWorkstate>(brokeredMessage.GetBody <string>()); if (driverWorkstate == null) { brokeredMessage.Complete(); return; } try { driverWorkstate = _hosRepository.SaveDriverWorkstate(driverWorkstate); _sbqSender.Send(new BrokeredMessage(JsonConvert.SerializeObject(driverWorkstate))); brokeredMessage.Complete(); } catch { brokeredMessage.Abandon(); } } catch { brokeredMessage.DeadLetter(); } }
public static bool TryAbandon(this BrokeredMessage msg) { try { // Abandons a brokered message. This will cause the Service Bus to // unlock the message and make it available to be received again, // either by the same consumer or by another competing consumer. msg.Abandon(); // Return a result indicating that the message has been abandoned successfully. return(true); } catch (MessageLockLostException) { // It's too late to compensate the loss of a message lock. // We should just ignore it so that it does not break the receive loop. // We should be prepared to receive the same message again. } catch (MessagingException) { // There is nothing we can do as the connection may have been lost, // or the underlying topic/subscription may have been removed. // If Abandon() fails with this exception, the only recourse is to receive another message (possibly the same one). } return(false); }
protected void OnMessage(BrokeredMessage message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } try { var entity = _provider.Deserialize <T>(message); foreach (var callback in _callbacks) { callback(entity); } } catch (Exception ex) { Logger.LogError(ex.Message, ex); message.Abandon(new Dictionary <string, object> { { "Exception", ex.Message } }); throw; } }
static void Main(string[] args) { var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var topic = CloudConfigurationManager.GetSetting("topic"); var subscription = CloudConfigurationManager.GetSetting("subscription"); var client = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subscription); while (true) { BrokeredMessage message = client.Receive(); if (message != null) { try { if (message.Properties.Contains(new KeyValuePair <string, object>("messagetype", "ticket"))) { var ser = new DataContractSerializer(typeof(ticket)); var ticket = message.GetBody <ticket>(ser); Console.WriteLine("ticket_number: " + ticket.ticket_id); } message.Complete(); } catch (Exception ex) { // Indicate a problem, unlock message in subscription Console.WriteLine(ex); message.Abandon(); } } } }
static void Main(string[] args) { string queueName = "queue1"; string connection = "Endpoint=sb://ngtesb1.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=3s4PaCNkfQeuQ/YkxO2Z69riVAsdbBhZNK1Eo/2+Hrw=;TransportType=Amqp"; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection); var queue = factory.CreateQueueClient(queueName); while (true) { BrokeredMessage message = queue.Receive(); if (message != null) { try { Console.WriteLine("MessageId {0}", message.MessageId); Console.WriteLine("Delivery {0}", message.DeliveryCount); Console.WriteLine("Size {0}", message.Size); Console.WriteLine(message.GetBody <string>()); message.Complete(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); message.Abandon(); } } } }
private void OnMessage(IAsyncResult ar) { BrokeredMessage brokeredMessage = null; try { brokeredMessage = _queueClient.EndReceive(ar); if (brokeredMessage == null) { _logger.Write(LogLevel.Debug, "Received null message (i.e. the Azure ServiceBus library completed the async op without receiving a message)"); ReceiveMessage(); return; } var typeName = (string) brokeredMessage.Properties[MessageProperties.PayloadTypeName]; if (!CheckTypeName(typeName, brokeredMessage)) { ReceiveMessage(); return; } var type = Type.GetType(typeName, false); if (!CheckMessageType(type, brokeredMessage, typeName)) { ReceiveMessage(); return; } var method = _genericMethod.MakeGenericMethod(type); method.Invoke(this, new object[] {brokeredMessage}); brokeredMessage.Complete(); } catch (Exception exception) { _logger.Write(LogLevel.Error, "Failed to process " + brokeredMessage, exception); var targetInvoke = exception as TargetInvocationException; if (targetInvoke != null) { exception = exception.InnerException; } var e = new BusMessageErrorEventArgs(brokeredMessage, exception); CommandBusFailed(this, e); if (brokeredMessage != null) { if (e.MessageTask == MessageHandling.RemoveMessage) { brokeredMessage.Complete(); } else { brokeredMessage.Abandon(); } } } ReceiveMessage(); }
private Task OnMessage(BrokeredMessage message) { _isListening = true; Interlocked.Increment(ref _dequeuedCounter); var data = message.GetBody <T>(); // get a random worker var worker = _workers.ToList().Random(); if (worker == null) { message.Abandon(); return(Task.FromResult(0)); } var workItem = new QueueEntry <T>(message.LockToken.ToString(), data, this); try { worker.Action(workItem); if (worker.AutoComplete) { workItem.CompleteAsync().Wait(); } } catch (Exception ex) { Interlocked.Increment(ref _workerErrorsCounter); Log.Error().Exception(ex).Message("Error sending work item to worker: {0}", ex.Message).Write(); workItem.AbandonAsync().Wait(); } return(Task.FromResult(0)); }
private static void ServiceBusRecieve() { string qName = "76BusQueue"; string connection = "Endpoint=sb://alewife.servicebus.windows.net/;SharedAccessKeyName=76BusReceiver;SharedAccessKey=/ot1r8HCUNnLScKABbOHharCzOBQqoNtvbxlfVKPyRQ=;TransportType=Amqp"; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection); QueueClient queue = factory.CreateQueueClient(qName); var counter = 1; while (true) { BrokeredMessage bm = queue.Receive(); if (bm != null) { try { Console.WriteLine("MessageId {0}", bm.MessageId); Console.WriteLine(counter); Console.WriteLine(bm.GetBody <string>()); bm.Complete(); } catch (Exception ex) { Console.WriteLine(ex.Message); bm.Abandon(); } } counter++; } }
public override void Run() { string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); Client = QueueClient.CreateFromConnectionString(connectionString, QueueName); BrokeredMessage message = Client.Receive(); string body = message.GetBody <string>(); using (MailMessage mm = new MailMessage("*****@*****.**", "*****@*****.**")) { mm.Subject = "Testing Worker Role"; mm.Body = body; mm.IsBodyHtml = false; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; NetworkCredential NetworkCred = new NetworkCredential("*****@*****.**", "politm12"); smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = 587; smtp.Send(mm); } message.Complete(); message.Abandon(); }
private async Task HandleEventForMultipleDeployments(BrokeredMessage eventToHandle) { try { var eventType = Type.GetType(eventToHandle.ContentType); // Should be using json serialization var theEvent = JsonConvert.DeserializeObject(eventToHandle.GetBody <string>(), eventType); var client = _queueClients[eventType]; var message = JsonConvert.SerializeObject(theEvent); var brokeredMessage = new BrokeredMessage(message) { MessageId = message.GetHashCode().ToString(), ContentType = eventToHandle.ContentType }; client.Send(brokeredMessage); } catch (Exception ex) { Console.WriteLine(" Abandoning {0}: {1}", eventToHandle.MessageId, ex.Message); await Task.Delay(100); eventToHandle.Abandon(); } }
private static void TopicReceive(int subscription) { var topicName = "topicdemo"; var subToProcess = "Subscription" + subscription; var connection = "Endpoint=sb://alewife.servicebus.windows.net/;SharedAccessKeyName=Receiver;SharedAccessKey=Vqa3SwP4qH5/+8ikB4B/BNMPQCRDuV/AiUYsUofWebo=;TransportType=Amqp"; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection); SubscriptionClient clientA = factory.CreateSubscriptionClient(topicName, subToProcess); while (true) { BrokeredMessage message = clientA.Receive(); if (message != null) { try { Console.WriteLine("MessageId:{0}", message.MessageId); Console.WriteLine(message.GetBody <string>()); message.Complete(); } catch (Exception ex) { Console.WriteLine(ex.Message); message.Abandon(); } } } }
private async void ProcessCoverageAddedMessage(Task <BrokeredMessage> t) { BrokeredMessage message = t.Result; try { // Process message from subscription. Console.WriteLine("\n**Coverage Added**"); var @event = message.GetBody <CoverageAddedEvent>(); Console.WriteLine("Body: " + @event.PolicyNumber); Console.WriteLine("StreamRevision: " + message.Properties["StreamRevision"]); int revisionNumber = (int)message.Properties["StreamRevision"]; var policy = this.RetrievePolicy(@event.PolicyNumber + "_" + (revisionNumber - 1)); policy.ApplyEvent(@event); CreateVersionOfPolicy(policy); // Remove message from subscription. await message.CompleteAsync(); } catch (Exception ex) { Console.WriteLine(ex); // Indicates a problem, unlock message in subscription. message.Abandon(); } }
private async void ProcessPolicyCreatedMessage(Task <BrokeredMessage> t) { BrokeredMessage message = t.Result; try { // Process message from subscription. Console.WriteLine("\n**PolicyIssued**"); var @event = message.GetBody <PolicyCreatedEvent>(); Console.WriteLine("Body: " + @event.PolicyNumber); Console.WriteLine("StreamRevision: " + message.Properties["StreamRevision"]); var policy = new InsurancePolicy(null); //Yuck! policy.ApplyEvent(@event); CreateVersionOfPolicy(policy); // Remove message from subscription. await message.CompleteAsync(); } catch (Exception ex) { Console.WriteLine(ex); // Indicates a problem, unlock message in subscription. message.Abandon(); } }
private bool CheckTypeName(string typeName, BrokeredMessage msg) { if (typeName != null) { return(true); } _logger.Write(LogLevel.Error, "Received message is not a AzureCommandBus message ('PayloadTypeName' property is missing)."); var e = new BusMessageErrorEventArgs(msg, new UnknownMessageException( "Received message is not a AzureCommandBus message ('PayloadTypeName' property is missing).")); BusFailed(this, e); if (e.MessageTask == MessageHandling.PutMessageBackInQueue) { msg.Abandon(); } else { msg.Complete(); } return(false); }
static void ReceiveMessage() { TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider; if (_namespaceManager.TopicExists("DataCollectionTopic")) { MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider); //MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Inventory"); MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Dashboard"); BrokeredMessage receivedMessage = null; try { while ((receivedMessage = receiver.Receive()) != null) { ProcessMessage(receivedMessage); receivedMessage.Complete(); } factory.Close(); _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory"); // _namespaceManager.DeleteTopic("DataCollectionTopic"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); receivedMessage.Abandon(); } } }
/// <summary> /// Listens for numMessages consecutive messages /// </summary> /// <param name="numMessages">Number of messages to listen to</param> /// <returns>The last received message</returns> public override T Listen <T>(int numMessages) { int messages = numMessages; T messageBody = default(T); // Continuously process messages received from the HighMessages subscription while (messages > 0) { BrokeredMessage message = SubClient.Receive(TimeSpan.FromSeconds(15)); messages--; if (message != null) { try { messageBody = message.GetBody <T>(); // Remove message from subscription message.Complete(); } catch (Exception) { // Indicate a problem, unlock message in subscription message.Abandon(); } } } return(messageBody); }
static void Main(string[] args) { Console.Title = "Cheap Purchases Subscriber"; SubscriptionClient subscriptionClient = SubscriptionClient.Create("productsalestopic", "CheapPurchases"); // Continuously process messages received from the ExpensivePurchases subscription while (true) { BrokeredMessage message = subscriptionClient.Receive(); if (message != null) { try { Console.WriteLine("Received purchase: Message id: {0}, Product name: {1}, Product price: {2}.", message.MessageId, message.Properties["ProductName"], message.Properties["ProductPrice"]); // Remove printed message from subscription message.Complete(); } catch (Exception) { // In case of an error, unlock the message in subscription message.Abandon(); } } } }
public void HandleRegenerateSite() { long n = 0; allMessages = factory.CreateMessageReceiver(regenSiteTopic + "/subscriptions/AllMessages", ReceiveMode.PeekLock); while (_running) { BrokeredMessage message = allMessages.Receive(); if (message != null) { // let the message go back to the pool Int64.TryParse(message.Properties["MessageNumber"].ToString(), out n); message.Abandon(); try { if (n > maxMessage) { maxMessage = n; Console.WriteLine("\r\nAccepted message to regenerate site: {0} ", n); RebuildWebsite(); } else { // Console.WriteLine("\r\nSkipping: {0} ",n); } } catch (Exception) { } Thread.Sleep(8000); // wait 5 seconds to give other consumers a chance on this message. } } }
static void Main(string[] args) { string connectionString = Convert.ToString(ConfigurationManager.AppSettings["ServiceBus.ConnectionString"]); QueueClient qClient = QueueClient.CreateFromConnectionString(connectionString); // Continuously process messages sent to the "TestQueue" while (true) { BrokeredMessage message = qClient.Receive(); if (message != null) { try { QueueMessage msg = message.GetBody <QueueMessage>(); Console.WriteLine( $"Received Email {msg.Value} from {msg.Name} at {msg.Time}" ); //Console.WriteLine("MessageID: " + message.MessageId); //Remove message from queue message.Complete(); System.Threading.Thread.Sleep(1000); } catch (Exception e) { Console.WriteLine(e.Message); // Indicate a problem, unlock message in queue message.Abandon(); } } } }
private void OnBrokerMessage(BrokeredMessage brokeredMessage) { try { //Ignore messages from self if (brokeredMessage.Properties[SidAttributeName].ToString() == _sid) { brokeredMessage.Complete(); return; } var json = brokeredMessage.Properties[DataAttributeName].ToString(); var message = _jsonSerializer.DeserializeFromString<Message>(json); var pipeline = Composable.GetExport<IXSocketPipeline>(); var controller = Composable.GetExports<IXSocketController>().First(p => p.Alias == message.Controller); controller.ProtocolInstance = new XSocketInternalProtocol(); pipeline.OnIncomingMessage(controller, message); brokeredMessage.Complete(); } catch (Exception ex) { Composable.GetExport<IXLogger>().Error(ex.ToString()); // Indicates a problem if (brokeredMessage.DeliveryCount > 3) { brokeredMessage.DeadLetter(); } else { brokeredMessage.Abandon(); } } }
public async Task <CommandMessage> ReceiveCommandAsync(TimeSpan waitTime) { BrokeredMessage bm = null; CommandMessage commandMessage = null; AssertThingsAccess(); using (bm = await _messagingPolicy.ExecuteAsync(() => _subscriptionClient.ReceiveAsync(waitTime))) { try { if (bm != null) { commandMessage = bm.GetBody <CommandMessage>(); await _messagingPolicy.ExecuteAsync(() => bm.CompleteAsync()); } } catch { _messagingPolicy.Execute(() => { bm.Abandon(); }); } } return(commandMessage); }
private async Task ProcessMessage(BrokeredMessage message) { try { if (!this.IsValidMessage(message)) { // Send the message to the Dead Letter queue for further analysis. await message.DeadLetterAsync("Invalid message", "The message Id is invalid"); Trace.WriteLine("Invalid Message. Sending to Dead Letter queue"); } // Simulate message processing. await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false); Trace.WriteLine("Consumer " + RoleEnvironment.CurrentRoleInstance.Id + " : Message processed successfully: " + message.MessageId); // Complete the message. await message.CompleteAsync(); } catch (Exception ex) { // Abandon the message when appropriate. If the message reaches the MaxDeliveryCount limit, it will be automatically deadlettered. message.Abandon(); Trace.TraceError("An error has occurred while processing the message: " + ex.Message); } }
/// <summary> /// Processes a message. Must perform error handling and also message completion or abandoning. /// </summary> /// <param name="message">The incoming Service Bus Message to process</param> /// <param name="cancellationToken">When Set, indicates that processing should stop.</param> public void ReceiveMessage(BrokeredMessage message, CancellationToken cancellationToken) { try { ReceiveMessageImpl(message, cancellationToken); message.Complete(); } catch { message.Abandon(); } }
public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { try { ServiceBusEventSource.Log.SessionMessageReceived(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId); // Handle the message. await _messageHandler(session, message); } catch (Exception exception) { ServiceBusEventSource.Log.SessionMessageReceiverException(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId, "OnMessage", exception.Message, exception.StackTrace); // Don't allow other messages to be processed. if (_options.RequireSequentialProcessing) { message.Abandon(); session.Abort(); } throw; } }
private async Task ProcessMessageTask(BrokeredMessage receivedMessage) { try { // Process the message Trace.WriteLine("Processing received messages"); if (!IsValid(receivedMessage)) { await receivedMessage.DeadLetterAsync("Invalid message", "Message Id is invalid or there is no message body"); Trace.WriteLine("Invalid message. Sending to dead letter queue"); } await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false); var messageData = receivedMessage.GetBody<MessageData>(); //var roleInstanceId = RoleEnvironment.IsAvailable // ? RoleEnvironment.CurrentRoleInstance.Id // : string.Empty; var traceMsg = string.Format("Received message with sequence #: {0}, Id: {1}, MessageBodyId:{2}, MessageData:{3}, PartitionKey:{4}, RowKey:{5} by Role:{6}", receivedMessage.SequenceNumber, receivedMessage.MessageId, messageData.Id, messageData.Data, "" , messageData.PartitionKey, messageData.RowKey); //var traceMsg = string.Format("Received message with sequence #: {0}, Id: {1}, MessageBodyId:{2}, MessageData:{3} by Role:{4}", // receivedMessage.SequenceNumber,receivedMessage.MessageId,messageData.Id,messageData.Data, RoleEnvironment.CurrentRoleInstance.Id); Trace.WriteLine(traceMsg); var insertOp = TableOperation.Insert(messageData); _tableRef.Execute(insertOp); await receivedMessage.CompleteAsync(); } catch (Exception ex) { receivedMessage.Abandon(); Trace.TraceError("Exception processing message: {0}", ex.Message); if (ex.InnerException != null) { Trace.TraceError("Inner Exception: {0}", ex.InnerException.Message); } } }
public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { try { ServiceBusEventSource.Log.SessionMessageReceived(_receiverNamespace, _receiverPath, message.MessageId, message.CorrelationId, message.SessionId, message.DeliveryCount, message.Size); // Handle the message. await _messageHandler(session, message) .ConfigureAwait(false); } catch (Exception exception) { ServiceBusEventSource.Log.MessagePumpExceptionReceived(_receiverNamespace, _receiverPath, "OnSessionMessage", exception); // Don't allow other messages to be processed. if (_options.RequireSequentialProcessing) { message.Abandon(); session.Abort(); } throw; } }
private async Task Handle(BrokeredMessage brokeredMessage) { dynamic innerMessage = JsonConvert.DeserializeObject(brokeredMessage.GetBody<string>(), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, DateFormatHandling = DateFormatHandling.IsoDateFormat }) as IMessage; try { await _dispatcher.Handle(innerMessage); await brokeredMessage.CompleteAsync(); } catch (Exception exception) { if (brokeredMessage.DeliveryCount >= 5) { brokeredMessage.DeadLetter(exception.GetBaseException().Message, exception.GetBaseException().ToString()); } brokeredMessage.Abandon(); } }
private void OnBrokerMessage(BrokeredMessage message) { try { Composable.GetExport<IXLogger>().Debug("Message Arrived {@m}", message); var m = this.Serializer.DeserializeFromString<Message>(message.Properties["JSON"].ToString()); var pipe = Composable.GetExport<IXSocketPipeline>(); var ctrl = Composable.GetExports<IXSocketController>().First(p => p.Alias == m.Controller); ctrl.ProtocolInstance = new XSocketInternalProtocol(); pipe.OnIncomingMessage(ctrl, m); message.Complete(); } catch (Exception) { // Indicates a problem, unlock message in subscription if (message.DeliveryCount > 3) message.DeadLetter(); else message.Abandon(); } }
//CHECK WETHER MESSAGE FROM WEB APP private bool isMessageFromWebApp(BrokeredMessage msg) { string appId = msg.GetBody<string>(); if (appId != AppConfiguration.ApplicationId){ msg.Abandon(); return false; } return true; }
static bool SafeAbandon(BrokeredMessage msg) { try { // Abandons a brokered message. This will cause the Service Bus to unlock the message and make it available to be received again, // either by the same consumer or by another competing consumer. msg.Abandon(); // Return a result indicating that the message has been abandoned successfully. return true; } catch (MessageLockLostException) { // It's too late to compensate the loss of a message lock. We should just ignore it so that it does not break the receive loop. // We should be prepared to receive the same message again. } catch (MessagingException) { // There is nothing we can do as the connection may have been lost, or the underlying topic/subscription may have been removed. // If Abandon() fails with this exception, the only recourse is to receive another message (possibly the same one). } return false; }
private static void HandleMessage(BrokeredMessage msg, bool singleMessage = true) { var index = -1; try { object content; if (msg.Properties.TryGetValue("index", out content)) { index = (int) content; } msg.Properties.TryGetValue("time", out content); var sentTime = string.Empty; if (content != null) { sentTime = (string) content; } msg.Properties.TryGetValue("color", out content); if (content != null) { ConsoleColor color; Enum.TryParse((string) content, out color); Console.ForegroundColor = color; } var body = new StreamReader(msg.GetBody<Stream>(), Encoding.UTF8).ReadToEnd(); Console.WriteLine("Body: {0}, sent : {1}, received: {2}, DeliveryCount: {3}", body, sentTime, DateTime.Now.ToString("HH:mm:ss.fff"), msg.DeliveryCount); if (singleMessage) { msg.Complete(); } } catch (Exception) { Console.WriteLine("Error handling message {0} -> Abandon", index); if (singleMessage) { msg.Abandon(); } } }