Esempio n. 1
0
        private static void ReceiveMessage()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;;

            if (_namespaceManager.TopicExists("DataCollectionTopic"))
            {
                MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider);

                //Same as Queue ReceiveMode.PeekLock is default
                MessageReceiver receiver  = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Inventory");
                MessageReceiver receiver1 = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Dashboard");

                BrokeredMessage receivedMessage = null;
                try
                {
                    Console.WriteLine($"From Inventory");
                    while ((receivedMessage = receiver.Receive()) != null)
                    {
                        ProcessMessage(receivedMessage);
                        receivedMessage.Complete();
                    }
                    Console.WriteLine($"From Dashboard");
                    while ((receivedMessage = receiver1.Receive()) != null)
                    {
                        ProcessMessage(receivedMessage);
                        receivedMessage.Complete();
                    }
                    factory.Close();
                    _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory");
                    _namespaceManager.DeleteSubscription("DataCollectionTopic", "Dashboard");
                    _namespaceManager.DeleteTopic("DataCollectionTopic");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    receivedMessage.Abandon();
                }

                #region With Collection
                //IEnumerable<BrokeredMessage> receivedMessageList = receiver.ReceiveBatch(2);
                //try
                //{
                //    foreach (var item in receivedMessageList)
                //    {
                //        ProcessMessage(item);
                //        item.Complete();
                //    }
                //    factory.Close();
                //    _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory");
                //    //_namespaceManager.DeleteSubscription("DataCollectionTopic", "Dashboard");
                //    //_namespaceManager.DeleteTopic("DataCollectionTopic");
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex.ToString());
                //}
                #endregion
            }
        }
Esempio n. 2
0
        public IListener CreateListener(string path, bool allowRetries)
        {
            var receiver = MessagingFactory.CreateMessageReceiver(path,
                                                                  allowRetries ? ReceiveMode.PeekLock : ReceiveMode.ReceiveAndDelete);

            return(new PacketListener(receiver, this));
        }
Esempio n. 3
0
        public void Scenario10_QueueRequestResponse(string queue, string replyTo)
        {
            WorkerThread receiverThread = new WorkerThread(this.Scenario11_QueueReceiver);

            receiverThread.Start(queue);

            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            MessageSender sender = factory.CreateMessageSender(queue);

            MemoryStream    stream  = new MemoryStream(Encoding.UTF8.GetBytes("Request"));
            BrokeredMessage message = new BrokeredMessage(stream);

            message.MessageId          = Guid.NewGuid().ToString();
            message.ReplyTo            = replyTo;
            message.Properties["time"] = DateTime.UtcNow;

            sender.Send(message);

            MessageReceiver receiver = factory.CreateMessageReceiver(replyTo);

            BrokeredMessage response = receiver.Receive();

            response.Complete();

            sender.Close();
            receiver.Close();
            factory.Close();
        }
        static void ReceiveMessage()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;

            if (_namespaceManager.TopicExists("DataCollectionTopic"))
            {
                MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider);
                //MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Inventory");
                MessageReceiver receiver        = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Dashboard");
                BrokeredMessage receivedMessage = null;
                try
                {
                    while ((receivedMessage = receiver.Receive()) != null)
                    {
                        ProcessMessage(receivedMessage);
                        receivedMessage.Complete();
                    }
                    factory.Close();
                    _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory");
                    // _namespaceManager.DeleteTopic("DataCollectionTopic");
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    receivedMessage.Abandon();
                }
            }
        }
Esempio n. 5
0
        static async Task AsyncMain()
        {
            MessagingFactory fact = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings["ConnectionString"]);

            var sender = fact.CreateMessageSender("destinationQueue", "queue2");

            var receiver = fact.CreateMessageReceiver("queue2", ReceiveMode.PeekLock);

            BrokeredMessage msg;
            BrokeredMessage recMsg;

            var i = 0;

            while (i < 5000)
            {
                recMsg = await receiver.ReceiveAsync();

                msg = new BrokeredMessage();

                if (recMsg != null)
                {
                    using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        msg.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddMinutes(6);

                        await recMsg.CompleteAsync();

                        await sender.SendAsync(msg);

                        scope.Complete();
                        i++;
                    }
                }
            }
        }
Esempio n. 6
0
        public void HandleRegenerateSite()
        {
            long n = 0;

            allMessages = factory.CreateMessageReceiver(regenSiteTopic + "/subscriptions/AllMessages", ReceiveMode.PeekLock);
            while (_running)
            {
                BrokeredMessage message = allMessages.Receive();

                if (message != null)
                {
                    // let the message go back to the pool
                    Int64.TryParse(message.Properties["MessageNumber"].ToString(), out n);
                    message.Abandon();

                    try {
                        if (n > maxMessage)
                        {
                            maxMessage = n;
                            Console.WriteLine("\r\nAccepted message to regenerate site: {0} ", n);
                            RebuildWebsite();
                        }
                        else
                        {
                            // Console.WriteLine("\r\nSkipping: {0} ",n);
                        }
                    }
                    catch (Exception) {
                    }
                    Thread.Sleep(8000); // wait 5 seconds to give other consumers a chance on this message.
                }
            }
        }
Esempio n. 7
0
        static async Task Deadletter()
        {
            try
            {
                string           ServiceBusConnectionString = "Endpoint=sb://pricechange.servicebus.windows.net/;SharedAccessKeyName=cartitempricechange;SharedAccessKey=zOK+zZifCv4xX4f0af4Bctrg6tXeLKvwD9vhBT9YlZ8=";
                string           TopicName        = "pricechange-topic";
                string           SubscriptionName = "pricechange-topic-subscription";
                MessagingFactory factory          = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString);
                string           path             = Microsoft.ServiceBus.Messaging.SubscriptionClient.FormatDeadLetterPath(TopicName, SubscriptionName);
                Microsoft.ServiceBus.Messaging.MessageReceiver deadletterReceiver = factory.CreateMessageReceiver(path);

                BrokeredMessage msg = deadletterReceiver.Receive();
                if (msg != null)
                {
                    var messageBody     = new StreamReader(msg.GetBody <Stream>(), Encoding.UTF8).ReadToEnd();
                    var receivedMessage = JsonConvert.DeserializeObject <ServiceBusMessage>(messageBody);

                    Console.WriteLine($"Received message: UserInfo:{receivedMessage.Id}");
                    Console.ReadKey();
                    msg.Complete();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Start()
        {
            while (Enabled)
            {
                _factory = MessagingFactory.CreateFromConnectionString(_connectionString);
                var messageReceiver = _factory.CreateMessageReceiver(_path, ReceiveMode.PeekLock);

                var brokeredMessage = messageReceiver.Receive();

                if (brokeredMessage == null)
                {
                    continue;
                }
                var messageType    = brokeredMessage.Label;
                var replyTo        = brokeredMessage.ReplyTo;
                var replySessionId = brokeredMessage.ReplyToSessionId;

                var messageHandler = MessageHandlerFactory.GetHandler(string.Empty);
                messageHandler.Forwarder = _forwarder;

                Console.WriteLine("Received message {0} on {1} and forwarded to {2}", messageType, _path, _forwarder);

                var response = messageHandler.HandleRequestResponse(brokeredMessage);

                if (!string.IsNullOrEmpty(replyTo))
                {
                    var responseMessageClient = new ResponseMessageClient(_connectionString, replyTo, replySessionId);
                    Console.WriteLine("Send message response");
                    responseMessageClient.SendResponse((MemoryStream)response, messageType);
                }

                messageReceiver.Complete(brokeredMessage.LockToken);
            }
        }
Esempio n. 9
0
        protected static void AzureMessageConsumer(MessagingFactory f)
        {
            //use the already created messaging factory to create a msg receiver
            MessageReceiver testQueueReceiver = f.CreateMessageReceiver("colors");

            while (true)
            {
                using (BrokeredMessage retrievedMessage = testQueueReceiver.Receive())
                {

                    try
                    {
                        string msgResult = retrievedMessage.GetBody<string>();

                        //call SP to insert the data into the proper table
                        InsertSQL(msgResult);

                        Console.WriteLine("Message received: " + msgResult);
                        retrievedMessage.Complete();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                        retrievedMessage.Abandon();
                    }
                }
            }
        }
        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 ****");
            }
        }
Esempio n. 11
0
        private void Listen(ReceiveMode receiveMode)
        {
            var mr = _messagingFactory.CreateMessageReceiver(_subscription.FullPath, receiveMode);

            while (_isListening)
            {
                BrokeredMessage message = null;
                try
                {
                    message = mr.Receive();
                }
                catch (TimeoutException)
                {
                    ListeningTimedOut?.Invoke();
                    continue;
                }
                catch (OperationCanceledException) //When Cancel() is called on client or factory
                {
                    return;
                }
                catch (Exception ex)
                {
                    ExceptionOccured?.Invoke(message, ex);
                    return;
                }

                if (message == null)
                {
                    continue;
                }

                try
                {
                    var isMessageHandled = HandleMessage(message);
                    if (receiveMode == ReceiveMode.PeekLock)
                    {
                        if (isMessageHandled)
                        {
                            message.Complete();
                        }
                        else
                        {
                            message.Abandon();
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (receiveMode == ReceiveMode.PeekLock)
                    {
                        message.Abandon();
                    }

                    ExceptionOccured?.Invoke(message, ex);
                }

                Thread.Sleep(50);
            }
        }
Esempio n. 12
0
        private void InitConncection()
        {
            messagingFactory             = MessagingFactory.CreateFromConnectionString(ConfigurationManager.ConnectionStrings["AzureSB"].ConnectionString);
            messagingFactory.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(5), 10);


            imageSender   = messagingFactory.CreateMessageSender(ConfigurationManager.AppSettings["OutQ"]);
            statusSender  = messagingFactory.CreateMessageSender(ConfigurationManager.AppSettings["StatusQ"]);
            configReciver = messagingFactory.CreateMessageReceiver(ConfigurationManager.AppSettings["InQ"]);
        }
 public ConnectToTopic()
 {
     connectionString = "Endpoint=sb://nitprodevstd.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bVW5y5kVXRbG4FU0g45OUuWELdsGWVLsongkRjWS+uk=";
     topicName        = "nitorprodevstdtopic";
     subscription1    = "nitorprodevstdtopicsub1";
     messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
     messageSender    = messagingFactory.CreateMessageSender(topicName);
     messageReceiver  = messagingFactory.CreateMessageReceiver(topicName + "/subscriptions/" + subscription1);
     options          = new OnMessageOptions();
 }
Esempio n. 14
0
        static void Main(string[] args)
        {
            Console.Write("Enter some subscription name: ");
            string name = Console.ReadLine();

            var serviceNamespace = "msswit2013relay";
            var issuerName       = "owner";
            var issuerSecret     = "IqyIwa7gNjBO89HT+3Vd1CcoBbyibvcv6Hd92J+FtPg=";

            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Empty);

            TokenProvider    tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);
            NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider);

            if (!namespaceManager.TopicExists("MyTopic"))
            {
                namespaceManager.CreateTopic(new TopicDescription("MyTopic"));
            }

            Console.WriteLine("topic ready");

            if (!namespaceManager.SubscriptionExists("MyTopic", "subscription-" + name))
            {
                namespaceManager.CreateSubscription("MyTopic", "subscription-" + name);
            }

            Console.WriteLine("subscription ready");

            MessagingFactory factory  = MessagingFactory.Create(uri, tokenProvider);
            MessageReceiver  receiver = factory.CreateMessageReceiver("MyTopic/subscriptions/subscription-" + name);

            while (true)
            {
                BrokeredMessage receivedMessage = receiver.Receive();
                if (receivedMessage != null)
                {
                    try
                    {
                        Console.WriteLine("label: {0}", receivedMessage.Label);
                        Console.WriteLine("login: {0}", receivedMessage.Properties["login"]);
                        Console.WriteLine("pass: {0}", receivedMessage.GetBody <ServiceBusTestMessage>().Password);
                        receivedMessage.Complete();
                    }
                    catch (Exception e)
                    {
                        receivedMessage.Abandon();
                        Console.WriteLine(e.Message);
                    }
                }
                else
                {
                    Thread.Sleep(new TimeSpan(0, 0, 10));
                }
            }
        }
Esempio n. 15
0
        public string RecieveMesage()
        {
            //Receiving a message
            MessageReceiver testReceiver = _factory.CreateMessageReceiver(_queue);
            BrokeredMessage message      = testReceiver.Receive();
            String          messageText  = message.GetBody <string>();

            message.Complete();

            return(messageText);
        }
        public MessageProcessor(string queueName, string serviceNameSpace, string issuer, string key)
        {
            // Create Token Provider and Service Uri
            var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer, key);
            var serviceUri    = ServiceBusEnvironment.CreateServiceUri("sb", serviceNameSpace, string.Empty);

            // Create a messaging receiver
            _factory         = MessagingFactory.Create(serviceUri, tokenProvider);
            _messageReceiver = _factory.CreateMessageReceiver(queueName);
            //_messageSender = _factory.CreateMessageSender(queueName);
        }
        public MessageProcessor(string queueName, string serviceNameSpace, string issuer, string key)
        {
            // Create Token Provider and Service Uri
            var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer, key);
            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNameSpace, string.Empty);

            // Create a messaging receiver
            _factory = MessagingFactory.Create(serviceUri, tokenProvider);
            _messageReceiver = _factory.CreateMessageReceiver(queueName);
            //_messageSender = _factory.CreateMessageSender(queueName);
        }
Esempio n. 18
0
 public MessageReceiver GetMessageReceiver(MessagingFactory factory, string queueSubscription)
 {
     try
     {
         return(factory.CreateMessageReceiver(queueSubscription));
     }
     catch (Exception ex)
     {
         throw;
     }
 }
        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));
        }
        public async Task StartAsync_CallsMessagingProviderToCreateReceiver()
        {
            MessageReceiver receiver = _messagingFactory.CreateMessageReceiver(_entityPath);

            _mockMessagingProvider.Setup(p => p.CreateMessageReceiver(_messagingFactory, _entityPath)).Returns(receiver);

            MessagingCommunicationException ex = await Assert.ThrowsAsync <MessagingCommunicationException>(async() =>
            {
                await _listener.StartAsync(CancellationToken.None);
            });

            Assert.Equal("No such host is known", ex.Message);

            _mockMessagingProvider.VerifyAll();
        }
Esempio n. 21
0
        public async Task StartAsync_CallsMessagingProviderToCreateReceiver()
        {
            MessageReceiver receiver = _messagingFactory.CreateMessageReceiver(_entityPath);

            _mockMessagingProvider.Setup(p => p.CreateMessageReceiver(_messagingFactory, _entityPath)).Returns(receiver);

            MessagingCommunicationException ex = await Assert.ThrowsAsync <MessagingCommunicationException>(async() =>
            {
                await _listener.StartAsync(CancellationToken.None);
            });

            Assert.Equal("Unable to connect to Service Bus using HTTP connectivity mode.", ex.Message);

            _mockMessagingProvider.VerifyAll();
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            TokenProvider    token    = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", "H+rYJ3XugZAx4AwBWbgkgiqBzdxiFOY2ZR9FicPK840=");
            Uri              path     = ServiceBusEnvironment.CreateServiceUri("sb", "ajaybus", "");
            MessagingFactory factory  = MessagingFactory.Create(path, token);
            MessageReceiver  reciever = factory.CreateMessageReceiver("DetailmessageTopic/subscriptions/High");
            BrokeredMessage  msg;

            while ((msg = reciever.Receive()) != null)
            {
                Console.WriteLine("hello");
                Console.WriteLine("Message:" + msg.GetBody <String>() + "\t Priority:   " + msg.Properties["priority"]);
                msg.Complete();
            }
            Console.WriteLine("The High Priority Queue completed");
            reciever = factory.CreateMessageReceiver("DetailmessageTopic/subscriptions/Low");
            while ((msg = reciever.Receive()) != null)
            {
                Console.WriteLine("hello");
                Console.WriteLine("Message:" + msg.GetBody <String>() + "\t Priority: " + msg.Properties["priority"]);
                msg.Complete();
            }
            Console.WriteLine("The Low Priority Queue completed");
        }
Esempio n. 23
0
        /// <summary>
        /// Creates a <see cref="MessageReceiver"/> for the specified ServiceBus entity.
        /// </summary>
        /// <remarks>
        /// You can override this method to customize the <see cref="MessageReceiver"/>.
        /// </remarks>
        /// <param name="factory">The <see cref="MessagingFactory"/> to use.</param>
        /// <param name="entityPath">The ServiceBus entity to create a <see cref="MessageReceiver"/> for.</param>
        /// <returns></returns>
        public virtual MessageReceiver CreateMessageReceiver(MessagingFactory factory, string entityPath)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (string.IsNullOrEmpty(entityPath))
            {
                throw new ArgumentNullException("entityPath");
            }

            MessageReceiver receiver = factory.CreateMessageReceiver(entityPath);

            receiver.PrefetchCount = _config.PrefetchCount;
            return(receiver);
        }
            public async Task ReceiveMessages()
            {
                messageReceiver = factory.CreateMessageReceiver(queuename);
                stopwatch.Restart();
                stopwatch.Start();

                for (int i = 0; i < numberOfMessages; i++)
                {
                    Task.Factory.StartNew(ReceiveMessage);
                }

                var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                Console.WriteLine("{0} messages received in {1} ms", numberOfMessages, elapsedMilliseconds);
                Console.WriteLine("Received {0} per second", numberOfMessages == 0 ? 0L : (1000 * (long)numberOfMessages) / (long)elapsedMilliseconds);
            }
        static void Main(string[] args)
        {
            // ***************************************************************************************
            // This sample demonstrates how to use MessagePeek feature to look into the content of
            // Service bus entities (Queues , Subscriptions).
            // ***************************************************************************************
            Program.GetNamespaceAndCredentials();

            MessagingFactory messagingFactory = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString);
            MessageReceiver  messageReciever  = messagingFactory.CreateMessageReceiver(Program.ServiceBusentityPath);

            BrokeredMessage msg;

            while (true)
            {
                msg = messageReciever.Peek();
                if (msg != null)
                {
                    Console.WriteLine("{0} {1} - {2} - {3}", msg.EnqueuedTimeUtc.ToLocalTime().ToShortDateString(), msg.EnqueuedTimeUtc.ToLocalTime().ToLongTimeString(), msg.SequenceNumber, msg.Label);
                    var listViewItems = msg.Properties.Select(p => new[] { p.Key, p.Value.ToString() }).ToArray();
                    for (int propIndex = 0; propIndex < listViewItems.Length; propIndex++)
                    {
                        Console.Write("{0}: {1}\t", listViewItems[propIndex][0], listViewItems[propIndex][1]);
                    }

                    Stream stream = msg.GetBody <Stream>();
                    if (stream != null)
                    {
                        StreamReader reader = new StreamReader(stream);
                        string       text   = reader.ReadToEnd();
                        if (text != null)
                        {
                            Console.WriteLine("\n{0}\n", text);
                        }
                    }
                }
                else
                {
                    break;
                }
            }

            messagingFactory.Close();
            Console.WriteLine("Press [Enter] to quit...");
            Console.ReadLine();
        }
Esempio n. 26
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 ReceiveMessages()
            {
                messageReceiver = factory.CreateMessageReceiver(queuename);
                stopwatch.Restart();
                stopwatch.Start();

                for (int i = 0; i < numberOfMessages; i++)
                {
                    var message = await messageReceiver.ReceiveAsync();

                    await messageReceiver.CompleteAsync(message.LockToken);
                }

                var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                Console.WriteLine("{0} messages received in {1} ms", numberOfMessages, elapsedMilliseconds);
                Console.WriteLine("Received {0} per second", numberOfMessages == 0 ? 0L : (1000 * (long)numberOfMessages) / (long)elapsedMilliseconds);
            }
            public async Task ReceiveMessages()
            {
                List <Task> tasks = new List <Task>();

                messageReceiver = factory.CreateMessageReceiver(queuename);
                stopwatch.Restart();
                stopwatch.Start();

                for (int i = 0; i < numberOfMessages; i++)
                {
                    tasks.Add(Task.Factory.StartNew(ReceiveMessage));
                }

                Task.WaitAll(tasks.ToArray());
                var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                Console.WriteLine("{0} messages received in {1} ms", numberOfMessages, elapsedMilliseconds);
                Console.WriteLine("Received {0} per second", numberOfMessages == 0 ? 0L : (1000 * (long)numberOfMessages) / (long)elapsedMilliseconds);
            }
Esempio n. 29
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();
        }
Esempio n. 30
0
            internal Binding(MessagingFactory messagingFactory, NamespaceManager namespaceManager, AzureQueueMqSettings settings, Action <string> logMessage, Action <string> logError)
            {
                var queueName = settings.QueueNameBuilderForSubscriber(typeof(T));

                _receiver = messagingFactory.CreateMessageReceiver(queueName, ReceiveMode.PeekLock);
                _excludeQueuesFromLogging = new LoggingConfiguration().ExcludeQueuesFromLogging();

                if (!namespaceManager.QueueExists(queueName))
                {
                    var queueDescription = new QueueDescription(queueName);
                    namespaceManager.CreateQueue(settings.QueueBuilderConfig(queueDescription, typeof(T)));
                }

                _receiver.OnMessage(message =>
                {
                    try
                    {
                        var bodyStream = message.GetBody <Stream>();

                        using (var reader = new StreamReader(bodyStream))
                        {
                            var body = reader.ReadToEnd();

                            if (!_excludeQueuesFromLogging.Contains(queueName))
                            {
                                logMessage($"Received '{queueName}': {body}");
                            }

                            Subject.OnNext(JObject.Parse(body)["data"].ToObject <T>());
                        }
                    }
                    catch (Exception ex)
                    {
                        logError($"Message {queueName}': {message} -> consumer error: {ex}");
                    }
                }, new OnMessageOptions {
                    AutoComplete = true
                });
            }
Esempio n. 31
0
        private static async Task <ReadResult> DoReadOperation(string connectionString, string path, TimeSpan timeout, bool useCached, Func <MessageReceiver, Task <ReadResult> > operation)
        {
            MessagingFactory mfactory      = null;
            MessageReceiver  requestClient = null;

            try
            {
                if (useCached)
                {
                    requestClient = ServiceBusMessagingFactory.Instance.GetMessageReceiver(connectionString, path, timeout);
                }
                else
                {
                    mfactory      = ServiceBusMessagingFactory.CreateMessagingFactoryWithTimeout(connectionString, timeout);
                    requestClient = mfactory.CreateMessageReceiver(path);
                }
                return(await operation.Invoke(requestClient).ConfigureAwait(false));
            }
            finally
            {
                requestClient?.Close();
                mfactory?.Close();
            }
        }
Esempio n. 32
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);
        }
        /// <summary>
        /// Creates a <see cref="MessageReceiver"/> for the specified ServiceBus entity.
        /// </summary>
        /// <remarks>
        /// You can override this method to customize the <see cref="MessageReceiver"/>.
        /// </remarks>
        /// <param name="factory">The <see cref="MessagingFactory"/> to use.</param>
        /// <param name="entityPath">The ServiceBus entity to create a <see cref="MessageReceiver"/> for.</param>
        /// <returns></returns>
        public virtual MessageReceiver CreateMessageReceiver(MessagingFactory factory, string entityPath)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (string.IsNullOrEmpty(entityPath))
            {
                throw new ArgumentNullException("entityPath");
            }

            MessageReceiver receiver = factory.CreateMessageReceiver(entityPath);
            receiver.PrefetchCount = _config.PrefetchCount;
            return receiver;
        }
Esempio n. 34
0
        static async Task RunDeviceEndpoint(IPEndPoint deviceEP, MessagingFactory messagingFactory)
        {
            var deviceServer = new TcpListener(deviceEP);
            deviceServer.Start(10);

            try
            {
                do
                {
                    TcpClient connection = await deviceServer.AcceptTcpClientAsync();
                    if (connection != null)
                    {
                        try
                        {
                            var pendingSessions = new Queue<string>();
                            connection.NoDelay = true; // flush writes immediately to the wire
                            connection.ReceiveTimeout = timeout;
                            NetworkStream deviceConnectionStream = connection.GetStream();
                            var readBuffer = new byte[64];
                            if (await deviceConnectionStream.ReadAsync(readBuffer, 0, 4) == 4)
                            {
                                int deviceId = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(readBuffer, 0));

                                try
                                {
                                    Task<BrokeredMessage> queueReceive = null;
                                    Task<int> socketRead = null;
                                    Task pingDelay = null;
                                    var cancelPing = new CancellationTokenSource();

                                    // set up the receiver for the per-device queue and senbder for the response queue
                                    var deviceQueueReceiver = messagingFactory.CreateMessageReceiver(string.Format("dev-{0:X8}", deviceId), ReceiveMode.PeekLock);
                                    var responseQueueSender = messagingFactory.CreateMessageSender(string.Format("ingress"));

                                    do
                                    {
                                        // receive from the queue
                                        queueReceive = queueReceive ?? deviceQueueReceiver.ReceiveAsync();
                                        // read from the socket
                                        socketRead = socketRead ?? deviceConnectionStream.ReadAsync(readBuffer, 0, 1);
                                        // ping delay
                                        pingDelay = pingDelay ?? Task.Delay(TimeSpan.FromSeconds(235), cancelPing.Token);

                                        // wait for any of the four operations (including completion) to be done
                                        var completedTask = await Task.WhenAny(queueReceive, socketRead, pingDelay, ClosingEvent.Task);

                                        if (completedTask == socketRead)
                                        {
                                            try
                                            {
                                                // read from the socket completed and not a ping
                                                if (socketRead.Result == 1)
                                                {
                                                    if (readBuffer[0] != PingFrame[0])
                                                    {
                                                        await responseQueueSender.SendAsync(new BrokeredMessage()
                                                            {
                                                                SessionId = pendingSessions.Dequeue(),
                                                                Properties = {{"Ack", (int) readBuffer[0]}}
                                                            });
                                                    }
                                                }
                                                else
                                                {
                                                    // no more data from the socket. Break out of the loop.
                                                    break;
                                                }
                                            }
                                            finally
                                            {
                                                socketRead = null;
                                            }
                                        }
                                        else if (completedTask == queueReceive)
                                        {
                                            try
                                            {
                                                // read from the queue completed
                                                var message = queueReceive.Result;
                                                if (message != null)
                                                {
                                                    var command = message.Properties["Cmd"] as string;
                                                    if (command != null)
                                                    {
                                                        switch (command.ToUpperInvariant())
                                                        {
                                                            case "ON":
                                                                pendingSessions.Enqueue(message.ReplyToSessionId);
                                                                await deviceConnectionStream.WriteAsync(OnFrame, 0, OnFrame.Length);
                                                                await message.CompleteAsync();
                                                                cancelPing.Cancel();
                                                                break;
                                                            case "OFF":
                                                                pendingSessions.Enqueue(message.ReplyToSessionId);
                                                                await deviceConnectionStream.WriteAsync(OffFrame, 0, OffFrame.Length);
                                                                await message.CompleteAsync();
                                                                cancelPing.Cancel();
                                                                break;
                                                        }
                                                    }
                                                }
                                            }
                                            finally
                                            {
                                                queueReceive = null;
                                            }
                                        }
                                        else if (completedTask == pingDelay)
                                        {
                                            try
                                            {
                                                if (pingDelay.IsCanceled)
                                                {
                                                    cancelPing = new CancellationTokenSource();
                                                }
                                                else
                                                {
                                                    await deviceConnectionStream.WriteAsync(PingFrame, 0, PingFrame.Length);
                                                }
                                            }
                                            finally
                                            {
                                                pingDelay = null;
                                            }
                                        }
                                        else
                                        {
                                            // closing event was fired
                                            break;
                                        }
                                    }
                                    while (true);
                                }
                                finally
                                {
                                    connection.Close();
                                }
                            }
                            else
                            {
                                connection.Close();
                            }
                        }
                        catch (SocketException se)
                        {
                            // log
                            Trace.TraceError(se.Message);
                            connection.Close();
                        }
                        catch (IOException e)
                        {
                            Trace.TraceError(e.Message);
                            connection.Close();
                        }
                        catch (Exception e)
                        {
                            Trace.TraceError(e.Message);
                        }
                    }
                } while (true);
            }
            finally
            {
                deviceServer.Stop();
            }
        }