public async Task ClientCanConnectUsingSasCredential()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: false))
            {
                var options          = new ServiceBusClientOptions();
                var audience         = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName);
                var connectionString = TestEnvironment.BuildConnectionStringWithSharedAccessSignature(scope.QueueName, audience);
                var parsed           = ServiceBusConnectionStringProperties.Parse(connectionString);
                var credential       = new AzureSasCredential(parsed.SharedAccessSignature);

                await using (var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, credential, options))
                {
                    Assert.That(async() =>
                    {
                        ServiceBusReceiver receiver = null;

                        try
                        {
                            receiver = client.CreateReceiver(scope.QueueName);
                        }
                        finally
                        {
                            await(receiver?.DisposeAsync() ?? new ValueTask());
                        }
                    }, Throws.Nothing);
                }
            }
        }
Exemplo n.º 2
0
        public void ToConnectionStringAllowsSharedAccessSignatureAuthorization()
        {
            var fakeConnection = "Endpoint=sb://not-real.servicebus.windows.net/;SharedAccessSignature=[not_real]";
            var properties     = ServiceBusConnectionStringProperties.Parse(fakeConnection);

            Assert.That(() => properties.ToConnectionString(), Throws.Nothing, "Validation should accept the shared access signature authorization.");
        }
Exemplo n.º 3
0
        private async Task ServiceBusMessagePump_PublishServiceBusMessage_MessageSuccessfullyProcessed(Encoding messageEncoding, string connectionStringKey)
        {
            // Arrange
            var operationId      = Guid.NewGuid().ToString();
            var transactionId    = Guid.NewGuid().ToString();
            var connectionString = Configuration.GetValue <string>(connectionStringKey);
            ServiceBusConnectionStringProperties serviceBusConnectionString = ServiceBusConnectionStringProperties.Parse(connectionString);

            await using (var client = new ServiceBusClient(connectionString))
                await using (ServiceBusSender messageSender = client.CreateSender(serviceBusConnectionString.EntityPath))
                {
                    var order        = OrderGenerator.Generate();
                    var orderMessage = order.AsServiceBusMessage(operationId, transactionId, encoding: messageEncoding);

                    // Act
                    await messageSender.SendMessageAsync(orderMessage);

                    // Assert
                    var receivedEvent = _serviceBusEventConsumerHost.GetReceivedEvent(operationId);
                    Assert.NotEmpty(receivedEvent);
                    var deserializedEventGridMessage = EventParser.Parse(receivedEvent);
                    Assert.NotNull(deserializedEventGridMessage);
                    var orderCreatedEvent = Assert.Single(deserializedEventGridMessage.Events);
                    Assert.NotNull(orderCreatedEvent);
                    var orderCreatedEventData = orderCreatedEvent.GetPayload <OrderCreatedEventData>();
                    Assert.NotNull(orderCreatedEventData);
                    Assert.NotNull(orderCreatedEventData.CorrelationInfo);
                    Assert.Equal(order.Id, orderCreatedEventData.Id);
                    Assert.Equal(order.Amount, orderCreatedEventData.Amount);
                    Assert.Equal(order.ArticleNumber, orderCreatedEventData.ArticleNumber);
                    Assert.Equal(transactionId, orderCreatedEventData.CorrelationInfo.TransactionId);
                    Assert.Equal(operationId, orderCreatedEventData.CorrelationInfo.OperationId);
                    Assert.NotEmpty(orderCreatedEventData.CorrelationInfo.CycleId);
                }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Tries receiving a single dead lettered message on the Azure Service Bus dead letter queue.
        /// </summary>
        /// <param name="connectionString">The connection string to connect to the Azure Service Bus.</param>
        public async Task AssertDeadLetterMessageAsync(string connectionString)
        {
            var properties = ServiceBusConnectionStringProperties.Parse(connectionString);
            var options    = new ServiceBusReceiverOptions {
                SubQueue = SubQueue.DeadLetter
            };

            await using (var client = new ServiceBusClient(connectionString))
                await using (var receiver = client.CreateReceiver(properties.EntityPath, options))
                {
                    RetryPolicy <ServiceBusReceivedMessage> retryPolicy =
                        Policy.HandleResult <ServiceBusReceivedMessage>(result => result is null)
                        .WaitAndRetryForeverAsync(index => TimeSpan.FromSeconds(1));

                    await Policy.TimeoutAsync(TimeSpan.FromMinutes(2))
                    .WrapAsync(retryPolicy)
                    .ExecuteAsync(async() =>
                    {
                        ServiceBusReceivedMessage message = await receiver.ReceiveMessageAsync();
                        if (message != null)
                        {
                            _logger.LogInformation("Received dead lettered message in test suite");
                            await receiver.CompleteMessageAsync(message);
                        }
                        else
                        {
                            _logger.LogInformation("No dead lettered message received in test suite, retrying...");
                        }

                        return(message);
                    });
                }
        }
Exemplo n.º 5
0
        public async Task ServiceBusQueueMessagePumpUsingManagedIdentity_PublishServiceBusMessage_MessageSuccessfullyProcessed()
        {
            // Arrange
            var    config           = TestConfig.Create();
            string connectionString = config.GetServiceBusConnectionString(ServiceBusEntityType.Queue);
            ServiceBusConnectionStringProperties properties = ServiceBusConnectionStringProperties.Parse(connectionString);

            ServicePrincipal servicePrincipal = config.GetServiceBusServicePrincipal();
            string           tenantId         = config.GetTenantId();

            using (TemporaryEnvironmentVariable.Create(EnvironmentVariables.AzureTenantId, tenantId))
                using (TemporaryEnvironmentVariable.Create(EnvironmentVariables.AzureServicePrincipalClientId, servicePrincipal.ClientId))
                    using (TemporaryEnvironmentVariable.Create(EnvironmentVariables.AzureServicePrincipalClientSecret, servicePrincipal.ClientSecret))
                    {
                        var options = new WorkerOptions();
                        options.AddEventGridPublisher(config)
                        .AddServiceBusQueueMessagePumpUsingManagedIdentity(
                            queueName: properties.EntityPath,
                            serviceBusNamespace: properties.FullyQualifiedNamespace,
                            clientId: servicePrincipal.ClientId,
                            configureMessagePump: opt => opt.AutoComplete = true)
                        .WithServiceBusMessageHandler <OrdersAzureServiceBusMessageHandler, Order>();

                        // Act
                        await using (var worker = await Worker.StartNewAsync(options))
                            await using (var service = await TestMessagePumpService.StartNewAsync(config, _logger))
                            {
                                // Assert
                                await service.SimulateMessageProcessingAsync(connectionString);
                            }
                    }
        }
Exemplo n.º 6
0
        public AzureServiceBusTestEnvironment(IMessageSink messageSink)
        {
            var solutionRoot = SolutionPaths.Root;
            var terraformResourceDirectory = Path.Combine(solutionRoot, "build", "terraform", "azure", "service_bus");
            var credentials = AzureCredentials.Instance;

            // don't try to run terraform if not authenticated.
            if (credentials is Unauthenticated)
            {
                return;
            }

            _terraform = new TerraformResources(terraformResourceDirectory, credentials, messageSink);

            var resourceGroupName = AzureResources.CreateResourceGroupName("service-bus-test");

            _variables = new Dictionary <string, string>
            {
                ["resource_group"]       = resourceGroupName,
                ["servicebus_namespace"] = "dotnet-" + Guid.NewGuid()
            };

            _terraform.Init();
            _terraform.Apply(_variables);

            ServiceBusConnectionString           = _terraform.Output("connection_string");
            ServiceBusConnectionStringProperties = ServiceBusConnectionStringProperties.Parse(ServiceBusConnectionString);
        }
Exemplo n.º 7
0
        public MessagingConfiguration(IOptions <MessageSources> messageSources, MessageHandlerRegistry registry, IServiceScopeFactory scopeFactory, LogCorrelationHandler logCorrelationHandler)
        {
            ServiceBusClient CreateClient(MessageSource s)
            {
                if (!string.IsNullOrEmpty(s.ConnectionString))
                {
                    return(new ServiceBusClient(s.ConnectionString));
                }
                if (s.CredentialType == nameof(AzureCliCredential))
                {
                    return(new ServiceBusClient(s.Namespace, new AzureCliCredential()));
                }
                if (s.CredentialType == nameof(DefaultAzureCredential))
                {
                    return(new ServiceBusClient(s.Namespace, new DefaultAzureCredential()));
                }
                throw new InvalidOperationException("Could not create ServiceBusClient");
            }

            string GetEntityName(MessageSource s) =>
            string.IsNullOrEmpty(s.EntityName) ?
            ServiceBusConnectionStringProperties.Parse(s.ConnectionString).EntityPath :
            s.EntityName;

            (ServiceBusClient, ServiceBusProcessor) CreateSubscriptionClient(Subscription s)
            {
                var client = CreateClient(s);

                return(client, client.CreateProcessor(GetEntityName(s), s.Name,
                                                      new ServiceBusProcessorOptions
                {
                    AutoCompleteMessages = false,
                    MaxConcurrentCalls = s.MaxConcurrentCalls
                }));
            }

            (ServiceBusClient, ServiceBusProcessor) CreateQueueClient(Queue q)
            {
                var client = CreateClient(q);

                return(client, client.CreateProcessor(GetEntityName(q),
                                                      new ServiceBusProcessorOptions
                {
                    AutoCompleteMessages = false,
                    MaxConcurrentCalls = q.MaxConcurrentCalls
                }));
            }

            Dispatchers = messageSources
                          .Value
                          .Subscriptions
                          .Select(subscription => new MessageDispatcher(scopeFactory, CreateSubscriptionClient(subscription), registry, logCorrelationHandler))
                          .Concat(
                messageSources
                .Value
                .Queues
                .Select(queue => new MessageDispatcher(scopeFactory, CreateQueueClient(queue), registry, logCorrelationHandler))
                )
                          .ToList();
        }
Exemplo n.º 8
0
        public async Task ServiceBusTopicMessagePumpWithNamespaceScopedConnectionString_PublishesServiceBusMessage_MessageSuccessfullyProcessed()
        {
            // Arrange
            var    config = TestConfig.Create();
            string topicConnectionString     = config.GetServiceBusConnectionString(ServiceBusEntityType.Topic);
            var    properties                = ServiceBusConnectionStringProperties.Parse(topicConnectionString);
            string namespaceConnectionString = properties.GetNamespaceConnectionString();

            var options = new WorkerOptions();

            options.AddEventGridPublisher(config)
            .AddServiceBusTopicMessagePump(
                topicName: properties.EntityPath,
                subscriptionName: "Test-Receive-All-Topic-Only",
                getConnectionStringFromConfigurationFunc: configuration => namespaceConnectionString,
                configureMessagePump: opt => opt.AutoComplete = true)
            .WithServiceBusMessageHandler <OrdersAzureServiceBusMessageHandler, Order>();

            // Act
            await using (var worker = await Worker.StartNewAsync(options))
                await using (var service = await TestMessagePumpService.StartNewAsync(config, _logger))
                {
                    // Assert
                    await service.SimulateMessageProcessingAsync(topicConnectionString);
                }
        }
        private string DetermineEntityPath(string connectionString = null)
        {
            if (_tokenCredential is null && !string.IsNullOrWhiteSpace(connectionString))
            {
                var properties = ServiceBusConnectionStringProperties.Parse(connectionString);

                if (string.IsNullOrWhiteSpace(properties.EntityPath))
                {
                    // Connection string doesn't include the entity so we're using the message pump settings
                    if (string.IsNullOrWhiteSpace(EntityName))
                    {
                        throw new ArgumentException("No Azure Service Bus entity name was specified while the connection string is scoped to the namespace");
                    }

                    return(EntityName);
                }

                return(properties.EntityPath);
            }

            if (string.IsNullOrWhiteSpace(EntityName))
            {
                throw new ArgumentException("No Azure Service Bus entity name was specified while the managed identity authentication requires this");
            }

            return(EntityName);
        }
Exemplo n.º 10
0
        public MessagePublisher(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString) || !connectionString.ToLower().Contains("entitypath"))
            {
                throw new ArgumentNullException($"ConnectionString must be supplied with EnitityPath");
            }

            _entityPath = ServiceBusConnectionStringProperties.Parse(connectionString).EntityPath;
            _client     = new ServiceBusClient(connectionString);
        }
        /// <summary>
        ///   Ensures that a Service Bus namespace is available.  If the <see cref="ServiceBusConnectionString"/> override was set for the environment,
        ///   that namespace will be respected.  Otherwise, a new Service Bus namespace will be created on Azure for this test run.
        /// </summary>
        ///
        /// <returns>The active Service Bus namespace for this test run.</returns>
        ///
        private NamespaceProperties ParseServiceBusNamespace(string serviceBusConnectionString)
        {
            var parsed = ServiceBusConnectionStringProperties.Parse(serviceBusConnectionString);

            return(new NamespaceProperties
                   (
                       parsed.Endpoint.Host.Substring(0, parsed.Endpoint.Host.IndexOf('.')),
                       serviceBusConnectionString.Replace($";EntityPath={parsed.EntityPath}", string.Empty),
                       false
                   ));
        }
        private ServiceBusAdministrationClient CreateSharedKeyTokenClient()
        {
            var properties = ServiceBusConnectionStringProperties.Parse(GetConnectionString());
            var credential = new AzureNamedKeyCredential(properties.SharedAccessKeyName, properties.SharedAccessKey);

            return(InstrumentClient(
                       new ServiceBusAdministrationClient(
                           TestEnvironment.FullyQualifiedNamespace,
                           credential,
                           InstrumentClientOptions(new ServiceBusAdministrationClientOptions()))));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Sends an Azure Service Bus message to the message pump.
        /// </summary>
        /// <param name="connectionString">The connection string to connect to the service bus.</param>
        /// <param name="message">The message to send.</param>
        public async Task SendMessageToServiceBusAsync(string connectionString, ServiceBusMessage message)
        {
            Guard.NotNullOrWhitespace(connectionString, nameof(connectionString));

            ServiceBusConnectionStringProperties serviceBusConnectionString = ServiceBusConnectionStringProperties.Parse(connectionString);

            await using (var client = new ServiceBusClient(connectionString))
                await using (ServiceBusSender messageSender = client.CreateSender(serviceBusConnectionString.EntityPath))
                {
                    await messageSender.SendMessageAsync(message);
                }
        }
        private ServiceBusAdministrationClient CreateSasTokenClient()
        {
            var properties = ServiceBusConnectionStringProperties.Parse(GetConnectionString());
            var resource   = ServiceBusAdministrationClient.BuildAudienceResource(TestEnvironment.FullyQualifiedNamespace);
            var signature  = new SharedAccessSignature(resource, properties.SharedAccessKeyName, properties.SharedAccessKey);
            var credential = new AzureSasCredential(signature.Value);

            return(InstrumentClient(
                       new ServiceBusAdministrationClient(
                           TestEnvironment.FullyQualifiedNamespace,
                           credential,
                           InstrumentClientOptions(new ServiceBusAdministrationClientOptions()))));
        }
Exemplo n.º 15
0
        public void ParseIgnoresUnknownTokens()
        {
            var endpoint         = "test.endpoint.com";
            var eventHub         = "some-path";
            var sasKey           = "sasKey";
            var sasKeyName       = "sasName";
            var connectionString = $"Endpoint=sb://{ endpoint };SharedAccessKeyName={ sasKeyName };Unknown=INVALID;SharedAccessKey={ sasKey };EntityPath={ eventHub };Trailing=WHOAREYOU";
            var parsed           = ServiceBusConnectionStringProperties.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.EntityPath, Is.EqualTo(eventHub), "The Service Bus path should match.");
        }
Exemplo n.º 16
0
 public async Task SendWithNamedKeyCredential()
 {
     await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
     {
         var properties = ServiceBusConnectionStringProperties.Parse(TestEnvironment.ServiceBusConnectionString);
         var credential = new AzureNamedKeyCredential(properties.SharedAccessKeyName, properties.SharedAccessKey);
         await using var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, credential, new ServiceBusClientOptions
         {
             TransportType = ServiceBusTransportType.AmqpWebSockets
         });
         var sender = client.CreateSender(scope.QueueName);
         await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
     }
 }
Exemplo n.º 17
0
        private static ServiceBusReceiver CreateServiceBusReceiver(
            ServiceBusClient client,
            string connectionString,
            string subscriptionName)
        {
            var properties = ServiceBusConnectionStringProperties.Parse(connectionString);

            if (subscriptionName is null)
            {
                return(client.CreateReceiver(properties.EntityPath));
            }

            return(client.CreateReceiver(properties.EntityPath, subscriptionName));
        }
Exemplo n.º 18
0
        public void ParseCorrectlyParsesANamespaceConnectionString()
        {
            var endpoint              = "test.endpoint.com";
            var sasKey                = "sasKey";
            var sasKeyName            = "sasName";
            var sharedAccessSignature = "fakeSAS";
            var connectionString      = $"Endpoint=sb://{ endpoint };SharedAccessKeyName={ sasKeyName };SharedAccessKey={ sasKey };SharedAccessSignature={ sharedAccessSignature }";
            var parsed                = ServiceBusConnectionStringProperties.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.SharedAccessSignature, Is.EqualTo(sharedAccessSignature), "The precomputed SAS should match.");
            Assert.That(parsed.EntityPath, Is.Null, "The Service Bus path was not included in the connection string");
        }
Exemplo n.º 19
0
        public void ParseDoesNotForceTokenOrdering(string connectionString,
                                                   string endpoint,
                                                   string eventHub,
                                                   string sasKeyName,
                                                   string sasKey,
                                                   string shardAccessSignature)
        {
            var parsed = ServiceBusConnectionStringProperties.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.SharedAccessSignature, Is.EqualTo(shardAccessSignature), "The precomputed SAS should match.");
            Assert.That(parsed.EntityPath, Is.EqualTo(eventHub), "The Service Bus path should match.");
        }
Exemplo n.º 20
0
        /// <summary>
        /// Simulate the message processing of the message pump using the Service Bus.
        /// </summary>
        public async Task SimulateMessageProcessingAsync()
        {
            if (_serviceBusEventConsumerHost is null)
            {
                throw new InvalidOperationException(
                          "Cannot simulate the message pump because the service is not yet started; please start this service before simulating");
            }

            var operationId   = Guid.NewGuid().ToString();
            var transactionId = Guid.NewGuid().ToString();

            string connectionString           = _configuration.GetServiceBusConnectionString(_entity);
            var    connectionStringProperties = ServiceBusConnectionStringProperties.Parse(connectionString);

            await using (var client = new ServiceBusClient(connectionString))
                await using (ServiceBusSender messageSender = client.CreateSender(connectionStringProperties.EntityPath))
                {
                    try
                    {
                        Order             order        = GenerateOrder();
                        ServiceBusMessage orderMessage = order.AsServiceBusMessage(operationId, transactionId);
                        await messageSender.SendMessageAsync(orderMessage);

                        string receivedEvent = _serviceBusEventConsumerHost.GetReceivedEvent(operationId);
                        Assert.NotEmpty(receivedEvent);

                        EventBatch <Event> eventBatch = EventParser.Parse(receivedEvent);
                        Assert.NotNull(eventBatch);
                        Event orderCreatedEvent = Assert.Single(eventBatch.Events);
                        Assert.NotNull(orderCreatedEvent);

                        var orderCreatedEventData = orderCreatedEvent.GetPayload <OrderCreatedEventData>();
                        Assert.NotNull(orderCreatedEventData);
                        Assert.NotNull(orderCreatedEventData.CorrelationInfo);
                        Assert.Equal(order.Id, orderCreatedEventData.Id);
                        Assert.Equal(order.Amount, orderCreatedEventData.Amount);
                        Assert.Equal(order.ArticleNumber, orderCreatedEventData.ArticleNumber);
                        Assert.Equal(transactionId, orderCreatedEventData.CorrelationInfo.TransactionId);
                        Assert.Equal(operationId, orderCreatedEventData.CorrelationInfo.OperationId);
                        Assert.NotEmpty(orderCreatedEventData.CorrelationInfo.CycleId);
                    }
                    finally
                    {
                        await messageSender.CloseAsync();
                    }
                }
        }
Exemplo n.º 21
0
        public void ParseDoesAcceptsHostNamesAndUrisForTheEndpoint(string endpointValue)
        {
            var connectionString = $"Endpoint={ endpointValue };EntityPath=dummy";
            var parsed           = ServiceBusConnectionStringProperties.Parse(connectionString);

            if (!Uri.TryCreate(endpointValue, UriKind.Absolute, out var valueUri))
            {
                valueUri = new Uri($"fake://{ endpointValue }");
            }

            Assert.That(parsed.Endpoint.Port, Is.EqualTo(-1), "The default port should be used.");
            Assert.That(parsed.Endpoint.Host, Does.Not.Contain(" "), "The host name should not contain any spaces.");
            Assert.That(parsed.Endpoint.Host, Does.Not.Contain(":"), "The host name should not contain any port separators (:).");
            Assert.That(parsed.Endpoint.Host, Does.Not.Contain(valueUri.Port), "The host name should not contain the port.");
            Assert.That(parsed.Endpoint.Host, Is.EqualTo(valueUri.Host), "The host name should have been normalized.");
            Assert.That(parsed.Endpoint.ToString(), Does.StartWith(GetServiceBusEndpointScheme()), "The parser's endpoint scheme should have been used.");
        }
Exemplo n.º 22
0
        public void ToConnectionStringProducesTheConnectionStringForSharedAccessSignatures()
        {
            var properties = new ServiceBusConnectionStringProperties
            {
                Endpoint              = new Uri("sb://place.endpoint.ext"),
                EntityPath            = "HubName",
                SharedAccessSignature = "FaKe#$1324@@"
            };

            var connectionString = properties.ToConnectionString();

            Assert.That(connectionString, Is.Not.Null, "The connection string should not be null.");
            Assert.That(connectionString.Length, Is.GreaterThan(0), "The connection string should have content.");

            var parsed = ServiceBusConnectionStringProperties.Parse(connectionString);

            Assert.That(parsed, Is.Not.Null, "The connection string should be parsable.");
            Assert.That(PropertiesAreEquivalent(properties, parsed), Is.True, "The connection string should parse into the source properties.");
        }
Exemplo n.º 23
0
        /// <summary>
        ///   Ensures that a Service Bus namespace is available.  If the <see cref="OverrideServiceBusConnectionString"/> override was set for the environment,
        ///   that namespace will be respected.  Otherwise, a new Service Bus namespace will be created on Azure for this test run.
        /// </summary>
        ///
        /// <returns>The active Service Bus namespace for this test run.</returns>
        ///
        private NamespaceProperties EnsureServiceBusNamespace()
        {
            if (!string.IsNullOrEmpty(OverrideServiceBusConnectionString))
            {
                var parsed = ServiceBusConnectionStringProperties.Parse(OverrideServiceBusConnectionString);

                return(new NamespaceProperties
                       (
                           parsed.Endpoint.Host.Substring(0, parsed.Endpoint.Host.IndexOf('.')),
                           OverrideServiceBusConnectionString.Replace($";EntityPath={ parsed.EntityPath }", string.Empty),
                           false
                       ));
            }

            return(Task
                   .Run(async() => await ServiceBusScope.CreateNamespaceAsync().ConfigureAwait(false))
                   .ConfigureAwait(false)
                   .GetAwaiter()
                   .GetResult());
        }
Exemplo n.º 24
0
        public async Task ServiceBusQueueMessagePumpWithNamespaceScopedConnectionString_PublishesServiceBusMessage_MessageSuccessfullyProcessed()
        {
            // Arrange
            var    config = TestConfig.Create();
            string entityConnectionString    = config.GetServiceBusConnectionString(ServiceBusEntityType.Queue);
            var    properties                = ServiceBusConnectionStringProperties.Parse(entityConnectionString);
            string namespaceConnectionString = properties.GetNamespaceConnectionString();

            var options = new WorkerOptions();

            options.AddEventGridPublisher(config)
            .AddServiceBusQueueMessagePump(properties.EntityPath, configuration => namespaceConnectionString, opt => opt.AutoComplete = true)
            .WithServiceBusMessageHandler <OrdersAzureServiceBusMessageHandler, Order>();

            // Act
            await using (var worker = await Worker.StartNewAsync(options))
                await using (var service = await TestMessagePumpService.StartNewAsync(config, _logger))
                {
                    // Assert
                    await service.SimulateMessageProcessingAsync(entityConnectionString);
                }
        }
Exemplo n.º 25
0
        public void ToConnectionStringNormalizesTheEndpointScheme(string scheme)
        {
            var properties = new ServiceBusConnectionStringProperties
            {
                Endpoint            = new Uri(string.Concat(scheme, "myhub.servicebus.windows.net")),
                EntityPath          = "HubName",
                SharedAccessKey     = "FaKe#$1324@@",
                SharedAccessKeyName = "RootSharedAccessManagementKey"
            };

            var connectionString = properties.ToConnectionString();

            Assert.That(connectionString, Is.Not.Null, "The connection string should not be null.");
            Assert.That(connectionString.Length, Is.GreaterThan(0), "The connection string should have content.");

            var parsed = ServiceBusConnectionStringProperties.Parse(connectionString);

            Assert.That(parsed, Is.Not.Null, "The connection string should be parsable.");
            Assert.That(parsed.Endpoint.Host, Is.EqualTo(properties.Endpoint.Host), "The host name of the endpoints should match.");

            var expectedScheme = new Uri(string.Concat(GetServiceBusEndpointScheme(), "fake.fake.com")).Scheme;

            Assert.That(parsed.Endpoint.Scheme, Is.EqualTo(expectedScheme), "The endpoint scheme should have been overridden.");
        }
Exemplo n.º 26
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="ServiceBusTestEnvironment"/> class.
 /// </summary>
 ///
 public ServiceBusTestEnvironment() : base("servicebus")
 {
     ActiveServiceBusNamespace = new Lazy <NamespaceProperties>(EnsureServiceBusNamespace, LazyThreadSafetyMode.ExecutionAndPublication);
     ParsedConnectionString    = new Lazy <ServiceBusConnectionStringProperties>(() => ServiceBusConnectionStringProperties.Parse(ServiceBusConnectionString), LazyThreadSafetyMode.ExecutionAndPublication);
 }
Exemplo n.º 27
0
        public void ParseToConnectionStringsArguments(string connectionString)
        {
            ExactTypeConstraint typeConstraint = connectionString is null ? Throws.ArgumentNullException : Throws.ArgumentException;

            Assert.That(() => ServiceBusConnectionStringProperties.Parse(connectionString), typeConstraint);
        }
Exemplo n.º 28
0
        public void ParseDoesNotAllowAnInvalidEndpointFormat(string endpointValue)
        {
            var connectionString = $"Endpoint={endpointValue }";

            Assert.That(() => ServiceBusConnectionStringProperties.Parse(connectionString), Throws.InstanceOf <FormatException>());
        }
Exemplo n.º 29
0
 public void ParseConsidersMissingValuesAsMalformed(string connectionString)
 {
     Assert.That(() => ServiceBusConnectionStringProperties.Parse(connectionString), Throws.InstanceOf <FormatException>());
 }
 /// <summary>
 ///   Initializes a new instance of the <see cref="ServiceBusTestEnvironment"/> class.
 /// </summary>
 ///
 public ServiceBusTestEnvironment()
 {
     ActiveServiceBusNamespace    = new Lazy <NamespaceProperties>(() => EnsureServiceBusNamespace(OverrideServiceBusConnectionString), LazyThreadSafetyMode.ExecutionAndPublication);
     SecondaryServiceBusNamespace = new Lazy <NamespaceProperties>(() => EnsureServiceBusNamespace(OverrideSecondaryServiceBusConnectionString), LazyThreadSafetyMode.ExecutionAndPublication);
     ParsedConnectionString       = new Lazy <ServiceBusConnectionStringProperties>(() => ServiceBusConnectionStringProperties.Parse(ServiceBusConnectionString), LazyThreadSafetyMode.ExecutionAndPublication);
 }