public async Task Send100SyncMessages_WhenHandlerThrowsException_DeadLetters()
        {
#pragma warning disable 4014
            Task.Run(async() =>
#pragma warning restore 4014
            {
                for (int i = 0; i < 100; i++)
                {
                    await this.sender.Send(new Message {
                        Bar = i
                    });
                }
            });

            await this.context.Wait(handlerCalls : 50);

            this.context.HandlerCalls.Should().BeInvoked(ntimes: 50);

            // Wait a bit in order to let the bus deadletter
            await Task.Delay(10000);

            MessageReceiver deadLetterReceiver = await MessagingFactory.Create()
                                                 .CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(ReceiverEndpointName), ReceiveMode.ReceiveAndDelete);

            IEnumerable <BrokeredMessage> deadLetteredMessages = await deadLetterReceiver.ReceiveBatchAsync(50);

            deadLetteredMessages.Should().HaveCount(50)
            .And.OnlyContain(b => b.DeliveryCount == 10);
        }
Ejemplo n.º 2
0
        private string GetDeadLetterQueueName(Type messageContractType)
        {
            var queuePath           = _router.Route(messageContractType, QueueOrTopic.Queue);
            var deadLetterQueueName = QueueClient.FormatDeadLetterPath(queuePath);

            return(deadLetterQueueName);
        }
        public int Handle(ResendFromDeadLetterQueue cmd)
        {
            var dlqClient = this.messagingFactory.CreateQueueClient(
                QueueClient.FormatDeadLetterPath(cmd.Name),
                ReceiveMode.ReceiveAndDelete);
            var qClient = this.messagingFactory.CreateQueueClient(cmd.Name);

            if (cmd.All)
            {
                QueueDescription queueDescription = null;
                do
                {
                    Resend(cmd, dlqClient, qClient);
                    queueDescription = this.namespaceManager.GetQueue(cmd.Name);
                }while (queueDescription.MessageCountDetails.DeadLetterMessageCount > 0);
            }
            else
            {
                Resend(cmd, dlqClient, qClient);
            }

            Console.WriteLine("Finished resending to queue");

            return(0);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            const string queueName = "MyDemoQueue1";

            var connectionString = CloudConfigurationManager.GetSetting("ServiceBusConnectionString");

            // QueueClient client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            string      deadLetterQueueName = QueueClient.FormatDeadLetterPath(queueName);
            QueueClient client = QueueClient.CreateFromConnectionString(connectionString, deadLetterQueueName);

            OnMessageOptions options = new OnMessageOptions
            {
                AutoComplete     = false,
                AutoRenewTimeout = TimeSpan.FromMinutes(1)
            };

            client.OnMessage((message) =>
            {
                try
                {
                    Console.WriteLine("Body: {0}, MessageID: {1}, Test Property: {2}", message.GetBody <string>(), message.MessageId, message.Properties["TestProperty"]);
                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receving Messages Complete, Press Any Key to Exit!");
            Console.ReadLine();
        }
Ejemplo n.º 5
0
        public static void RetrieveMessageFromDeadLetterForQueue()
        {
            var receiverFactory = MessagingFactory.Create(
                "sb://<NS>.servicebus.windows.net/",
                new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", ""),
                NetMessagingTransportSettings = { BatchFlushInterval = new TimeSpan(0, 0, 0) }
            });

            string data = QueueClient.FormatDeadLetterPath("queuedemo");

            var receiver = receiverFactory.CreateMessageReceiver(data);

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

                lock (Console.Out)
                {
                    Console.WriteLine(message.MessageId);
                }

                await message.CompleteAsync();
            },
                new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 1
            });
        }
Ejemplo n.º 6
0
        public void SplitQueuePath_IfDLQPath_ReturnsPathToParentEntity()
        {
            string path = QueueClient.FormatDeadLetterPath(TestEntityPath);

            string[] result = NamespaceManagerExtensions.SplitQueuePath(path);

            Assert.NotNull(result);
            Assert.Equal(2, result.Length);
            Assert.Equal(TestEntityPath, result[0]);
        }
Ejemplo n.º 7
0
        public AzureMessageQueue(string connectionString, Queue queue, bool deadLetter = false)
        {
            _connectionStr    = connectionString;
            IsDeadLetterQueue = deadLetter;

            Queue = !deadLetter ? queue : new Model.Queue(queue.Name, QueueType.Error, 0xFF0000, queue.ContentFormat);

            var name = !deadLetter ? queue.Name : QueueClient.FormatDeadLetterPath(queue.Name);

            Main = QueueClient.CreateFromConnectionString(connectionString, name, ReceiveMode.ReceiveAndDelete);
        }
        string GetDlqEntityPath()
        {
            if (sourceQueueDescription != null)
            {
                return(QueueClient.FormatDeadLetterPath(sourceQueueDescription.Path));
            }

            return(SubscriptionClient.FormatDeadLetterPath(
                       sourceSubscriptionWrapper.SubscriptionDescription.TopicPath,
                       sourceSubscriptionWrapper.SubscriptionDescription.Name));
        }
        public ConnectToQueue()
        {
            connectionString = "Endpoint=sb://nitprodev.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=ITfvDogxy7Kuc/wbTPu1HP7g1Mh7eqSvtaP/E6y3HH0=";
            queueName        = "nitprodevqueue";
            messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
            messageSender    = messagingFactory.CreateMessageSender(queueName);
            messageReceiver  = messagingFactory.CreateMessageReceiver(queueName);
            options          = new OnMessageOptions();

            var client    = QueueClient.CreateFromConnectionString(connectionString, queueName);
            var deadQueue = QueueClient.CreateFromConnectionString(connectionString, QueueClient.FormatDeadLetterPath(client.Path));
        }
Ejemplo n.º 10
0
        public static void Main()
        {
            // Get credentials and create a client for receiving messages:
            GetUserCredentials();
            MessagingFactory messagingFactory = CreateMessagingFactory();
            QueueClient      queueClient      = messagingFactory.CreateQueueClient("OrdersService");

            // Read messages from queue until it is empty:
            Console.WriteLine("Reading messages from queue...");

            BrokeredMessage receivedMessage;

            while ((receivedMessage = queueClient.Receive(TimeSpan.FromSeconds(10))) != null)
            {
                int retryCount = 0;
                while (retryCount < MaxRetryCount)
                {
                    if (ProcessOrder(receivedMessage))
                    {
                        break;
                    }
                    else
                    {
                        retryCount++;
                    }
                }

                if (retryCount == MaxRetryCount)
                {
                    Console.WriteLine("Adding Order {0} with {1} number of items and {2} total to DeadLetter queue", receivedMessage.Properties["OrderNumber"],
                                      receivedMessage.Properties["NumberOfItems"], receivedMessage.Properties["OrderTotal"]);
                    receivedMessage.DeadLetter("UnableToProcess", "Failed to process in reasonable attempts");
                }
            }

            Console.WriteLine();
            Console.WriteLine("No more messages left in queue. Logging dead lettered messages...");

            // Log the dead-lettered messages that could not be processed:
            QueueClient     deadLetterClient = messagingFactory.CreateQueueClient(QueueClient.FormatDeadLetterPath(queueClient.Path), ReceiveMode.ReceiveAndDelete);
            BrokeredMessage receivedDeadLetterMessage;

            while ((receivedDeadLetterMessage = deadLetterClient.Receive(TimeSpan.FromSeconds(10))) != null)
            {
                LogOrder(receivedDeadLetterMessage);
            }

            Console.WriteLine();
            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 11
0
        //*********************************************************************
        ///
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        ///
        //*********************************************************************

        public void CompleteMessage(BrokeredMessage message)
        {
            try
            {
                var    queName = message.Properties["QueueName"] as string;
                object deadLetterReason;

                if (message.Properties.TryGetValue("DeadLetterReason", out deadLetterReason))
                {
                    queName = QueueClient.FormatDeadLetterPath(queName);
                }
                else if (0 < message.LockedUntilUtc.CompareTo(DateTime.UtcNow))
                {
                    try
                    {
                        message.Complete();
                        return;
                    }
                    catch (Exception ex)
                    {
                        if (!ex.Message.Contains("already been removed"))
                        {
                            throw;
                        }
                    }
                }

                //var bmList = ReadQueueBatch((QueueNameEnum)Enum.Parse(typeof(QueueNameEnum), queName), 100, false);
                var bmList = ReadQueueBatch(queName, 100, false);

                foreach (var bm in bmList)
                {
                    if (bm.SequenceNumber == message.SequenceNumber)
                    {
                        bm.Complete();
                    }
                    else
                    {
                        bm.Abandon();
                    }

                    bm.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Exception in CmpQueue.CompleteMessage() : " +
                                    Utilities.UnwindExceptionMessages(ex));
            }
        }
        public static List <IMessage <T> > GetDeadLetteredMessages <T>(string connectionStringName, int messagesCount = 10, bool deleteAfterReceiving = true)
        {
            var connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];

            if (connectionStringSettings == null)
            {
                throw new ArgumentException("Invalid connection string name has been supplied", "connectionStringName");
            }
            var messagingFactory = MessagingFactory.CreateFromConnectionString(connectionStringSettings.ConnectionString);

            var queueName   = typeof(T).QueueName();
            var receiveMode = deleteAfterReceiving ? ReceiveMode.ReceiveAndDelete : ReceiveMode.PeekLock;
            var queueClient = messagingFactory.CreateQueueClient(QueueClient.FormatDeadLetterPath(queueName), receiveMode);

            var items = new List <IMessage <T> >();

            var brokeredMessages = queueClient.ReceiveBatch(messagesCount);

            if (brokeredMessages == null)
            {
                return(items);
            }

            foreach (var brokeredMessage in brokeredMessages)
            {
                if (!deleteAfterReceiving)
                {
                    brokeredMessage.Abandon(); //Unlock message in queue
                }

                var messageBody = brokeredMessage.GetBody <string>();
                var message     = messageBody.DeserializeToMessage <T>();

                message.RetryAttempts = ParseInt(brokeredMessage.Properties["RetryCount"]);
                message.Error         = new MessageError
                {
                    ErrorCode  = GetValue(brokeredMessage.Properties, "ErrorCode"),
                    Message    = GetValue(brokeredMessage.Properties, "ErrorMessage"),
                    StackTrace = GetValue(brokeredMessage.Properties, "StackTrace")
                };

                items.Add(message);
            }

            return(items);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            var cnnStr = ConfigurationManager.ConnectionStrings["servicebus"].ConnectionString;
            var queues = ConfigurationManager.AppSettings["queues"].Split('|');

            foreach (var queueName in queues)
            {
                Console.SetCursorPosition(1, 1);
                Console.Write(new string(' ', Console.WindowWidth));
                Console.SetCursorPosition(1, 1);
                Console.WriteLine($"queue name: {queueName}");
                var queue          = QueueClient.CreateFromConnectionString(cnnStr, queueName);
                var factory        = MessagingFactory.CreateFromConnectionString(cnnStr);
                var deadLetterPath = QueueClient.FormatDeadLetterPath(queueName);
                var dlqReceiver    = factory.CreateMessageReceiver(deadLetterPath, ReceiveMode.PeekLock);

                while (true)
                {
                    var msg = dlqReceiver.Receive();
                    if (msg == null)
                    {
                        break;
                    }
                    Console.SetCursorPosition(1, 3);
                    Console.Write(new string(' ', Console.WindowWidth));
                    Console.SetCursorPosition(1, 3);
                    Console.WriteLine($"msg content: {msg.MessageId}");
                    try
                    {
                        // Send message to queue
                        var bm = msg.Clone();
                        queue.Send(bm);
                        //
                        msg.Complete();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            Console.SetCursorPosition(1, 5);
            Console.WriteLine("Press any key to exit!");
            Console.Read();
        }
Ejemplo n.º 14
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            //var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);

            Client = factory.CreateQueueClient(QueueName);

            DeadLetterClient = factory.CreateQueueClient(QueueClient.FormatDeadLetterPath(Client.Path));


            // Initialize the connection to Service Bus Queue
            return(base.OnStart());
        }
Ejemplo n.º 15
0
        public static void Initialize(string connectionString, string queueName)
        {
            NamespaceManager nsManager = NamespaceManager.CreateFromConnectionString(connectionString);
            MessagingFactory factory   = MessagingFactory.CreateFromConnectionString(connectionString);

            QueueDescription queue_description = new QueueDescription(queueName);

            queue_description.DefaultMessageTimeToLive = new TimeSpan(0, 0, 10);
            queue_description.EnableDeadLetteringOnMessageExpiration = true;
            queue_description.MaxDeliveryCount = 4;

            Client             = factory.CreateQueueClient(queueName);
            Client.RetryPolicy = RetryExponential.Default;

            var dfQueue = QueueClient.FormatDeadLetterPath(Client.Path);

            DeadLetterClient = factory.CreateQueueClient(dfQueue);
        }
Ejemplo n.º 16
0
        async Task PickUpAndFixDeadletters(MessagingFactory receiverFactory, string queueName, MessageSender resubmitSender, CancellationToken cancellationToken)
        {
            var doneReceiving = new TaskCompletionSource <bool>();

            var dlqReceiver = await receiverFactory.CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock);

            // close the receiver and factory when the CancellationToken fires
            cancellationToken.Register(
                async() =>
            {
                await dlqReceiver.CloseAsync();
                doneReceiving.SetResult(true);
            });

            // register the OnMessageAsync callback
            dlqReceiver.OnMessageAsync(
                async message =>
            {
                var resubmitMessage = message.Clone();
                if (resubmitMessage.Label != null && resubmitMessage.Label.Equals("Physicist"))
                {
                    lock (Console.Out)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(
                            "\t\tFixing: \n\t\t\tMessageId = {0}, \n\t\t\tSequenceNumber = {1}, \n\t\t\tLabel = {2}",
                            message.MessageId,
                            message.SequenceNumber,
                            message.Label);
                        Console.ResetColor();
                    }
                    resubmitMessage.Label = "Scientist";
                    await resubmitSender.SendAsync(resubmitMessage);
                }
                await message.CompleteAsync();
            },
                new OnMessageOptions {
                AutoComplete = true, MaxConcurrentCalls = 1
            });

            await doneReceiving.Task;
        }
        private static void ReceiveMessagesFromDeadLetter()
        {
            Console.WriteLine("\nReceiving message from Dead Letter Queue...");
            BrokeredMessage message = null;

            var deadLetterPath = QueueClient.FormatDeadLetterPath(QueueName);

            var deadLetterClient = QueueClient.Create(deadLetterPath);

            while (true)
            {
                try
                {
                    message = deadLetterClient.Receive(TimeSpan.FromSeconds(5));

                    if (message != null)
                    {
                        Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>()));
                        // Further custom message processing could go here...
                        message.Complete();
                    }
                    else
                    {
                        //no more messages in the queue
                        break;
                    }
                }
                catch (MessagingException e)
                {
                    if (!e.IsTransient)
                    {
                        Console.WriteLine(e.Message);
                        throw;
                    }
                    else
                    {
                        HandleTransientErrors(e);
                    }
                }
            }
            queueClient.Close();
        }
Ejemplo n.º 18
0
        protected void Button11_Click(object sender, EventArgs e)
        {
            NamespaceManager nsmgr = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString(System.Configuration.ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]);

            var         queueDeadletterPath   = QueueClient.FormatDeadLetterPath("Bus2");
            QueueClient deadletterQueueClient = QueueClient.Create(queueDeadletterPath);

            while (nsmgr.GetQueue("bus2").MessageCountDetails.DeadLetterMessageCount > 0)
            {
                var message = deadletterQueueClient.Receive();
                if (message != null)
                {
                    SendMessage("bus2", message.Clone());
                    message.Complete();
                }
            }


            Refresh();
        }
Ejemplo n.º 19
0
        public async Task FlushAsync()
        {
            await ForEachMessageAsyncUsingReceiveAndDeleteMode(async message => await Task.Run(() => { }));


            do
            {
                var deadLetterPath   = QueueClient.FormatDeadLetterPath(Name);
                var deadLetterClient = QueueClient.CreateFromConnectionString(ConnectionString, 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);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            string connectionString = ConfigurationManager.AppSettings["ServiceBusConnection"];

            MessagingFactory factory       = MessagingFactory.CreateFromConnectionString(connectionString);
            var             deadLetterPath = QueueClient.FormatDeadLetterPath("trade-input");
            var             dlqReceiver    = factory.CreateMessageReceiver(deadLetterPath, ReceiveMode.ReceiveAndDelete);
            BrokeredMessage message;

            while ((message = dlqReceiver.Receive()) != null)
            {
                string body;
                using (var stream = message.GetBody <Stream>())
                    using (var streamReader = new StreamReader(stream, Encoding.UTF8))
                    {
                        body = streamReader.ReadToEnd();
                    }
                Console.WriteLine($"Message Received {body}");
            }
            Console.Read();
        }
Ejemplo n.º 21
0
        public IEnumerable <BrokeredMessage> ReadAllBatch(QueueNameEnum queueNameEnum,
                                                          int count, bool getDeadLetter, bool abandon)
        {
            try
            {
                QueueClient qc        = null;
                var         queueName = queueNameEnum.ToString();

                if (getDeadLetter)
                {
                    queueName = QueueClient.FormatDeadLetterPath(queueName);
                }

                qc = GetQueue(queueName, true);

                return(ReadAllBatch(qc, count, abandon));
            }
            catch (Exception ex)
            {
                throw new Exception("Exception in CmpQueue.ReadQueueBatch() : " +
                                    Utilities.UnwindExceptionMessages(ex));
            }
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            var workerConfigurationManager = new WorkerConfigurationManager();
            var workerConfiguration        = workerConfigurationManager.GetWorkerConfiguration();

            var connectionString    = workerConfiguration.ConnectionString;
            var queueName           = workerConfiguration.QueueName;
            var deadLetterQueueName = QueueClient.FormatDeadLetterPath(queueName);

            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            client.OnMessage(message =>
            {
                Console.WriteLine($"Message body: {message.GetBody<String>()}");
                Console.WriteLine($"Message id: {message.MessageId}");
            });

            //RetrieveLoop(client);

            //PeekMessages(client, stopwatch);

            Console.ReadLine();
        }
 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);
         }
     }
 }
Ejemplo n.º 24
0
        public ActionResult DeadletterQueue()
        {
            // Create the queue if it does not exist already
            string      connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var         namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            var         client           = QueueClient.CreateFromConnectionString(connectionString, "ProcessingQueue");
            QueueClient deadLetterClient = QueueClient.Create(QueueClient.FormatDeadLetterPath(client.Path), ReceiveMode.PeekLock);

            IEnumerable <BrokeredMessage> receivedDeadLetterMessages;
            var poisonMessages = new List <string>();

            while ((receivedDeadLetterMessages = deadLetterClient.ReceiveBatch(32, TimeSpan.FromSeconds(10))) != null)
            {
                foreach (var receivedDeadLetterMessage in receivedDeadLetterMessages)
                {
                    var messageBodyType = Type.GetType(receivedDeadLetterMessage.Properties["messageType"].ToString());
                    if (messageBodyType == null)
                    {
                        poisonMessages.Add(receivedDeadLetterMessage.MessageId + ": no message body type specified");
                        continue;
                    }

                    //Use reflection to figure out the type of object contained in the message body, and extract it
                    MethodInfo method      = typeof(BrokeredMessage).GetMethod("GetBody", new Type[] { });
                    MethodInfo generic     = method.MakeGenericMethod(messageBodyType);
                    var        messageBody = generic.Invoke(receivedDeadLetterMessage, null);
                    poisonMessages.Add(JsonConvert.SerializeObject(messageBody));
                }
                if (receivedDeadLetterMessages.Count() == 0)
                {
                    break;
                }
            }

            return(View(poisonMessages));
        }
Ejemplo n.º 25
0
        public async Task Test_LockError_MessageFlow <T>(T _)
            where T : IMessage, new() // be careful with this, if the test doesn't run it's because the T validation is broken
        {
            _.CheckInlineType();      // inline data check

            await NamespaceManager.CreateFromConnectionString(NamespaceHelper.GetConnectionString()).ScorchNamespace();

            MessageQueue.LockTimers.Release();
            MessageQueue.BrokeredMessages.Release();

            using (var ts = new CancellationTokenSource())
                using (IMessenger msn = new Messenger(NamespaceHelper.GetConnectionString()))
                {
                    var message = new T();
                    await msn.Send(message);

                    msn.Receive <T>(
                        async m =>
                    {
                        await m.Lock();
                        await Task.Delay(TimeSpan.FromSeconds(5), ts.Token);
                        await m.Error();

                        ts.Cancel(); // kill switch
                    });

                    try
                    {
                        await Task.Delay(TimeSpan.FromMinutes(2), ts.Token);
                    }
                    catch (TaskCanceledException) { /* soak the kill switch */ }

                    var qClient  = QueueClient.CreateFromConnectionString(NamespaceHelper.GetConnectionString(), QueueClient.FormatDeadLetterPath(typeof(T).GetQueueName()));
                    var rMessage = (await qClient.ReadBatchAsync <T>(1)).First();

                    rMessage.ShouldBeEquivalentTo(message);

                    MessageQueue.BrokeredMessages.Should().BeEmpty();
                    MessageQueue.LockTimers.Should().BeEmpty();
                }
        }
        public async Task WhenMessageReachesMaximumNumberOfRetries_MessageIsDeadlettered()
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write("{ Bar: 1 }");
            writer.Flush();
            stream.Position = 0;

            var tm = new TransportMessage {
                MessageType = typeof(Message).AssemblyQualifiedName
            };

            tm.SetBody(stream);

            MessageSender messageSender = await this.messagingFactory.CreateMessageSenderAsync(ReceiverEndpointName);

            await messageSender.SendAsync(tm.ToBrokeredMessage());

            MessageReceiver deadLetterReceiver = await this.messagingFactory.CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(ReceiverEndpointName), ReceiveMode.ReceiveAndDelete);

            IEnumerable <BrokeredMessage> deadLetteredMessages = await deadLetterReceiver.ReceiveBatchAsync(10);

            // That's not really a good assertion here. But how far should I compare exception, stacktrace etc.
            deadLetteredMessages.Should().HaveCount(1);
            deadLetteredMessages.Single()
            .Properties.Where(p => p.Key.StartsWith(HeaderKeys.FailurePrefix, StringComparison.InvariantCultureIgnoreCase))
            .Should().NotBeEmpty();
        }
Ejemplo n.º 27
0
        static void Test(NamespaceManager namespaceManager, MessagingFactory messageFactory)
        {
            var q = namespaceManager.GetQueue(QueueName);
            var t = namespaceManager.GetTopic(TopicName);

            var gf = namespaceManager.GetTopics();

            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }


            QueueClient myQueueClient = messageFactory.CreateQueueClient(QueueName);

            try
            {
                BrokeredMessage sendMessage = new BrokeredMessage("Hello World !");
                myQueueClient.Send(sendMessage);

                //// Receive the message from the queue
                //BrokeredMessage receivedMessage = myQueueClient.Receive(TimeSpan.FromSeconds(5));

                //if (receivedMessage != null)
                //{
                //    Console.WriteLine(string.Format("Message received: {0}", receivedMessage.GetBody<string>()));
                //    receivedMessage.Complete();
                //}

                //Check for messages that are older than they should be
                int      minutesOld = 1;
                DateTime oldest     = DateTime.UtcNow.AddMinutes(-minutesOld);

                int oldMessageCount             = 0;
                List <BrokeredMessage> messages = new List <BrokeredMessage>(myQueueClient.PeekBatch(1000));

                foreach (BrokeredMessage b in messages)
                {
                    if (b.EnqueuedTimeUtc < oldest)
                    {
                        oldMessageCount++;
                    }
                }

                BrokeredMessage bd = myQueueClient.Receive();
                bd.DeadLetter();

                //check for dead letter messages
                QueueClient dlClient = messageFactory.CreateQueueClient(QueueClient.FormatDeadLetterPath(QueueName));

                List <BrokeredMessage> dlMessages = new List <BrokeredMessage>(dlClient.PeekBatch(1000));
                int i = dlMessages.Count;

                //b.DeadLetter();


                if (!namespaceManager.TopicExists(TopicName))
                {
                    namespaceManager.CreateTopic(TopicName);
                }


                if (!namespaceManager.SubscriptionExists(TopicName, SubName))
                {
                    namespaceManager.CreateSubscription(TopicName, SubName);
                }



                TopicClient topicClient = messageFactory.CreateTopicClient(TopicName);

                topicClient.Send(new BrokeredMessage("Message"));

                SubscriptionDescription s = namespaceManager.GetSubscription(TopicName, SubName);

                SubscriptionClient subClient = messageFactory.CreateSubscriptionClient(TopicName, SubName);

                List <BrokeredMessage> subMessages = new List <BrokeredMessage>(subClient.PeekBatch(1000));
                BrokeredMessage        bms         = subClient.Receive();
                bms.DeadLetter();

                foreach (BrokeredMessage b in messages)
                {
                    if (b.EnqueuedTimeUtc < oldest)
                    {
                        oldMessageCount++;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception {0}", e.ToString());
                throw;
            }
            finally
            {
                if (messageFactory != null)
                {
                    messageFactory.Close();
                }
            }
            //Send Message
        }
Ejemplo n.º 28
0
        public ConsumeDeatMsgForm(LoadAppSettings loadAppSettings)
        {
            //初始化两个队列的messageReceiver
            //1.bankgateway -creditassignmentgrantnotificationqueue
            string grantQueuename           = ConfigurationManager.AppSettings["creditassignmentgrantQName"];
            string batchCreditQueueName     = ConfigurationManager.AppSettings["bookcreditcreatebatchQName"]; //债转关系银行回调
            string confirmdebtpurchaseQName = ConfigurationManager.AppSettings["confirmdebtpurchaseQName"];
            string confirmredemptionQName   = ConfigurationManager.AppSettings["confirmredemptionQName"];
            string advancedebtforbankQName  = ConfigurationManager.AppSettings["advancedebtforbankQName"];
            string batchbookcreditQName     = ConfigurationManager.AppSettings["batchbookcreditQName"];
            var    namespaceManager         = NamespaceManager.CreateFromConnectionString(loadAppSettings.ServiceBusConnectionString);

            if (!namespaceManager.QueueExists(grantQueuename))
            {
                MessageBox.Show($"不存在{grantQueuename}该队列");
                return;
            }
            if (!namespaceManager.QueueExists(batchCreditQueueName))
            {
                MessageBox.Show($"不存在{batchCreditQueueName}该队列");
                return;
            }
            if (!namespaceManager.QueueExists(confirmdebtpurchaseQName))
            {
                MessageBox.Show($"不存在{confirmdebtpurchaseQName}该队列");
                return;
            }
            if (!namespaceManager.QueueExists(confirmredemptionQName))
            {
                MessageBox.Show($"不存在{confirmredemptionQName}该队列");
                return;
            }
            if (!namespaceManager.QueueExists(advancedebtforbankQName))
            {
                MessageBox.Show($"不存在{advancedebtforbankQName}该队列");
                return;
            }
            if (!namespaceManager.QueueExists(batchbookcreditQName))
            {
                MessageBox.Show($"不存在{batchbookcreditQName}该队列");
                return;
            }
            var messagingFactory = MessagingFactory.CreateFromConnectionString(loadAppSettings.ServiceBusConnectionString);

            this.messageReceiverGrant           = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(grantQueuename), ReceiveMode.ReceiveAndDelete);           //放款银行回调
            this.messageReceiverBatchCredit     = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(batchCreditQueueName), ReceiveMode.ReceiveAndDelete);     //债转关系银行回调
            this.messageReiceiverPurchase       = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(confirmdebtpurchaseQName), ReceiveMode.ReceiveAndDelete); //购买债转通知交易
            this.messageReceiverRedemption      = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(confirmredemptionQName), ReceiveMode.ReceiveAndDelete);   //赎回确认通知交易
            this.messageReceiverAdvanceDebt     = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(advancedebtforbankQName), ReceiveMode.ReceiveAndDelete);  //债转放款
            this.messageReceiverBatchbookcredit = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(batchbookcreditQName), ReceiveMode.ReceiveAndDelete);     //批量债转
            CheckForIllegalCrossThreadCalls     = false;
            this.loadAppSettings = loadAppSettings;
            this.InitializeComponent();
        }
Ejemplo n.º 29
0
        public void ReturnMessageToSourceQueue(string fromQueueName, ServiceBusMQ.Model.QueueItem itm)
        {
            var queue           = QueueClient.CreateFromConnectionString(ConnectionString, fromQueueName);
            var deadLetterQueue = QueueClient.CreateFromConnectionString(ConnectionString, QueueClient.FormatDeadLetterPath(fromQueueName), ReceiveMode.ReceiveAndDelete);

            ReturnMessageToSourceQueue(queue, deadLetterQueue, itm);
        }
Ejemplo n.º 30
0
        public void ReturnAll(string fromQueueName)
        {
            var queue           = QueueClient.CreateFromConnectionString(ConnectionString, fromQueueName);
            var deadLetterQueue = QueueClient.CreateFromConnectionString(ConnectionString, QueueClient.FormatDeadLetterPath(fromQueueName), ReceiveMode.PeekLock);

            foreach (var msg in deadLetterQueue.ReceiveBatch(0xFFFF))
            {
                try {
                    queue.Send(msg);
                    msg.Abandon();
                    //queue.Send(message.Clone());
                } catch (Exception ex) {
                    TryFindMessage(null);
                }
            }
        }