Example #1
0
        public void InitialiseTopic()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            string connectionString = CloudConfigurationManager.GetSetting("ServiceBus.TopicConnectionString");

            _topicClient = SubscriptionClient.CreateFromConnectionString(connectionString, "recreateindex", "WebRoles");

            Task.Run(() =>
            {
                _topicClient.OnMessage(async receivedMessage =>
                {
                    var sequenceNumber = receivedMessage.SequenceNumber;
                    try
                    {
                        await _throttling.Execute(async() => ReCreateSearcher());
                    }
                    catch (Exception ex)
                    {
                        //no idea why it does not work but well, log it
                        Trace.TraceWarning("Exception occurred during the read of message '" + sequenceNumber + "': " + ex.Message);
                    }
                }, new OnMessageOptions {
                    AutoComplete = true
                });

                _completedEvent.WaitOne();
            });
        }
Example #2
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;
                }
            }
        }
        public void IsClosedCorrectlyReflectsStateOfObject()
        {
            var    ip            = "1.1.1.1";
            var    port          = 1883;
            var    eventData     = "Test data";
            string connectionKey = "123";
            var    moqSocket     = new MoqSocket();
            var    protocol      = new MqttClientProtocol(new LogCompositor(), moqSocket);
            var    bldr          = new MqttConnectMessageBuilder
            {
                ClientId = "UnitTest"
            };

            protocol.ConnectAsync(bldr, ip, port, SocketEncryption.None, eventData);

            var subscriptionItem = new SubscriptionItem
            {
                TopicName        = "a/b/+",
                QualityOfService = QualityOfService.AtMostOnce
            };

            var subClient = new SubscriptionClient(protocol, subscriptionItem, connectionKey);

            Assert.IsTrue(subClient.IsClosed);

            subClient.OnMessage(msg =>
            {
                Assert.IsNotNull(msg);
                Assert.IsTrue(msg.MessageType == MessageType.Publish);
            });

            Assert.IsFalse(subClient.IsClosed);
            subClient.Close();
            Assert.IsTrue(subClient.IsClosed);
        }
        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 #5
0
        public void InitialiseTopic()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            string connectionString = CloudConfigurationManager.GetSetting("ServiceBus.TopicConnectionString");
            _topicClient = SubscriptionClient.CreateFromConnectionString(connectionString, "recreateindex", "WebRoles");

            Task.Run(() =>
            {
                _topicClient.OnMessage(async receivedMessage =>
                {
                    var sequenceNumber = receivedMessage.SequenceNumber;
                    try
                    {
                        await _throttling.Execute(async () => ReCreateSearcher());
                    }
                    catch (Exception ex)
                    {
                        //no idea why it does not work but well, log it
                        Trace.TraceWarning("Exception occurred during the read of message '" + sequenceNumber + "': " + ex.Message);
                    }
                }, new OnMessageOptions {
                    AutoComplete = true
                });

                _completedEvent.WaitOne();
            });
        }
Example #6
0
        /// <summary>
        /// Subscribes to a stream of messages that match a .NET type.
        /// </summary>
        /// <typeparam name="T">The type to subscribe to</typeparam>
        /// <param name="onMessage">The action to run when a message arrives.</param>
        /// <param name="configure">The configure action.</param>
        public void Subscribe <T>(Action <T> onMessage, Action <ISubscriptionConfiguration> configure) where T : class
        {
            Type messageType = typeof(T);

            ISubscriptionConfiguration configuration = this.Configuration.SubscriptionConfiguration();

            configure(configuration);

            string topic = this.CreateTopicIfNotExists <T>(configuration);

            string realSubscriptionId = configuration.Subscription.ToLowerInvariant();

            if (!this.namespaceManager.SubscriptionExists(topic, realSubscriptionId))
            {
                SqlFilter filter = new SqlFilter(string.Format("[Message.Type.FullName] = '{0}'", messageType.FullName));
                SubscriptionDescription dataCollectionTopic = this.namespaceManager.CreateSubscription(topic, realSubscriptionId, filter);
            }

            string             descriptor = topic + ":" + realSubscriptionId;
            SubscriptionClient client     = this.subscriptionClients.GetOrAdd(
                descriptor,
                (d) =>
            {
                return(SubscriptionClient.CreateFromConnectionString(
                           this.Configuration.ConnectionString,
                           topic,
                           realSubscriptionId,
                           configuration.ReceiveMode));
            });

            OnMessageOptions options = new OnMessageOptions()
            {
                AutoComplete       = false,
                MaxConcurrentCalls = configuration.MaxConcurrentCalls
            };


            client.OnMessage(envelope =>
            {
                try
                {
                    this.Configuration.Logger.InfoFormat(
                        "Message was received on Subscription {0} Topic {1} with MessageId {2}",
                        realSubscriptionId,
                        topic,
                        envelope.MessageId);

                    object message = JsonConvert.DeserializeObject(envelope.GetBody <string>(), messageType);
                    onMessage(message as T);
                    envelope.Complete();
                }
                catch (Exception ex)
                {
                    this.Configuration.Logger.Fatal(ex);
                    envelope.Abandon();
                }
            },
                             options);
        }
        /// <summary>
        ///     Receives the messages in an endless asynchronous loop.
        /// </summary>
        private void ReceiveMessages(Action <BrokeredMessage> messageHandler)
        {
            var options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
            _client.OnMessage(msg => { messageHandler(msg); }, options);
        }
 public void OnMessage <T>(Action <T> handler)
 {
     _subscriptionClient.OnMessage(brokeredMessage =>
     {
         var message = GetMessage <T>(brokeredMessage);
         handler(message);
     });
 }
Example #9
0
        public void Subscribe <T>(string subscriptionId, Action <T> onMessage) where T : class
        {
            string topicName          = this.CreateTopicIfNotExists <T>();
            string realSubscriptionId = subscriptionId.ToLowerInvariant();

            if (!this.namespaceManager.SubscriptionExists(topicName, realSubscriptionId))
            {
                SubscriptionDescription dataCollectionTopic = this.namespaceManager.CreateSubscription(topicName, realSubscriptionId);
            }

            string descriptor = topicName + ":" + realSubscriptionId;

            subscriptionActions.AddOrUpdate(descriptor, new Delegate[] { onMessage }, (key, oldValue) => oldValue.Concat(new Delegate[] { onMessage }));

            Func <SubscriptionClient> clientSetup = () =>
            {
                SubscriptionClient client = SubscriptionClient.CreateFromConnectionString(
                    this.connectionString,
                    topicName,
                    realSubscriptionId,
                    ReceiveMode.PeekLock);

                OnMessageOptions options = new OnMessageOptions();
                options.AutoComplete       = true;
                options.MaxConcurrentCalls = 1;

                client.OnMessage(envelope =>
                {
                    if (!envelope.Properties.ContainsKey("Message.Type.AssemblyQualifiedName"))
                    {
                        envelope.DeadLetter();
                        return;
                    }

                    string messageTypeAssemblyQualifiedName = envelope.Properties["Message.Type.AssemblyQualifiedName"].ToString();

                    IEnumerable <Delegate> actions = subscriptionActions[descriptor]
                                                     .Where(a => a.GetType().GetGenericArguments().First().AssemblyQualifiedName == messageTypeAssemblyQualifiedName);

                    if (actions.Any())
                    {
                        Type messageType = actions.First().GetType().GetGenericArguments().First();

                        foreach (Delegate action in actions)
                        {
                            object message = JsonConvert.DeserializeObject(envelope.GetBody <string>(), messageType);

                            action.DynamicInvoke(message);
                        }
                    }
                },
                                 options);

                return(client);
            };

            this.subscriptionClients.GetOrAdd(descriptor, clientSetup.Invoke());
        }
Example #10
0
 public void Setup()
 {
     Client             = TopicClient.CreateFromConnectionString(ConnectionString, Path);
     SubscriptionClient =
         SubscriptionClient.CreateFromConnectionString(
             "Endpoint=sb://gensb-rt-dev.servicebus.windows.net/;SharedAccessKeyName=Listen;SharedAccessKey=2PBClMF5iwCyewaxGia84zpnvAIt9lCgwC1jx8ivObc=",
             Path, "persistence2");
     SubscriptionClient.OnMessage(MessageReceived);
 }
Example #11
0
 public void OnUpdateMessage(Action <BrokeredMessage> callback)
 {
     _subscriptionClient.OnMessage(callback, new OnMessageOptions
     {
         AutoComplete = false,
         //AutoRenewTimeout = TimeSpan.FromSeconds(10),
         MaxConcurrentCalls = 5
     });
 }
Example #12
0
        static void Main(string[] args)
        {
            string connectionString =
                ConfigurationManager.ConnectionStrings["AzureServiceBus"].ConnectionString;
            string topic = ConfigurationManager.AppSettings["Topic"];

            // here we create a subscription to all messages of a topic which is created for a specific Identify tenant
            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.SubscriptionExists(topic, "AllMessages"))
            {
                namespaceManager.CreateSubscription(topic, "AllMessages");
            }

            // create a client for the subcription above to receive message
            SubscriptionClient client =
                SubscriptionClient.CreateFromConnectionString(connectionString, topic, "AllMessages");

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

            client.OnMessage((message) =>
            {
                try
                {
                    // Process message from subscription.
                    Console.WriteLine("\n**Message**");
                    var stream = message.GetBody <Stream>();
                    stream.Seek(0, SeekOrigin.Begin);
                    var messageJson = new StreamReader(stream, Encoding.UTF8).ReadToEnd();

                    Console.WriteLine("MessageID: " + message.MessageId);
                    Console.WriteLine("CorrelationId: " + message.CorrelationId);
                    // This tells you what kind of event that happened on the Identify side
                    Console.WriteLine("MessageType: " + message.Properties["MessageType"]);
                    Console.WriteLine("AppId: " + message.Properties["AppId"]);
                    Console.WriteLine("MessageJson: " + messageJson);
                    // Remove message from subscription.
                    message.Complete();
                }
                // For demonstration purpose only. You know that you should never do generic code, right? :)
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    // Indicates a problem, unlock message in subscription.
                    message.Abandon();
                }
            }, options);

            Console.ReadLine();
        }
Example #13
0
        private static void ReceiveTopicMessages(SubscriptionClient subscriptionClient)
        {
            subscriptionClient.OnMessage(message =>
            {
                var text = message.GetBody <string>();

                Console.WriteLine("Received: " + text);
            }
                                         , new OnMessageOptions());
        }
Example #14
0
        public void Start()
        {
            var onMessageOptions = new OnMessageOptions()
            {
                AutoComplete       = false,
                MaxConcurrentCalls = _concurrentReceivers
            };

            _subscriptionClient.OnMessage(message => ProcessMessage(message), onMessageOptions);
        }
 public void OnMessage <T>(Action <T> anonymousMethod)
 {
     _subscriptionClient.OnMessage((message) => {
         var messageFormat = message.GetBody <T>();
         anonymousMethod(messageFormat);
     }, new OnMessageOptions()
     {
         MaxConcurrentCalls = 100
     });
 }
Example #16
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var host = new JobHost();

            Console.WriteLine("Subscriber Start");

            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, "Storm", "StormSubcription");

            // Configure the callback options.
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete = false;

            // options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    var data = message.GetBody <string>();

                    WarnDataset warnDataset = JsonConvert.DeserializeObject <WarnDataset>(data);

                    System.Data.Entity.Spatial.DbGeography shape = DbGeography.PolygonFromText(warnDataset.SHAPE.ToString(), 4326);


                    //System.Data.Entity.Spatial.DbGeography shape= DbGeography.PolygonFromText("POLYGON ((-95.08 38.04, -95.08 37.86, -94.69 37.87, -94.66 38.03, -95.08 38.04))", 4326);

                    // This code will move to another project

                    using (var db = new DataLakeEntities())
                    {
                        int insertWeatherDatasets = db.uspInsertWarningData(warnDataset.WARNINGTYPE, warnDataset.MESSAGEID, shape, warnDataset.ZTIME_END, warnDataset.ZTIME_START, warnDataset.ID, warnDataset.ISSUEWFO);
                    }

                    // Remove message from subscription.
                    message.Complete();
                }

                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    message.Abandon();
                }
            }, options);



            Console.ReadLine();

            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
Example #17
0
        private static void ReadTopic(SubscriptionClient client)
        {
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete = false;

            client.OnMessage(message =>
            {
                Console.WriteLine("[Message] " + message.GetBody <string>());
                message.Complete();
            }, options);
        }
Example #18
0
        private void ConnectToChatSession(string sessionId)
        {
            // Create new subscription that filters messages to that session ID
            chatSessionSubscriptionName = Guid.NewGuid().ToString();
            SqlFilter filter = new SqlFilter(string.Format("SessionId = '{0}'", sessionId));

            // Register a receiver on the subscription (filters by session ID)
            SubscriptionDescription subscriptionDescription = new SubscriptionDescription(chatTopicPath, chatSessionSubscriptionName);

            namespaceManager.CreateSubscription(subscriptionDescription, filter);
            chatSessionClient = SubscriptionClient.CreateFromConnectionString(serviceBusConnectionString, chatTopicPath, chatSessionSubscriptionName);
            chatSessionClient.OnMessage(ReceiveChatMessage);
        }
        public void StartSettingsWath()
        {
            _serviceBusHelper.CreateSubscription(_subscriptionName);
            _client = _serviceBusHelper.GetSubscriptionClient(_subscriptionName);

            _client.OnMessage(message =>
            {
                var newSettings = message.GetBody <Settings>();
                UpdateConfig(newSettings);
                MessageBox.Show($@"New part size: {newSettings.PartSize}");
                message.Complete();
            });
        }
        public void Start()
        {
            var factory = MessagingFactory.CreateFromConnectionString(_connectionString);

            _subscriptionClient = factory.CreateSubscriptionClient(_consumerProperties.QueueName, _consumerProperties.SubscriptionName);

            var options = new OnMessageOptions()
            {
                AutoComplete       = false,
                MaxConcurrentCalls = _consumerProperties.ConsumersQuantity,
                AutoRenewTimeout   = _consumerProperties.MessageLockTimeout
            };

            _subscriptionClient.OnMessage(Consume, options);
        }
Example #21
0
        public void Receive()
        {
            _client.OnMessage(m =>
            {
                Console.WriteLine("Message body: " + m.GetBody <String>());
                Console.WriteLine("Message id: " + m.MessageId);

                _client.Complete(m.LockToken);

                Thread.Sleep(1000);
            }, new OnMessageOptions()
            {
                AutoComplete = false
            });
        }
Example #22
0
        public InboundEventProvider(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;

            _topicClient = SubscriptionClient.CreateFromConnectionString(ServiceBusConfig.AzureEventingTopicConnectionString, Topics.EventingTopic, ServiceBusConfig.EventingTopicQueueName);

            // Configure the callback options.
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete       = true;
            options.AutoRenewTimeout   = TimeSpan.FromMinutes(1);
            options.MaxConcurrentCalls = 1;             // Indicates the maximum number of concurrent calls to the callback the pump should initiate

            _topicClient.OnMessage((message) =>
            {
                try
                {
                    if (message.Properties["Type"] != null && message.Properties["DepartmentId"] != null && message.Properties["ItemId"] != null)
                    {
                        switch ((EventingTypes)int.Parse(message.Properties["Type"].ToString()))
                        {
                        case EventingTypes.PersonnelStatusUpdated:
                            ProcessPersonnelStatusChanged?.Invoke(int.Parse(message.Properties["DepartmentId"].ToString()), int.Parse(message.Properties["ItemId"].ToString()));
                            break;

                        case EventingTypes.UnitStatusUpdated:
                            ProcessUnitStatusChanged?.Invoke(int.Parse(message.Properties["DepartmentId"].ToString()), int.Parse(message.Properties["ItemId"].ToString()));
                            break;

                        case EventingTypes.CallsUpdated:
                            ProcessCallStatusChanged?.Invoke(int.Parse(message.Properties["DepartmentId"].ToString()), int.Parse(message.Properties["ItemId"].ToString()));
                            break;

                        case EventingTypes.PersonnelStaffingUpdated:
                            ProcessPersonnelStaffingChanged?.Invoke(int.Parse(message.Properties["DepartmentId"].ToString()), int.Parse(message.Properties["ItemId"].ToString()));
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                }
            }, options);
        }
Example #23
0
        /// <summary>
        /// <see cref="MyCompany.Common.EventBus.IEventBus"/>
        /// </summary>
        public void RegisterHandler()
        {
            if (_readTopics != null)
            {
                var eventDrivenMessagingOptions = new OnMessageOptions();
                eventDrivenMessagingOptions.AutoComplete       = true;
                eventDrivenMessagingOptions.ExceptionReceived += OnExceptionReceived;
                eventDrivenMessagingOptions.MaxConcurrentCalls = 5;

                foreach (var topic in _readTopics)
                {
                    SubscriptionClient client = SubscriptionClient.CreateFromConnectionString(_connectionString, topic, _subscriptionName);
                    client.OnMessage(OnMessageArrived, eventDrivenMessagingOptions);
                }
            }
        }
Example #24
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var host = new JobHost();

            Console.WriteLine("Subscriber Start");

            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, "Weather", "WeatherSubcription");

            // Configure the callback options.
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete = false;

            // options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    var data = message.GetBody <string>();

                    WeatherDatasets weatherDatasets = JsonConvert.DeserializeObject <WeatherDatasets>(data);

                    // This code will move to another project

                    using (var db = new DataLakeEntities())
                    {
                        int insertWeatherDatasets = db.uspInsertWeatherDatasetsData(weatherDatasets.date, weatherDatasets.datatype, weatherDatasets.station, weatherDatasets.attributes, weatherDatasets.value);
                    }

                    // Remove message from subscription.
                    message.Complete();
                }

                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    message.Abandon();
                }
            }, options);


            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
Example #25
0
        private void CreateSubscription()
        {
            if (!namespaceManager.TopicExists(topicName))
            {
                namespaceManager.CreateTopic(topicName);
            }

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

            var messagingFactory = MessagingFactory.Create(namespaceManager.Address, namespaceManager.Settings.TokenProvider);

            subscriptionClient = messagingFactory.CreateSubscriptionClient(topicName, subscriptionName);
            subscriptionClient.OnMessage(ProcessMessage);
        }
Example #26
0
        private void Form1_Load(object sender, EventArgs e)
        {
            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Client.OnMessage((message) =>
            {
                try
                {
                    // Process message from subscription.
                    l("Echo: " + message.GetBody <string>());

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

            new Thread(() =>
            {
                try
                {
                    l("Loading");
                    storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(Properties.Settings.Default.storage);

                    ps = new PublicStore(storageAccount, "base");

                    dlog = new log("base", "LogsAdminDebug", storageAccount);

                    this.Invoke((MethodInvoker) delegate()
                    {
                        this.toolStrip1.Visible = true;
                    });

                    g("Load successful");
                }
                catch (Exception ex1)
                {
                    ex(System.Reflection.MethodBase.GetCurrentMethod().Name + " " + ex1.ToString());
                }
            }).Start();
        }
 protected override void ListenInternal(Action<Message> onMessageReceived, CancellationToken cancellationToken)
 {
     _handleMessage = onMessageReceived;
     var options = new OnMessageOptions
     {
         MaxConcurrentCalls = 10
     };
     if (Pattern == MessagePattern.PublishSubscribe)
     {
         _subscriptionClient.OnMessage(Handle, options);
     }
     else
     {
         _queueClient.OnMessage(Handle, options);
     }
     cancellationToken.WaitHandle.WaitOne();
 }
Example #28
0
        /// <summary>
        /// Method to Receive a message from a subscription
        /// </summary>
        /// <param name="userName">the username of the user to get messages</param>
        public static void ReceiveMessageSubscription(string userName)
        {
            //to avoid any typo, lower the string
            string userNameLow = userName.ToLowerInvariant();

            //Retrieve the connection string
            string connectionString =
                ConfigurationManager.AppSettings["Service.Bus.ConnectionString"] ?? null;

            if (connectionString != null)
            {
                //Retrieve the topic's name
                string topicName = ConfigurationManager.AppSettings["Service.Bus.Topic"];

                //Create the subscription client object
                SubscriptionClient Client =
                    SubscriptionClient.CreateFromConnectionString
                        (connectionString, topicName, userNameLow);

                // Configure the callback options
                OnMessageOptions options = new OnMessageOptions();
                //enable manual control of the method complete
                options.AutoComplete = false;
                //Every 5 seconds we check for new messages
                options.AutoRenewTimeout = TimeSpan.FromSeconds(5);

                Client.OnMessage((message) =>
                {
                    try
                    {
                        // Process message from subscription
                        Console.WriteLine("\n**Message Received!**");
                        Console.WriteLine("\t" + message.GetBody <string>());
                        Console.WriteLine("\n");

                        // Remove message from subscription.
                        message.Complete();
                    }
                    catch (Exception)
                    {
                        // Indicates a problem, unlock message in subscription
                        message.Abandon();
                    }
                }, options);
            }
        }
Example #29
0
        //Not in use
        public string SubscribeMessage(string Topic, string Subcription)
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, Topic, Subcription);

            // Configure the callback options.

            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete = false;

            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            string msg = string.Empty;

            Client.OnMessage((message) =>
            {
                try

                {
                    // Process message from subscription.

                    // Console.WriteLine("\n**High Messages**");
                    msg = message.GetBody <string>();
                    //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);

            return(msg);
        }
Example #30
0
        public ResponsePipeline(ITopicFactory topicFactory)
        {
            // Since we're in a constructor, we can't use the await keyword, so we'll wait the old fashioned synchonous way.
            // The clientTask.Wait() is a blocking call. This call doesn't actually create the subscription, we do that on
            // pre-application initialization, since it's faster to do it once for the whole app up-front, instead of lazily
            // somwhere buried in a constructor, plus doing it lazily causes a dead-lock.
            var requestSubscriptionName = string.Format(Settings.ServiceBusResponseSubscriptionNameFormat, Environment.MachineName);
            var clientTask = topicFactory.CreateSubscriptionClientAsync(Settings.ServiceBusResponseTopicName, requestSubscriptionName);

            clientTask.Wait();

            // Do a quick check to ensure that the task didn't throw an exception and wasn't cancelled.
            if (clientTask.IsFaulted || clientTask.IsCanceled)
            {
                throw new ServiceBusException($"Failed to create and subscribe to the response topic for subscription '{requestSubscriptionName}'.", clientTask.Exception);
            }

            // Store the result in a local field as we don't want it to be garbage collected.
            _responseSubscription = clientTask.Result;

            // We only get one shot at processing the message, because the SubscriptionClient is set to ReceiveAndDelete.
            // This means that we don't have to call Complete() or Abandon() on messages, and also means we only need
            // one call to service bus to handle a message. We are publishing the message into an observable sequence
            // which will ensure only one thread handles the message at a time (even if there are multiple subscribers
            // to the observable sequence), but we'll set the MaxConcurrentCalls to something greater than 1, because the
            // observable sequence will hold the messages in memory while they are waiting to be processed. The
            // combination of these qualities means we can essentially prefetch messages while we are processing a
            // message. This does create multiple threads for each message, but the observable sequence will synchronize
            // them all back to the same thread. It's a small price to pay for prefetching ability.
            var options = new OnMessageOptions
            {
                AutoComplete       = true,
                MaxConcurrentCalls = 5  // Drain 5 at a time into memory, so we can do a bit of prefetching.
            };

            // Using the OnMessage delegate will handle the internal polling (or sockets, depending on mode) for us.
            // When we receive a message, we'll push it through the observable sequence. The OnNext() call will block
            // until all subscriptions have received the message, but we don't have any heavy processing happening, so
            // it's not a big deal and we are using ReceiveAndDelete anyways, so it doesn't matter how long the OnNext()
            // call takes.
            _responseSubscription.OnMessage(bm =>
            {
                _responseMessages.OnNext(bm);
            }, options);
        }
Example #31
0
        public AzureTopicAsyncResult(ManualResetEvent @event, SubscriptionClient subscriptionClient)
        {
            m_Event = @event;
            m_SubscriptionClient   = subscriptionClient;
            IsCompleted            = false;
            CompletedSynchronously = false;
            var options = new OnMessageOptions();

            options.AutoComplete     = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
            m_SubscriptionClient.OnMessage(message =>
            {
                m_BrokeredMessage = message.Clone();
                message.Complete();
                CompletedSynchronously = true;
                m_Event.Set();
            }, options);
        }
Example #32
0
        public bool Start(string dmsTallerId)
        {
            try
            {
                //connectionString = ConfigurationManager.AppSettings["CitaTallerAzureBusSubscribe"];
                var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
                if (!namespaceManager.SubscriptionExists(topicName, SubscripName))
                {
                    // Defino un filtro para un taller. Y creo la suscripción con ese filtro.
                    dmsTallerId = dmsTallerId.Replace("-", "").Trim().ToUpper();
                    if (string.IsNullOrEmpty(dmsTallerId))
                        {
                        namespaceManager.CreateSubscription(topicName, SubscripName);
                        }
                    else
                        {
                        SqlFilter DmsTallerIdFilter = new SqlFilter("DmsTallerId = '" + dmsTallerId + "'");
                        namespaceManager.CreateSubscription(topicName, SubscripName, DmsTallerIdFilter);
                        }
                }
                // Creo un cliente para este NameSpace + Topic + Subscription
                Client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, SubscripName);
                Connected = true;
                // Defino las opciones para el callback (evento)
                ClientOptions = new OnMessageOptions();
                ClientOptions.AutoComplete = false;
                ClientOptions.MaxConcurrentCalls = 1;
                ClientOptions.AutoRenewTimeout = TimeSpan.FromMinutes(1);
            }
            catch (Exception ex)
            {
                Connected = false;
                ErrorMsg(ex.Message);
            }

                // Definimos el callback (event)
            Client.OnMessage((busMessage) =>
            {
                try
                {
                    if (Closing)
                    {
                        busMessage.Abandon();
                        return;
                    }

                    Message message = new Message();
                    message.SolicitudID = busMessage.Properties["SolicitudID"].ToString();
                    message.DmsTallerId = busMessage.Properties["DmsTallerId"].ToString();

                    OcxOnMessage(message);
                    // Eliminamos el mensaje de la suscripción
                    busMessage.Complete();
                }
                catch (Exception ex)
                {
                    // Hemos tenido un crash. Liberamos el mensaje y quedará pendiente.
                    busMessage.Abandon();
                    ErrorMsg(ex.Message);
                }
            }, ClientOptions);
            return true;
        }
        public void StartEvents(Action<CheckEvent> action)
        {
            using (new TraceLogicalScope(source, "StartEvents"))
            {
                try
                {
                    eventPath = String.Format("{0}/Events", dc);

                    eventSubscription = String.Format("{0}-{1}-Subscription", node, dc);

                    this.source.TraceData(TraceEventType.Verbose, 0, new object[] { "Path", eventPath });

                    string connectionString = configuration.ServiceBus.ConnectionString;

                    this.source.TraceData(TraceEventType.Verbose, 0, new object[] { "ConnectionString", connectionString });

                    this.CreateTopic(dc, eventPath);

                    this.CreateCheckEventSubscription(dc, eventPath, eventSubscription);

                    OnMessageOptions options = new OnMessageOptions()
                    {
                        AutoComplete = true, // Indicates if the message-pump should call complete on messages after the callback has completed processing.
                        MaxConcurrentCalls = 1 // Indicates the maximum number of concurrent calls to the callback the pump should initiate
                    };

                    if(this.eventClient != null)
                        this.StopEvents();

                    this.eventClient = SubscriptionClient.CreateFromConnectionString(connectionString, eventPath, eventSubscription, ReceiveMode.PeekLock);

                    eventClient.OnMessage((BrokeredMessage message) =>
                    {
                        using(new TraceLogicalScope(source, "Receiving a message"))
                        {
                            try
                            {
                                if (message != null)
                                {
                                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CheckEvent));

                                    CheckEvent ev = serializer.ReadObject(message.GetBody<Stream>()) as CheckEvent;

                                    action.Invoke(ev);
                                }
                            }
                            catch(Exception ex)
                            {
                                source.TraceData(TraceEventType.Error, 0, ex);

                                throw;
                            }
                        }
                    }, options);

                    source.TraceEvent(TraceEventType.Verbose, 0, "Listening for Events...");
                }
                catch (Exception ex)
                {
                    source.TraceData(TraceEventType.Error, 0, ex);

                    throw;
                }
            }
        }