Пример #1
0
        static void Main(string[] args)
        {
            var customer_id      = "[customer_id]";
            var password         = "******";
            var user             = "******";
            var connectionString = string.Format("Endpoint=sb://qbranch-qnet-ew.servicebus.windows.net/;SharedSecretIssuer={0};SharedSecretValue={1}", user, password);

            var factory        = MessagingFactory.CreateFromConnectionString(connectionString);
            var deadLetterPath = SubscriptionClient.FormatDeadLetterPath("message-out-from-qnet", string.Format("{0}-ticket", customer_id));
            var client         = factory.CreateMessageReceiver(deadLetterPath, ReceiveMode.ReceiveAndDelete);

            while (true)
            {
                var message = client.Receive();

                if (message != null)
                {
                    var ser  = new DataContractSerializer(typeof(ticket));
                    var body = message.GetBody <ticket>(ser);

                    Console.WriteLine(body.ticket_id);
                    File.WriteAllText(@"deadletter_" + body.ticket_id + "_" + message.MessageId + ".txt", JsonConvert.SerializeObject(body, Formatting.Indented));
                }
            }
        }
Пример #2
0
        public static void RetrieveMessageFromDeadLetterForSubscription()
        {
            var receiverFactory = MessagingFactory.Create(
                "sb://<NS>.servicebus.windows.net/",
                new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", ""),
                NetMessagingTransportSettings = { BatchFlushInterval = new TimeSpan(0, 0, 0) }
            });

            string data = SubscriptionClient.FormatDeadLetterPath("mrkartopic", "mrkarsub1");

            var receiver = receiverFactory.CreateMessageReceiver(data);

            receiver.OnMessageAsync(
                async message =>
            {
                var body = message.GetBody <Stream>();

                lock (Console.Out)
                {
                    Console.WriteLine("Message ID :" + message.MessageId);
                }

                await message.CompleteAsync();
            },
                new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 1
            });
        }
        public static MessageReceiver CreateMessageReceiver(this ServiceBusSettings settings, string topic, string subscription)
        {
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);

            return(messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(topic, subscription)));
        }
        private static MessageReceiver CreateDeadLetterQueueClient(string connectionString, string topicName, string subscriptionName)
        {
            var builder             = new ServiceBusConnectionStringBuilder(connectionString);
            var factory             = MessagingFactory.CreateFromConnectionString(builder.ToString());
            var deadLetterQueuePath = SubscriptionClient.FormatDeadLetterPath(topicName, subscriptionName);

            return(factory.CreateMessageReceiver(deadLetterQueuePath));
        }
        string GetDlqEntityPath()
        {
            if (sourceQueueDescription != null)
            {
                return(QueueClient.FormatDeadLetterPath(sourceQueueDescription.Path));
            }

            return(SubscriptionClient.FormatDeadLetterPath(
                       sourceSubscriptionWrapper.SubscriptionDescription.TopicPath,
                       sourceSubscriptionWrapper.SubscriptionDescription.Name));
        }
Пример #6
0
            public void NewThread()
            {
                string connectionString = "";
                string topicPath        = "";
                string subscriptionName = "";

                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);
                var deadLetterPath       = SubscriptionClient.FormatDeadLetterPath(topicPath, subscriptionName);
                var dlqMessageReceiver   = factory.CreateMessageReceiver(deadLetterPath, ReceiveMode.ReceiveAndDelete);

                var thr = Thread.CurrentThread.Name;
                int messageBatchSize = 100;

                while (dlqMessageReceiver.ReceiveBatch(messageBatchSize) != null)
                {
                    Console.Write($"{thr}#");
                }
            }
        public async Task FlushAsync()
        {
            await ForEachMessageAsyncUsingReceiveAndDeleteMode(async message => await Task.Run(() => { }));

            do
            {
                var deadLetterPath             = SubscriptionClient.FormatDeadLetterPath(_topic.Name, Name);
                var deadLetterMessagingFactory = MessagingFactory.CreateFromConnectionString(_topic.ConnectionString);
                var deadLetterClient           =
                    await
                    deadLetterMessagingFactory.CreateMessageReceiverAsync(deadLetterPath,
                                                                          ReceiveMode.ReceiveAndDelete);

                var messages = await deadLetterClient.ReceiveBatchAsync(100, TimeSpan.FromMilliseconds(1000));

                var brokeredMessages = messages as BrokeredMessage[] ?? messages.ToArray();
                if (!brokeredMessages.Any())
                {
                    break;
                }
            } while (true);
        }
 void GetEntityData(bool deadLetterQueueData, out long messageCount, out string entityPath)
 {
     if (deadLetterQueueData)
     {
         if (queueDescription != null)
         {
             var queueDescription2 = serviceBusHelper.GetQueue(queueDescription.Path);
             messageCount = queueDescription2.MessageCountDetails.DeadLetterMessageCount;
             entityPath   = QueueClient.FormatDeadLetterPath(queueDescription.Path);
         }
         else
         {
             var subscriptionDescription = serviceBusHelper.GetSubscription(subscriptionWrapper.TopicDescription.Path,
                                                                            subscriptionWrapper.SubscriptionDescription.Name);
             messageCount = subscriptionDescription.MessageCountDetails.DeadLetterMessageCount;
             entityPath   = SubscriptionClient.FormatDeadLetterPath(subscriptionWrapper.SubscriptionDescription.TopicPath,
                                                                    subscriptionWrapper.SubscriptionDescription.Name);
         }
     }
     else
     {
         if (queueDescription != null)
         {
             var queueDescription2 = serviceBusHelper.GetQueue(queueDescription.Path);
             messageCount = queueDescription2.MessageCountDetails.ActiveMessageCount;
             entityPath   = queueDescription.Path;
         }
         else
         {
             var subscriptionDescription = serviceBusHelper.GetSubscription(subscriptionWrapper.TopicDescription.Path,
                                                                            subscriptionWrapper.SubscriptionDescription.Name);
             messageCount = subscriptionDescription.MessageCountDetails.ActiveMessageCount;
             entityPath   = SubscriptionClient.FormatSubscriptionPath(subscriptionWrapper.SubscriptionDescription.TopicPath,
                                                                      subscriptionWrapper.SubscriptionDescription.Name);
         }
     }
 }
        private async void ProcessQueuedMessages(SubscriptionClient client)
        {
            try
            {
                MessagingFactory factory                 = MessagingFactory.CreateFromConnectionString(connectionString);
                MessageReceiver  messageReceiver         = factory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(topicPath, subscriptionName));
                IEnumerable <BrokeredMessage> messageSet = messageReceiver.ReceiveBatch(10000);
                Debug.WriteLine("**** Received " + messageSet.Count() + " messages *****");
                foreach (BrokeredMessage message in messageSet)
                {
                    try
                    {
                        await processMessage(message);

                        Debug.WriteLine("**** ProcessQueuedMessages.processMessage completed ****");
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("**** Error ProcessQueuedMessages.processMessage " + e.ToString() + " ****");
                    }
                }
            } catch
            {
                Debug.WriteLine("**** Error ProcessQueuedMessages ****");
            }
        }
        private async void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnStart.Text == StopCaption)
                {
                    await CancelActions();

                    btnStart.Text = StartCaption;
                    return;
                }

                if (serviceBusHelper != null &&
                    ValidateParameters())
                {
                    startLog?.Invoke();
                    btnStart.Enabled = false;
                    Cursor.Current   = Cursors.WaitCursor;
                    //*****************************************************************************************************
                    //                                   Retrieve Messaging Factory
                    //*****************************************************************************************************
                    var messagingFactory = serviceBusHelper.MessagingFactory;

                    //*****************************************************************************************************
                    //                                   Initialize Statistics and Manager Action
                    //*****************************************************************************************************
                    actionCount               = 0;
                    receiverMessageNumber     = 0;
                    receiverMessagesPerSecond = 0;
                    receiverMinimumTime       = long.MaxValue;
                    receiverMaximumTime       = 0;
                    receiverAverageTime       = 0;
                    receiverTotalTime         = 0;
                    if (checkBoxReceiverEnableGraph.Checked)
                    {
                        chart.Series.ToList().ForEach(s => s.Points.Clear());
                    }
                    managerResetEvent = new ManualResetEventSlim(false);
                    Action <CancellationTokenSource> managerAction = cts =>
                    {
                        if (cts == null)
                        {
                            return;
                        }
                        try
                        {
                            managerResetEvent.Wait(cts.Token);
                        }
                        catch (OperationCanceledException)
                        {
                        }
                        if (!cts.IsCancellationRequested)
                        {
                            Invoke((MethodInvoker)async delegate
                            {
                                btnStart.Text = StartCaption;
                                await MainForm.SingletonMainForm.RefreshSelectedEntity();
                            });
                        }
                    };

                    Action updateGraphAction = () =>
                    {
                        var  ok  = true;
                        long max = 10;
                        while (!graphCancellationTokenSource.IsCancellationRequested && (actionCount > 1 || ok))
                        {
                            ok = true;
                            long receiveMessageNumber = 0;
                            long receiveTotalTime     = 0;
                            while (ok && receiveMessageNumber < max)
                            {
                                ok = blockingCollection.TryTake(out var tuple, 10);
                                if (ok)
                                {
                                    receiveMessageNumber += tuple.Item1;
                                    receiveTotalTime     += tuple.Item2;
                                    if (receiveMessageNumber > max)
                                    {
                                        max = receiveMessageNumber;
                                    }
                                }
                            }
                            if (receiveMessageNumber > 0)
                            {
                                var receiveTuple = new Tuple <long, long, DirectionType>(receiveMessageNumber, receiveTotalTime, DirectionType.Receive);
                                if (InvokeRequired)
                                {
                                    Invoke(new UpdateStatisticsDelegate(InternalUpdateStatistics), receiveTuple.Item1, receiveTuple.Item2, receiveTuple.Item3);
                                }
                                else
                                {
                                    InternalUpdateStatistics(receiveTuple.Item1,
                                                             receiveTuple.Item2,
                                                             receiveTuple.Item3);
                                }
                            }
                        }
                        if (Interlocked.Decrement(ref actionCount) == 0)
                        {
                            managerResetEvent.Set();
                        }
                    };

                    AsyncCallback updateGraphCallback = a =>
                    {
                        var action = a.AsyncState as Action;
                        if (action != null)
                        {
                            action.EndInvoke(a);
                            if (Interlocked.Decrement(ref actionCount) == 0)
                            {
                                managerResetEvent.Set();
                            }
                        }
                    };

                    blockingCollection = new BlockingCollection <Tuple <long, long, DirectionType> >();
                    //*****************************************************************************************************
                    //                                   Receiving messages from a Subscription
                    //*****************************************************************************************************
                    var currentSubscription = subscriptionWrapper.SubscriptionDescription;
                    if (currentSubscription == null)
                    {
                        throw new ArgumentException(NoSubscriptionSelected);
                    }
                    var currentReceiveMode = cboReceivedMode.Text == PeekLock ?
                                             ReceiveMode.PeekLock :
                                             ReceiveMode.ReceiveAndDelete;
                    var currentMoveToDeadLetterQueue   = checkBoxMoveToDeadLetter.Checked;
                    var currentReadFromDeadLetterQueue = checkBoxReadFromDeadLetter.Checked;

                    try
                    {
                        receiverCancellationTokenSource  = new CancellationTokenSource();
                        receiverCancellationTokenSource  = new CancellationTokenSource();
                        receiverBrokeredMessageInspector = cboReceiverInspector.SelectedIndex > 0
                                                      ? Activator.CreateInstance(serviceBusHelper.BrokeredMessageInspectors[cboReceiverInspector.Text]) as IBrokeredMessageInspector
                                                      : null;

                        Action <int> receiverAction = taskId =>
                        {
                            var allSessionsAccepted = false;

                            while (!allSessionsAccepted)
                            {
                                try
                                {
                                    MessageReceiver messageReceiver;
                                    if (currentReadFromDeadLetterQueue)
                                    {
                                        messageReceiver =
                                            messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(currentSubscription.TopicPath,
                                                                                                                           currentSubscription.Name),
                                                                                   currentReceiveMode);
                                    }
                                    else
                                    {
                                        if (currentSubscription.RequiresSession)
                                        {
                                            var subscriptionClient = messagingFactory.CreateSubscriptionClient(currentSubscription.TopicPath,
                                                                                                               currentSubscription.Name,
                                                                                                               currentReceiveMode);
                                            messageReceiver = subscriptionClient.AcceptMessageSession(TimeSpan.FromSeconds(sessionTimeout));
                                        }
                                        else
                                        {
                                            messageReceiver = messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatSubscriptionPath(currentSubscription.TopicPath,
                                                                                                                                               currentSubscription.Name),
                                                                                                     currentReceiveMode);
                                        }
                                    }
                                    messageReceiver.PrefetchCount = prefetchCount;
                                    string traceMessage;
                                    if (checkBoxReceiverUseTransaction.Checked)
                                    {
                                        using (var scope = new TransactionScope())
                                        {
                                            serviceBusHelper.ReceiveMessages(messageReceiver,
                                                                             taskId,
                                                                             receiveTimeout,
                                                                             filter,
                                                                             currentMoveToDeadLetterQueue,
                                                                             checkBoxCompleteReceive.Checked,
                                                                             checkBoxDeferMessage.Checked,
                                                                             checkBoxEnableReceiverLogging.Checked,
                                                                             checkBoxReceiverVerboseLogging.Checked,
                                                                             checkBoxReceiverEnableStatistics.Checked,
                                                                             checkBoxReceiveBatch.Checked,
                                                                             receiverBatchSize,
                                                                             checkBoxReceiverThinkTime.Checked,
                                                                             receiverThinkTime,
                                                                             receiverBrokeredMessageInspector,
                                                                             UpdateStatistics,
                                                                             receiverCancellationTokenSource,
                                                                             out traceMessage);
                                            var builder = new StringBuilder(traceMessage);
                                            if (checkBoxReceiverCommitTransaction.Checked)
                                            {
                                                scope.Complete();
                                                builder.AppendLine(TransactionCommitted);
                                            }
                                            else
                                            {
                                                builder.AppendLine(TransactionAborted);
                                            }
                                            traceMessage = builder.ToString();
                                        }
                                    }
                                    else
                                    {
                                        serviceBusHelper.ReceiveMessages(messageReceiver,
                                                                         taskId,
                                                                         receiveTimeout,
                                                                         filter,
                                                                         currentMoveToDeadLetterQueue,
                                                                         checkBoxCompleteReceive.Checked,
                                                                         checkBoxDeferMessage.Checked,
                                                                         checkBoxEnableReceiverLogging.Checked,
                                                                         checkBoxReceiverVerboseLogging.Checked,
                                                                         checkBoxReceiverEnableStatistics.Checked,
                                                                         checkBoxReceiveBatch.Checked,
                                                                         receiverBatchSize,
                                                                         checkBoxReceiverThinkTime.Checked,
                                                                         receiverThinkTime,
                                                                         receiverBrokeredMessageInspector,
                                                                         UpdateStatistics,
                                                                         receiverCancellationTokenSource,
                                                                         out traceMessage);
                                    }
                                    if (!string.IsNullOrWhiteSpace(traceMessage))
                                    {
                                        writeToLog(traceMessage.Substring(0, traceMessage.Length - 1));
                                    }
                                    allSessionsAccepted = !currentSubscription.RequiresSession;
                                }
                                catch (TimeoutException ex)
                                {
                                    if (currentSubscription.RequiresSession)
                                    {
                                        writeToLog(string.Format(NoMoreSessionsToAccept, taskId));
                                        allSessionsAccepted = true;
                                    }
                                    else
                                    {
                                        HandleException(ex);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HandleException(ex);
                                }
                            }
                        };

                        // Define Receiver AsyncCallback
                        AsyncCallback receiverCallback = a =>
                        {
                            var action = a.AsyncState as Action <int>;
                            if (action != null)
                            {
                                action.EndInvoke(a);
                                if (Interlocked.Decrement(ref actionCount) == 0)
                                {
                                    managerResetEvent.Set();
                                }
                            }
                        };

                        // Start Receiver Actions
                        for (var i = 0; i < receiverTaskCount; i++)
                        {
                            receiverAction.BeginInvoke(i, receiverCallback, receiverAction);
                            Interlocked.Increment(ref actionCount);
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex);
                    }
                    if (actionCount > 0)
                    {
                        managerCancellationTokenSource = new CancellationTokenSource();
                        managerAction.BeginInvoke(managerCancellationTokenSource, null, null);
                        graphCancellationTokenSource = new CancellationTokenSource();
                        updateGraphAction.BeginInvoke(updateGraphCallback, updateGraphAction);
                        Interlocked.Increment(ref actionCount);
                        btnStart.Text = StopCaption;
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                btnStart.Enabled = true;
                Cursor.Current   = Cursors.Default;
            }
        }
Пример #11
0
        /// <summary>
        /// Using a <see cref="Task"/>, clears all dead letters from the topic and subscription of the
        /// provided <paramref name="topicName"/> and <paramref name="topicSubscriptionName"/>.
        /// </summary>
        /// <param name="topicName">The name of the topic.</param>
        /// <param name="topicSubscriptionName">The name of the subscription.</param>
        /// <returns></returns>
        protected virtual CancellationTokenSource CleanUpDeadLetters(string topicName, string topicSubscriptionName)
        {
            var brokeredMessageRenewCancellationTokenSource  = new CancellationTokenSource();
            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/Servicebus" }
            };
            int lockIssues = 0;

            Action <BrokeredMessage, IMessage> leaveDeadlLetterInQueue = (deadLetterBrokeredMessage, deadLetterMessage) =>
            {
                // Remove message from queue
                try
                {
                    deadLetterBrokeredMessage.Abandon();
                    lockIssues = 0;
                }
                catch (MessageLockLostException)
                {
                    lockIssues++;
                    Logger.LogWarning(string.Format("The lock supplied for abandon for the skipped dead-letter message '{0}' is invalid.", deadLetterBrokeredMessage.MessageId));
                }
                Logger.LogDebug(string.Format("A dead-letter message of type {0} arrived with the id '{1}' but left in the queue due to settings.", deadLetterMessage.GetType().FullName, deadLetterBrokeredMessage.MessageId));
            };
            Action <BrokeredMessage> removeDeadlLetterFromQueue = deadLetterBrokeredMessage =>
            {
                // Remove message from queue
                try
                {
                    deadLetterBrokeredMessage.Complete();
                    lockIssues = 0;
                }
                catch (MessageLockLostException)
                {
                    lockIssues++;
                    Logger.LogWarning(string.Format("The lock supplied for complete for the skipped dead-letter message '{0}' is invalid.", deadLetterBrokeredMessage.MessageId));
                }
                Logger.LogDebug(string.Format("A dead-letter message arrived with the id '{0}' but was removed as processing was skipped due to settings.", deadLetterBrokeredMessage.MessageId));
            };

            Task.Factory.StartNewSafely(() =>
            {
                int loop = 0;
                while (!brokeredMessageRenewCancellationTokenSource.Token.IsCancellationRequested)
                {
                    lockIssues = 0;
                    MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConnectionString);
                    string deadLetterPath    = SubscriptionClient.FormatDeadLetterPath(topicName, topicSubscriptionName);
                    MessageReceiver client   = factory.CreateMessageReceiver(deadLetterPath, ReceiveMode.PeekLock);

                    IEnumerable <BrokeredMessage> brokeredMessages = client.ReceiveBatch(1000);

                    foreach (BrokeredMessage brokeredMessage in brokeredMessages)
                    {
                        if (lockIssues > 10)
                        {
                            break;
                        }
                        try
                        {
                            Logger.LogDebug(string.Format("A dead-letter message arrived with the id '{0}'.", brokeredMessage.MessageId));
                            string messageBody = brokeredMessage.GetBody <string>();

                            // Closure protection
                            BrokeredMessage message = brokeredMessage;
                            try
                            {
                                AzureBusHelper.ReceiveEvent
                                (
                                    messageBody,
                                    @event =>
                                {
                                    bool isRequired = BusHelper.IsEventRequired(@event.GetType());
                                    if (!isRequired)
                                    {
                                        removeDeadlLetterFromQueue(message);
                                    }
                                    else
                                    {
                                        leaveDeadlLetterInQueue(message, @event);
                                    }
                                    return(true);
                                },
                                    string.Format("id '{0}'", brokeredMessage.MessageId),
                                    () =>
                                {
                                    removeDeadlLetterFromQueue(message);
                                },
                                    () => { }
                                );
                            }
                            catch
                            {
                                AzureBusHelper.ReceiveCommand
                                (
                                    messageBody,
                                    command =>
                                {
                                    bool isRequired = BusHelper.IsEventRequired(command.GetType());
                                    if (!isRequired)
                                    {
                                        removeDeadlLetterFromQueue(message);
                                    }
                                    else
                                    {
                                        leaveDeadlLetterInQueue(message, command);
                                    }
                                    return(true);
                                },
                                    string.Format("id '{0}'", brokeredMessage.MessageId),
                                    () =>
                                {
                                    removeDeadlLetterFromQueue(message);
                                },
                                    () => { }
                                );
                            }
                        }
                        catch (Exception exception)
                        {
                            TelemetryHelper.TrackException(exception, null, telemetryProperties);
                            // Indicates a problem, unlock message in queue
                            Logger.LogError(string.Format("A dead-letter message arrived with the id '{0}' but failed to be process.", brokeredMessage.MessageId), exception: exception);
                            try
                            {
                                brokeredMessage.Abandon();
                            }
                            catch (MessageLockLostException)
                            {
                                lockIssues++;
                                Logger.LogWarning(string.Format("The lock supplied for abandon for the skipped dead-letter message '{0}' is invalid.", brokeredMessage.MessageId));
                            }
                        }
                    }

                    client.Close();

                    if (loop++ % 5 == 0)
                    {
                        loop = 0;
                        Thread.Yield();
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
                try
                {
                    brokeredMessageRenewCancellationTokenSource.Dispose();
                }
                catch (ObjectDisposedException) { }
            }, brokeredMessageRenewCancellationTokenSource.Token);

            return(brokeredMessageRenewCancellationTokenSource);
        }
Пример #12
0
        /// <summary>
        /// Using a <see cref="Task"/>, clears all dead letters from the topic and subscription of the
        /// provided <paramref name="topicName"/> and <paramref name="topicSubscriptionName"/>.
        /// </summary>
        /// <param name="topicName">The name of the topic.</param>
        /// <param name="topicSubscriptionName">The name of the subscription.</param>
        /// <returns></returns>
        protected virtual CancellationTokenSource CleanUpDeadLetters(string topicName, string topicSubscriptionName)
        {
            var brokeredMessageRenewCancellationTokenSource  = new CancellationTokenSource();
            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/Servicebus" }
            };
            int lockIssues = 0;

#if NET452
            Action <BrokeredMessage, IMessage> leaveDeadlLetterInQueue = (deadLetterBrokeredMessage, deadLetterMessage) =>
#endif
#if NETSTANDARD2_0
            Action <IMessageReceiver, BrokeredMessage, IMessage> leaveDeadlLetterInQueue = (client, deadLetterBrokeredMessage, deadLetterMessage) =>
#endif
            {
                // Remove message from queue
                try
                {
#if NET452
                    deadLetterBrokeredMessage.Abandon();
#endif
#if NETSTANDARD2_0
                    client.AbandonAsync(deadLetterBrokeredMessage.SystemProperties.LockToken).Wait(1500);
#endif
                    lockIssues = 0;
                }
                catch (MessageLockLostException)
                {
                    lockIssues++;
                    Logger.LogWarning(string.Format("The lock supplied for abandon for the skipped dead-letter message '{0}' is invalid.", deadLetterBrokeredMessage.MessageId));
                }
                Logger.LogDebug(string.Format("A dead-letter message of type {0} arrived with the id '{1}' but left in the queue due to settings.", deadLetterMessage.GetType().FullName, deadLetterBrokeredMessage.MessageId));
            };
#if NET452
            Action <BrokeredMessage> removeDeadlLetterFromQueue = (deadLetterBrokeredMessage) =>
#endif
#if NETSTANDARD2_0
            Action <IMessageReceiver, BrokeredMessage> removeDeadlLetterFromQueue = (client, deadLetterBrokeredMessage) =>
#endif
            {
                // Remove message from queue
                try
                {
#if NET452
                    deadLetterBrokeredMessage.Complete();
#endif
#if NETSTANDARD2_0
                    client.CompleteAsync(deadLetterBrokeredMessage.SystemProperties.LockToken).Wait(1500);
#endif
                    lockIssues = 0;
                }
                catch (MessageLockLostException)
                {
                    lockIssues++;
                    Logger.LogWarning(string.Format("The lock supplied for complete for the skipped dead-letter message '{0}' is invalid.", deadLetterBrokeredMessage.MessageId));
                }
                Logger.LogDebug(string.Format("A dead-letter message arrived with the id '{0}' but was removed as processing was skipped due to settings.", deadLetterBrokeredMessage.MessageId));
            };

            Task.Factory.StartNewSafely(() =>
            {
                int loop = 0;
                while (!brokeredMessageRenewCancellationTokenSource.Token.IsCancellationRequested)
                {
                    lockIssues = 0;
                    IEnumerable <BrokeredMessage> brokeredMessages;

#if NET452
                    MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConnectionString);
                    string deadLetterPath    = SubscriptionClient.FormatDeadLetterPath(topicName, topicSubscriptionName);
                    MessageReceiver client   = factory.CreateMessageReceiver(deadLetterPath, ReceiveMode.PeekLock);
                    brokeredMessages         = client.ReceiveBatch(1000);
#endif
#if NETSTANDARD2_0
                    string deadLetterPath  = EntityNameHelper.FormatDeadLetterPath(EntityNameHelper.FormatSubscriptionPath(topicName, topicSubscriptionName));
                    MessageReceiver client = new MessageReceiver(ConnectionString, deadLetterPath, ReceiveMode.PeekLock);
                    Task <IList <BrokeredMessage> > receiveTask = client.ReceiveAsync(1000);
                    receiveTask.Wait(10000);
                    if (receiveTask.IsCompleted && receiveTask.Result != null)
                    {
                        brokeredMessages = receiveTask.Result;
                    }
                    else
                    {
                        brokeredMessages = Enumerable.Empty <BrokeredMessage>();
                    }
#endif

                    foreach (BrokeredMessage brokeredMessage in brokeredMessages)
                    {
                        if (lockIssues > 10)
                        {
                            break;
                        }
                        try
                        {
                            Logger.LogDebug(string.Format("A dead-letter message arrived with the id '{0}'.", brokeredMessage.MessageId));
                            string messageBody = brokeredMessage.GetBodyAsString();

                            // Closure protection
                            BrokeredMessage message = brokeredMessage;
                            try
                            {
                                AzureBusHelper.ReceiveEvent
                                (
                                    messageBody,
                                    @event =>
                                {
                                    bool isRequired = BusHelper.IsEventRequired(@event.GetType());
                                    if (!isRequired)
                                    {
#if NET452
                                        removeDeadlLetterFromQueue(message);
#endif
#if NETSTANDARD2_0
                                        removeDeadlLetterFromQueue(client, message);
#endif
                                    }
                                    else
                                    {
#if NET452
                                        leaveDeadlLetterInQueue(message, @event);
#endif
#if NETSTANDARD2_0
                                        leaveDeadlLetterInQueue(client, message, @event);
#endif
                                    }
                                    return(true);
                                },
                                    string.Format("id '{0}'", brokeredMessage.MessageId),
                                    ExtractSignature(message),
                                    SigningTokenConfigurationKey,
                                    () =>
                                {
#if NET452
                                    removeDeadlLetterFromQueue(message);
#endif
#if NETSTANDARD2_0
                                    removeDeadlLetterFromQueue(client, message);
#endif
                                },
                                    () => { }
                                );
                            }
                            catch
                            {
                                AzureBusHelper.ReceiveCommand
                                (
                                    messageBody,
                                    command =>
                                {
                                    bool isRequired = BusHelper.IsEventRequired(command.GetType());
                                    if (!isRequired)
                                    {
#if NET452
                                        removeDeadlLetterFromQueue(message);
#endif
#if NETSTANDARD2_0
                                        removeDeadlLetterFromQueue(client, message);
#endif
                                    }
                                    else
                                    {
#if NET452
                                        leaveDeadlLetterInQueue(message, command);
#endif
#if NETSTANDARD2_0
                                        leaveDeadlLetterInQueue(client, message, command);
#endif
                                    }
                                    return(true);
                                },
                                    string.Format("id '{0}'", brokeredMessage.MessageId),
                                    ExtractSignature(message),
                                    SigningTokenConfigurationKey,
                                    () =>
                                {
#if NET452
                                    removeDeadlLetterFromQueue(message);
#endif
#if NETSTANDARD2_0
                                    removeDeadlLetterFromQueue(client, message);
#endif
                                },
                                    () => { }
                                );
                            }
                        }
                        catch (Exception exception)
                        {
                            TelemetryHelper.TrackException(exception, null, telemetryProperties);
                            // Indicates a problem, unlock message in queue
                            Logger.LogError(string.Format("A dead-letter message arrived with the id '{0}' but failed to be process.", brokeredMessage.MessageId), exception: exception);
                            try
                            {
#if NET452
                                brokeredMessage.Abandon();
#endif
#if NETSTANDARD2_0
                                client.AbandonAsync(brokeredMessage.SystemProperties.LockToken).Wait(1500);
#endif
                            }
                            catch (MessageLockLostException)
                            {
                                lockIssues++;
                                Logger.LogWarning(string.Format("The lock supplied for abandon for the skipped dead-letter message '{0}' is invalid.", brokeredMessage.MessageId));
                            }
                        }
                    }
#if NET452
                    client.Close();
#endif
#if NETSTANDARD2_0
                    client.CloseAsync().Wait(1500);
#endif

                    if (loop++ % 5 == 0)
                    {
                        loop = 0;
                        Thread.Yield();
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
                try
                {
                    brokeredMessageRenewCancellationTokenSource.Dispose();
                }
                catch (ObjectDisposedException) { }
            }, brokeredMessageRenewCancellationTokenSource.Token);

            return(brokeredMessageRenewCancellationTokenSource);
        }