コード例 #1
0
        static void Main(string[] args)
        {
            GetUserCredentials();
            TokenProvider tokenProvider = null;
            Uri serviceUri = null;
            CreateTokenProviderAndServiceUri(out tokenProvider, out serviceUri);

            NamespaceManager namespaceManager = new NamespaceManager(serviceUri, tokenProvider);
            Console.WriteLine("Creating Topic 'IssueTrackingTopic'...");
            if (namespaceManager.TopicExists("IssueTrackingTopic"))
                namespaceManager.DeleteTopic("IssueTrackingTopic");

            MessagingFactory factory = null;
            TopicDescription myTopic = namespaceManager.CreateTopic(TopicName);
            // Criar duas Subscrições
            Console.WriteLine("Creating Subscriptions 'AuditSubscription' and 'AgentSubscription'...");
            SubscriptionDescription myAuditSubscription = namespaceManager.CreateSubscription((myTopic.Path, "AuditSubscription");
            SubscriptionDescription myAgentSubscription = namespaceManager.CreateSubscription(myTopic.Path, "AgentSubscription");
            TopicClient myTopicClient = CreateTopicClient(serviceUri, tokenProvider, myTopic, out factory);
            List<BrokeredMessage> messageList = new List<BrokeredMessage>();
            messageList.Add(CreateIssueMessage("1", "First message information"));
            messageList.Add(CreateIssueMessage("2", "Second message information"));
            messageList.Add(CreateIssueMessage("3", "Third message information"));
            Console.WriteLine("\nSending messages to topic...");
            SendListOfMessages(messageList, myTopicClient);

            Console.WriteLine("\nFinished sending messages, press ENTER to clean up and exit.");
            myTopicClient.Close();
            Console.ReadLine();
            namespaceManager.DeleteTopic(TopicName);
        }
コード例 #2
0
        static void DeleteTopicsAndSubscriptions(NamespaceManager namespaceManager)
        {
            Console.WriteLine("\nDeleting topic and subscriptions from previous run if any.");

            try
            {
                namespaceManager.DeleteTopic(Program.TopicName);
            }
            catch (MessagingEntityNotFoundException)
            {
                Console.WriteLine("No topic found to delete.");
            }

            Console.WriteLine("Delete completed.");
        }
コード例 #3
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);
            }
        }
コード例 #4
0
        private static void CreateTopic()
        {
            NamespaceManager namespaceManager = NamespaceManager.Create();

            Console.WriteLine("\nCreating Topic '{0}'...", TopicName);

            // Delete if exists
            if (namespaceManager.TopicExists(TopicName))
            {
                namespaceManager.DeleteTopic(TopicName);
            }

            var topicDesc = namespaceManager.CreateTopic(TopicName);

            namespaceManager.CreateSubscription(topicDesc.Path, SubscriptionName1);
            namespaceManager.CreateSubscription(topicDesc.Path, SubscriptionName2);
        }
コード例 #5
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;
                    }
                }
            }
        }
コード例 #6
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);
        }
コード例 #7
0
        public void TestGetSubscriptions()
        {
            string           name      = "testSubscription";
            string           topicName = "TestGetSubscriptions";
            NamespaceManager ns        = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);

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

                IEnumerable <SubscriptionDescription> suscriptions = ns.GetSubscriptions(topicName);
                Assert.IsTrue(suscriptions.First().Name.Equals(name));
            }
            finally
            {
                ns.DeleteTopic(topicName);
            }
        }
コード例 #8
0
        private static void Main()
        {
            Console.WriteLine("Creating topic.");

            //Create a topic
            if (NamespaceManager == null)
            {
                throw new FieldAccessException("NamespaceManager is NULL");
            }

            //Only uncomment this when testing creating a fresh topic
            if (NamespaceManager.TopicExists(TopicName))
            {
                NamespaceManager.DeleteTopic(TopicName);
            }
            NamespaceManager.CreateTopic(TopicName);

            Console.WriteLine("Topic was created.");
            Console.WriteLine("Wait until the subscription is created, then press Enter when ready to send.");
            Console.ReadLine();

            //Create a topic client
            _topicClient = MessagingFactory.CreateTopicClient(TopicName);

            var hash = LargeMessageHelper.LargeMessageHelper.GetMd5HashFromFile(FileName);

            var bytes       = System.IO.File.ReadAllBytes(FileName);
            var sendMessage = new BrokeredMessage(bytes);

            LargeMessageHelper.LargeMessageHelper.SendLargeMessage(_topicClient, sendMessage);

            //This proves that sending as one message will fail
            //_topicClient.Send(sendMessage);

            Console.WriteLine("Sent message (Hash={0}, Size={1} bytes)", hash, bytes.Length);
            Console.WriteLine();
            Console.WriteLine("Press Enter to close.");
            Console.ReadLine();
        }
コード例 #9
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);
            }
        }
コード例 #10
0
        public void TearDown()
        {
            foreach (var entity in entitiesToDelete.GroupBy(e => new { e.Name, e.EntityType }).Select(e => e.First()))
            {
                switch (entity.EntityType)
                {
                case QueueOrTopic.Queue:
                    if (_namespaceManager.QueueExists(entity.Name))
                    {
                        _namespaceManager.DeleteQueue(entity.Name);
                    }
                    break;

                case QueueOrTopic.Topic:
                    _namespaceManager.DeleteTopic(entity.Name);
                    break;

                default:
                    break;
                }
            }
        }
コード例 #11
0
        public void TestTopic()
        {
            string           name        = "testTopic2";
            NamespaceManager ns          = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);
            TopicDescription description = ns.CreateTopic(name);

            Assert.IsTrue(null != description);

            if (!ns.TopicExists(name, out description))
            {
                Assert.Fail("Topic did not exist");
            }
            else
            {
                Assert.IsTrue(null != description);
                ns.DeleteTopic(name);
                if (ns.TopicExists(name, out description))
                {
                    Assert.Fail("Topic was not deleted");
                }
            }
        }
コード例 #12
0
        public void TestLongSubscriptionName()
        {
            string           topicName      = "TestLogSubscriptionName";
            string           tooLongSubName = "ServiceBusTest-f7b6c694-b264-40e1-bacb-0e30ca8b33e9";
            NamespaceManager ns             = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);

            TopicDescription description = ns.CreateTopic(topicName);

            Assert.IsTrue(null != description);
            try
            {
                ns.CreateSubscription(topicName, tooLongSubName);
                Assert.IsFalse(true);
            }
            catch (ArgumentOutOfRangeException)
            {
                Assert.IsTrue(true);
            }
            finally
            {
                ns.DeleteTopic(topicName);
            }
        }
コード例 #13
0
        protected override void CreateTopic(NamespaceManager nsm)
        {
            if (nsm.TopicExists(topicName))
            {
                nsm.DeleteTopic(topicName);
            }

            if (!nsm.TopicExists(topicName))
            {
                // this topic will use Namespace related Shared Access Key
                TopicDescription td = new TopicDescription(topicName);
                nsm.CreateTopic(td);
            }

            _tc = _cf.CreateTopicClient(nsName, topicName, nsKeyName, nsKey);


            if (!nsm.SubscriptionExists(topicName, topicSubName))
            {
                nsm.CreateSubscription(topicName, topicSubName);
            }
            _sc = _cf.CreateSubscriptionClient(nsName, topicName, topicSubName, nsKeyName, nsKey);
        }
コード例 #14
0
        private void OnUnsubscribe(object sender, UnsubscribeMessage message)
        {
            subscriptionThreads[message.SubscriptionId].Abort();
            subscriptionThreads.Remove(message.SubscriptionId);

            subscriptionClients[message.SubscriptionId].Close();
            var topic = subscriptionClients[message.SubscriptionId].TopicPath;

            subscriptionClients.Remove(message.SubscriptionId);


            namespaceManager.DeleteSubscription(topic, message.SubscriptionId.ToString());
            if (namespaceManager.GetTopic(topic).SubscriptionCount <= 0)
            {
                namespaceManager.DeleteTopic(topic);
                topicClients.Remove(topic);
            }

            Send(new UnsubscribedMessage
            {
                RequestId = message.RequestId
            });
        }
コード例 #15
0
        static void CreateTopicsAndSubscriptions()
        {
            // If the topic exists, delete it.
            if (NamespaceMgr.TopicExists(TopicPath))
            {
                NamespaceMgr.DeleteTopic(TopicPath);
            }

            // Create the topic.
            NamespaceMgr.CreateTopic(TopicPath);

            // Subscription for all orders
            NamespaceMgr.CreateSubscription
                (TopicPath, "allOrdersSubscription");


            // Subscriptions for USA and EU regions
            NamespaceMgr.CreateSubscription(TopicPath, "usaSubscription",
                                            new SqlFilter("Region = 'USA'"));
            NamespaceMgr.CreateSubscription(TopicPath, "euSubscription",
                                            new SqlFilter("Region = 'EU'"));
            NamespaceMgr.CreateSubscription(TopicPath, "euSubscription2",
                                            new SqlFilter("Region = 'eu'"));

            // Subscriptions for large orders, high value orders and loyal USA customers.
            NamespaceMgr.CreateSubscription(TopicPath, "largeOrderSubscription",
                                            new SqlFilter("Items > 30"));
            NamespaceMgr.CreateSubscription(TopicPath, "highValueSubscription",
                                            new SqlFilter("Value > 500"));
            NamespaceMgr.CreateSubscription(TopicPath, "loyaltySubscription",
                                            new SqlFilter("Loyalty = true AND Region = 'USA'"));

            // Correlation subscription for UK orders.
            NamespaceMgr.CreateSubscription(TopicPath, "ukSubscription",
                                            new CorrelationFilter("UK"));
        }
コード例 #16
0
        public Form1()
        {
            InitializeComponent();

            if (!DesignMode)
            {
                //Create a topic
                if (_namespaceManager == null)
                {
                    throw new FieldAccessException("NamespaceManager is NULL");
                }

                //Only uncomment this when testing creating a fresh topic
                if (_namespaceManager.TopicExists(TopicName))
                {
                    _namespaceManager.DeleteTopic(TopicName);
                }
                _namespaceManager.CreateTopic(TopicName);


                //Create a topic client
                _topicClient = _messagingFactory.CreateTopicClient(TopicName);
            }
        }
コード例 #17
0
        public async Task Run(string namespaceAddress, string manageToken)
        {
            // This sample demonstrates how to use advanced filters with ServiceBus topics and subscriptions.
            // The sample creates a topic and 3 subscriptions with different filter definitions.
            // Each receiver will receive matching messages depending on the filter associated with a subscription.

            // NOTE:
            // This is primarily an example illustrating the management features related to setting up 
            // Service Bus subscriptions. It is DISCOURAGED for applications to routinely set up and 
            // tear down topics and subscriptions as a part of regular message processing. Managing 
            // topics and subscriptions is a system configuration operation. 

            // Create messaging factory and ServiceBus namespace client.
            var sharedAccessSignatureTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken);
            var namespaceManager = new NamespaceManager(namespaceAddress, sharedAccessSignatureTokenProvider);

            Console.WriteLine("\nCreating a topic and 3 subscriptions.");

            // Create a topic and several subscriptions; clean house ahead of time
            if (await namespaceManager.TopicExistsAsync(TopicName))
            {
                await namespaceManager.DeleteTopicAsync(TopicName);
            }

            var topicDescription = await namespaceManager.CreateTopicAsync(TopicName);
            Console.WriteLine("Topic created.");

            // Create a subscription for all messages sent to topic.
            await namespaceManager.CreateSubscriptionAsync(topicDescription.Path, SubscriptionAllMessages, new TrueFilter());
            Console.WriteLine("Subscription {0} added with filter definition set to TrueFilter.", SubscriptionAllMessages);
            

            // Create a subscription that'll receive all orders which have color "blue" and quantity 10.

            await namespaceManager.CreateSubscriptionAsync(
                topicDescription.Path,
                SubscriptionColorBlueSize10Orders,
                new SqlFilter("color = 'blue' AND quantity = 10"));
            Console.WriteLine(
                "Subscription {0} added with filter definition \"color = 'blue' AND quantity = 10\".",
                 SubscriptionColorBlueSize10Orders);

            // Create a subscription that'll receive all orders which have color "red"
            await namespaceManager.CreateSubscriptionAsync(
                topicDescription.Path,
                SubscriptionColorRed,
                new RuleDescription
                {
                    Name = "RedRule",
                    Filter = new SqlFilter("color = 'red'"),
                    Action = new SqlRuleAction(
                        "SET quantity = quantity / 2;" +
                        "REMOVE priority;" +
                        "SET sys.CorrelationId = 'low';")
                });
            Console.WriteLine("Subscription {0} added with filter definition \"color = 'red'\" and action definition.", SubscriptionColorRed);
     
            // Create a subscription that'll receive all high priority orders.
            namespaceManager.CreateSubscription(topicDescription.Path, SubscriptionHighPriorityOrders, 
                new CorrelationFilter { Label = "red", CorrelationId = "high"});
            Console.WriteLine("Subscription {0} added with correlation filter definition \"high\".", SubscriptionHighPriorityOrders);
     
            Console.WriteLine("Create completed.");


            await this.SendAndReceiveTestsAsync(namespaceAddress, sharedAccessSignatureTokenProvider);


            Console.WriteLine("Press [Enter] to quit...");
            Console.ReadLine();

            Console.WriteLine("\nDeleting topic and subscriptions from previous run if any.");

            try
            {
                namespaceManager.DeleteTopic(TopicName);
            }
            catch (MessagingEntityNotFoundException)
            {
                Console.WriteLine("No topic found to delete.");
            }

            Console.WriteLine("Delete completed.");
        }
コード例 #18
0
 public void DeleteTopic(string path)
 {
     _namespaceManager.DeleteTopic(path);
 }
コード例 #19
0
ファイル: BusBuilder.cs プロジェクト: nblumhardt/Nimbus
        /// <summary>
        ///     Danger! Danger, Will Robinson!
        /// </summary>
        private static void RemoveAllExistingNamespaceElements(NamespaceManager namespaceManager)
        {
            var tasks = new List<Task>();

            var queuePaths = namespaceManager.GetQueues().Select(q => q.Path).ToArray();
            queuePaths
                .Do(queuePath => tasks.Add(Task.Run(() => namespaceManager.DeleteQueue(queuePath))))
                .Done();

            var topicPaths = namespaceManager.GetTopics().Select(t => t.Path).ToArray();
            topicPaths
                .Do(topicPath => tasks.Add(Task.Run(() => namespaceManager.DeleteTopic(topicPath))))
                .Done();

            tasks.WaitAll();
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: pravinrest/azure
        public async Task Run(string namespaceAddress, string manageToken)
        {
            // Create the Topic / Subscription entities
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken);
            var namespaceManager = new NamespaceManager(namespaceAddress, tokenProvider);
            var topicDescription = new TopicDescription(TopicName);

            // Delete the topic if it already exists before creation.
            if (await namespaceManager.TopicExistsAsync(topicDescription.Path))
            {
                await namespaceManager.DeleteTopicAsync(topicDescription.Path);
            }
            await namespaceManager.CreateTopicAsync(topicDescription);

            await Task.WhenAll(
                // this sub receives messages for Priority = 1
                namespaceManager.CreateSubscriptionAsync(
                    new SubscriptionDescription(TopicName, "Priority1Subscription"),
                    new RuleDescription(new SqlFilter("Priority = 1"))),
                // this sub receives messages for Priority = 2
                namespaceManager.CreateSubscriptionAsync(
                    new SubscriptionDescription(TopicName, "Priority2Subscription"),
                    new RuleDescription(new SqlFilter("Priority = 2"))),
                // this sub receives messages for Priority Less than 2
                namespaceManager.CreateSubscriptionAsync(
                    new SubscriptionDescription(TopicName, "PriorityLessThan2Subscription"),
                    new RuleDescription(new SqlFilter("Priority > 2")))
                );


            // Start senders and receivers:
            Console.WriteLine("\nLaunching senders and receivers...");

            //send messages to topic
            var messagingFactory = MessagingFactory.Create(namespaceAddress, tokenProvider);

            var topicClient = messagingFactory.CreateTopicClient(TopicName);

            Console.WriteLine("Preparing to send messages to {0}...", topicClient.Path);

            // Send messages to queue:
            Console.WriteLine("Sending messages to topic {0}", topicClient.Path);

            var rand = new Random();

            for (var i = 0; i < 100; ++i)
            {
                var msg = new BrokeredMessage()
                {
                    TimeToLive = TimeSpan.FromMinutes(2),
                    Properties =
                    {
                        { "Priority", rand.Next(1, 4) }
                    }
                };

                await topicClient.SendAsync(msg);

                this.OutputMessageInfo("Sent: ", msg);
            }

            Console.WriteLine();


            // All messages sent
            Console.WriteLine("\nSender complete. Press ENTER");
            Console.ReadLine();

            // start receive
            Console.WriteLine("Receiving messages by priority ...");
            var subClient1 = messagingFactory.CreateSubscriptionClient(
                TopicName,
                new SubscriptionDescription(TopicName, "Priority1Subscription").Name,
                ReceiveMode.ReceiveAndDelete);
            var subClient2 = messagingFactory.CreateSubscriptionClient(
                TopicName,
                new SubscriptionDescription(TopicName, "Priority2Subscription").Name,
                ReceiveMode.ReceiveAndDelete);
            var subClient3 = messagingFactory.CreateSubscriptionClient(
                TopicName,
                new SubscriptionDescription(TopicName, "PriorityLessThan2Subscription").Name,
                ReceiveMode.ReceiveAndDelete);

            while (true)
            {
                try
                {
                    // Please see the README.md file regarding this loop and
                    // the handling strategy below.
                    var message = await subClient1.ReceiveAsync(TimeSpan.Zero) ??
                                  (await subClient2.ReceiveAsync(TimeSpan.Zero) ??
                                   await subClient3.ReceiveAsync(TimeSpan.Zero));

                    if (message != null)
                    {
                        this.OutputMessageInfo("Received: ", message);
                    }
                    else
                    {
                        break;
                    }
                }
                catch (MessageNotFoundException)
                {
                    Console.WriteLine("Got MessageNotFoundException, waiting for messages to be available");
                }
                catch (MessagingException e)
                {
                    Console.WriteLine("Error: " + e.Message);
                }
            }

            Console.WriteLine("\nReceiver complete. press ENTER");
            Console.ReadLine();

            // Cleanup:
            namespaceManager.DeleteTopic(TopicName);
        }
コード例 #21
0
        static void Main(string[] args)
        {
            string topicName = "yutopic";//主题名称
            //服务总线连接字符串,在Portal上直接获取
            string servicebusConnectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            NamespaceManager nm = NamespaceManager.CreateFromConnectionString(servicebusConnectionString);

            //删除已经存在的同名主题
            if (nm.TopicExists(topicName))
            {
                nm.DeleteTopic(topicName);
            }

            TopicDescription topic = new TopicDescription(topicName);
            string           keyB  = SharedAccessAuthorizationRule.GenerateRandomKey();
            string           keyc  = SharedAccessAuthorizationRule.GenerateRandomKey();

            topic.Authorization.Add(new SharedAccessAuthorizationRule("FromPartB", keyB, new AccessRights[] { AccessRights.Listen }));
            topic.Authorization.Add(new SharedAccessAuthorizationRule("FromPartC", keyc, new AccessRights[] { AccessRights.Listen }));

            //创建的主题,默认并不包含分区
            nm.CreateTopic(topic);

            Console.WriteLine("B部门访问秘钥:" + keyB);
            Console.WriteLine("C部门访问秘钥:" + keyc);

            nm.CreateSubscription(topicName, "high_value", new SqlFilter("value >= 1000"));
            nm.CreateSubscription(topicName, "low_value", new SqlFilter("value < 1000"));

            TopicClient client = TopicClient.CreateFromConnectionString(servicebusConnectionString, topicName);

            int orderNumber = 1;

            while (true)
            {
                Console.Write("输入第" + orderNumber + "号订单金额:");
                string value      = Console.ReadLine();
                int    orderValue = 0;
                if (int.TryParse(value, out orderValue))
                {
                    var message = new BrokeredMessage();
                    message.Properties.Add("order_number", orderNumber);
                    message.Properties.Add("value", orderValue);
                    client.Send(message);
                    Console.WriteLine("第" + orderNumber + "号订单已经发出!");
                    orderNumber++;
                }
                else
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("无效的输入,请重新输入。");
                    }
                }
            }
        }
コード例 #22
0
 public void Execute(DeleteTopicCommand command)
 {
     _namespaceManager.DeleteTopic(command.Path);
 }
コード例 #23
0
        public async Task Run(string namespaceAddress, string manageToken)
        {
            // This sample demonstrates how to use advanced filters with ServiceBus topics and subscriptions.
            // The sample creates a topic and 3 subscriptions with different filter definitions.
            // Each receiver will receive matching messages depending on the filter associated with a subscription.

            // NOTE:
            // This is primarily an example illustrating the management features related to setting up
            // Service Bus subscriptions. It is DISCOURAGED for applications to routinely set up and
            // tear down topics and subscriptions as a part of regular message processing. Managing
            // topics and subscriptions is a system configuration operation.

            // Create messaging factory and ServiceBus namespace client.
            var sharedAccessSignatureTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken);
            var namespaceManager = new NamespaceManager(namespaceAddress, sharedAccessSignatureTokenProvider);

            Console.WriteLine("\nCreating a topic and 3 subscriptions.");

            // Create a topic and several subscriptions; clean house ahead of time
            if (await namespaceManager.TopicExistsAsync(TopicName))
            {
                await namespaceManager.DeleteTopicAsync(TopicName);
            }

            var topicDescription = await namespaceManager.CreateTopicAsync(TopicName);

            Console.WriteLine("Topic created.");

            // Create a subscription for all messages sent to topic.
            await namespaceManager.CreateSubscriptionAsync(topicDescription.Path, SubscriptionAllMessages, new TrueFilter());

            Console.WriteLine("Subscription {0} added with filter definition set to TrueFilter.", SubscriptionAllMessages);


            // Create a subscription that'll receive all orders which have color "blue" and quantity 10.

            await namespaceManager.CreateSubscriptionAsync(
                topicDescription.Path,
                SubscriptionColorBlueSize10Orders,
                new SqlFilter("color = 'blue' AND quantity = 10"));

            Console.WriteLine(
                "Subscription {0} added with filter definition \"color = 'blue' AND quantity = 10\".",
                SubscriptionColorBlueSize10Orders);

            // Create a subscription that'll receive all orders which have color "red"
            await namespaceManager.CreateSubscriptionAsync(
                topicDescription.Path,
                SubscriptionColorRed,
                new RuleDescription
            {
                Name   = "RedRule",
                Filter = new SqlFilter("color = 'red'"),
                Action = new SqlRuleAction(
                    "SET quantity = quantity / 2;" +
                    "REMOVE priority;" +
                    "SET sys.CorrelationId = 'low';")
            });

            Console.WriteLine("Subscription {0} added with filter definition \"color = 'red'\" and action definition.", SubscriptionColorRed);

            // Create a subscription that'll receive all high priority orders.
            namespaceManager.CreateSubscription(topicDescription.Path, SubscriptionHighPriorityOrders,
                                                new CorrelationFilter {
                Label = "red", CorrelationId = "high"
            });
            Console.WriteLine("Subscription {0} added with correlation filter definition \"high\".", SubscriptionHighPriorityOrders);

            Console.WriteLine("Create completed.");


            await this.SendAndReceiveTestsAsync(namespaceAddress, sharedAccessSignatureTokenProvider);


            Console.WriteLine("Press [Enter] to quit...");
            Console.ReadLine();

            Console.WriteLine("\nDeleting topic and subscriptions from previous run if any.");

            try
            {
                namespaceManager.DeleteTopic(TopicName);
            }
            catch (MessagingEntityNotFoundException)
            {
                Console.WriteLine("No topic found to delete.");
            }

            Console.WriteLine("Delete completed.");
        }
コード例 #24
0
 private static void DeleteTopic()
 {
     namespaceManager.DeleteTopic(TopicName);
 }
コード例 #25
0
 private void CleanupTopics(string topicName)
 {
     _sourceNamespaceManager.DeleteTopic(topicName);
     _destinationNamespaceManager.DeleteTopic(topicName);
 }
コード例 #26
0
        public async Task Run(string namespaceAddress, string manageToken)
        {
            // Create the Topic / Subscription entities 
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken);
            var namespaceManager = new NamespaceManager(namespaceAddress, tokenProvider);
            var topicDescription = new TopicDescription(TopicName);

            // Delete the topic if it already exists before creation. 
            if (await namespaceManager.TopicExistsAsync(topicDescription.Path))
            {
                await namespaceManager.DeleteTopicAsync(topicDescription.Path);
            }
            await namespaceManager.CreateTopicAsync(topicDescription);
            await Task.WhenAll(
                // this sub receives messages for Priority = 1
                namespaceManager.CreateSubscriptionAsync(
                    new SubscriptionDescription(TopicName, "Priority1Subscription"),
                    new RuleDescription(new SqlFilter("Priority = 1"))),
                // this sub receives messages for Priority = 2
                namespaceManager.CreateSubscriptionAsync(
                    new SubscriptionDescription(TopicName, "Priority2Subscription"),
                    new RuleDescription(new SqlFilter("Priority = 2"))),
                // this sub receives messages for Priority Less than 2
                namespaceManager.CreateSubscriptionAsync(
                    new SubscriptionDescription(TopicName, "PriorityLessThan2Subscription"),
                    new RuleDescription(new SqlFilter("Priority > 2")))
                );


            // Start senders and receivers:
            Console.WriteLine("\nLaunching senders and receivers...");

            //send messages to topic            
            var messagingFactory = MessagingFactory.Create(namespaceAddress, tokenProvider);

            var topicClient = messagingFactory.CreateTopicClient(TopicName);

            Console.WriteLine("Preparing to send messages to {0}...", topicClient.Path);

            // Send messages to queue:
            Console.WriteLine("Sending messages to topic {0}", topicClient.Path);

            var rand = new Random();
            for (var i = 0; i < 100; ++i)
            {
                var msg = new BrokeredMessage()
                {
                    TimeToLive = TimeSpan.FromMinutes(2),
                    Properties =
                    {
                        { "Priority", rand.Next(1, 4) }
                    }
                };

                await topicClient.SendAsync(msg);

                this.OutputMessageInfo("Sent: ", msg);
            }

            Console.WriteLine();


            // All messages sent
            Console.WriteLine("\nSender complete. Press ENTER");
            Console.ReadLine();

            // start receive
            Console.WriteLine("Receiving messages by priority ...");
            var subClient1 = messagingFactory.CreateSubscriptionClient(
                TopicName,
                new SubscriptionDescription(TopicName, "Priority1Subscription").Name,
                ReceiveMode.ReceiveAndDelete);
            var subClient2 = messagingFactory.CreateSubscriptionClient(
                TopicName,
                new SubscriptionDescription(TopicName, "Priority2Subscription").Name,
                ReceiveMode.ReceiveAndDelete);
            var subClient3 = messagingFactory.CreateSubscriptionClient(
                TopicName,
                new SubscriptionDescription(TopicName, "PriorityLessThan2Subscription").Name,
                ReceiveMode.ReceiveAndDelete);

            while (true)
            {
                try
                {
                    // Please see the README.md file regarding this loop and 
                    // the handling strategy below. 
                    var message = await subClient1.ReceiveAsync(TimeSpan.Zero) ??
                                  (await subClient2.ReceiveAsync(TimeSpan.Zero) ?? 
                                   await subClient3.ReceiveAsync(TimeSpan.Zero));

                    if (message != null)
                    {
                        this.OutputMessageInfo("Received: ", message);
                    }
                    else
                    {
                        break;
                    }
                }
                catch (MessageNotFoundException)
                {
                    Console.WriteLine("Got MessageNotFoundException, waiting for messages to be available");
                }
                catch (MessagingException e)
                {
                    Console.WriteLine("Error: " + e.Message);
                }
            }

            Console.WriteLine("\nReceiver complete. press ENTER");
            Console.ReadLine();

            // Cleanup:
            namespaceManager.DeleteTopic(TopicName);
        }
コード例 #27
0
ファイル: BusBuilder.cs プロジェクト: nhuhuynh/Nimbus
        /// <summary>
        ///     Danger! Danger, Will Robinson!
        /// </summary>
        private static void RemoveAllExistingNamespaceElements(NamespaceManager namespaceManager, ILogger logger)
        {
            logger.Debug("Removing all existing namespace elements. IMPORTANT: This should only be done in your regression test suites.");

            var tasks = new List<Task>();
            var queuePaths = namespaceManager.GetQueues().Select(q => q.Path).ToArray();
            queuePaths
                .Do(queuePath => tasks.Add(Task.Run(() => namespaceManager.DeleteQueue(queuePath))))
                .Done();

            var topicPaths = namespaceManager.GetTopics().Select(t => t.Path).ToArray();
            topicPaths
                .Do(topicPath => tasks.Add(Task.Run(() => namespaceManager.DeleteTopic(topicPath))))
                .Done();

            tasks.WaitAll();
        }
コード例 #28
0
 public ServiceBusTopicHelper ClearTopics()
 {
     _subscribers.ForEach((s) => _namespaceManager.DeleteTopic(s.Item1));
     return(this);
 }
コード例 #29
0
        /// <summary>
        /// Receives a notification when a new inter-role communication event occurs.
        /// </summary>
        public override void OnNext(TestRunStartEvent msg)
        {
            var numInstances = RoleEnvironment.CurrentRoleInstance.Role.Instances.Count - 1;

            var topicBaseCommunicator = this.interRoleCommunicator as InterRoleCommunicationExtension;

            if (topicBaseCommunicator != null)
            {
                topicBaseCommunicator.Settings.EnableAsyncPublish  = msg.EnableAsyncPublish;
                topicBaseCommunicator.Settings.EnableAsyncDispatch = msg.EnableAsyncDispatch;
            }

            if (msg.RequireTopicCleanup)
            {
                // Delete the IRC topic first so that instances will have enough time to recreate senders and receivers.
                var serviceBusSettings = ConfigurationManager.GetSection(ServiceBusConfigurationSettings.SectionName) as ServiceBusConfigurationSettings;
                var pubsubType         = ConfigurationManager.AppSettings[CommonConsts.ConfigSettingPubSubType];

                if (pubsubType.Equals(CommonConsts.ConfigSettingPubSubTypeValueTopic))
                {
                    var topicEndpoint = serviceBusSettings.Endpoints.Get(CommonConsts.TopicServiceBusEndpointName);
                    var credentials   = TokenProvider.CreateSharedSecretTokenProvider(topicEndpoint.IssuerName, topicEndpoint.IssuerSecret);
                    var address       = ServiceBusEnvironment.CreateServiceUri("sb", topicEndpoint.ServiceNamespace, String.Empty);
                    var nsManager     = new NamespaceManager(address, credentials);

                    if (nsManager.GetTopics().Where(t => String.Compare(t.Path, topicEndpoint.TopicName, true) == 0).Count() > 0)
                    {
                        nsManager.DeleteTopic(topicEndpoint.TopicName);
                    }
                }
            }

            if (msg.PurgeTraceLogTable)
            {
                // Purge WADLogsTable.
                PurgeTraceLogTable();
            }

            // Tell ACK subscriber how many messages it should expect to receive and reset the ACK counter.
            this.ackSubscriber.SetExpectedAckCount(msg.MessageCount * numInstances);
            this.ackSubscriber.ResetAckCounter();

            var testRun = new TestRunTableEntity()
            {
                TestRunID     = msg.TestRunID,
                MessageCount  = msg.MessageCount,
                MessageSize   = msg.MessageSize,
                InstanceCount = numInstances,
                StartDateTime = DateTime.UtcNow,
                EndDateTime   = new DateTime(1900, 1, 1)
            };

            var testRunsTable = new TestRunEntityTableContext(this.tableClient.BaseUri.ToString(), this.tableClient.Credentials);

            testRunsTable.TableName = this.testRunsTableName;

            try
            {
                testRunsTable.AddTestRun(testRun);
            }
            catch (DataServiceRequestException ex)
            {
                if (ex.IsEntityAlreadyExists())
                {
                    testRunsTable.UpdateTestRun(testRun);
                }
            }

            using (TraceManager.WorkerRoleComponent.TraceScope("Publishing IRC events", msg.TestRunID, msg.MessageCount, msg.MessageSize))
            {
                for (int i = 1; i <= msg.MessageCount; i++)
                {
                    DemoPayload payload = new DemoPayload(msg.TestRunID, i, numInstances, DateTime.UtcNow);

                    // Create a data portion of the payload equal to the message size specified in the test run settings.
                    payload.Data = new byte[msg.MessageSize];
                    (new Random()).NextBytes(payload.Data);

                    InterRoleCommunicationEvent ircEvent = new InterRoleCommunicationEvent(payload);

                    // Update publish time so that it accurately reflects the current time.
                    payload.PublishTickCount = HighResolutionTimer.CurrentTickCount;
                    payload.PublishTime      = DateTime.UtcNow;

                    // Publish the IRC event.
                    this.interRoleCommunicator.Publish(ircEvent);
                }
            }
        }
コード例 #30
0
        public void DeleteTopic(string topicName)
        {
            NamespaceManager namespaceManager = CreateNamespaceManager();

            namespaceManager.DeleteTopic(topicName);
        }
コード例 #31
0
 static void DeleteTopicsAndSubscriptions(NamespaceManager namespaceManager)
 {
     try
     {
         namespaceManager.DeleteTopic(Conts.TopicName);
     }
     catch { }
 }