コード例 #1
0
ファイル: TokenService.cs プロジェクト: dzimchuk/SASRotation
        private async Task <string> GetSharedAccessSignature(string ruleName)
        {
            var queueName = configuration.Find("QueueName");

            var manager     = NamespaceManager.CreateFromConnectionString(configuration.Find("ServiceBusConnectionString"));
            var description = await manager.GetQueueAsync(queueName);

            SharedAccessAuthorizationRule rule;

            if (!description.Authorization.TryGetSharedAccessAuthorizationRule(ruleName, out rule))
            {
                throw new Exception($"Authorization rule {ruleName} was not found");
            }

            var address      = ServiceBusEnvironment.CreateServiceUri("sb", configuration.Find("Namespace"), string.Empty);
            var queueAddress = address + queueName;

            return(SharedAccessSignatureTokenProvider.GetSharedAccessSignature(ruleName, rule.PrimaryKey, queueAddress,
                                                                               TimeSpan.FromSeconds(int.Parse(configuration.Find("SignatureExpiration")))));
        }
コード例 #2
0
        public void ShouldNotCreateInputQueueWhenConfiguredNotTo(AzureServiceBusMode mode)
        {
            var manager   = NamespaceManager.CreateFromConnectionString(StandardAzureServiceBusTransportFactory.ConnectionString);
            var queueName = Guid.NewGuid().ToString("N");

            Assert.IsFalse(manager.QueueExists(queueName));

            var recieverActivator = new BuiltinHandlerActivator();
            var bus = Configure.With(recieverActivator)
                      .Logging(l => l.ColoredConsole())
                      .Transport(t =>
                                 t.UseAzureServiceBus(StandardAzureServiceBusTransportFactory.ConnectionString, queueName, mode)
                                 .DoNotCreateQueues())
                      .Start();

            Assert.IsFalse(manager.QueueExists(queueName));

            Using(recieverActivator);
            Using(bus);
        }
コード例 #3
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);
        }
コード例 #4
0
        protected void SendQueueMessage <T>(T message)
        {
            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }

            // Initialize the connection to Service Bus Queue
            var client = QueueClient.CreateFromConnectionString(connectionString, QueueName);

            // Create message, with the message body being automatically serialized
            BrokeredMessage brokeredMessage = new BrokeredMessage(message);

            brokeredMessage.Properties["messageType"] = message.GetType().AssemblyQualifiedName;
            client.Send(brokeredMessage);
        }
コード例 #5
0
        public void SubscriptionModification()
        {
            string topicName        = "SubscriptionModification";
            string SubscriptionName = "SubscriptionModification".ToLower() + Guid.NewGuid().ToString().Substring(0, 5);
            var    ns = NamespaceManager.CreateFromConnectionString(TestServiceBus.serviceBusConnectionString);

            try
            {
                ns.CreateTopic(topicName);
                SubscriptionDescription initialDesc = ns.CreateSubscription(topicName, SubscriptionName);
                initialDesc.MaxDeliveryCount = 3;
                SubscriptionDescription retDesc = ns.UpdateSubscription(initialDesc);
                SubscriptionDescription getDesc = ns.GetSubscription(topicName, SubscriptionName);
                Assert.IsTrue(getDesc.MaxDeliveryCount == retDesc.MaxDeliveryCount);
            }
            finally
            {
                ns.DeleteTopic(topicName);
            }
        }
コード例 #6
0
        private void InitializeTopic()
        {
            _namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);

            try
            {
                if (!_namespaceManager.TopicExists(_cancellationTopicName))
                {
                    var desc = new TopicDescription(_cancellationTopicName)
                    {
                        DefaultMessageTimeToLive = _cancellationMessageTimeToLive
                    };
                    _namespaceManager.CreateTopic(desc);
                }
            }
            catch { }

            _topicClient = TopicClient.CreateFromConnectionString(_connectionString,
                                                                  _cancellationTopicName);
        }
コード例 #7
0
        static void Main(string[] args)
        {
            NamespaceManager namespaceManager      = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]);
            EventHubClient   eventHubReceiveClient = EventHubClient.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"], EventHubName);
            var consumerGroup            = eventHubReceiveClient.GetDefaultConsumerGroup();
            EventHubDescription eventHub = namespaceManager.GetEventHub(EventHubName);

            // Register event processor with each shard to start consuming messages
            foreach (var partitionId in eventHub.PartitionIds)
            {
                consumerGroup.RegisterProcessor <CustomEventProcessor>(new Lease()
                {
                    PartitionId = partitionId
                }, new CustomCheckpointManager());
            }

            // Wait for the user to exit this application.
            Console.WriteLine("\nPress ENTER to exit...\n");
            Console.ReadLine();
        }
        public async Task Should_properly_set_EnableDeadLetteringOnMessageExpiration_on_the_created_entity()
        {
            var namespaceManager = new NamespaceManagerAdapter(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value));

            var settings   = new DefaultConfigurationValues().Apply(new SettingsHolder());
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.Subscriptions().EnableDeadLetteringOnMessageExpiration(true);

            var creator = new AzureServiceBusSubscriptionCreator(settings);

            const string subscriptionName = "sub7";
            await creator.Create(topicPath, subscriptionName, metadata, sqlFilter, namespaceManager);

            var foundDescription = await namespaceManager.GetSubscription(topicPath, subscriptionName);

            Assert.IsTrue(foundDescription.EnableDeadLetteringOnMessageExpiration);

            await namespaceManager.DeleteSubscription(new SubscriptionDescription(topicPath, subscriptionName));
        }
コード例 #9
0
        public async Task Properly_sets_RequiresDuplicateDetection_on_the_created_entity()
        {
            var namespaceManager = new NamespaceManagerAdapter(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value));

            var settings   = new DefaultConfigurationValues().Apply(new SettingsHolder());
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.Queues().RequiresDuplicateDetection(true);

            var creator = new AzureServiceBusQueueCreator(settings);

            await creator.Create("myqueue", namespaceManager);

            var real = await namespaceManager.GetQueue("myqueue");

            Assert.IsTrue(real.RequiresDuplicateDetection);

            //cleanup
            await namespaceManager.DeleteQueue("myqueue");
        }
コード例 #10
0
        public async Task Properly_sets_DefaultMessageTimeToLive_on_the_created_entity()
        {
            var namespaceManager = new NamespaceManagerAdapter(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value));

            var settings   = new DefaultConfigurationValues().Apply(new SettingsHolder());
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.Queues().DefaultMessageTimeToLive(TimeSpan.FromDays(1));

            var creator = new AzureServiceBusQueueCreator(settings);

            await creator.Create("myqueue", namespaceManager);

            var real = await namespaceManager.GetQueue("myqueue");

            Assert.AreEqual(TimeSpan.FromDays(1), real.DefaultMessageTimeToLive);

            //cleanup
            await namespaceManager.DeleteQueue("myqueue");
        }
コード例 #11
0
        protected WindowsServiceBusClient(IWindowsServiceBusConfiguration sbConfiguration)
        {
            if (sbConfiguration == null)
            {
                throw new ArgumentNullException("sbConfiguration");
            }

            sbConfiguration.Validate();

            try
            {
                NsManager = NamespaceManager.CreateFromConnectionString(sbConfiguration.ConnectionString);
            }
            catch (Exception ex)
            {
                throw new MessagingException(
                          "An error occurred while attempting to access the specified Windows service bus. See inner exception for more details.",
                          ex);
            }
        }
コード例 #12
0
        public async Task Properly_sets_EnableExpress_on_the_created_entity_that_qualifies_condition()
        {
            var namespaceManager = new NamespaceManagerAdapter(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value));

            var settings   = new DefaultConfigurationValues().Apply(new SettingsHolder());
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.Queues().EnableExpress(name => name == "myqueue", true);

            var creator = new AzureServiceBusQueueCreator(settings);

            await creator.Create("myqueue", namespaceManager);

            var real = await namespaceManager.GetQueue("myqueue");

            Assert.IsTrue(real.EnableExpress, "Queue should be marked as express, but it wasn't.");

            //cleanup
            await namespaceManager.DeleteQueue("myqueue");
        }
コード例 #13
0
        public async Task Uses_queue_description_when_provided_by_user()
        {
            var settings         = new DefaultConfigurationValues().Apply(new SettingsHolder());
            var extensions       = new TransportExtensions <AzureServiceBusTransport>(settings);
            var namespaceManager = new NamespaceManagerAdapter(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value));

            var descriptionToUse = new QueueDescription("myqueue");

            extensions.Queues().DescriptionFactory((name, s) => descriptionToUse);

            var creator = new AzureServiceBusQueueCreator(settings);

            var description = await creator.Create("myqueue", namespaceManager);

            Assert.IsTrue(await namespaceManager.QueueExists("myqueue"));
            Assert.AreEqual(descriptionToUse, description);

            //cleanup
            await namespaceManager.DeleteQueue("myqueue");
        }
コード例 #14
0
        public ServiceBusManager(ServiceBusQueueOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _options = options;

            _clients          = new Dictionary <string, QueueClient>(options.Queues.Length);
            _namespaceManager = NamespaceManager.CreateFromConnectionString(options.ConnectionString);
            _messagingFactory = MessagingFactory.CreateFromConnectionString(options.ConnectionString);

            // If we have this option set to true then we will create all clients up-front, otherwise
            // the creation will be delayed until the first client is retrieved
            if (options.CheckAndCreateQueues)
            {
                CreateQueueClients();
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            //Initialize
            ParseArgs(args);
            string           connectionString = GetServiceBusConnectionString();
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            Manage.CreateEventHub(eventHubName, numberOfPartitions, namespaceManager);

            Receiver r = new Receiver(eventHubName, connectionString);

            r.MessageProcessingWithPartitionDistribution();

            Sender s = new Sender(eventHubName, numberOfMessages);

            s.SendEvents();

            Console.WriteLine("Press enter key to stop worker.");
            Console.ReadLine();
        }
        public async Task Should_properly_set_EnableDeadLetteringOnMessageExpiration_on_the_created_entity()
        {
            var namespaceManager = new NamespaceManagerAdapterInternal(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value));

            var settings   = DefaultConfigurationValues.Apply(SettingsHolderFactory.BuildWithSerializer());
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.UseForwardingTopology().Subscriptions().EnableDeadLetteringOnMessageExpiration(true);

            var creator = new AzureServiceBusForwardingSubscriptionCreator(settings.Get <TopologySettings>().SubscriptionSettings);

            const string subscriptionName = "endpoint7";
            await creator.Create(topicPath, subscriptionName, metadata, sqlFilter, namespaceManager, forwardToQueue);

            var foundDescription = await namespaceManager.GetSubscription(topicPath, subscriptionName);

            Assert.IsTrue(foundDescription.EnableDeadLetteringOnMessageExpiration);

            await namespaceManager.DeleteSubscription(new SubscriptionDescription(topicPath, subscriptionName));
        }
コード例 #17
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }

            // Initialize the connection to Service Bus Queue
            Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);
            Client.PrefetchCount = PrefetchCount;

            return(base.OnStart());
        }
コード例 #18
0
        public void SubscriptionCreationCustom()
        {
            string topicName = "SubscriptionCreationCustom";
            string path      = "SubscriptionCreationCustom".ToLower();
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.serviceBusConnectionString);

            try
            {
                ns.CreateTopic(topicName);
                SubscriptionDescription desc        = new SubscriptionDescription(topicName, path);
                SubscriptionDescription initialDesc = ns.CreateSubscription(desc);
                SubscriptionDescription exists      = null;
                Assert.IsTrue(ns.SubscriptionExists(topicName, path, out exists));
            }
            finally
            {
                ns.DeleteSubscription(topicName, path);
                ns.DeleteTopic(topicName);
            }
        }
コード例 #19
0
        internal static async Task <ISubscription> ForAsync(AzureServiceBusConfiguration configuration, Type eventType, string subscriptionName)
        {
            var topicPath = Conventions.TopicPath(eventType);

            var namespaceManager   = NamespaceManager.CreateFromConnectionString(configuration.ConnectionString);
            var subscriptionExists = await namespaceManager.SubscriptionExistsAsync(topicPath, subscriptionName);

            if (!subscriptionExists)
            {
                await namespaceManager.CreateSubscriptionAsync(topicPath, subscriptionName);
            }

            var messagingFactory = MessagingFactory.CreateFromConnectionString(configuration.ConnectionString);

            var subscriptionPath = SubscriptionClient.FormatSubscriptionPath(topicPath, subscriptionName);

            var receiver = await messagingFactory.CreateMessageReceiverAsync(subscriptionPath, ReceiveMode.PeekLock);

            return(new Subscription(receiver, eventType));
        }
        public async Task Should_set_forwarding_to_an_explicitly_provided_forwardto()
        {
            var namespaceManager = new NamespaceManagerAdapterInternal(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value), AzureServiceBusConnectionString.Value);

            var queueCreator     = new AzureServiceBusQueueCreator(new TopologyQueueSettings(), DefaultConfigurationValues.Apply(SettingsHolderFactory.BuildWithSerializer()));
            var queueToForwardTo = await queueCreator.Create("forwardto", namespaceManager);

            var creator = new AzureServiceBusSubscriptionCreator(new TopologySubscriptionSettings());

            const string subscriptionName = "sub15";
            await creator.Create(topicPath, subscriptionName, metadata, sqlFilter, namespaceManager, queueToForwardTo.Path);

            var foundDescription = await namespaceManager.GetSubscription(topicPath, subscriptionName);

            Assert.That(foundDescription.ForwardTo.EndsWith(queueToForwardTo.Path));

            await namespaceManager.DeleteSubscription(new SubscriptionDescription(topicPath, subscriptionName));

            await namespaceManager.DeleteQueue(queueToForwardTo.Path);
        }
        public async Task Should_properly_set_EnableBatchedOperations_on_the_created_entity()
        {
            var namespaceManager = new NamespaceManagerAdapterInternal(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value), AzureServiceBusConnectionString.Value);

            var settings   = DefaultConfigurationValues.Apply(SettingsHolderFactory.BuildWithSerializer());
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.Subscriptions().EnableBatchedOperations(false);

            var creator = new AzureServiceBusSubscriptionCreator(settings.Get <TopologySettings>().SubscriptionSettings);

            const string subscriptionName = "sub5";
            await creator.Create(topicPath, subscriptionName, metadata, sqlFilter, namespaceManager);

            var foundDescription = await namespaceManager.GetSubscription(topicPath, subscriptionName);

            Assert.IsFalse(foundDescription.EnableBatchedOperations);

            await namespaceManager.DeleteSubscription(new SubscriptionDescription(topicPath, subscriptionName));
        }
コード例 #22
0
        static void Main(string[] args)
        {
            while (true)
            {
                var suc = NamespaceManager.CreateFromConnectionString(_connection);

                if (suc.TopicExists(_topicName))
                {
                    var subscription = suc.GetSubscriptions(_topicName).ToList();

                    foreach (var s in subscription)
                    {
                        var name   = s.Name;
                        var active = s.MessageCountDetails.ActiveMessageCount;
                        var dead   = s.MessageCountDetails.DeadLetterMessageCount;

                        Console.WriteLine($"{s.Name}____{s.Status}:::{active} ---- Morti:::{dead}");

                        var infos = new Dictionary <string, SubsInfo>
                        {
                            {
                                name,
                                new SubsInfo()
                                {
                                    ActiveMessage = (int)active,
                                    DeadMessage   = (int)dead,
                                    SubName       = name
                                }
                            }
                        };


                        _CleanMessagesInSub(name, infos.FirstOrDefault());
                    }


                    Console.WriteLine($"------------------------------------------------------------------");
                    Thread.Sleep(3000);
                }
            }
        }
コード例 #23
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(NewWorkOrdersQName))
            {
                namespaceManager.CreateQueue(NewWorkOrdersQName);
            }

            if (!namespaceManager.QueueExists(UpdatedWorkOrersQName))
            {
                namespaceManager.CreateQueue(UpdatedWorkOrersQName);
            }

            if (!namespaceManager.QueueExists(CommunicationPackagesQName))
            {
                namespaceManager.CreateQueue(CommunicationPackagesQName);
            }


            // Initialize the connection to Service Bus Queue
            NewWorkOrders         = QueueClient.CreateFromConnectionString(connectionString, NewWorkOrdersQName);
            UpdatedWorkOrders     = QueueClient.CreateFromConnectionString(connectionString, UpdatedWorkOrersQName);
            CommunicationPackages = QueueClient.CreateFromConnectionString(connectionString, CommunicationPackagesQName);

            Pusher = new PushCommunicator.Pusher();
            PackageSweepLastDone = DateTime.Now.AddSeconds(-60);

            TaskList = new List <Task>();

            IsStopped            = false;
            WOSweepOccuring      = false;
            PackageSweepOccuring = false;

            return(base.OnStart());
        }
コード例 #24
0
        public INamespaceManager Create(string @namespace)
        {
            var namespacesDefinition = settings.Get <NamespaceConfigurations>(WellKnownConfigurationKeys.Topology.Addressing.Namespaces);
            var connectionString     = @namespace;

            if (!ConnectionString.IsConnectionString(connectionString))
            {
                connectionString = namespacesDefinition.GetConnectionString(connectionString);
            }

            NamespaceManager manager;

            if (settingsFactory != null)
            {
                var s       = settingsFactory(connectionString);
                var builder = new ServiceBusConnectionStringBuilder(connectionString);
                manager = new NamespaceManager(builder.GetAbsoluteRuntimeEndpoints(), s);
            }
            else
            {
                if (tokenProviderFactory != null)
                {
                    var s = new NamespaceManagerSettings()
                    {
                        TokenProvider = tokenProviderFactory(connectionString)
                    };
                    var builder = new ServiceBusConnectionStringBuilder(connectionString);
                    manager = new NamespaceManager(builder.GetAbsoluteRuntimeEndpoints(), s);
                }
                else
                {
                    manager = NamespaceManager.CreateFromConnectionString(connectionString);
                }

                if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.NamespaceManagers.RetryPolicy))
                {
                    manager.Settings.RetryPolicy = settings.Get <RetryPolicy>(WellKnownConfigurationKeys.Connectivity.NamespaceManagers.RetryPolicy);
                }
            }
            return(new NamespaceManagerAdapter(manager));
        }
コード例 #25
0
        public async Task Test_LockError_MessageFlow <T>(T _)
            where T : IMessage, new() // be careful with this, if the test doesn't run it's because the T validation is broken
        {
            _.CheckInlineType();      // inline data check

            await NamespaceManager.CreateFromConnectionString(NamespaceHelper.GetConnectionString()).ScorchNamespace();

            MessageQueue.LockTimers.Release();
            MessageQueue.BrokeredMessages.Release();

            using (var ts = new CancellationTokenSource())
                using (IMessenger msn = new Messenger(NamespaceHelper.GetConnectionString()))
                {
                    var message = new T();
                    await msn.Send(message);

                    msn.Receive <T>(
                        async m =>
                    {
                        await m.Lock();
                        await Task.Delay(TimeSpan.FromSeconds(5), ts.Token);
                        await m.Error();

                        ts.Cancel(); // kill switch
                    });

                    try
                    {
                        await Task.Delay(TimeSpan.FromMinutes(2), ts.Token);
                    }
                    catch (TaskCanceledException) { /* soak the kill switch */ }

                    var qClient  = QueueClient.CreateFromConnectionString(NamespaceHelper.GetConnectionString(), QueueClient.FormatDeadLetterPath(typeof(T).GetQueueName()));
                    var rMessage = (await qClient.ReadBatchAsync <T>(1)).First();

                    rMessage.ShouldBeEquivalentTo(message);

                    MessageQueue.BrokeredMessages.Should().BeEmpty();
                    MessageQueue.LockTimers.Should().BeEmpty();
                }
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: jcorioland/GlobalAzure2015
        static void Main(string[] args)
        {
            string sbConnectionString =
                "YOURSERVICEBUSCONNECTIONSTRING";

            string topicName = "SimpleTopic";

            var namespaceManager = NamespaceManager.CreateFromConnectionString(sbConnectionString);


            TopicDescription topicDescription = null;

            if (!namespaceManager.TopicExists(topicName))
            {
                topicDescription = namespaceManager.CreateTopic(topicName);
            }
            else
            {
                topicDescription = namespaceManager.GetTopic(topicName);
            }

            MessagingFactory factory     = MessagingFactory.CreateFromConnectionString(sbConnectionString);
            TopicClient      topicClient = factory.CreateTopicClient(topicDescription.Path);

            CreateSubscription(namespaceManager, factory, topicName, "Subscription1");
            CreateSubscription(namespaceManager, factory, topicName, "Subscription2");
            //CreateSubscription(namespaceManager, factory, topicName, "Subscription2");

            Console.WriteLine("Message à envoyer : ");
            string message = Console.ReadLine();

            while (message != "exit")
            {
                topicClient.Send(new BrokeredMessage(message));

                Console.WriteLine("Message à envoyer : ");
                message = Console.ReadLine();
            }

            topicClient.Close();
        }
コード例 #27
0
        protected async Task ServiceBusQueueTriggerToBlobTestImpl()
        {
            // ServiceBus tests need the following environment var:
            // "AzureWebJobsServiceBus" -- the connection string for the ServiceBus account
            string testQueueName    = "test-input";
            string connectionString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.ServiceBus);
            var    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            await namespaceManager.DeleteQueueAsync(testQueueName);

            await namespaceManager.CreateQueueAsync(testQueueName);

            QueueClient queueClient = QueueClient.CreateFromConnectionString(connectionString, testQueueName);

            var resultBlob = Fixture.TestContainer.GetBlockBlobReference("completed");
            await resultBlob.DeleteIfExistsAsync();

            string  id      = Guid.NewGuid().ToString();
            JObject message = new JObject
            {
                { "count", 0 },
                { "id", id }
            };

            using (Stream stream = new MemoryStream())
                using (TextWriter writer = new StreamWriter(stream))
                {
                    writer.Write(message.ToString());
                    writer.Flush();
                    stream.Position = 0;

                    await queueClient.SendAsync(new BrokeredMessage(stream) { ContentType = "text/plain" });
                }

            queueClient.Close();

            // now wait for function to be invoked
            string result = await TestHelpers.WaitForBlobAsync(resultBlob);

            Assert.Equal(TestHelpers.RemoveByteOrderMarkAndWhitespace(id), TestHelpers.RemoveByteOrderMarkAndWhitespace(result));
        }
コード例 #28
0
        public IMessagePublisher GetPublisher(string connectionString, string publisherName)
        {
            var publisherKey = $"{connectionString}_{publisherName}";

            if (_publishers.TryGetValue(publisherKey, out TopicServiceBusPublisher existingPublisher))
            {
                return(existingPublisher);
            }

            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            var topicDescription = namespaceManager.TopicExists(publisherName)
                ? namespaceManager.GetTopic(publisherName)
                : namespaceManager.CreateTopic(publisherName);

            var publisher = new TopicServiceBusPublisher(connectionString, topicDescription.Path);

            _publishers.TryAdd(publisherKey, publisher);

            return(publisher);
        }
コード例 #29
0
        public void SubscriptionCreationAutoDeleteOnIdle()
        {
            string topicName = "SubscriptionCreationAutoDeleteOnIdle";
            string path      = "SubscriptionCreationAutoDeleteOnIdle".ToLower();
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.serviceBusConnectionString);

            try
            {
                ns.CreateTopic(topicName);
                SubscriptionDescription desc = new SubscriptionDescription(topicName, path);
                desc.AutoDeleteOnIdle = TimeSpan.FromMinutes(6); // min is 5 min
                SubscriptionDescription initialDesc = ns.CreateSubscription(desc);
                SubscriptionDescription exists      = null;
                Assert.IsTrue(ns.SubscriptionExists(topicName, path, out exists));
                Assert.IsTrue(exists.AutoDeleteOnIdle.TotalMinutes == 6);
            }
            finally
            {
                ns.DeleteTopic(topicName);
            }
        }
コード例 #30
0
        public void TopicModification2()
        {
            string TopicName = "TopicModification2".ToLower() + Guid.NewGuid().ToString().Substring(0, 5);
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.serviceBusConnectionString);

            try
            {
                TopicDescription initialDesc = ns.CreateTopic(TopicName);
                TopicDescription newDesc     = new TopicDescription(TopicName);
                newDesc.DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(5);
                TopicDescription retDesc = ns.UpdateTopic(newDesc);
                TopicDescription getDesc = ns.GetTopic(TopicName);
                Assert.IsTrue(getDesc.DuplicateDetectionHistoryTimeWindow == retDesc.DuplicateDetectionHistoryTimeWindow);
                Assert.IsTrue(getDesc.DuplicateDetectionHistoryTimeWindow != initialDesc.DuplicateDetectionHistoryTimeWindow);
                Assert.IsTrue(getDesc.DuplicateDetectionHistoryTimeWindow == newDesc.DuplicateDetectionHistoryTimeWindow);
            }
            finally
            {
                ns.DeleteTopic(TopicName);
            }
        }