예제 #1
0
        /// <summary>
        ///   Creates a Service Bus scope associated with a queue instance, intended to be used in the context
        ///   of a single test and disposed when the test has completed.
        /// </summary>
        ///
        /// <param name="enablePartitioning">When <c>true</c>, partitioning will be enabled on the queue that is created.</param>
        /// <param name="enableSession">When <c>true</c>, a session will be enabled on the queue that is created.</param>
        /// <param name="forceQueueCreation">When <c>true</c>, forces creation of a new queue even if an environmental override was specified to use an existing one.</param>
        /// <param name="caller">The name of the calling method; this is intended to be populated by the runtime.</param>
        ///
        /// <returns>The requested Service Bus <see cref="QueueScope" />.</returns>
        ///
        /// <remarks>
        ///   If an environmental override was set to use an existing Service Bus queue resource and the <paramref name="forceQueueCreation" /> flag
        ///   was not set, the existing queue will be assumed with no validation.  In this case the <paramref name="enablePartitioning" /> and
        ///   <paramref name="enableSession" /> parameters are also ignored.
        /// </remarks>
        ///
        public static async Task <QueueScope> CreateWithQueue(bool enablePartitioning,
                                                              bool enableSession,
                                                              bool forceQueueCreation          = false,
                                                              [CallerMemberName] string caller = "")
        {
            // If there was an override and the force flag is not set for creation, then build a scope
            // for the specified queue.

            if ((!string.IsNullOrEmpty(TestEnvironment.OverrideQueueName)) && (!forceQueueCreation))
            {
                return(new QueueScope(TestEnvironment.ServiceBusNamespace, TestEnvironment.OverrideQueueName, false));
            }

            // Create a new queue specific to the scope being created.

            caller = (caller.Length < 16) ? caller : caller.Substring(0, 15);

            var azureSubscription   = TestEnvironment.ServiceBusAzureSubscription;
            var resourceGroup       = TestEnvironment.ServiceBusResourceGroup;
            var serviceBusNamespace = TestEnvironment.ServiceBusNamespace;
            var token = await AquireManagementTokenAsync().ConfigureAwait(false);

            string CreateName() => $"{ Guid.NewGuid().ToString("D").Substring(0, 13) }-{ caller }";

            using (var client = new ServiceBusManagementClient(new TokenCredentials(token))
            {
                SubscriptionId = azureSubscription
            })
            {
                var queueParameters = new SBQueue(enablePartitioning: enablePartitioning, requiresSession: enableSession, maxSizeInMegabytes: 1024);
                var queue           = await CreateRetryPolicy <SBQueue>().ExecuteAsync(() => client.Queues.CreateOrUpdateAsync(resourceGroup, serviceBusNamespace, CreateName(), queueParameters)).ConfigureAwait(false);

                return(new QueueScope(serviceBusNamespace, queue.Name, true));
            }
        }
예제 #2
0
        public async Task CreateTopicAndSubscription()
        {
#if !SNIPPET
            string topicName        = Guid.NewGuid().ToString("D").Substring(0, 8);
            string subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8);
            string connectionString = TestEnvironment.ServiceBusConnectionString;
            var    client           = new ServiceBusAdministrationClient(connectionString);
#endif
            try
            {
                #region Snippet:CreateTopicAndSubscription
#if SNIPPET
                string connectionString = "<connection_string>";
                string topicName        = "<topic_name>";
                var    client           = new ServiceBusManagementClient(connectionString);
#endif
                var topicOptions = new CreateTopicOptions(topicName)
                {
                    AutoDeleteOnIdle                    = TimeSpan.FromDays(7),
                    DefaultMessageTimeToLive            = TimeSpan.FromDays(2),
                    DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
                    EnableBatchedOperations             = true,
                    EnablePartitioning                  = false,
                    MaxSizeInMegabytes                  = 2048,
                    RequiresDuplicateDetection          = true,
                    UserMetadata = "some metadata"
                };

                topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                                        "allClaims",
                                                        new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));

                TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions);

#if SNIPPET
                string subscriptionName = "<subscription_name>";
#endif
                var subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName)
                {
                    AutoDeleteOnIdle         = TimeSpan.FromDays(7),
                    DefaultMessageTimeToLive = TimeSpan.FromDays(2),
                    EnableBatchedOperations  = true,
                    UserMetadata             = "some metadata"
                };
                SubscriptionProperties createdSubscription = await client.CreateSubscriptionAsync(subscriptionOptions);

                #endregion
                Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic)
                {
                    MaxMessageSizeInKilobytes = topicOptions.MaxMessageSizeInKilobytes
                });
                Assert.AreEqual(subscriptionOptions, new CreateSubscriptionOptions(createdSubscription));
            }
            finally
            {
                await client.DeleteTopicAsync(topicName);
            }
        }
        /// <summary>
        ///   Creates a Service Bus scope associated with a topic instance, intended to be used in the context
        ///   of a single test and disposed when the test has completed.
        /// </summary>
        ///
        /// <param name="enablePartitioning">When <c>true</c>, partitioning will be enabled on the topic that is created.</param>
        /// <param name="enableSession">When <c>true</c>, a session will be enabled on the topic that is created.</param>
        /// <param name="topicSubscriptions">The set of subscriptions to create for the topic.  If <c>null</c>, a default subscription will be assumed.</param>
        /// <param name="forceTopicCreation">When <c>true</c>, forces creation of a new topic even if an environmental override was specified to use an existing one.</param>
        /// <param name="caller">The name of the calling method; this is intended to be populated by the runtime.</param>
        ///
        /// <returns>The requested Service Bus <see cref="TopicScope" />.</returns>
        ///
        /// <remarks>
        ///   If an environmental override was set to use an existing Service Bus queue resource and the <paramref name="forceTopicCreation" /> flag
        ///   was not set, the existing queue will be assumed with no validation.  In this case the <paramref name="enablePartitioning" />,
        ///   <paramref name="enableSession" />, and <paramref name="topicSubscriptions" /> parameters are also ignored.
        /// </remarks>
        ///
        public static async Task <TopicScope> CreateWithTopic(bool enablePartitioning,
                                                              bool enableSession,
                                                              IEnumerable <string> topicSubscriptions = null,
                                                              bool forceTopicCreation          = false,
                                                              [CallerMemberName] string caller = "")
        {
            caller = (caller.Length < 16) ? caller : caller.Substring(0, 15);
            topicSubscriptions ??= new[] { "default-subscription" };

            var azureSubscription   = ServiceBusTestEnvironment.Instance.SubscriptionId;
            var resourceGroup       = ServiceBusTestEnvironment.Instance.ResourceGroup;
            var serviceBusNamespace = ServiceBusTestEnvironment.Instance.ServiceBusNamespace;
            var token = await AquireManagementTokenAsync().ConfigureAwait(false);

            using (var client = new ServiceBusManagementClient(ResourceManagerUri, new TokenCredentials(token))
            {
                SubscriptionId = azureSubscription
            })
            {
                // If there was an override and the force flag is not set for creation, then build a scope for the
                // specified topic.  Query the topic resource to build the list of its subscriptions for the scope.

                if ((!string.IsNullOrEmpty(ServiceBusTestEnvironment.Instance.OverrideTopicName)) && (!forceTopicCreation))
                {
                    var subscriptionPage = await CreateRetryPolicy <IPage <SBSubscription> >().ExecuteAsync(() => client.Subscriptions.ListByTopicAsync(resourceGroup, serviceBusNamespace, ServiceBusTestEnvironment.Instance.OverrideTopicName)).ConfigureAwait(false);

                    var existingSubscriptions = new List <string>(subscriptionPage.Select(item => item.Name));

                    while (!string.IsNullOrEmpty(subscriptionPage.NextPageLink))
                    {
                        subscriptionPage = await CreateRetryPolicy <IPage <SBSubscription> >().ExecuteAsync(() => client.Subscriptions.ListByTopicAsync(resourceGroup, serviceBusNamespace, ServiceBusTestEnvironment.Instance.OverrideTopicName)).ConfigureAwait(false);

                        existingSubscriptions.AddRange(subscriptionPage.Select(item => item.Name));
                    }

                    return(new TopicScope(ServiceBusTestEnvironment.Instance.ServiceBusNamespace, ServiceBusTestEnvironment.Instance.OverrideTopicName, existingSubscriptions, false));
                }

                // Create a new topic specific for the scope being created.

                string CreateName() => $"{ Guid.NewGuid().ToString("D").Substring(0, 13) }-{ caller }";

                var duplicateDetection = TimeSpan.FromMinutes(10);
                var topicParameters    = new SBTopic(enablePartitioning: enablePartitioning, duplicateDetectionHistoryTimeWindow: duplicateDetection, maxSizeInMegabytes: 1024);
                var topic = await CreateRetryPolicy <SBTopic>().ExecuteAsync(() => client.Topics.CreateOrUpdateAsync(resourceGroup, serviceBusNamespace, CreateName(), topicParameters)).ConfigureAwait(false);

                var subscriptionParams = new SBSubscription(requiresSession: enableSession, duplicateDetectionHistoryTimeWindow: duplicateDetection, maxDeliveryCount: 10);

                var activeSubscriptions = await Task.WhenAll
                                          (
                    topicSubscriptions.Select(subscriptionName =>
                                              CreateRetryPolicy <SBSubscription>().ExecuteAsync(() => client.Subscriptions.CreateOrUpdateAsync(resourceGroup, serviceBusNamespace, topic.Name, subscriptionName, subscriptionParams)))

                                          ).ConfigureAwait(false);

                return(new TopicScope(serviceBusNamespace, topic.Name, activeSubscriptions.Select(item => item.Name).ToList(), true));
            }
        }
예제 #4
0
        static async Task MainAsync()
        {
            string token = await GetAuthorizationHeaderAsync()
                           .ConfigureAwait(false);

            TokenCredentials           creds  = new TokenCredentials(token);
            ServiceBusManagementClient client = new ServiceBusManagementClient(creds)
            {
                SubscriptionId = subscriptionId
            };

            // Get alias connstring and Create Service and Consumer Groups.
            // Note: In a real world scenario you would do this operations outside of your client and then add the Alias connection strings to your client.
            String aliasPrimaryConnectionString;
            String aliasSecondaryConnectionString;

            try
            {
                var accessKeys = client.DisasterRecoveryConfigs.ListKeys(resourceGroupName, geoDRPrimaryNS, alias, "RootManageSharedAccessKey");
                aliasPrimaryConnectionString   = accessKeys.AliasPrimaryConnectionString;
                aliasSecondaryConnectionString = accessKeys.AliasSecondaryConnectionString;
            }
            catch
            {
                var accessKeys = client.DisasterRecoveryConfigs.ListKeys(resourceGroupName, geoDRSecondaryNS, alias, "RootManageSharedAccessKey");
                aliasPrimaryConnectionString   = accessKeys.AliasPrimaryConnectionString;
                aliasSecondaryConnectionString = accessKeys.AliasSecondaryConnectionString;
            }

            var ServiceBusConnectionString = aliasPrimaryConnectionString;
            var topicName = "mytopic";

            var topicClient = new TopicClient(ServiceBusConnectionString, topicName);

            try
            {
                for (var i = 0; i < 10; i++)
                {
                    // Create a new message to send to the queue
                    string messageBody = $"Message {i}";
                    var    message     = new Message(Encoding.UTF8.GetBytes(messageBody));

                    // Write the body of the message to the console
                    Console.WriteLine($"Sending message: {messageBody}");

                    // Send the message to the queue
                    await topicClient.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }

            Console.WriteLine("Sending done. Press enter to exit.");
            Console.ReadLine();
        }
예제 #5
0
 public ServiceBusMgmtClient(
     string subscriptionId,
     RestClient restClient
     )
 {
     _serviceBusManagementClient = new ServiceBusManagementClient(restClient)
     {
         SubscriptionId = subscriptionId
     };
 }
        public async Task GetNamespaceProperties()
        {
            var client = new ServiceBusManagementClient(TestEnvironment.ServiceBusConnectionString);

            NamespaceProperties nsInfo = await client.GetNamespacePropertiesAsync();

            Assert.NotNull(nsInfo);
            // Assert.AreEqual(MessagingSku.Standard, nsInfo.MessagingSku);    // Most CI systems generally use standard, hence this check just to ensure the API is working.
            Assert.AreEqual(NamespaceType.Messaging, nsInfo.NamespaceType); // Common namespace type used for testing is messaging.
        }
예제 #7
0
        static async Task MainAsync(string[] args)
        {
            try
            {
                var wiretapId = Guid.NewGuid().ToString();

                var context = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}");

                var result = await context.AcquireTokenAsync(
                    "https://management.core.windows.net/",
                    new ClientCredential(_clientId, _clientSecret)
                    );

                var creds    = new TokenCredentials(result.AccessToken);
                var sbClient = new ServiceBusManagementClient(creds)
                {
                    SubscriptionId = _subscriptionId
                };

                var subscriptionParameters = new SBSubscription
                {
                    DeadLetteringOnMessageExpiration = true,
                    DefaultMessageTimeToLive         = TimeSpan.FromSeconds(30),
                    AutoDeleteOnIdle = TimeSpan.FromMinutes(5)
                };

                await sbClient.Subscriptions.CreateOrUpdateAsync(_resourceGroupName, _serviceBusNamespace, _createOrderTopic, $"WireTap-{wiretapId}", subscriptionParameters);

                await sbClient.Subscriptions.CreateOrUpdateAsync(_resourceGroupName, _serviceBusNamespace, _checkInventoryTopic, $"WireTap-{wiretapId}", subscriptionParameters);

                await sbClient.Subscriptions.CreateOrUpdateAsync(_resourceGroupName, _serviceBusNamespace, _inventoryCheckedTopic, $"WireTap-{wiretapId}", subscriptionParameters);

                await sbClient.Subscriptions.CreateOrUpdateAsync(_resourceGroupName, _serviceBusNamespace, _paymentProcessedTopic, $"WireTap-{wiretapId}", subscriptionParameters);

                _createOrderSubscriptionClient      = new SubscriptionClient(_serviceBusConnectionString, _createOrderTopic, $"WireTap-{wiretapId}");
                _checkInventorySubscriptionClient   = new SubscriptionClient(_serviceBusConnectionString, _checkInventoryTopic, $"WireTap-{wiretapId}");
                _inventoryCheckedSubscriptionClient = new SubscriptionClient(_serviceBusConnectionString, _inventoryCheckedTopic, $"WireTap-{wiretapId}");
                _paymentProcessedSubscriptionClient = new SubscriptionClient(_serviceBusConnectionString, _paymentProcessedTopic, $"WireTap-{wiretapId}");

                RegisterCreateOrderOnMessageHandlerAndReceiveMessages();
                RegisterCheckInventoryOnMessageHandlerAndReceiveMessages();
                RegisterInventoryCheckedOnMessageHandlerAndReceiveMessages();
                RegisterPaymentProcessedOnMessageHandlerAndReceiveMessages();

                Console.WriteLine($"Wiretap Created. Listening for messages...");
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine();
            }

            Console.Read();
        }
        /// <summary>
        /// Creates new instance from ServiceBusClientExtensions
        /// </summary>
        /// <param name="subscription"></param>
        public ServiceBusClientExtensions(AzureSMProfile profile)
        {
            if (profile.Context.Subscription == null)
            {
                throw new ArgumentException(Resources.InvalidDefaultSubscription);
            }

            subscriptionId   = profile.Context.Subscription.Id.ToString();
            Subscription     = profile.Context.Subscription;
            ServiceBusClient = AzureSession.Instance.ClientFactory.CreateClient <ServiceBusManagementClient>(profile, profile.Context.Subscription, AzureEnvironment.Endpoint.ServiceManagement);
        }
예제 #9
0
        public async Task GetUpdateDeleteTopicAndSubscription()
        {
            string topicName           = Guid.NewGuid().ToString("D").Substring(0, 8);
            string subscriptionName    = Guid.NewGuid().ToString("D").Substring(0, 8);
            string connectionString    = TestEnvironment.ServiceBusConnectionString;
            var    client              = new ServiceBusManagementClient(connectionString);
            var    topicOptions        = new CreateTopicOptions(topicName);
            var    subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName);
            await client.CreateTopicAsync(topicOptions);

            await client.CreateSubscriptionAsync(subscriptionOptions);

            #region Snippet:GetTopic
            TopicProperties topic = await client.GetTopicAsync(topicName);

            #endregion
            #region Snippet:GetSubscription
            SubscriptionProperties subscription = await client.GetSubscriptionAsync(topicName, subscriptionName);

            #endregion
            #region Snippet:UpdateTopic
            topic.UserMetadata = "some metadata";
            TopicProperties updatedTopic = await client.UpdateTopicAsync(topic);

            #endregion
            Assert.AreEqual("some metadata", updatedTopic.UserMetadata);

            #region Snippet:UpdateSubscription
            subscription.UserMetadata = "some metadata";
            SubscriptionProperties updatedSubscription = await client.UpdateSubscriptionAsync(subscription);

            #endregion
            Assert.AreEqual("some metadata", updatedSubscription.UserMetadata);

            // need to delete the subscription before the topic, as deleting
            // the topic would automatically delete the subscription
            #region Snippet:DeleteSubscription
            await client.DeleteSubscriptionAsync(topicName, subscriptionName);

            #endregion
            Assert.That(
                async() =>
                await client.GetSubscriptionAsync(topicName, subscriptionName),
                Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));

            #region Snippet:DeleteTopic
            await client.DeleteTopicAsync(topicName);

            #endregion
            Assert.That(
                async() =>
                await client.GetTopicAsync(topicName),
                Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));
        }
        public static ServiceBusManagementClient GetServiceBusManagementClient(MockContext context, RecordedDelegatingHandler handler)
        {
            if (handler != null)
            {
                handler.IsPassThrough = true;
                ServiceBusManagementClient nhManagementClient = context.GetServiceClient <ServiceBusManagementClient>(handlers: handler);
                return(nhManagementClient);
            }

            return(null);
        }
        internal async Task <SBSubscription> InitializeAzureServiceBus(CancellationToken token)
        {
            _logger.LogInformation("initializing azure service bus backend");

            var creds = await GetCredentialsAsync(token).ConfigureAwait(false);

            var client = new ServiceBusManagementClient(creds)
            {
                SubscriptionId = _options.SubscriptionId,
            };

            var subscriptionParams = new SBSubscription
            {
                AutoDeleteOnIdle = TimeSpan.FromMinutes(5),
                MaxDeliveryCount = 1,
            };

            _logger.LogInformation("registering subscription");
            var subscription = await client.Subscriptions.CreateOrUpdateAsync(
                resourceGroupName : _options.ResourceGroup,
                namespaceName : _options.Namespace,
                topicName : _options.Topic,
                subscriptionName : Environment.MachineName,
                parameters : subscriptionParams,
                cancellationToken : token
                ).ConfigureAwait(false);

            _logger.LogInformation("clearing existing rules");
            var allRules = await client.Rules.ListBySubscriptionsAsync(
                resourceGroupName : _options.ResourceGroup,
                namespaceName : _options.Namespace,
                topicName : _options.Topic,
                subscriptionName : subscription.Name,
                cancellationToken : token
                ).ConfigureAwait(false);

            foreach (var rule in allRules)
            {
                await client.Rules.DeleteAsync(
                    resourceGroupName : _options.ResourceGroup,
                    namespaceName : _options.Namespace,
                    topicName : _options.Topic,
                    subscriptionName : subscription.Name,
                    ruleName : rule.Name,
                    cancellationToken : token
                    ).ConfigureAwait(false);
            }

            _logger.LogInformation("azure service bus backplane initialization complete");

            return(subscription);
        }
        /// <summary>
        /// Checks for the existence of a specific Azure Web Site, if it doesn't exist it will create it.
        /// </summary>
        /// <param name="client">The <see cref="ServiceBusManagementClient"/> that is performing the operation.</param>
        /// <param name="model">The DevOpsFlex rich model object that contains everything there is to know about this service bus spec.</param>
        /// <returns>The async <see cref="Task"/> wrapper.</returns>
        public static async Task CreateNamespaceIfNotExistsAsync(this ServiceBusManagementClient client, AzureServiceBusNamespace model)
        {
            Contract.Requires(client != null);
            Contract.Requires(model != null);

            await client.CreateNamespaceIfNotExistsAsync(
                FlexDataConfiguration.GetNaming <AzureServiceBusNamespace>()
                .GetSlotName(
                    model,
                    FlexDataConfiguration.Branch,
                    FlexDataConfiguration.Configuration),
                model.Region.GetEnumDescription());
        }
        private async Task <ServiceBusManagementClient> CreateServiceBusManagementClientAsync()
        {
            var token = await _authContext.GetTokenUsingSecret(_configuration.AzureManagementUrl);

            var credentials = new TokenCredentials(token);

            var serviceBusManagementClient = new ServiceBusManagementClient(credentials)
            {
                SubscriptionId = _configuration.Subscription
            };

            return(serviceBusManagementClient);
        }
        /// <summary>
        ///   Performs the tasks needed to remove an ephemeral Service Bus namespace used as a container for queue and topic instances
        ///   for a specific test run.
        /// </summary>
        ///
        /// <param name="namespaceName">The name of the namespace to delete.</param>
        ///
        public static async Task DeleteNamespaceAsync(string namespaceName)
        {
            var azureSubscription = ServiceBusTestEnvironment.Instance.SubscriptionId;
            var resourceGroup     = ServiceBusTestEnvironment.Instance.ResourceGroup;
            var token             = await AquireManagementTokenAsync().ConfigureAwait(false);

            using (var client = new ServiceBusManagementClient(ResourceManagerUri, new TokenCredentials(token))
            {
                SubscriptionId = azureSubscription
            })
            {
                await CreateRetryPolicy().ExecuteAsync(() => client.Namespaces.DeleteAsync(resourceGroup, namespaceName)).ConfigureAwait(false);
            }
        }
        public async Task ForwardingEntity()
        {
            // queueName--Fwd to--> destinationName--fwd dlq to-- > dqlDestinationName
            var queueName          = Guid.NewGuid().ToString("D").Substring(0, 8);
            var destinationName    = Guid.NewGuid().ToString("D").Substring(0, 8);
            var dlqDestinationName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var mgmtClient         = new ServiceBusManagementClient(TestEnvironment.ServiceBusConnectionString);

            await mgmtClient.CreateQueueAsync(dlqDestinationName);

            await mgmtClient.CreateQueueAsync(
                new CreateQueueOptions(destinationName)
            {
                ForwardDeadLetteredMessagesTo = dlqDestinationName
            });

            await mgmtClient.CreateQueueAsync(
                new CreateQueueOptions(queueName)
            {
                ForwardTo = destinationName
            });

            await using var sbClient = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
            ServiceBusSender sender = sbClient.CreateSender(queueName);
            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "mid"
            });

            ServiceBusReceiver        receiver = sbClient.CreateReceiver(destinationName);
            ServiceBusReceivedMessage msg      = await receiver.ReceiveMessageAsync();

            Assert.NotNull(msg);
            Assert.AreEqual("mid", msg.MessageId);
            await receiver.DeadLetterMessageAsync(msg.LockToken);

            receiver = sbClient.CreateReceiver(dlqDestinationName);
            msg      = await receiver.ReceiveMessageAsync();

            Assert.NotNull(msg);
            Assert.AreEqual("mid", msg.MessageId);
            await receiver.CompleteMessageAsync(msg.LockToken);

            await mgmtClient.DeleteQueueAsync(queueName);

            await mgmtClient.DeleteQueueAsync(destinationName);

            await mgmtClient.DeleteQueueAsync(dlqDestinationName);
        }
예제 #16
0
        public static ServiceBusNamespace[] GetNamespaces(SubscriptionCloudCredentials creds)
        {
            var sbMgmt          = new ServiceBusManagementClient(creds);
            var regionsResponse = sbMgmt.Namespaces.ListAsync( ).Result;

            int currentNamespace = 0, namespaceCount = regionsResponse.Count( );

            ServiceBusNamespace[] namespaces = new ServiceBusNamespace[namespaceCount];
            foreach (var region in regionsResponse)
            {
                namespaces[currentNamespace++] = region;
            }

            return(namespaces);
        }
예제 #17
0
        public static string[] GetRegions(SubscriptionCloudCredentials creds)
        {
            var sbMgmt          = new ServiceBusManagementClient(creds);
            var regionsResponse = sbMgmt.GetServiceBusRegionsAsync( ).Result;

            int currentRegion = 0, regionsCount = regionsResponse.Count( );

            string[] regions = new string[regionsCount];
            foreach (var region in regionsResponse)
            {
                regions[currentRegion++] = region.FullName;
            }

            return(regions);
        }
예제 #18
0
        private static async Task CreateQueue()
        {
            try
            {
                if (string.IsNullOrEmpty(namespaceName))
                {
                    throw new Exception("Namespace name is empty!");
                }

                var token = await GetToken();

                var creds    = new TokenCredentials(token);
                var sbClient = new ServiceBusManagementClient(creds)
                {
                    SubscriptionId = appOptions.SubscriptionId,
                };

                var queueParams = new SBQueue
                {
                    EnablePartitioning = false,
                    DeadLetteringOnMessageExpiration = true,
                    MaxSizeInMegabytes = 1024
                };

                Console.WriteLine("Creating queue...");

                foreach (var fila in appOptions.Queues)
                {
                    try
                    {
                        await sbClient.Queues.CreateOrUpdateAsync(resourceGroupName, namespaceName, fila, queueParams);

                        //var queueExists = await sbClient.Queues.GetAsync(resourceGroupName, namespaceName, QueueName);
                        Console.WriteLine("Created queue successfully.");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Could not create a queue...");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not create a queue...");
                Console.WriteLine(e.Message);
                throw e;
            }
        }
예제 #19
0
        public SBEntityManager(ServiceBusManagementClient client, string resourceGroup, string namespaceName)
        {
            if (String.IsNullOrWhiteSpace(resourceGroup))
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }
            if (String.IsNullOrWhiteSpace(namespaceName))
            {
                throw new ArgumentNullException(nameof(namespaceName));
            }

            Client = client ?? throw new ArgumentNullException(nameof(client));

            ResourceGroup = resourceGroup;
            Namespace     = namespaceName;
        }
        public async Task CreateQueue()
        {
            string queueName        = Guid.NewGuid().ToString("D").Substring(0, 8);
            string connectionString = TestEnvironment.ServiceBusConnectionString;

            try
            {
                #region Snippet:CreateQueue
                //@@ string connectionString = "<connection_string>";
                //@@ string queueName = "<queue_name>";
                var client           = new ServiceBusManagementClient(connectionString);
                var queueDescription = new QueueDescription(queueName)
                {
                    AutoDeleteOnIdle                    = TimeSpan.FromDays(7),
                    DefaultMessageTimeToLive            = TimeSpan.FromDays(2),
                    DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
                    EnableBatchedOperations             = true,
                    DeadLetteringOnMessageExpiration    = true,
                    EnablePartitioning                  = false,
                    ForwardDeadLetteredMessagesTo       = null,
                    ForwardTo                  = null,
                    LockDuration               = TimeSpan.FromSeconds(45),
                    MaxDeliveryCount           = 8,
                    MaxSizeInMegabytes         = 2048,
                    RequiresDuplicateDetection = true,
                    RequiresSession            = true,
                    UserMetadata               = "some metadata"
                };

                queueDescription.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                                            "allClaims",
                                                            new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));

                // The CreateQueueAsync method will return the created queue
                // which would include values for all of the
                // QueueDescription properties (the service will supply
                // default values for properties not included in the creation).
                QueueDescription createdQueue = await client.CreateQueueAsync(queueDescription);

                #endregion
                Assert.AreEqual(queueDescription, createdQueue);
            }
            finally
            {
                await new ServiceBusManagementClient(connectionString).DeleteQueueAsync(queueName);
            }
        }
        /// <summary>
        /// Handles the SelectionChanged event of the SubscriptionList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void SubscriptionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.btnDone.IsEnabled = false;

            this.progressBar.Visibility = Visibility.Visible;
            var selectedSubscription = (sender as ComboBox).SelectedItem as RM.Models.SubscriptionInner;

            Thread serviceBusThread = new Thread(new ThreadStart(() =>
            {
                try
                {
                    TokenCredentials tokenCredentials = new TokenCredentials(this.authResult.AccessToken);
                    ServiceBusManagementClient serviceBusManagementClient = new ServiceBusManagementClient(tokenCredentials);

                    serviceBusManagementClient.SubscriptionId = selectedSubscription.SubscriptionId;

                    List <NamespaceModelInner> serviceBusList = new List <NamespaceModelInner>();
                    var resp = serviceBusManagementClient.Namespaces.List();
                    serviceBusList.AddRange(resp);

                    while (!string.IsNullOrEmpty(resp.NextPageLink))
                    {
                        resp = serviceBusManagementClient.Namespaces.ListNext(resp.NextPageLink);
                        serviceBusList.AddRange(resp);
                    }

                    this.Dispatcher.Invoke(() =>
                    {
                        this.serviceBuses.Clear();
                        this.serviceBuses.Add(newServiceBus);
                        serviceBusList.ForEach(sub => this.serviceBuses.Add(sub));
                        this.comboServiceBusList.IsEnabled = true;
                        this.progressBar.Visibility        = Visibility.Hidden;
                    });
                }
                catch (Exception ex)
                {
                    Logger.LogError(CallInfo.Site(), ex, "Failed to get list of Service bus namespaces");

                    this.Dispatcher.Invoke(() => MessageBox.Show("Failed to get list of Service bus namespaces!!. Exiting", "Azure Error", MessageBoxButton.OKCancel, MessageBoxImage.Error));
                    Application.Current.Shutdown();
                }
            }));

            serviceBusThread.Start();
        }
예제 #22
0
        /// <summary>
        /// Gets the auth rules for a service bus and writes Application data.
        /// </summary>
        /// <param name="rgName">Name of the rg.</param>
        /// <param name="serviceBusManagementClient">The service bus management client.</param>
        /// <param name="selectedServiceBus">The selected service bus.</param>
        private void SetApplicationData(string rgName, ServiceBusManagementClient serviceBusManagementClient, NamespaceModelInner selectedServiceBus)
        {
            List <SharedAccessAuthorizationRuleInner> serviceBusAuthRuleList = new List <SharedAccessAuthorizationRuleInner>();
            var resp = serviceBusManagementClient.Namespaces.ListAuthorizationRulesAsync(rgName, selectedServiceBus.Name).ConfigureAwait(false).GetAwaiter().GetResult();

            serviceBusAuthRuleList.AddRange(resp);

            while (!string.IsNullOrEmpty(resp.NextPageLink))
            {
                resp = serviceBusManagementClient.Namespaces.ListAuthorizationRulesNextAsync(resp.NextPageLink).ConfigureAwait(false).GetAwaiter().GetResult();
                serviceBusAuthRuleList.AddRange(resp);
            }

            var selectedAuthRule = serviceBusAuthRuleList.FirstOrDefault(rule => rule.Rights != null && rule.Rights.Contains(AccessRights.Listen) && rule.Rights.Contains(AccessRights.Manage) && rule.Rights.Contains(AccessRights.Send));

            if (selectedAuthRule == null)
            {
                MessageBox.Show("Failed to find a suitable Authorization rule to use. Please create an Authorization rule with Listen, Manage and Send rights and retry the operation");
                this.Dispatcher.Invoke(() =>
                {
                    this.progressBar.Visibility = Visibility.Hidden;
                    this.btnDone.IsEnabled      = true;
                });
                return;
            }
            else
            {
                ApplicationData.Instance.ServiceBusSharedKey = serviceBusManagementClient.Namespaces.ListKeysAsync(
                    rgName,
                    selectedServiceBus.Name,
                    selectedAuthRule.Name).ConfigureAwait(false).GetAwaiter().GetResult().PrimaryKey;
                ApplicationData.Instance.ServiceBusKeyName = serviceBusManagementClient.Namespaces.ListKeysAsync(
                    rgName,
                    selectedServiceBus.Name,
                    selectedAuthRule.Name).ConfigureAwait(false).GetAwaiter().GetResult().KeyName;
                ApplicationData.Instance.ServiceBusUrl = selectedServiceBus.ServiceBusEndpoint;

                this.Dispatcher.Invoke(() =>
                {
                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();
                    this.Close();
                });
            }
        }
예제 #23
0
        public static IServiceCollection ConfigureServiceBus(this IServiceCollection services, IServiceBusSettings settings)
        {
            var managementClient = new ManagementClient(settings.ConnectionString);
            IServiceBusManagementClient serviceBusManagementClient = new ServiceBusManagementClient(managementClient);

            services.AddSingleton(managementClient);
            services.AddSingleton(serviceBusManagementClient);
            services.AddSingleton <IQueueClient>(new QueueClient(settings.ConnectionString, settings.QueueName));
            services.AddSingleton <ITopicClient>(new TopicClient(settings.ConnectionString, settings.TopicName));
            services.AddSingleton <ISubscriptionClient>(new SubscriptionClient(settings.ConnectionString, settings.TopicName, settings.SubscriptionName));
            services.AddSingleton <IServiceBusClient, ServiceBusClient>();

            serviceBusManagementClient.CreateQueue(settings.QueueName).Wait();
            serviceBusManagementClient.CreateTopic(settings.TopicName).Wait();
            serviceBusManagementClient.CreateSubscription(settings.TopicName, settings.SubscriptionName, settings.Filters).Wait();

            return(services);
        }
        private async Task EnsureTopic()
        {
            var context = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}");
            var token   = await context.AcquireTokenAsync("https://management.azure.com/", new ClientCredential(_clientId, _clientSecret));

            var creds    = new TokenCredentials(token.AccessToken);
            var sbClient = new ServiceBusManagementClient(creds)
            {
                SubscriptionId = _subscriptionId
            };
            var topicParams = new SBTopic()
            {
                EnableExpress           = _enableExpress,
                EnableBatchedOperations = _enableBatchOperations
            };

            await sbClient.Topics.CreateOrUpdateAsync(_resourceGroup, _namespaceName, _topicName, topicParams);
        }
예제 #25
0
 protected void InitializeClients(MockContext context)
 {
     if (!m_initialized)
     {
         lock (m_lock)
         {
             if (!m_initialized)
             {
                 _resourceManagementClient = ServiceBusManagementHelper.GetResourceManagementClient(context, new RecordedDelegatingHandler {
                     StatusCodeToReturn = HttpStatusCode.OK
                 });
                 _serviceBusManagementClient = ServiceBusManagementHelper.GetServiceBusManagementClient(context, new RecordedDelegatingHandler {
                     StatusCodeToReturn = HttpStatusCode.OK
                 });
             }
         }
     }
 }
        public async Task GetTopicRuntimeInfo()
        {
            var topicName        = nameof(GetTopicRuntimeInfo).ToLower() + Guid.NewGuid().ToString("D").Substring(0, 8);
            var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var client           = new ServiceBusManagementClient(TestEnvironment.ServiceBusConnectionString);

            await client.CreateTopicAsync(topicName);

            TopicProperties getTopic = await client.GetTopicAsync(topicName);

            // Changing Last Updated Time
            getTopic.AutoDeleteOnIdle = TimeSpan.FromMinutes(100);
            await client.UpdateTopicAsync(getTopic);

            await client.CreateSubscriptionAsync(topicName, subscriptionName);

            List <TopicRuntimeProperties> runtimeInfoList = new List <TopicRuntimeProperties>();

            await foreach (TopicRuntimeProperties topicRuntimeInfo in client.GetTopicsRuntimePropertiesAsync())
            {
                runtimeInfoList.Add(topicRuntimeInfo);
            }
            runtimeInfoList = runtimeInfoList.Where(e => e.Name.StartsWith(nameof(GetTopicRuntimeInfo).ToLower())).ToList();
            Assert.True(runtimeInfoList.Count == 1, $"Expected 1 topic but {runtimeInfoList.Count} topics returned");
            TopicRuntimeProperties runtimeInfo = runtimeInfoList.First();

            Assert.NotNull(runtimeInfo);

            Assert.AreEqual(topicName, runtimeInfo.Name);
            Assert.True(runtimeInfo.CreatedAt < runtimeInfo.UpdatedAt);
            Assert.True(runtimeInfo.UpdatedAt < runtimeInfo.AccessedAt);
            Assert.AreEqual(1, runtimeInfo.SubscriptionCount);

            TopicRuntimeProperties singleTopicRI = await client.GetTopicRuntimePropertiesAsync(runtimeInfo.Name);

            Assert.AreEqual(runtimeInfo.AccessedAt, singleTopicRI.AccessedAt);
            Assert.AreEqual(runtimeInfo.CreatedAt, singleTopicRI.CreatedAt);
            Assert.AreEqual(runtimeInfo.UpdatedAt, singleTopicRI.UpdatedAt);
            Assert.AreEqual(runtimeInfo.SizeInBytes, singleTopicRI.SizeInBytes);
            Assert.AreEqual(runtimeInfo.SubscriptionCount, singleTopicRI.SubscriptionCount);
            Assert.AreEqual(runtimeInfo.ScheduledMessageCount, singleTopicRI.ScheduledMessageCount);

            await client.DeleteTopicAsync(topicName);
        }
예제 #27
0
        private static async Task CreateNamespace()
        {
            try
            {
                if (!String.IsNullOrEmpty(appOptions.BusNSpace))
                {
                    namespaceName = appOptions.BusNSpace;
                }
                else
                {
                    Console.WriteLine("What would you like to call your Service Bus namespace?");
                    namespaceName = Console.ReadLine();

                    var token = await GetToken();

                    var creds    = new TokenCredentials(token);
                    var sbClient = new ServiceBusManagementClient(creds)
                    {
                        SubscriptionId = appOptions.SubscriptionId,
                    };

                    var namespaceParams = new SBNamespace
                    {
                        Location = appOptions.DataCenterLocation,
                        Sku      = new SBSku()
                        {
                            Tier = appOptions.ServiceBusSkuTier,
                            Name = appOptions.ServiceBusSkuName,
                        }
                    };

                    Console.WriteLine("Creating namespace...");
                    await sbClient.Namespaces.CreateOrUpdateAsync(resourceGroupName, namespaceName, namespaceParams);

                    Console.WriteLine("Created namespace successfully.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not create a namespace...");
                Console.WriteLine(e.Message);
                throw e;
            }
        }
예제 #28
0
        static async Task DeleteAliasSec()
        {
            // https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx#bk_portal
            string token = await GetAuthorizationHeaderAsync().ConfigureAwait(false);

            TokenCredentials           creds  = new TokenCredentials(token);
            ServiceBusManagementClient client = new ServiceBusManagementClient(creds)
            {
                SubscriptionId = subscriptionId
            };

            Console.WriteLine("Deleting the alias. Management operations can take 1-2 minutes to take effect.");
            client.DisasterRecoveryConfigs.Delete(resourceGroupName, geoDRSecondaryNS, alias);

            Console.WriteLine("Wait for the alias to be deleted.");
            await Task.Delay(TimeSpan.FromSeconds(60));

            Console.WriteLine("Alias deleted. Press enter to exit.");
            Console.ReadLine();
        }
        public async Task AuthenticateWithAAD()
        {
            var queueName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var topicName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var client    = new ServiceBusManagementClient(TestEnvironment.FullyQualifiedNamespace, TestEnvironment.Credential);

            var             queueOptions = new CreateQueueOptions(queueName);
            QueueProperties createdQueue = await client.CreateQueueAsync(queueOptions);

            Assert.AreEqual(queueOptions, new CreateQueueOptions(createdQueue));

            var             topicOptions = new CreateTopicOptions(topicName);
            TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions);

            Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic));

            await client.DeleteQueueAsync(queueName);

            await client.DeleteTopicAsync(topicName);
        }
        public async Task AuthenticateWithAAD()
        {
            var queueName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var topicName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var client    = new ServiceBusManagementClient(TestEnvironment.FullyQualifiedNamespace, TestEnvironment.Credential);

            QueueDescription queueDescription = new QueueDescription(queueName);
            QueueDescription createdQueue     = await client.CreateQueueAsync(queueDescription);

            Assert.AreEqual(queueDescription, createdQueue);

            TopicDescription topicDescription = new TopicDescription(topicName);
            TopicDescription createdTopic     = await client.CreateTopicAsync(topicDescription);

            Assert.AreEqual(topicDescription, createdTopic);

            await client.DeleteQueueAsync(queueName);

            await client.DeleteTopicAsync(topicName);
        }