コード例 #1
0
        public SubscriptionClient CreateSubscription(string subscriptionName, string roleInstanceId)
        {
            InitializeTopics();

            // If an existing subscription is there, delete it, so we can update the filter
            if (_namespaceManager.SubscriptionExists(_commandsForJobHostTopicName, subscriptionName))
            {
                _namespaceManager.DeleteSubscription(_commandsForJobHostTopicName, subscriptionName);
            }

            // Create the subscription again with the most up2date filter
            var desc = new SubscriptionDescription(_commandsForJobHostTopicName, subscriptionName);

            _namespaceManager.CreateSubscription
            (
                desc,
                new SqlFilter
                (
                    string.Format(@"{0} = '{1}'", GlobalConstants.SERVICEBUS_MESSAGE_PROP_ROLEINSTANCEID, roleInstanceId)
                )
            );

            // Subscribe with the subscription client
            var client = SubscriptionClient.CreateFromConnectionString(
                _connectionString,
                _commandsForJobHostTopicName,
                subscriptionName);

            client.RetryPolicy = RetryPolicy.Default;

            return(client);
        }
コード例 #2
0
        private static void ReceiveMessage()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;;

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

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

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

                #region With Collection
                //IEnumerable<BrokeredMessage> receivedMessageList = receiver.ReceiveBatch(2);
                //try
                //{
                //    foreach (var item in receivedMessageList)
                //    {
                //        ProcessMessage(item);
                //        item.Complete();
                //    }
                //    factory.Close();
                //    _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory");
                //    //_namespaceManager.DeleteSubscription("DataCollectionTopic", "Dashboard");
                //    //_namespaceManager.DeleteTopic("DataCollectionTopic");
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex.ToString());
                //}
                #endregion
            }
        }
コード例 #3
0
 private static void DeleteTopicSubscriptions(string topic)
 {
     if (nsManager.SubscriptionExists(topic, "DangeorusHomeTemperatureMessages"))
     {
         nsManager.DeleteSubscription(topic, "DangeorusHomeTemperatureMessages");
     }
     if (nsManager.SubscriptionExists(topic, "DangeorusCarTemperatureMessages"))
     {
         nsManager.DeleteSubscription(topic, "DangeorusCarTemperatureMessages");
     }
     if (nsManager.SubscriptionExists(topic, "TheftMessages"))
     {
         nsManager.DeleteSubscription(topic, "TheftMessages");
     }
 }
コード例 #4
0
        public void TestSubscription()
        {
            string           name         = "testSubscription";
            string           topicName    = "testTopicSubscription";
            NamespaceManager ns           = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);
            TopicDescription tdescription = ns.CreateTopic(topicName);

            Assert.IsTrue(null != tdescription);
            SubscriptionDescription sdescription = ns.CreateSubscription(topicName, name);

            Assert.IsTrue(null != sdescription);

            if (!ns.SubscriptionExists(topicName, name, out sdescription))
            {
                Assert.Fail("Subscription did not exist");
            }
            else
            {
                Assert.IsTrue(null != sdescription);
                ns.DeleteSubscription(topicName, name);
                if (ns.SubscriptionExists(topicName, name, out sdescription))
                {
                    Assert.Fail("Subscription was not deleted");
                }

                ns.DeleteTopic(topicName);
                if (ns.TopicExists(name, out tdescription))
                {
                    Assert.Fail("Topic was not deleted");
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Method is used for abandoned subscriptions deleting (subscriptions to temporaries queues on fanout topics).
        /// Should be fixed in new Masstransit releases.
        /// </summary>
        /// <param name="settings">Service bus settings.</param>
        private static void DeleteAbandonedSubscriptions(ServiceBusSettings settings)
        {
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri("sb", settings.AzureNamespace, string.Empty);
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", settings.AzureSharedAccessKey, TokenScope.Namespace);
            var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

            var queues = namespaceManager.GetQueues().Select(q => $"{namespaceManager.Address.AbsoluteUri.ToLower()}{q.Path.ToLower()}").ToList();

            var toExecute = new List <Action>();

            foreach (var topic in namespaceManager.GetTopics().Where(t => t.SubscriptionCount > 0))
            {
                foreach (var subscription in namespaceManager.GetSubscriptions(topic.Path).Where(s => !string.IsNullOrEmpty(s.ForwardTo)))
                {
                    if (!queues.Contains(subscription.ForwardTo.ToLower()))
                    {
                        toExecute.Add(() =>
                        {
                            namespaceManager.DeleteSubscription(topic.Path, subscription.Name);
                            Log.Information("Abandoned subscription removed: {topic} -> {subscription} -> {queue}",
                                            topic.Path, subscription.Name, subscription.ForwardTo);
                        });
                    }

                    Log.Debug("Found abandoned subscription: {topic} -> {subscription} -> {queue}", topic.Path, subscription.Name, subscription.ForwardTo);
                }
            }

            foreach (var execute in toExecute)
            {
                execute();
            }
        }
コード例 #6
0
        static void ReceiveMessage()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;

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

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    receivedMessage.Abandon();
                }
            }
        }
コード例 #7
0
ファイル: ChatViewModel.cs プロジェクト: pcbl/SampleSolution
        public void ConnectOrDisconnect(string username)
        {
            bool isConnecting = !IsConnected;

            IsConnected = !IsConnected;
            if (isConnecting)
            {
                //let´s create a new SenderID
                _senderId = Guid.NewGuid();
                var subscription = _busClient.CreateSubscription(_topicName, _senderId.ToString());
                //The subscription will delete itself when iddle more than 5 minutes!
                //That will be used case the application crashes
                subscription.AutoDeleteOnIdle = new TimeSpan(0, 5, 0);

                //Now we will use the subscription we just created and will create a Subscription Client
                //The idea is to print all messages that we receive!
                _currentSubscription = SubscriptionClient.CreateFromConnectionString(_connectionString, _topicName, _senderId.ToString());
                _currentSubscription.OnMessage(WhenMessageArrives);

                //Sending has joined message
                Send("**just joined**");
            }
            else
            {
                //Close subscription Client
                _currentSubscription.Close();
                //Then Remove it
                _busClient.DeleteSubscription(_topicName, _senderId.ToString());
            }
        }
コード例 #8
0
 public void DeleteSubscription(string subscriptionName)
 {
     if (_namespaceManager.SubscriptionExists(_cancellationTopicName, subscriptionName))
     {
         _namespaceManager.DeleteSubscription(_cancellationTopicName, subscriptionName);
     }
 }
コード例 #9
0
        static void Main(string[] args)
        {
            // Setup:
            ParseArgs(args);

            GetUserCredentials();
            CreateNamespaceClient();

            // Create topic
            Console.WriteLine("\nCreating Topic...");
            TopicDescription description = CreateTopic(topicPath);

            Console.WriteLine(
                "Created {0}", description.Path);

            // Create request subscription
            Console.WriteLine("\nCreating Subscriptions...");
            SubscriptionDescription requestSub = CreateSubscription(description.Path, requestSubName, false);

            Console.WriteLine(
                "Created {0}/{1}, RequiresSession = {2}",
                requestSub.TopicPath,
                requestSub.Name,
                requestSub.RequiresSession);
            SubscriptionDescription responseSub = CreateSubscription(description.Path, responseSubName, true);

            Console.WriteLine(
                "Created {0}/{1}, RequiresSession = {2}",
                responseSub.TopicPath,
                responseSub.Name,
                responseSub.RequiresSession);

            // Start clients and servers:
            Console.WriteLine("\nLaunching clients and servers...");
            StartClients();
            StartServers();

            Console.WriteLine("\nPress [Enter] to exit.");
            Console.ReadLine();

            // Cleanup:
            namespaceManager.DeleteSubscription(requestSub.TopicPath, requestSub.Name);
            namespaceManager.DeleteSubscription(responseSub.TopicPath, responseSub.Name);
            namespaceManager.DeleteTopic(description.Path);
            StopClients();
            StopServers();
        }
コード例 #10
0
        void DisconnectFromChatSession(string sessionId)
        {
            SayGoodBye(sessionId);

            //Delete the subscription and close the client
            namespaceManager.DeleteSubscription(chatTopicPath, chatSessionSubscriptionName);
            chatSessionClient.Close();
        }
コード例 #11
0
ファイル: Listener.cs プロジェクト: dotnetROC/2015-04
        public void Stop()
        {
            // stop the background thread
            _isInRunningState = false;
            _workerThread.Join();               // block this thread until child thread exits

            // perform any cleanup actions neccessary here
            _namespaceManager.DeleteSubscription(TopicPath, _subscriptionId.ToString());
        }
コード例 #12
0
        public AzureServiceBusMessageQueue Purge()
        {
            log.Warn("Purging logical queue {0}", InputQueue);

            namespaceManager.DeleteSubscription(topicDescription.Path, InputQueue);
            GetOrCreateSubscription(InputQueue);

            return(this);
        }
コード例 #13
0
        public ServiceBusTopicHelper Subscribe <T>(Action <T> receiveHandler,
                                                   string filterSqlStatement = null,
                                                   string subscriptionName   = null,
                                                   ReceiveMode receiveMode   = ReceiveMode.ReceiveAndDelete)
        {
            // if they asked for a subscription with a filter and no name, blow up
            if (!string.IsNullOrEmpty(filterSqlStatement) &&
                string.IsNullOrEmpty(subscriptionName))
            {
                throw new ArgumentException("If filterSqlStatement is provided, subscriptionName must also be provided.");
            }

            _receiveMode = receiveMode;
            SetupServiceBusEnvironment();
            var topicName = string.Format("Topic_{0}", typeof(T).Name);

            subscriptionName = string.IsNullOrEmpty(subscriptionName)
                ? string.Format("Subscription_{0}", typeof(T).Name)
                : subscriptionName;

            if (!_namespaceManager.TopicExists(topicName))
            {
                _namespaceManager.CreateTopic(topicName);
            }

            var topic = _namespaceManager.GetTopic(topicName);

            SubscriptionDescription subscription;

            // always create a new subscription just in case the calling code's changed expectations
            if (_namespaceManager.SubscriptionExists(topic.Path, subscriptionName))
            {
                _namespaceManager.DeleteSubscription(topic.Path, subscriptionName);
            }

            if (string.IsNullOrEmpty(filterSqlStatement))
            {
                subscription = _namespaceManager.CreateSubscription(topic.Path, subscriptionName);
            }
            else
            {
                var filter = new SqlFilter(filterSqlStatement);
                subscription = _namespaceManager.CreateSubscription(topic.Path, subscriptionName, filter);
            }

            var subscriptionClient = _messagingFactory.CreateSubscriptionClient(topicName, subscriptionName, receiveMode);

            _subscribers.Add(new Tuple <string, SubscriptionClient>(topicName, subscriptionClient));

            Begin <T>(receiveHandler, subscriptionClient);

            return(this);
        }
コード例 #14
0
ファイル: WSBMessageBus.cs プロジェクト: darrenferne/stuff
        public void Unsubscribe(Type messageType)
        {
            var metadata = _configuration.MessageDefinitions.FirstOrDefault(md => md.MessageType == messageType && md.MessageAction == Core.MessageAction.Event);

            if (metadata != null)
            {
                if (_namespaceManager.SubscriptionExists(metadata.QueueName, _configuration.EndpointName))
                {
                    _namespaceManager.DeleteSubscription(metadata.QueueName, _configuration.EndpointName);
                }
            }
        }
コード例 #15
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             // Clean up managed resources.
             subscriptionClient.Abort();
             namespaceManager.DeleteSubscription(CloudConstants.ResultsTopicName, schedulerInstanceGuid);
         }
     }
     disposed = true;
 }
 private void DeleteSubscription()
 {
     try
     {
         if (namespaceManager.SubscriptionExists(topicPath, subscriptionName))
         {
             namespaceManager.DeleteSubscription(topicPath, subscriptionName);
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine("**** Error DeleteSubscription " + e.ToString() + " ****");
     }
 }
コード例 #17
0
 public void DeleteSubscription(string topicPath, string path)
 {
     try
     {
         if (_servicebusNamespaceManager.SubscriptionExists(topicPath, path))
         {
             _servicebusNamespaceManager.DeleteSubscription(topicPath, path);
         }
     }
     catch (Exception ex)
     {
         new NotImplementedException();
     }
 }
コード例 #18
0
        static void Main(string[] args)
        {
            TokenProvider    token = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", "H+rYJ3XugZAx4AwBWbgkgiqBzdxiFOY2ZR9FicPK840=");
            Uri              path  = ServiceBusEnvironment.CreateServiceUri("sb", "ajaybus", "");
            NamespaceManager mgr   = new NamespaceManager(path, token);

            if (!mgr.TopicExists("DetailmessageTopic"))
            {
                mgr.CreateTopic("DetailmessageTopic");
            }
            Console.WriteLine("Topic Created");
            if (mgr.SubscriptionExists("DetailmessageTopic", "High"))
            {
                mgr.DeleteSubscription("DetailmessageTopic", "High");
            }
            SqlFilter filter = new SqlFilter("Priority>2");

            mgr.CreateSubscription("DetailmessageTopic", "High", filter);
            Console.WriteLine("The High Subscription is created");
            if (mgr.SubscriptionExists("DetailmessageTopic", "Low"))
            {
                mgr.DeleteSubscription("DetailmessageTopic", "Low");
            }
            filter = new SqlFilter("Priority<=2");
            mgr.CreateSubscription("DetailmessageTopic", "Low", filter);
            Console.WriteLine("The low Subscription created");
            MessagingFactory factory = MessagingFactory.Create(path, token);
            TopicClient      client  = factory.CreateTopicClient("DetailmessageTopic");

            for (int i = 0; i <= 5; i++)
            {
                BrokeredMessage msg = new BrokeredMessage("message:" + i);
                msg.Properties.Add("priority", i);
                client.Send(msg);
            }
            Console.Read();
        }
コード例 #19
0
        static void CreateTopicsAndSubscriptions(NamespaceManager namespaceManager)
        {
            // Create a topic and 3 subscriptions.
            topicDescription = namespaceManager.CreateTopic(Conts.TopicName);
            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.SubAllMessages);
            }
            catch { }

            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.SubHolding);
            }
            catch { }

            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.YoungHorses);
            }
            catch { }

            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.OldHorses);
            }
            catch { }


            namespaceManager.CreateSubscription(topicDescription.Path, Conts.SubAllMessages, new TrueFilter());
            namespaceManager.CreateSubscription(topicDescription.Path, Conts.SubHolding, new FalseFilter());
            //namespaceManager.CreateSubscription(topicDescription.Path, Conts.YoungHorses, new TrueFilter());
            //namespaceManager.CreateSubscription(topicDescription.Path, Conts.OldHorses, new TrueFilter());

            namespaceManager.CreateSubscription(topicDescription.Path, Conts.YoungHorses, new SqlFilter("HorseId > 5"));
            namespaceManager.CreateSubscription(topicDescription.Path, Conts.OldHorses, new SqlFilter("HorseId <= 5"));
        }
コード例 #20
0
        private static void CreateStartSubscription(string webJobName)
        {
            NamespaceManager nsMgr        = NamespaceManager.CreateFromConnectionString(ConfigurationManager.ConnectionStrings["AzureWebJobsServiceBus"].ConnectionString);
            string           environment  = ConfigurationManager.AppSettings["WebJobsEnvName"];
            string           topic        = ConfigurationManager.AppSettings["WebJobsTopicName"];
            string           subscription = $"{webJobName}{environment}StartMessages";

            if (nsMgr.SubscriptionExists(topic, subscription))
            {
                nsMgr.DeleteSubscription(topic, subscription);
            }

            SqlFilter startMessagesFilter = new SqlFilter($"Environment = '{environment}' AND JobName='{webJobName}'");

            nsMgr.CreateSubscription(topic, subscription, startMessagesFilter);
        }
コード例 #21
0
ファイル: NSBQClient.cs プロジェクト: Mike-McDonnell/Nebulus
        internal static void ConfigureServiceHUB()
        {
            try
            {
                //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

                ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder(NebulusClient.App.ClientConfiguration.ServiceBUSConenctionString);
                MessagingFactory messageFactory   = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
                NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

                var SubscriptionName = Environment.MachineName;

                if (NebulusClient.Properties.Settings.Default.SubscriptionNameLevel == 1)
                {
                    SubscriptionName = Environment.UserName;
                }

                if (NebulusClient.Properties.Settings.Default.SubscriptionNameLevel == 2)
                {
                    SubscriptionName = Environment.MachineName + "\\" + Environment.UserName;
                }

                if (NebulusClient.Properties.Settings.Default.SubscriptionNameLevel == 3)
                {
                    try
                    {
                        SubscriptionName = Environment.GetEnvironmentVariable("CLIENTNAME");
                    }
                    catch
                    { }
                }


                if (namespaceManager.SubscriptionExists(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, SubscriptionName))
                {
                    namespaceManager.DeleteSubscription(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, SubscriptionName);
                }

                namespaceManager.CreateSubscription(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, SubscriptionName, new SqlFilter(BuildRules()));

                NSBQClient = messageFactory.CreateSubscriptionClient(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, Environment.MachineName, ReceiveMode.ReceiveAndDelete);
            }
            catch (Exception ex)
            {
                AppLogging.Instance.Error("Error: Connecting to ServiceBus ", ex);
            }
        }
コード例 #22
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

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

            if (namespaceManager.TopicExists(topicName))
            {
                namespaceManager.DeleteTopic(topicName);
            }
        }
コード例 #23
0
        public static void RemoveEndpoint(string endpointName)
        {
            var serviceBusSettings = ConfigurationManager.GetSection(ServiceBusConfigurationSettings.SectionName) as ServiceBusConfigurationSettings;
            var serviceBusEndpoint = serviceBusSettings.Endpoints.Get(endpointName);

            if (serviceBusEndpoint != null)
            {
                var credentials      = TokenProvider.CreateSharedSecretTokenProvider(serviceBusEndpoint.IssuerName, serviceBusEndpoint.IssuerSecret);
                var address          = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusEndpoint.ServiceNamespace, String.Empty);
                var managementClient = new NamespaceManager(address, credentials);

                if (!String.IsNullOrEmpty(serviceBusEndpoint.TopicName) && !String.IsNullOrEmpty(serviceBusEndpoint.SubscriptionName))
                {
                    if (managementClient.GetTopics().Where(t => String.Compare(t.Path, serviceBusEndpoint.TopicName, true) == 0).Count() > 0)
                    {
                        if (managementClient.GetSubscriptions(serviceBusEndpoint.TopicName).Where(s => String.Compare(s.Name, serviceBusEndpoint.SubscriptionName, true) == 0).Count() > 0)
                        {
                            managementClient.DeleteSubscription(serviceBusEndpoint.TopicName, serviceBusEndpoint.SubscriptionName);
                            return;
                        }
                    }
                }

                if (!String.IsNullOrEmpty(serviceBusEndpoint.TopicName))
                {
                    if (managementClient.GetTopics().Where(t => String.Compare(t.Path, serviceBusEndpoint.TopicName, true) == 0).Count() > 0)
                    {
                        managementClient.DeleteTopic(serviceBusEndpoint.TopicName);
                        return;
                    }
                }

                if (!String.IsNullOrEmpty(serviceBusEndpoint.QueueName))
                {
                    if (managementClient.GetQueues().Where(q => String.Compare(q.Path, serviceBusEndpoint.QueueName, true) == 0).Count() > 0)
                    {
                        managementClient.DeleteQueue(serviceBusEndpoint.QueueName);
                        return;
                    }
                }
            }
        }
        public override async Task CloseAsync(string correlationId)
        {
            if (_topicClient != null && _topicClient.IsClosedOrClosing == false)
            {
                await _topicClient.CloseAsync();
            }

            if (_subscriptionClient != null && _subscriptionClient.IsClosedOrClosing == false)
            {
                await _subscriptionClient.CloseAsync();

                // Remove temporary subscriber
                if (_tempSubscriber == true)
                {
                    _namespaceManager?.DeleteSubscription(_topicName, _subscriptionName);
                }
            }

            _logger.Trace(correlationId, "Closed queue {0}", this);
        }
コード例 #25
0
        public BrainstormTopicClientTests()
        {
            var connectionString = Configuration.ServiceBusConnectionString;

            namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            if (namespaceManager.TopicExists(topicName))
            {
                namespaceManager.DeleteTopic(topicName);
            }
            namespaceManager.CreateTopic(topicName);

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

            namespaceManager.CreateSubscription(topicName, subscriptionName);

            this.configs = new TopicClientConfiguration(connectionString, ReceiveMode.PeekLock, topicName, subscriptionName);
        }
コード例 #26
0
            private void MakeSureSubscriptionExists(NamespaceManager namespaceManager, AzureTopicMqSettings settings,
                                                    string topicPath, string subscriptionName, bool removePrevious = false)
            {
                var subscriptionDescription = new SubscriptionDescription(topicPath, subscriptionName);

                if (!namespaceManager.SubscriptionExists(topicPath, subscriptionName))
                {
                    namespaceManager.CreateSubscription(settings.SubscriptionBuilderConfig(subscriptionDescription, typeof(T)));
                    _logMessage($"MakeSureSubscriptionExists: Created subscription: {subscriptionName}");
                }
                else
                {
                    if (removePrevious)
                    {
                        namespaceManager.DeleteSubscription(topicPath, subscriptionName);
                        namespaceManager.CreateSubscription(settings.SubscriptionBuilderConfig(subscriptionDescription, typeof(T)));
                        _logMessage($"MakeSureSubscriptionExists: Deleted and created subscription: {subscriptionName}");
                    }
                }
            }
コード例 #27
0
        public void ForwardMessageEvenWhenNoSubscriptionsExistInDestination()
        {
            var topicName           = $"_sbmf-{DateTime.UtcNow:yyyyMMddHHmmss}-{new Random().Next(10000, 99999)}";
            var subscriptionName    = "subscription1";
            var ignoreTopics        = "";
            var ignoreSubscriptions = "";

            var sourceClient = TopicClient.CreateFromConnectionString(_sourceConnectionString, topicName);

            "Given a topic exists on the destination bus with no subscriptions".x(() =>
            {
                _destinationNamespaceManager.CreateTopic(topicName);

                var subscriptions = _destinationNamespaceManager.GetSubscriptions(topicName);
                foreach (var subscription in subscriptions)
                {
                    _destinationNamespaceManager.DeleteSubscription(topicName, subscription.Name);
                }
            });
            "And the source topic has 1 subscription".x(() =>
            {
                _sourceNamespaceManager.CreateTopic(topicName);
                _sourceNamespaceManager.CreateSubscription(topicName, subscriptionName);
            });
            "And a message is sent to the source topic".x(() =>
            {
                sourceClient.Send(new BrokeredMessage(_testMessage));
            });
            "When the service has run".x(() =>
            {
                new ServiceBusMessageForwarder(_logger, null, _sourceConnectionString, _destinationConnectionString, _ignoreQueues, ignoreTopics, ignoreSubscriptions).Run();
            });
            "Then the message is still forwarded to the destination topic and no longer exists in the source topic's subscription".x(() =>
            {
                var sourceSubscriptionClient = SubscriptionClient.CreateFromConnectionString(_sourceConnectionString, topicName, subscriptionName);
                var messages = sourceSubscriptionClient.PeekBatch(10);
                messages.Count().Should().Be(0);
            });

            CleanupTopics(topicName);
        }
コード例 #28
0
        private void CleanServiceBusQueues()
        {
            if (_namespaceManager.QueueExists(ServiceBusArgumentsDisplayFunctions.StartQueueName))
            {
                _namespaceManager.DeleteQueue(ServiceBusArgumentsDisplayFunctions.StartQueueName);
            }

            if (_namespaceManager.QueueExists(ServiceBusArgumentsDisplayFunctions.FirstOutQueue))
            {
                _namespaceManager.DeleteQueue(ServiceBusArgumentsDisplayFunctions.FirstOutQueue);
            }

            if (_namespaceManager.SubscriptionExists(ServiceBusArgumentsDisplayFunctions.TopicName, ServiceBusArgumentsDisplayFunctions.SubscriptionName))
            {
                _namespaceManager.DeleteSubscription(ServiceBusArgumentsDisplayFunctions.TopicName, ServiceBusArgumentsDisplayFunctions.SubscriptionName);
            }

            if (_namespaceManager.TopicExists(ServiceBusArgumentsDisplayFunctions.TopicName))
            {
                _namespaceManager.DeleteTopic(ServiceBusArgumentsDisplayFunctions.TopicName);
            }
        }
コード例 #29
0
        private HeaterStatus DoCommunication(string correlationId, string action)
        {
            var subscriptionDesc = new SubscriptionDescription(_topicNameReceive, correlationId);

            subscriptionDesc.DefaultMessageTimeToLive = TimeSpan.FromSeconds(30);
            _namespaceMgr.CreateSubscription(subscriptionDesc, new CorrelationFilter(correlationId));

            Trace.TraceInformation("Performing Heater Action: {0}", action);
            _client.Send(CreateMessage(correlationId, action));

            var receiveClient  = _factory.CreateSubscriptionClient(_topicNameReceive, correlationId, ReceiveMode.ReceiveAndDelete);
            var receiveMessage = receiveClient.Receive();

            Stream ms = receiveMessage.GetBody <Stream>();
            var    s  = new StreamReader(ms).ReadToEnd();

            Trace.TraceInformation("Heater Reports: {0}", s);

            _namespaceMgr.DeleteSubscription(_topicNameReceive, correlationId);

            return(Parse(s));
        }
コード例 #30
0
        public AzureQueueClient(string clientUniqueName)
        {
            NamespaceManager namespaceManager = NamespaceManager.Create();
            var topicName = ClientConstants.SettingTopicName;

            try
            {
                if (namespaceManager.TopicExists(topicName))
                {
                    if (namespaceManager.SubscriptionExists(topicName, clientUniqueName))
                    {
                        namespaceManager.DeleteSubscription(topicName, clientUniqueName);
                    }

                    namespaceManager.CreateSubscription(topicName, clientUniqueName);
                }
            }
            catch (Exception e)
            {
                // ignored
            }
            _subscibtionClient = SubscriptionClient.Create(topicName, clientUniqueName, ReceiveMode.ReceiveAndDelete);
        }
コード例 #31
0
        static void CreateTopicsAndSubscriptions(NamespaceManager namespaceManager)
        {
            // Create a topic and 3 subscriptions.
            topicDescription = namespaceManager.CreateTopic(Conts.TopicName);
            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.SubAllMessages);
            }
            catch { }

            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.SubHolding);
            }
            catch { }

            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.YoungHorses);
            }
            catch { }

            try
            {
                namespaceManager.DeleteSubscription(topicDescription.Path, Conts.OldHorses);
            }
            catch { }

            namespaceManager.CreateSubscription(topicDescription.Path, Conts.SubAllMessages, new TrueFilter());
            namespaceManager.CreateSubscription(topicDescription.Path, Conts.SubHolding, new FalseFilter());
            //namespaceManager.CreateSubscription(topicDescription.Path, Conts.YoungHorses, new TrueFilter());
            //namespaceManager.CreateSubscription(topicDescription.Path, Conts.OldHorses, new TrueFilter());

            namespaceManager.CreateSubscription(topicDescription.Path, Conts.YoungHorses, new SqlFilter("HorseId > 5"));
            namespaceManager.CreateSubscription(topicDescription.Path, Conts.OldHorses, new SqlFilter("HorseId <= 5"));
        }