当前位置: 首页>>代码示例>>C#>>正文


C# BrokeredMessage.DeadLetterAsync方法代码示例

本文整理汇总了C#中BrokeredMessage.DeadLetterAsync方法的典型用法代码示例。如果您正苦于以下问题:C# BrokeredMessage.DeadLetterAsync方法的具体用法?C# BrokeredMessage.DeadLetterAsync怎么用?C# BrokeredMessage.DeadLetterAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BrokeredMessage的用法示例。


在下文中一共展示了BrokeredMessage.DeadLetterAsync方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ProcessMessage

        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);
            }
        }
开发者ID:calebjenkins,项目名称:cloud-design-patterns,代码行数:26,代码来源:WorkerRole.cs

示例2: DispatchReply

 async Task DispatchReply(BrokeredMessage m)
 {
     TaskCompletionSource<BrokeredMessage> tc;
     if (this.pendingRequests.TryGetValue(m.CorrelationId, out tc))
     {
         tc.SetResult(m);
     }
     else
     {
         // can't correlate, toss out
         await m.DeadLetterAsync();
     }
 }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:13,代码来源:RequestReplySender.cs

示例3: Respond

        async Task Respond(BrokeredMessage request, Func<BrokeredMessage, Task<BrokeredMessage>> handleRequest)
        {
            // evaluate ReplyTo
            if (!string.IsNullOrEmpty(request.ReplyTo))
            {
                Uri targetUri;

                if (Uri.TryCreate(request.ReplyTo, UriKind.RelativeOrAbsolute, out targetUri))
                {
                    // make the URI absolute to this namespace 
                    if (!targetUri.IsAbsoluteUri)
                    {
                        targetUri = new Uri(this.namespaceUri, targetUri);
                    }
                    var replyToken = GetReplyToken(targetUri);
                    if (replyToken == null)
                    {
                        await request.DeadLetterAsync("NoReplyToToken", "No 'tk' query parameter in ReplyTo field URI found");
                        return;
                    }
                    // truncate the query portion of the URI
                    targetUri = new Uri(targetUri.GetLeftPart(UriPartial.Path));
                    
                    // now we're reasonably confident that the input message can be
                    // replied to, so let's execute the message processing
                    try
                    {
                        // call the callback
                        var reply = await handleRequest(request);
                        // set the correlation-id on the reply 
                        reply.CorrelationId = request.MessageId;

                        var replyDestination = this.GetOrCreateReplyDestination(replyToken, targetUri);
                        var sender = await replyDestination.Factory.CreateMessageSenderAsync(targetUri.AbsolutePath.Substring(1));
                        await sender.SendAsync(reply);
                        await request.CompleteAsync();
                    }
                    catch (Exception e)
                    {
                        await request.DeadLetterAsync("ErrorHandlingMessage", e.Message);
                    }
                }
                else
                {
                    await request.DeadLetterAsync("NoReplyTo", "No ReplyTo field found");
                }
            }
        }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:48,代码来源:RequestReplyResponder.cs

示例4: ProcessMessageTask

        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);
                }
            }
        }
开发者ID:Gayuraj,项目名称:CompetingConsumersAzure.Topshelf,代码行数:37,代码来源:Subscriber.cs

示例5: OnMessageAsync

            public async Task OnMessageAsync(MessageSession session, BrokeredMessage message)
            {
                if (message.Label != null &&
                  message.ContentType != null &&
                  message.Label.Equals("RecipeStep", StringComparison.InvariantCultureIgnoreCase) &&
                  message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                {
                    var body = message.GetBody<Stream>();

                    dynamic recipeStep = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd());
                    lock (Console.Out)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine(
                            "\t\t\t\tMessage received:  \n\t\t\t\t\t\tSessionId = {0}, \n\t\t\t\t\t\tMessageId = {1}, \n\t\t\t\t\t\tSequenceNumber = {2}," +
                            "\n\t\t\t\t\t\tContent: [ step = {3}, title = {4} ]",
                            message.SessionId,
                            message.MessageId,
                            message.SequenceNumber,
                            recipeStep.step,
                            recipeStep.title);
                        Console.ResetColor();
                    }
                    await message.CompleteAsync();

                    if (recipeStep.step == 5)
                    {
                        // end of the session!
                        await session.CloseAsync();
                    }
                }
                else
                {
                    await message.DeadLetterAsync("BadMessage", "Unexpected message");
                }
            }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:36,代码来源:Program.cs

示例6: CancelRentalCar

        public static async Task CancelRentalCar(BrokeredMessage message, MessageSender nextStepQueue, MessageSender compensatorQueue)
        {
            try
            {
                var via = (message.Properties.ContainsKey("Via")
                    ? ((string) message.Properties["Via"] + ",")
                    : string.Empty) +
                          "cancelcar";

                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals(TravelBookingLabel, StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals(ContentTypeApplicationJson, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var body = message.GetBody<Stream>();
                        dynamic travelBooking = DeserializeTravelBooking(body);

                        // do we want to book a flight? No? Let's just forward the message to
                        // the next destination via transfer queue
                        if (travelBooking.car != null &&
                            travelBooking.car.reservationId != null)
                        {
                            lock (Console.Out)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Cancelling Rental Car");
                                Console.ResetColor();
                            }

                            // undo the reservation (or pretend to fail)
                            if (DateTime.UtcNow.Second <= 3)
                            {
                                throw new Exception("O_o");
                            }

                            // reset the id
                            travelBooking.car.reservationId = null;

                            // forward
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                        }
                        else
                        {
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                        }
                        // done with this job
                        await message.CompleteAsync();
                    }
                    else
                    {
                        await message.DeadLetterAsync(
                            new Dictionary<string, object>
                                    {
                                        {"DeadLetterReason", "BadMessage"},
                                        {"DeadLetterErrorDescription", "Unrecognized input message"},
                                        {"Via", via}
                                    });
                    }
                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                await message.AbandonAsync();
            }
        }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:69,代码来源:TravelBookingHandlers.cs

示例7: BookFlight

        public static async Task BookFlight(BrokeredMessage message, MessageSender nextStepQueue, MessageSender compensatorQueue)
        {
            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var via = (message.Properties.ContainsKey("Via")
                        ? ((string) message.Properties["Via"] + ",")
                        : string.Empty) +
                              "bookflight";

                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals(TravelBookingLabel, StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals(ContentTypeApplicationJson, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var body = message.GetBody<Stream>();
                        dynamic travelBooking = DeserializeTravelBooking(body);


                        // do we want to book a flight? No? Let's just forward the message to
                        // the next destination via transfer queue
                        if (travelBooking.flight == null)
                        {
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                            // done with this job
                            await message.CompleteAsync();
                        }
                        else
                        {
                            lock (Console.Out)
                            {
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine("Booking Flight");
                                Console.ResetColor();
                            }

                            // now we're going to simulate the work of booking a flight,
                            // which usually involves a call to a third party

                            // every 9th flight booking sadly goes wrong
                            if (message.SequenceNumber%9 == 0)
                            {
                                await message.DeadLetterAsync(
                                    new Dictionary<string, object>
                                    {
                                        {"DeadLetterReason", "TransactionError"},
                                        {"DeadLetterErrorDescription", "Failed to perform flight reservation"},
                                        {"Via", via}
                                    });
                            }
                            else
                            {
                                // every operation executed in the first 3 secs of any minute 
                                // tanks completely (simulates some local or external unexpected issue) 
                                if (DateTime.UtcNow.Second <= 3)
                                {
                                    throw new Exception("O_o");
                                }

                                // let's pretend we booked something
                                travelBooking.flight.reservationId = "A1B2C3";

                                await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                                // done with this job
                                await message.CompleteAsync();
                            }
                        }
                    }
                    else
                    {
                        await message.DeadLetterAsync(
                           new Dictionary<string, object>
                                    {
                                        {"DeadLetterReason", "BadMessage"},
                                        {"DeadLetterErrorDescription", "Unrecognized input message"},
                                        {"Via", via}
                                    });
                    }
                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                await message.AbandonAsync();
            }
        }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:88,代码来源:TravelBookingHandlers.cs


注:本文中的BrokeredMessage.DeadLetterAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。