static void Main(string[] args)
        {
            if (!ArgsAreValid(args))
            {
                OutputProgramIntroText();
                Console.WriteLine("Press Enter to exit...");
                Console.ReadLine();
                return;
            }

            string topicName        = args[0];
            string subscriptionName = args[1];
            string connectionString = args[2];

            try
            {
                var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName, ReceiveMode.ReceiveAndDelete);
                var options            = new OnMessageOptions
                {
                    AutoComplete       = true,
                    MaxConcurrentCalls = 1
                };

                Console.WriteLine($"Listening for messages on topic '{topicName}'...");
                Console.WriteLine("Press Ctrl+C to exit.");
                subscriptionClient.OnMessage(ReceiveMessage, options);
                Console.ReadLine();
            }
            catch (Exception exc)
            {
                Console.WriteLine($"General error. Exiting program.\n\nError Message: '{exc.Message}'\n\nStackTrace: '{exc.StackTrace}'");
            }
        }
        private void AddQueueHandler(string queueName)
        {
#if NETSTANDARD2_0
            var sbClient = new QueueClient(address, queueName, ReceiveMode.PeekLock);
            var sbWorker = new ServiceBusMqWorker(this, CreateMessageQueueClient(), queueName, sbClient);
            sbClient.RegisterMessageHandler(sbWorker.HandleMessageAsync,
                                            new MessageHandlerOptions(
                                                (eventArgs) => Task.CompletedTask)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            });
#else
            var options = new OnMessageOptions
            {
                // Cannot use AutoComplete because our HandleMessage throws errors into SS's handlers; this would
                // normally release the BrokeredMessage back to the Azure Service Bus queue, which we don't actually want

                AutoComplete = false,
                //AutoRenewTimeout = new TimeSpan()
                MaxConcurrentCalls = 1
            };

            var sbClient = QueueClient.CreateFromConnectionString(address, queueName, ReceiveMode.PeekLock);
            var sbWorker = new ServiceBusMqWorker(this, CreateMessageQueueClient(), queueName, sbClient);
            sbClient.OnMessage(sbWorker.HandleMessage, options);
#endif
            sbClients.GetOrAdd(queueName, sbClient);
        }
Example #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Process D2C Interactive Messages app\n");

            //this queue1's listen policy connection string
            string      connectionString = "Endpoint=sb://jziotservicebus1.servicebus.windows.net/;SharedAccessKeyName=listen;SharedAccessKey=2nZxyOMO14bo+plZXkcekNgGPHRJNdQ1ok2TMeSMo/g=;EntityPath=queue1";
            QueueClient Client           = QueueClient.CreateFromConnectionString(connectionString);

            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    var bodyStream      = message.GetBody <Stream>();
                    bodyStream.Position = 0;
                    var bodyAsString    = new StreamReader(bodyStream, Encoding.ASCII).ReadToEnd();

                    Console.WriteLine("Received message: {0} messageId: {1}", bodyAsString, message.MessageId);

                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receiving interactive messages from SB queue...");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Example #4
0
        public PushNotification()
        {
            var subscriptionName = Guid.NewGuid().ToString();
            var namespaceMgr     = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]);

            var subscriptionDescription = new SubscriptionDescription(ConfigurationManager.AppSettings["Microsoft.ServiceBus.Topic.Name"], subscriptionName)
            {
                AutoDeleteOnIdle = TimeSpan.FromMinutes(5)
            };

            namespaceMgr.CreateSubscription(subscriptionDescription);

            subscriptionClient = SubscriptionClient.CreateFromConnectionString(
                ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"],
                ConfigurationManager.AppSettings["Microsoft.ServiceBus.Topic.Name"],
                subscriptionName);

            var onMessageOptions = new OnMessageOptions()
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            subscriptionClient.OnMessage(message => ProcessMessage(message), onMessageOptions);
        }
Example #5
0
        private static void ProcesarComentario()
        {
            QueueClient Client =
                QueueClient.CreateFromConnectionString(connectionString, ColaComentarios);

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

            // Callback to handle received messages.
            Client.OnMessage((message) =>
            {
                try
                {
                    var comentario = message.GetBody <ComentarioModel>();
                    RepositorioMongoDbComentario.Agregar(comentario);

                    // Remove message from queue.
                    message.Complete();
                    ComentarioHub.NotificarComentarioNuevo(comentario);
                }
                catch (Exception)
                {
                    // Indicates a problem, unlock message in queue.
                    message.Abandon();
                }
            }, options);
        }
Example #6
0
        public void StartHandler(string IdUser)
        {
            serviceBusManager = new ServiceBusManager();

            try {
                TimeSpan         RenewTimeout = TimeSpan.FromSeconds(1);
                OnMessageOptions options      = new OnMessageOptions {
                    AutoComplete = false, MaxConcurrentCalls = 1, AutoRenewTimeout = RenewTimeout
                };


                serviceBusManager.GetClient().OnMessageAsync(async brokerMessage => {
                    try {
                        if (brokerMessage.SessionId == (IdUser))
                        {
                            var message = brokerMessage.GetBody <Stream>();
                            serviceBusManager.Message = JsonConvert.DeserializeObject <KindAds.Common.Models.Notification>(new StreamReader(message, true).ReadToEnd());
                            notification = serviceBusManager.Message;
                            await brokerMessage.CompleteAsync();
                            serviceBusManager.Close();

                            //Send to client
                            SendNotification(notification.Title, notification.Message);
                        }
                    }
                    catch (Exception e) {
                        brokerMessage.Abandon();
                    }
                }, options);
            }
            catch (Exception e) {
                var messageException = telemetry.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name);
                telemetry.Critical(messageException);
            }
        }
        private static void HandleCompanyTopic(string connectionString)
        {
            var clientCompany = SubscriptionClient.CreateFromConnectionString(connectionString, Constants.TopicName, Constants.Topics.Company.ToString());
            var options       = new OnMessageOptions {
                AutoComplete = false
            };


            clientCompany.OnMessage((message) =>
            {
                try
                {
                    // Process message from subscription.
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("\n**Company Application**");
                    Console.WriteLine("Body: " + message.GetBody <Applicant>());
                    Console.WriteLine("MessageID: " + message.MessageId);
                    Console.WriteLine("Application Type: " + message.Properties[Constants.CustomProperties.ApplicationType.ToString()]);

                    // Remove message from subscription.
                    message.Complete();
                }
                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    Console.WriteLine(ex.Message);
                    message.Abandon();
                }
            }, options);
        }
Example #8
0
        public Receiver(MessageReceiver messageReceiver, Uri inputAddress, IPipe<ReceiveContext> receivePipe, ReceiveSettings receiveSettings,
            IReceiveObserver receiveObserver, ITaskSupervisor supervisor)
        {
            _messageReceiver = messageReceiver;
            _inputAddress = inputAddress;
            _receivePipe = receivePipe;
            _receiveSettings = receiveSettings;
            _receiveObserver = receiveObserver;
            _supervisor = supervisor;

            _participant = supervisor.CreateParticipant();

            var options = new OnMessageOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = receiveSettings.AutoRenewTimeout,
                MaxConcurrentCalls = receiveSettings.MaxConcurrentCalls
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (_log.IsErrorEnabled)
                    _log.Error($"Exception received on receiver: {_inputAddress} during {x.Action}", x.Exception);

                _participant.SetComplete();
            };

            messageReceiver.OnMessageAsync(OnMessage, options);

            _participant.SetReady();

            SetupStopTask();
        }
Example #9
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();
        }
Example #10
0
        // consumes messages from the cloud's queue and prints it to console every 3 seconds
        static void Main(string[] args)
        {
            string connectionString =
                CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            QueueClient Client =
              QueueClient.CreateFromConnectionString(connectionString, QUEUE_NAME);

            // Configure the callback options.
            OnMessageOptions options = new OnMessageOptions();
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMilliseconds(3000);

            // Callback to handle received messages.
            Client.OnMessage((message) =>
            {
                try
                {
                    // Process message from queue.
                    Console.WriteLine("Body: " + message.GetBody<string>());
                    Console.WriteLine("MessageID: " + message.MessageId);
                    Console.WriteLine("Test Property: " +
                    message.Properties["TestProperty"]);

                    // Remove message from queue.
                    message.Complete();
                }
                catch (Exception)
                {
                    // Indicates a problem, unlock message in queue.
                    message.Abandon();
                }
            }, options);

            Console.ReadKey();
        }
Example #11
0
        static void Main(string[] args)
        {
            var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            QueueClient client = QueueClient.CreateFromConnectionString(connectionString, "MyQueue1");

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

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

            Console.WriteLine("Receving Messages Complete");
            Console.ReadLine();
        }
Example #12
0
        public override void OnMessage(OnMessageAction callback, OnMessageOptions options)
        {
            if (this.factory.OpenConnection())
            {
                if (this.session == null)
                {
                    this.session = new Session(this.factory.Connection);
                    this.link    = new ReceiverLink(this.session, "amqp-receive-link " + this.Path, this.Path);
                }

                // start the message pump
                this.link.Start(1,
                                (r, m) =>
                {
                    if (m != null)
                    {
                        BrokeredMessage brokeredMessage = new BrokeredMessage(m);
                        callback(brokeredMessage);

                        //  if autocomplete requested
                        if (options.AutoComplete)
                        {
                            r.Accept(m);
                        }
                    }
                });
            }
        }
Example #13
0
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                string connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

                SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, this.TopicName, this.SubscriptionName);

                // Configure the callback options.
                OnMessageOptions options = new OnMessageOptions();
                options.AutoComplete = false;
                options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

                Client.OnMessage((message) =>
                {
                    try
                    {
                        // Process message from subscription.
                        string body = message.GetBody<string>();
                        Trace.WriteLine(this.ConsumerName + " processed message : " + body);

                        // Remove message from subscription.
                        message.Complete();
                    }
                    catch (Exception)
                    {
                        // Indicates a problem, unlock message in subscription.
                        message.Abandon();
                    }
                }, options);
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Process D2C Interactive Messages app\n");

            string      connectionString = "Endpoint=sb://vetudainteractivemessaging.servicebus.windows.net/;SharedAccessKeyName=listen;SharedAccessKey=59egv6WVaN6XqOOQKSWJIyFlwKpFd6HUQR0kq1JrzQY=;EntityPath=d2cinteractive";
            QueueClient Client           = QueueClient.CreateFromConnectionString(connectionString);

            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    var bodyStream      = message.GetBody <Stream>();
                    bodyStream.Position = 0;
                    var bodyAsString    = new StreamReader(bodyStream, Encoding.ASCII).ReadToEnd();

                    Console.WriteLine("Received message: {0} messageId: {1}", bodyAsString, message.MessageId);

                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receiving interactive messages from SB queue...");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
        private void StartSubscriptionClient()
        {
            string connectionString = CloudConfigurationManager.GetSetting("SInnovations.Servicebus.ConnectionString");

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            TopicDescription td = new TopicDescription(TopicName);

            td.MaxSizeInMegabytes       = 512;
            td.DefaultMessageTimeToLive = new TimeSpan(0, 5, 0);

            if (!namespaceManager.TopicExists(TopicName))
            {
                namespaceManager.CreateTopic(td);
            }
            if (!namespaceManager.SubscriptionExists(TopicName, AllMessages))
            {
                namespaceManager.CreateSubscription(TopicName, AllMessages);
            }


            Client = SubscriptionClient.CreateFromConnectionString
                         (connectionString, TopicName, AllMessages);
            var options = new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 10
            };

            options.ExceptionReceived += options_ExceptionReceived;

            Client.OnMessageAsync(OnMessageAsync, options);
            CompletedEvent.WaitOne();
        }
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 public ServiceBusConfiguration()
 {
     MessageOptions = new OnMessageOptions
     {
         MaxConcurrentCalls = 16
     };
 }
        // it runs in a separate thread, so if it crashes it will not terminate the main thread of the ConsoleApp
        public void RunAndBlock()
        {
            CancellationTokenSrc = new CancellationTokenSource();
            Utils.Logger.Info("***CommandQueueHost: start listening");

            // Receive BusQueue message
            OnMessageOptions options = new OnMessageOptions();   // Configure the callback options.
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
            if (gCommandQueueClient != null)
                gCommandQueueClient.OnMessage((receivedMessage) =>
                {
                    // The queueClient.OnMessage() ReceiveMessage always gets a new Thread from a Threadpool.
                    // If that crashes that will not crash the Main thread of the ConsoleExe app; neither crash the QueueHost.RunAndBlock() that waits for these Messages

                    //from "StorageQueue vs ServiceBusQueue vs. EventHub.txt"
                    //Service Bus Queue performance:
                    //1.Devoloping and running it on the PC locally; queue requests go to Azure datacenter:
                    //> first message arrives after 450msec, because the queueClient has to be created once
                    //> next messages using the same queueClient arrives in 39, 45, 60 msec.Great
                    // > which is fine, because we don't poll it every 5 seconds. Great subscriber model.
                    //2.When WebJob, and WedApp are both in the same Azure datacentre where the queue is. I measure 14msec to 500msec times. A typical: 50msec
                    ProcessReceivedMessage(receivedMessage);
                }, options);

            CancellationTokenSrc.Token.WaitHandle.WaitOne();    // wait forever or until cancelled
            Utils.Logger.Info("*CommandQueueHost: end listening");
        }
        public void Initialize(EntityInfoInternal entity, Func <IncomingMessageDetailsInternal, ReceiveContextInternal, Task> callback, Func <Exception, Task> errorCallback, Action <Exception> criticalError, Func <ErrorContext, Task <ErrorHandleResult> > processingFailureCallback, int maximumConcurrency)
        {
            incomingCallback               = callback;
            this.criticalError             = criticalError;
            this.errorCallback             = errorCallback ?? EmptyErrorCallback;
            this.processingFailureCallback = processingFailureCallback;
            this.entity = entity;

            fullPath = entity.Path;
            if (entity.Type == EntityType.Subscription)
            {
                var topic = entity.RelationShips.First(r => r.Type == EntityRelationShipTypeInternal.Subscription);
                fullPath = SubscriptionClient.FormatSubscriptionPath(topic.Target.Path, entity.Path);
            }

            wrapInScope = settings.TransportTransactionMode == TransportTransactionMode.SendsAtomicWithReceive;
            // batching will be applied for transaction modes other than SendsAtomicWithReceive
            completionCanBeBatched = !wrapInScope;

            var numberOfClients = settings.NumberOfClients;
            var concurrency     = maximumConcurrency / (double)numberOfClients;

            maxConcurrentCalls = concurrency > 1 ? (int)Math.Round(concurrency, MidpointRounding.AwayFromZero) : 1;
            if (Math.Abs(maxConcurrentCalls - concurrency) > 0)
            {
                logger.InfoFormat("The maximum concurrency on message receiver instance for '{0}' has been adjusted to '{1}', because the total maximum concurrency '{2}' wasn't divisable by the number of clients '{3}'", fullPath, maxConcurrentCalls, maximumConcurrency, numberOfClients);
            }

            internalReceivers = new IMessageReceiverInternal[numberOfClients];
            onMessageOptions  = new OnMessageOptions[numberOfClients];

            // when we don't batch we don't need the completion infrastructure
            completion = completionCanBeBatched ? new MultiProducerConcurrentCompletion <Guid>(1000, TimeSpan.FromSeconds(1), 6, numberOfClients) : null;
        }
Example #19
0
        public void Subscribe <TSubscriber>(Func <TSubscriber> subscriberFactory) where TSubscriber : IBusSubscriber
        {
            var subscriberType = typeof(TSubscriber);

            TryToManageServiceBus <TSubscriber>();

            // TODO: Use UGS' listener
            var subscriptionClient = SubscriptionClient.CreateFromConnectionString(
                GetServiceBusConnectionString(),
                TopicName,
                SubscriptionName);

            var onMessageOptions = new OnMessageOptions
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            onMessageOptions.ExceptionReceived += MessageReceivingException;

            try
            {
                subscriptionClient.OnMessageAsync((message) => ProcessBrokeredMessage(subscriberFactory, message),
                                                  onMessageOptions);
            }
            catch (Exception ex)
            {
                _logger.Error("Unable to subscribe to UGS Service bus. Missing subscription?", ex);
                throw;
            }
            SubscriberClients.Add(subscriberType, subscriptionClient);
        }
Example #20
0
        static void Main(string[] args)
        {
            Console.WriteLine("Process D2C Interactive Messages app\n");

            string      connectionString = "{service bus listen connection string}";
            QueueClient Client           = QueueClient.CreateFromConnectionString(connectionString, "d2cnesh");

            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    var bodyStream      = message.GetBody <Stream>();
                    bodyStream.Position = 0;
                    var bodyAsString    = new StreamReader(bodyStream, Encoding.ASCII).ReadToEnd();

                    Console.WriteLine("Received message: {0} messageId: {1}", bodyAsString, message.MessageId);

                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receiving interactive messages from SB queue...");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Example #21
0
        static void Main(string[] args)
        {
            //Add an item into a queue named mikepfq
            var conn = "Endpoint=sb://mikepfsb.servicebus.windows.net/;SharedAccessKeyName=mypolicy;SharedAccessKey=[update me];EntityPath=mikepfq";

            var client = QueueClient.CreateFromConnectionString(conn);

            var message = new BrokeredMessage("Hello world!");

            client.Send(message);

            //Read the message
            var options = new OnMessageOptions
            {
                AutoComplete = false
            };

            client.OnMessage(m =>
            {
                Console.WriteLine("Message: " + m.GetBody <string>());
                m.Complete();
            }, options);

            Console.ReadKey();
        }
Example #22
0
        static void ReceiveAndProcessPizzaOrdesUsingOnMessage(int threads)
        {
            // Create a new client
            m_QueueClient = QueueClient.CreateFromConnectionString
                                (PizzaStationSettings.ConnectionString, PizzaStationSettings.QueueName);

            // Set the options for using OnMessage
            var options = new OnMessageOptions()
            {
                AutoComplete       = false,
                MaxConcurrentCalls = threads,
                AutoRenewTimeout   = TimeSpan.FromSeconds(30)
            };

            // Create a message pump using OnMessage
            m_QueueClient.OnMessage(message =>
            {
                // Deserializse the message body
                var order = message.GetBody <PizzaOrder>();

                // Process the message
                CookPizza(order);

                // Complete the message
                message.Complete();
            }, options);


            Console.WriteLine("Receiving, hit enter to exit");
            Console.ReadLine();
            StopReceiving();
        }
        private static void RegisterOnMessageCallback(SubscriptionClient client)
        {
            var options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            client.OnMessage((message) =>
            {
                try
                {
                    // Process message from subscription.
                    Console.WriteLine("Body: " + message.GetBody <string>());
                    Console.WriteLine("MessageID: " + message.MessageId);
                    Console.WriteLine("Message Number: " + message.Properties["MessageNumber"]);

                    // Remove message from subscription.
                    message.Complete();
                }
                catch (Exception)
                {
                    // Indicates a problem, unlock message in subscription.
                    message.Abandon();
                }
            }, options);
        }
Example #24
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();
        }
        public void Initialize(EntityInfo entity, Func <IncomingMessageDetails, ReceiveContext, Task> callback, Func <Exception, Task> errorCallback, Func <ErrorContext, Task <ErrorHandleResult> > processingFailureCallback, int maximumConcurrency)
        {
            receiveMode = settings.Get <ReceiveMode>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.ReceiveMode);

            incomingCallback               = callback;
            this.errorCallback             = errorCallback ?? EmptyErrorCallback;
            this.processingFailureCallback = processingFailureCallback;
            this.entity = entity;

            fullPath = entity.Path;
            if (entity.Type == EntityType.Subscription)
            {
                var topic = entity.RelationShips.First(r => r.Type == EntityRelationShipType.Subscription);
                fullPath = SubscriptionClient.FormatSubscriptionPath(topic.Target.Path, entity.Path);
            }

            var transportTransactionMode = settings.HasExplicitValue <TransportTransactionMode>() ? settings.Get <TransportTransactionMode>() : settings.SupportedTransactionMode();

            wrapInScope            = transportTransactionMode == TransportTransactionMode.SendsAtomicWithReceive;
            completionCanBeBatched = !wrapInScope;
            autoRenewTimeout       = settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.AutoRenewTimeout);
            numberOfClients        = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.NumberOfClientsPerEntity);
            var concurrency = maximumConcurrency / (double)numberOfClients;

            maxConcurrentCalls = concurrency > 1 ? (int)Math.Round(concurrency, MidpointRounding.AwayFromZero) : 1;
            if (Math.Abs(maxConcurrentCalls - concurrency) > 0)
            {
                logger.InfoFormat("The maximum concurrency on message receiver instance for '{0}' has been adjusted to '{1}', because the total maximum concurrency '{2}' wasn't divisable by the number of clients '{3}'", fullPath, maxConcurrentCalls, maximumConcurrency, numberOfClients);
            }

            internalReceivers = new IMessageReceiver[numberOfClients];
            onMessageOptions  = new OnMessageOptions[numberOfClients];
            completion        = new MultiProducerConcurrentCompletion <Guid>(1000, TimeSpan.FromSeconds(1), 6, numberOfClients);
        }
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            string testConnection = "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=abc123=";

            _messagingFactory = MessagingFactory.CreateFromConnectionString(testConnection);
            OnMessageOptions messageOptions = new OnMessageOptions();

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageOptions);

            ServiceBusConfiguration config = new ServiceBusConfiguration
            {
                MessageOptions = messageOptions
            };

            _mockMessagingProvider   = new Mock <MessagingProvider>(MockBehavior.Strict, config);
            config.MessagingProvider = _mockMessagingProvider.Object;

            _mockMessagingProvider.Setup(p => p.CreateMessageProcessor(_entityPath))
            .Returns(_mockMessageProcessor.Object);

            ServiceBusTriggerExecutor triggerExecutor = new ServiceBusTriggerExecutor(_mockExecutor.Object);

            _listener = new ServiceBusListener(_messagingFactory, _entityPath, triggerExecutor, config);
        }
        public AzureServiceBusSubscriptionService(string connectionString, ILogger logger)
        {
            if (String.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString));
            if (logger == null) throw new ArgumentNullException(nameof(logger));

            _connectionString = connectionString;
            _logger = logger;

            var namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);
            _clients = new Dictionary<string, SubscriptionClient>();
            foreach (var topic in TOPICS)
            {
                var subscriptionName = getSubscriptionName(topic);
                if (!namespaceManager.SubscriptionExists(topic, subscriptionName))
                {
                    var description = new SubscriptionDescription(topic, subscriptionName);
                    description.DefaultMessageTimeToLive = TOPIC_MESSAGE_TTL;
                    namespaceManager.CreateSubscription(description);
                }
                _clients.Add(topic, SubscriptionClient.CreateFromConnectionString(
                    _connectionString,
                    topic,
                    subscriptionName,
                    ReceiveMode.ReceiveAndDelete));
            }

            _messageOptions = new OnMessageOptions()
            {
                AutoComplete = false,
                AutoRenewTimeout = TimeSpan.FromMinutes(1)
            };
        }
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 public ServiceBusConfiguration()
 {
     MessageOptions = new OnMessageOptions
     {
         MaxConcurrentCalls = 16
     };
 }
Example #29
0
        protected virtual void RegisterReceiverMessageHandler(Action <BrokeredMessage> receiverMessageHandler, OnMessageOptions receiverMessageHandlerOptions)
        {
            ReceiverMessageHandler        = receiverMessageHandler;
            ReceiverMessageHandlerOptions = receiverMessageHandlerOptions;

            ServiceBusReceiver.OnMessage(ReceiverMessageHandler, ReceiverMessageHandlerOptions);
        }
Example #30
0
        static void Main(string[] args)
        {
            Console.WriteLine("Process D2C Interactive Messages app\n");

            string connectionString = "{service bus listen connection string}";
            QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "d2cnesh");

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

            Client.OnMessage((message) =>
            {
                try
                {
                    var bodyStream = message.GetBody<Stream>();
                    bodyStream.Position = 0;
                    var bodyAsString = new StreamReader(bodyStream, Encoding.ASCII).ReadToEnd();

                    Console.WriteLine("Received message: {0} messageId: {1}", bodyAsString, message.MessageId);

                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receiving interactive messages from SB queue...");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
 /// <summary>
 ///     Start listening to the message bus
 /// </summary>
 public override void Start()
 {
     var messageOptions = new OnMessageOptions();
     messageOptions.AutoComplete = false;
     messageOptions.ExceptionReceived += ProcessExceptionRecieved;
     CurrentSubscription.OnMessage(ProcessRecievedMessage, messageOptions);
 }
        private void Start()
        {
            try
            {
                var options = new OnMessageOptions
                {
                    AutoComplete     = false,
                    AutoRenewTimeout = TimeSpan.FromMinutes(1)
                };
                options.ExceptionReceived += LogErrors;

                Client.OnMessageAsync(async brokerMessage =>
                {
                    try
                    {
                        var body    = brokerMessage.GetBody <string>();
                        var obj     = JsonConvert.DeserializeObject <Message>(body);
                        var context = GlobalHost.ConnectionManager.GetHubContext <NotificationHub>();
                        await context.Clients.All.SendMessage(obj.Body);
                        brokerMessage.Complete();
                    }
                    catch (Exception ex)
                    {
                        brokerMessage.Abandon();
                    }
                }, options);
            }
            catch
            {
                Start();
            }
        }
Example #33
0
        private static void ReceiveMessageUsingOnMessage(int concurrentMessages)
        {
            _queueClient = QueueClient.CreateFromConnectionString(_connectionString, _queueName);

            var options = new OnMessageOptions()
            {
                AutoComplete       = false,
                MaxConcurrentCalls = concurrentMessages,
                AutoRenewTimeout   = TimeSpan.FromSeconds(30)
            };

            //Creates a message pump
            _queueClient.OnMessage(message =>
            {
                var sr = message.GetBody <ServiceRequest>();
                ProcessServiceRequest(sr);
                message.Complete();
            }, options);

            Console.WriteLine("Type exit to stop receiving messages");
            var resposne = Console.ReadLine();

            if (resposne.Equals("exit"))
            {
                StopReceiving();
            }
        }
        async Task InitializeAndStartReceiver(int i, ConcurrentQueue <Exception> exceptions)
        {
            try
            {
                var internalReceiver = await clientEntities.Get(fullPath, entity.Namespace.Alias)
                                       .ConfigureAwait(false);

                var options = new OnMessageOptions
                {
                    AutoComplete       = false,
                    AutoRenewTimeout   = settings.AutoRenewTimeout,
                    MaxConcurrentCalls = maxConcurrentCalls
                };
                options.ExceptionReceived += OptionsOnExceptionReceived;
                internalReceivers[i]       = internalReceiver ?? throw new Exception($"MessageReceiverNotifier did not get a MessageReceiver instance for entity path {fullPath}, this is probably due to a misconfiguration of the topology");
                onMessageOptions[i]        = options;

                internalReceiver.OnMessage(m => ReceiveMessage(internalReceiver, m, i, pipelineInvocationTasks), options);

                isRunning = true;
            }
            catch (Exception ex)
            {
                exceptions.Enqueue(ex);
            }
        }
Example #35
0
        public static void DoWork(bool SB)
        {
            System.Threading.ThreadPool.SetMaxThreads(10, 10);
            var connectionString = "Endpoint=sb://servicebus-namespace-2.servicebus.windows.net/;SharedAccessKeyName=servicebus-env-002-servicebus-namespace-2-pankil;SharedAccessKey=856mIAhotFSpkSXA0uts2uXmn4Ud87k9w21Vb5ZsBew=";
            var topicName        = "main-topic-env-002-servicebus-namespace-2";
            var subscriptionName = "AllocationOrchestration_Pankil/$DeadLetterQueue";
            SubscriptionClient subscriptionClient = null;

            //int i = 0;
            while (true)
            {
                try
                {
                    OnMessageOptions options = new OnMessageOptions();
                    options.AutoComplete       = false;
                    options.MaxConcurrentCalls = 10;

                    subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName, ReceiveMode.PeekLock);

                    subscriptionClient.OnMessage(msg =>
                    {
                        Console.WriteLine(string.Format("{0}: Thread Started: {1}", DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.fff"), msg.CorrelationId));
                        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(AnotherLongTask), msg);
                    }, options);
                }
                catch (Exception ex)
                {
                    //Log Error
                }
                finally
                {
                    subscriptionClient = null;
                }
            }
        }
        static void ReceiveQueueMessages(QueueClient Client)
        {
            // Configure the callback options.
            OnMessageOptions options = new OnMessageOptions();
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            // Callback to handle received messages.
            Client.OnMessage((message) =>
            {
                try
                {
                    // Process message from queue.
                    Console.WriteLine("Body: " + message.GetBody<string>());
                    Console.WriteLine("MessageID: " + message.MessageId);
                    Console.WriteLine("Test Property: " +
                    message.Properties["TestProperty"]);

                    // Remove message from queue.
                    message.Complete();
                }
                catch (Exception)
                {
                    // Indicates a problem, unlock message in queue.
                    message.Abandon();
                }
            }, options);
            Console.ReadLine();
        }
Example #37
0
        private void SetGreaterThenSubscription(MessagingFactory factory, NamespaceManager namespaceManager)
        {
            if (!namespaceManager.SubscriptionExists(this._currentTopic, "GreaterThenSubscription"))
            {
                return;
            }

            var client  = factory.CreateSubscriptionClient(this._currentTopic, "GreaterThenSubscription");
            var options = new OnMessageOptions
            {
                AutoComplete     = false,
                AutoRenewTimeout = TimeSpan.FromMinutes(1)
            };

            client.OnMessage((message) =>
            {
                try
                {
                    var m = message.GetBody <string>();
                    this._sync.Send(arg =>
                    {
                        GreaterThenMessages.Add(m);
                    }, null);
                }
                catch (Exception ex)
                {
                    message.Abandon();
                }
            }, options);
        }
Example #38
0
        static void Main(string[] args)
        {
            var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            QueueClient client = QueueClient.CreateFromConnectionString(connectionString, "MyQueue1");

            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

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

            Console.WriteLine("Receving Messages Complete");
            Console.ReadLine();
        }
        public async Task StartListening(TriggerConfig triggerInput)
        {
            // Configure the callback options
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete       = false;
            options.MaxConcurrentCalls = 10;

            // create the relevant client and the onMessage listener
            if (triggerInput.QueueName != null && triggerInput.QueueName.Length > 1)
            {
                queueReceiver = messagingFactory.CreateQueueClient(triggerInput.QueueName, ReceiveMode.PeekLock);
                queueReceiver.OnMessageAsync(async message =>
                {
                    await processMessage(message, logMessageStub);
                }, options);
                isListening = true;
            }
            else
            {
                subscriptionReceiver = messagingFactory.CreateSubscriptionClient(triggerInput.TopicName, triggerInput.SubscriptionName, ReceiveMode.PeekLock);
                subscriptionReceiver.OnMessageAsync(async message =>
                {
                    await processMessage(message, logMessageStub);
                }, options);
                isListening = true;
            }
        }
Example #40
0
 public void Start(Func<BrokeredMessage, Task> messageHandler)
 {
     var options = new OnMessageOptions {MaxConcurrentCalls = 1};
     //_client.RetryPolicy = new RetryExponential();
     options.ExceptionReceived += (sender, args) => OnException(sender as BrokeredMessage, (dynamic) args.Exception);
     _client.OnMessageAsync(messageHandler, options);
 }
Example #41
0
        static void Main(string[] args)
        {
            Console.WriteLine("Process D2C Interactive Messages app\n");

            string connectionString = "Endpoint=sb://devneuzyhubsb2.servicebus.windows.net/;SharedAccessKeyName=listen;SharedAccessKey=8ZGE4q+yUg2V3crhVd+kWHN/mf4UdqvKZDxAhaF63EA=";
            QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "d2ctutorial");

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

            Client.OnMessage((message) =>
            {
                try
                {
                    var bodyStream = message.GetBody<Stream>();
                    bodyStream.Position = 0;
                    var bodyAsString = new StreamReader(bodyStream, Encoding.ASCII).ReadToEnd();

                    Console.WriteLine("Received message: {0} messageId: {1}", bodyAsString, message.MessageId);

                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receiving interactive messages from SB queue...");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Example #42
0
        static void Main(string[] args)
        {
            Console.WriteLine("Process D2C Interactive Messages app\n");

            string      connectionString = "HostName=srramdemo.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=Wj7vlYAiMTQIjdDe+niS3IRmn6ZoTUU9rYeEisZjmHU=";
            QueueClient Client           = QueueClient.CreateFromConnectionString(connectionString, "d2ctutorial");

            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    var bodyStream      = message.GetBody <Stream>();
                    bodyStream.Position = 0;
                    var bodyAsString    = new StreamReader(bodyStream, Encoding.ASCII).ReadToEnd();

                    Console.WriteLine("Received message: {0} messageId: {1}", bodyAsString, message.MessageId);

                    message.Complete();
                }
                catch (Exception)
                {
                    message.Abandon();
                }
            }, options);

            Console.WriteLine("Receiving interactive messages from SB queue...");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Example #43
0
        public Receiver(MessageReceiver messageReceiver, Uri inputAddress, IPipe <ReceiveContext> receivePipe, ReceiveSettings receiveSettings,
                        IReceiveObserver receiveObserver, ITaskSupervisor supervisor)
        {
            _messageReceiver = messageReceiver;
            _inputAddress    = inputAddress;
            _receivePipe     = receivePipe;
            _receiveSettings = receiveSettings;
            _receiveObserver = receiveObserver;
            _supervisor      = supervisor;

            _participant = supervisor.CreateParticipant();

            var options = new OnMessageOptions
            {
                AutoComplete       = false,
                AutoRenewTimeout   = receiveSettings.AutoRenewTimeout,
                MaxConcurrentCalls = receiveSettings.MaxConcurrentCalls
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Error($"Exception received on receiver: {_inputAddress} during {x.Action}", x.Exception);
                }

                _participant.SetComplete();
            };

            messageReceiver.OnMessageAsync(OnMessage, options);

            _participant.SetReady();

            SetupStopTask();
        }
Example #44
0
        public static void LookupNotification()
        {
            QueueClient qc = QueueClient.CreateFromConnectionString(
                sbQueueAdminConnectinString,
                sbQueueName);
            OnMessageOptions options = new OnMessageOptions();
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            // Callback to handle received messages.
            qc.OnMessage((message) =>
            {
                try
                {
                    // Process message from event processor host.
                    if (message.Properties.Keys.Contains("message-source") && (string)message.Properties["message-source"] == "evh")
                    {
                        var o = message.GetBody<System.IO.Stream>();
                        using (var r = new StreamReader(o))
                        {
                            var msg = r.ReadToEnd();
                            Console.WriteLine("Body: " + msg);
                            Console.WriteLine("MessageID: " + message.MessageId);
                            SendNotificationAsync(msg);
                            // Remove message from queue.
                            message.Complete();
                        }

                    }
                    else
                    {
                        // Process message from stream analytics.
                        var msg = message.GetBody<string>();
                        
                            Console.WriteLine("Body: " + msg);
                            Console.WriteLine("MessageID: " + message.MessageId);
                            SendNotificationAsync(msg);
                            // Remove message from queue.
                            message.Complete();
                    }
                }
                catch (Exception exp)
                {
                    // Indicates a problem, unlock message in queue.
                    Console.WriteLine("EXCEPTION:" + exp.Message);
                    if(exp.InnerException != null)
                    {
                        Console.WriteLine("INNER:" + exp.Message);
                    }
                    if(exp.StackTrace != null)
                    {
                        Console.WriteLine($"Stack:{exp.StackTrace}");
                    }
                    message.Abandon();
                    //message.Complete();
                }
            }, options);
        }
        /// <summary>
        /// Constructs a new instance.
        /// </summary>
        /// <param name="messageOptions">The <see cref="OnMessageOptions"/> to use.</param>
        public MessageProcessor(OnMessageOptions messageOptions)
        {
            if (messageOptions == null)
            {
                throw new ArgumentNullException("messageOptions");
            }

            MessageOptions = messageOptions;
        }
Example #46
0
        static void Main(string[] args)
        {
            //initialize, then poll Azure Service Bus for new messages
            Initialize();

            //initialize Service Bus Queue
            WriteLog("INFO", string.Format("Connecting to service bus topic {0}", AzureServiceBusTopicName.ToString()));
            SubscriptionClient sbClient = SubscriptionClient.CreateFromConnectionString(connectionString, AzureServiceBusTopicName, AzureServiceBusSubscriptionName);

            OnMessageOptions option = new OnMessageOptions();
            option.AutoComplete = false; //we'll manually pop message out of queue after processing it
            option.AutoRenewTimeout = TimeSpan.FromSeconds(10);
            option.MaxConcurrentCalls = 1; //only pull one message at a time

            //prep for continuous run
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                _quitEvent.Set();
                eArgs.Cancel = true;
            };

            // wait for incoming message
            sbClient.OnMessage((message) =>
            {
                try
                {
                    WriteLog("INFO", "New message received.");
                    foreach (var prop in message.Properties)
                    {
                        WriteLog("INFO", string.Format("Message Property: {0}:{1}", prop.Key, prop.Value));

                    }

                    //process call to API
                    ProcessMessage(message);

                    //remove message from subscription
                    message.Complete();
                }
                catch (Exception ex)
                {
                    //leave message in queue
                    message.Abandon();

                    WriteLog("ERROR", ex.Message);
                }
            }, option);

            //wait
            WriteLog("INFO", "Polling....");

            _quitEvent.WaitOne();

            // cleanup/shutdown and quit
            if (!sbClient.IsClosed) { sbClient.Close(); }
        }
Example #47
0
        public Handler()
        {
            string connectionString =
              CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "TestingQueue");

            OnMessageOptions options = new OnMessageOptions();
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            _client = Client;
            _options = options;
        }
        public void Initialize(EndpointAddress inputAddress, EndpointAddress errorAddress)
        {
            QueueUtilities.CreateQueue(inputAddress.QueueName);

            var inputQueueClient = QueueClient.Create(inputAddress.QueueName);
            var options = new OnMessageOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = TimeSpan.FromMinutes(1),
                MaxConcurrentCalls = 1
            };
            inputQueueClient.OnMessage(OnMessage, options);
        }
        public void ProcessMessagesForSubscription() {
            var gt = typeof(IReceivedMessage<>).MakeGenericType(data.EndPointData.MessageType);
            methodInfo = data.EndPointData.DeclaredType.GetMethod("Handle", new Type[] { gt });

            options = new OnMessageOptions() {
                AutoComplete = false,
                MaxConcurrentCalls = Math.Max(1, data.EndPointData.AttributeData.MaxConcurrentCalls) //Make the app webscale
            };
            options.ExceptionReceived += options_ExceptionReceived;

            //ProcessMessagesForSubscriptionLegacy();
            ProcessMessagesForSubscriptionAzure();
        }
        public override async Task StartAsyncCore(CancellationToken cancellationToken)
        {

            cancellationToken.ThrowIfCancellationRequested();

            _messageWrapper.CreateTopicIfDoesntExistSilent(_globalSettings.DiscoTopicName, 1024, new TimeSpan(2, 0, 0, 0));

            var eventDrivenMessagingOptions = new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 5 };
            eventDrivenMessagingOptions.ExceptionReceived += OnExceptionReceived;

            _receiver = await _messageWrapper.CreateMessageReceiverAsync(_globalSettings.DiscoTopicName, "Notifications", ReceiveMode.PeekLock);
            _receiver.OnMessageAsync(ProcessMessageAsync, eventDrivenMessagingOptions);
        }
        private void GetQueueMessage()
        {
            string connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
              //CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            QueueClient Client =
              QueueClient.CreateFromConnectionString(connectionString, ConfigurationManager.AppSettings["ServiceBus.Queue.Name"]);

            // Configure the callback options
            OnMessageOptions options = new OnMessageOptions();
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            /*
            // Callback to handle received messages
            Client.OnMessage((message) =>
            {
                try
                {
                    // Process message from queue
                    Response.Write("Body: " + message.GetBody<string>());
                    Response.Write("MessageID: " + message.MessageId);
                    Response.Write("Name: " +
                    message.Properties["Name"]);
                    Label1.Text = "MessageID: " + message.MessageId + " Name: " + message.Properties["Name"];
                    // Remove message from queue
                    message.Complete();
                }
                catch (Exception exc)
                {
                    // Indicates a problem, unlock message in queue
                    Label1.Text = "Recv: " + exc.Message;
                    message.Abandon();
                }
            }, options);
            */
            BrokeredMessage message = Client.Receive(new TimeSpan(0,0,3));
            try
            {
                if (message != null)
                {
                    //Label1.Text = " Name: " + message.Properties["Name"] + " Time: " + message.Properties["Time"];
                    message.Complete();
                }
                else Label1.Text = "NULL";
            }
            catch(Exception exc)
            {
                Label1.Text = exc.Message;
            }
            Client.Close();
        }
        public EventTopicSubscriber(string connectionString, string topicName, string subscriptionName, 
            OnMessageOptions options, IEventDispatcher eventDispatcher, ILogger logger)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName))
                namespaceManager.CreateSubscription(topicName, subscriptionName);

            _client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName);
            _options = options;
            _eventDispatcher = eventDispatcher;
            _logger = logger;
            _stopEvent = new ManualResetEvent(false);
        }
Example #53
0
        private void process()
        {
            var queueName = Startup.Configuration["AppSettings:LogQueueName"];
            var sbConnString = Startup.Configuration["Data:ServiceBusConnection"];
            var queueClient = QueueClient.CreateFromConnectionString(sbConnString, queueName);

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

            queueClient.OnMessage((message) =>
            {
                try
                {
                    var msgBody = message.GetBody<string>();

                    

                    var serializer = new XmlSerializer(typeof(DivineLog));

                    var divineLog = (DivineLog)serializer.Deserialize(new StringReader(msgBody));


                    var loggerHub = connectionManager;
                    // var loggerHub = new DivineLoggerHub();
                    JsonSerializer jsonSerializer = new JsonSerializer();
                    jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    var serializedLog = JObject.FromObject(divineLog, jsonSerializer);
                    //logger.LogInformation("LogViewer_ServiceBus_Receiver", "JObject Deserialized " + divineLog.Message);
                    DivineSocket.SendAsync(serializedLog.ToString(Formatting.None));
                    loggerHub.Clients.All.broadCastLog(divineLog);
                    //logger.LogInformation("LogViewer_ServiceBus_Receiver", "Sent to all client " + divineLog.Message);
                    message.Complete();
                }
                catch (Exception ex)
                {
                    //logger.LogError("LogViewer_ServiceBus_Receiver", ex.Message, exception: ex);
                    Debug.WriteLine("ERRRRROR::" + ex.Message);

                    message.Abandon();
                }
            }, options);

        }
Example #54
0
        static void Main(string[] args)
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            QueueClient queue = QueueClient.CreateFromConnectionString(connectionString, "contentitems");

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

            

            queue.OnMessage((message) =>
            {
                try
                {
                    string messageBody = message.GetBody<string>();
                    Console.WriteLine("Body: " + messageBody);
                    //WriteLineToFile("Body: " + message.GetBody<string>());

                    Order order = JsonConvert.DeserializeObject<Order>(messageBody);

                    Console.WriteLine("Order : " + order.Id + ":" + order.Customer.Name);

                    Console.WriteLine("Message Id: " + message.MessageId);
                    //WriteLineToFile("Message Id: " + message.MessageId);

                    Console.WriteLine("Property.Id " + message.Properties["id"]);
                    //WriteLineToFile("Property.Id " + message.Properties["id"]);

                    message.Complete();
                    //WriteLineToFile("Message Completed");
                }
                catch (Exception exp)
                {
                    message.Abandon();
                    Console.WriteLine(exp.Message + ":Abandon");
                    //WriteLineToFile("Abandon");
                }
            }, options);


            Console.ReadLine();

        }
        public override void Run()
        {
            try
            {
                var nsManager = NamespaceManager.CreateFromConnectionString(CommonResources.ConnectionStrings.AzureServiceBus);
                if (!nsManager.QueueExists(QueueName))
                    nsManager.CreateQueue(QueueName);

                _client = QueueClient.CreateFromConnectionString(CommonResources.ConnectionStrings.AzureServiceBus, QueueName);
                _client.PrefetchCount = 10;

                var eventDrivenMessagingOptions = new OnMessageOptions
                {
                    AutoComplete = true,
                    MaxConcurrentCalls = 10
                };
                eventDrivenMessagingOptions.ExceptionReceived += OnExceptionReceived;

                Console.WriteLine(" > {0} - Sending {1} test messages", DateTime.Now, MsgsToSend);
                Stopwatch.Start();
                SendMessages();
                Stopwatch.Stop();
                Console.WriteLine(" > {0} - {1} of {2} sent in {3} ms", DateTime.Now, MsgsToSend, MsgsToSend, Stopwatch.ElapsedMilliseconds);

                Thread.Sleep(2000);
                Console.WriteLine(" > {0} - Recieving {1} test messages", DateTime.Now, MsgsToSend);
                Stopwatch.Restart();
                _client.OnMessage(OnMessageArrived, eventDrivenMessagingOptions);

                Console.WriteLine("Press any key to close connection");
            }
            catch (Exception ex)
            {
                Console.WriteLine(" > Exception received: {0}",
                    ex.Message);
            }
            finally
            {
                Console.ReadLine();
                _client.Close();
            }

            Console.WriteLine("Press any key to close application");
            Console.ReadLine();
        }
        public async Task CompleteProcessingMessageAsync_Failure_AbandonsMessage()
        {
            OnMessageOptions options = new OnMessageOptions
            {
                AutoComplete = false
            };
            MessageProcessor processor = new MessageProcessor(options);

            BrokeredMessage message = new BrokeredMessage();
            FunctionResult result = new FunctionResult(false);
            var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
            {
                await processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None);
            });

            // this verifies that we initiated the abandon
            Assert.True(ex.ToString().Contains("Microsoft.ServiceBus.Messaging.BrokeredMessage.BeginAbandon"));
        }
        public void ReceiveMessages(string subscription, Func<BrokeredMessage, Task> processMessageTask)
        {
            var options = new OnMessageOptions();
            options.AutoComplete = true;
            options.MaxConcurrentCalls = 10;
            options.ExceptionReceived += this.OptionsOnExceptionReceived;

            this.subscriptionClient.OnMessageAsync(
                 async (msg) =>
                 {
                     // Will block the current thread if Stop is called.
                     this.pauseProcessingEvent.WaitOne();

                     // Execute processing task here
                     await processMessageTask(msg);
                 },
                 options);
        }
Example #58
0
        public Receiver(NamespaceContext context, ClientContext clientContext, IPipe<ReceiveContext> receivePipe, ClientSettings clientSettings,
            ITaskSupervisor supervisor, ISendEndpointProvider sendEndpointProvider, IPublishEndpointProvider publishEndpointProvider)
        {
            _context = context;
            _clientContext = clientContext;
            _receivePipe = receivePipe;
            _clientSettings = clientSettings;
            _sendEndpointProvider = sendEndpointProvider;
            _publishEndpointProvider = publishEndpointProvider;

            _tracker = new DeliveryTracker(DeliveryComplete);

            _participant = supervisor.CreateParticipant($"{TypeMetadataCache<Receiver>.ShortName} - {clientContext.InputAddress}", Stop);

            var options = new OnMessageOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = clientSettings.AutoRenewTimeout,
                MaxConcurrentCalls = clientSettings.MaxConcurrentCalls
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (!(x.Exception is OperationCanceledException))
                {
                    if (_log.IsErrorEnabled)
                        _log.Error($"Exception received on receiver: {clientContext.InputAddress} during {x.Action}", x.Exception);
                }

                if (_tracker.ActiveDeliveryCount == 0)
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Receiver shutdown completed: {0}", clientContext.InputAddress);

                    _participant.SetComplete();
                }
            };

            clientContext.OnMessageAsync(OnMessage, options);

            _participant.SetReady();
        }
        public async Task CompleteProcessingMessageAsync_Success_CompletesMessage_WhenAutoCompleteFalse()
        {
            OnMessageOptions options = new OnMessageOptions
            {
                AutoComplete = false
            };
            MessageProcessor processor = new MessageProcessor(options);

            BrokeredMessage message = new BrokeredMessage();
            FunctionResult result = new FunctionResult(true);
            var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
            {
                await processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None);
            });

            // The service bus APIs aren't unit testable, so in this test suite
            // we rely on exception stacks to verify APIs are called as expected.
            // this verifies that we initiated the completion
            Assert.True(ex.ToString().Contains("Microsoft.ServiceBus.Messaging.BrokeredMessage.BeginComplete"));
        }
        public async Task SubscribeToQueue()
        {
            if (_messageDispatcher == null) throw new Exception("No dispatcher registered");

            var options = new OnMessageOptions { MaxConcurrentCalls = _concurrentHandlerLimit };
            var receiver = await GetSubscriptionClient();
            receiver.OnMessageAsync(async (message) =>
            {
                try
                {
                    await _messageDispatcher.DispatchAsync(message);
                }
                catch (Exception e)
                {
                    message.Abandon();
                    _logger.Error(e, "OnReceiveSubscriptionMessageReceiver Error handling message {0}. Exception: {1}", message.MessageId, e.Message);
                }

            }, options);
        }