public KeyVaultClient(ConnectionParams connection, CredentialParams credential)
        {
            _keyVault = connection.GetAsNullableString("key_vault")
                        ?? connection.GetAsNullableString("uri")
                        ?? connection.GetAsNullableString("KeyVault");
            if (_keyVault == null)
            {
                throw new ArgumentNullException("KeyVault parameter is not defined");
            }
            if (!_keyVault.StartsWith("http"))
            {
                _keyVault = "https://" + _keyVault + ".vault.azure.net";
            }

            _clientId = credential.AccessId ?? credential.GetAsNullableString("ClientId");
            if (_clientId == null)
            {
                throw new ArgumentNullException("CliendId parameter is not defined");
            }

            _clientKey  = credential.AccessKey ?? credential.GetAsNullableString("ClientKey");
            _thumbPrint = credential.GetAsNullableString("thumbprint")
                          ?? credential.GetAsNullableString("ThumbPrint");
            if (_clientKey == null && _thumbPrint == null)
            {
                throw new ArgumentNullException("Neither ClientKey or ThumbPrint parameters are not defined");
            }

            _client = new Microsoft.Azure.KeyVault.KeyVaultClient(
                new Microsoft.Azure.KeyVault.KeyVaultClient.AuthenticationCallback(GetAccessToken));
        }
        private void UpdateConnection(ConnectionParams connection, CredentialParams credential)
        {
            if (string.IsNullOrEmpty(connection.Uri))
            {
                var uri = connection.Protocol + "://" + connection.Host;
                if (connection.Port != 0)
                {
                    uri += ":" + connection.Port;
                }
                connection.Uri = uri;
            }
            else
            {
                var uri = new Uri(connection.Uri);
                connection.Protocol = uri.Scheme;
                connection.Host     = uri.Host;
                connection.Port     = uri.Port;
            }

            if (connection.Protocol == "https")
            {
                connection.AddSection("credential",
                                      credential.GetAsNullableString("internal_network") == null ? credential : new CredentialParams());
            }
            else
            {
                connection.AddSection("credential", new CredentialParams());
            }
        }
        /// <summary>
        /// Resolves connection options from connection and credential parameters.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        /// <returns>resolved options or throw error</returns>
        public async Task <ConfigParams> ResolveAsync(string correlationId)
        {
            List <ConnectionParams> connections = await _connectionResolver.ResolveAllAsync(correlationId);

            // Validate if cluster (multiple connections) is supported
            if (connections.Count > 0 && !_clusterSupported)
            {
                throw new ConfigException(
                          correlationId,
                          "MULTIPLE_CONNECTIONS_NOT_SUPPORTED",
                          "Multiple (cluster) connections are not supported"
                          );
            }

            // Validate connections
            foreach (var connection in connections)
            {
                ValidateConnection(correlationId, connection);
            }

            CredentialParams credential = await _credentialResolver.LookupAsync(correlationId);

            credential = credential != null ? credential : new CredentialParams();

            // Validate credential
            ValidateCredential(correlationId, credential);

            var options = ComposeOptions(connections, credential, _options);

            return(options);
        }
Пример #4
0
        private string ComposeUri(List <ConnectionParams> connections, CredentialParams credential)
        {
            // Define connection part
            var    connectionConfig = new ConfigParams();
            string connectionString = null;

            foreach (var connection in connections)
            {
                var uri = connection.Uri;
                if (!string.IsNullOrWhiteSpace(uri))
                {
                    connectionString = uri;
                }

                var host = connection.Host;
                if (!string.IsNullOrWhiteSpace(host))
                {
                    var dataSource = "tcp:" + host;

                    var port = connection.Port;
                    if (port != default)
                    {
                        dataSource = dataSource + "," + port.ToString();
                    }

                    connectionConfig["Data Source"] = dataSource;
                }

                var database = connection.GetAsNullableString("database");
                if (!string.IsNullOrWhiteSpace(database))
                {
                    connectionConfig["Initial Catalog"] = database;
                }
            }

            // Define authentication part
            var credentialConfig = new ConfigParams();

            if (credential != null)
            {
                var username = credential.Username;
                if (!string.IsNullOrWhiteSpace(username))
                {
                    credentialConfig["User Id"] = username;
                }

                var password = credential.Password;
                if (!string.IsNullOrWhiteSpace(password))
                {
                    credentialConfig["Password"] = password;
                }
            }

            return(string.Join(";", new[]
            {
                connectionString != null ? connectionString.TrimEnd(';') : JoinParams(connectionConfig),
                JoinParams(credentialConfig)
            }));
        }
Пример #5
0
        private ConfigParams ComposeOptions(List <ConnectionParams> connections, CredentialParams credential)
        {
            credential = credential ?? new CredentialParams();

            // Construct options and copy over credentials
            var options = new ConfigParams().SetDefaults(credential);

            var globalUri  = "";
            var uriBuilder = new StringBuilder();

            // Process connections, find or construct uri
            foreach (var connection in connections)
            {
                options = options.SetDefaults(connection);

                if (globalUri != "")
                {
                    continue;
                }

                var uri = connection.Uri;
                if (!string.IsNullOrEmpty(uri))
                {
                    globalUri = uri;
                    continue;
                }

                if (uriBuilder.Length > 0)
                {
                    uriBuilder.Append(",");
                }

                var protocol = connection.GetProtocolWithDefault("nats");
                uriBuilder.Append(protocol);

                var host = connection.Host;
                uriBuilder.Append("://");
                uriBuilder.Append(host);

                var port = connection.GetAsIntegerWithDefault("port", 4222);
                uriBuilder.Append(":");
                uriBuilder.Append(port.ToString());
            }

            // Set connection uri
            if (globalUri != "")
            {
                options.SetAsObject("uri", globalUri);
            }
            else
            {
                options.SetAsObject("uri", uriBuilder.ToString());
            }

            return(options);
        }
Пример #6
0
        public void TestUsername()
        {
            var сredential = new CredentialParams();

            сredential.Username = null;
            Assert.Null(сredential.Username);

            сredential.Username = "******";
            Assert.Equal(сredential.Username, "Kate Negrienko");
        }
Пример #7
0
        public void TestAccessKey()
        {
            var сredential = new CredentialParams();

            сredential.AccessKey = null;
            Assert.Null(сredential.AccessKey);

            сredential.AccessKey = "key";
            Assert.Equal(сredential.AccessKey, "key");
        }
Пример #8
0
        public void TestPassword()
        {
            CredentialParams сredential = new CredentialParams();

            сredential.Password = null;
            Assert.Null(сredential.Password);

            сredential.Password = "******";
            Assert.Equal(сredential.Password, "qwerty");
        }
 /// <summary>
 /// Creates an new instance of the connection parameters.
 /// </summary>
 /// <param name="connection">connection parameters</param>
 /// <param name="credential">credential parameters</param>
 public AwsConnectionParams(ConnectionParams connection, CredentialParams credential)
 {
     if (connection != null)
     {
         Append(connection);
     }
     if (credential != null)
     {
         Append(credential);
     }
 }
Пример #10
0
        public void TestStoreKey()
        {
            var сredential = new CredentialParams();

            сredential.StoreKey = null;
            Assert.Null(сredential.StoreKey);

            сredential.StoreKey = "Store key";
            Assert.Equal(сredential.StoreKey, "Store key");
            Assert.True(сredential.UseCredentialStore);
        }
        public static AzureStorageConnectionParams FromConfig(ConfigParams config)
        {
            var result = new AzureStorageConnectionParams();

            var credentials = CredentialParams.ManyFromConfig(config);

            foreach (var credential in credentials)
            {
                result.Append(credential);
            }

            var connections = ConnectionParams.ManyFromConfig(config);

            foreach (var connection in connections)
            {
                result.Append(connection);
            }

            return(result);
        }
        /// <summary>
        /// Composes connection and credential parameters into connection options.
        /// This method can be overriden in child classes.
        /// </summary>
        /// <param name="connections">a list of connection parameters</param>
        /// <param name="credential">credential parameters</param>
        /// <param name="parameters">optional parameters</param>
        /// <returns>a composed connection options.</returns>
        protected ConfigParams ComposeOptions(IList <ConnectionParams> connections, CredentialParams credential, ConfigParams parameters)
        {
            // Connection options
            var options = new ConfigParams();

            // Merge connection parameters
            foreach (var connection in connections)
            {
                options = MergeConnection(options, connection);
            }

            // Merge credential parameters
            options = MergeCredential(options, credential);

            // Merge optional parameters
            options = MergeOptional(options, parameters);

            // Perform final processing
            options = FinalizeOptions(options);

            return(options);
        }
Пример #13
0
        /// <summary>
        /// Opens the component with given connection and credential parameters.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        /// <param name="connections">connection parameters</param>
        /// <param name="credential">credential parameters</param>
        public override async Task OpenAsync(string correlationId, List <ConnectionParams> connections, CredentialParams credential)
        {
            var connection = connections?.FirstOrDefault();

            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connections));
            }

            var connectionFactory = new ConnectionFactory();

            if (!string.IsNullOrEmpty(connection.Uri))
            {
                var uri = new Uri(connection.Uri);
                connectionFactory.Uri = uri;
            }
            else
            {
                connectionFactory.HostName = connection.Host;
                connectionFactory.Port     = connection.Port != 0 ? connection.Port : 5672;
            }

            if (credential != null && !string.IsNullOrEmpty(credential.Username))
            {
                //if (!string.IsNullOrEmpty(connection.Protocol))
                //connectionFactory.Protocol = Protocols.DefaultProtocol;
                connectionFactory.UserName = credential.Username;
                connectionFactory.Password = credential.Password;
            }

            try
            {
                _connection = connectionFactory.CreateConnection();
            }
            catch (Exception ex)
            {
                var uri = connection.Uri;
                if (string.IsNullOrEmpty(uri))
                {
                    uri = $"rabbitmq://{connectionFactory.HostName}:{connectionFactory.Port}";
                }

                throw new ConnectionException(
                          correlationId,
                          "CANNOT_CONNECT",
                          "Cannot connect to RabbitMQ at " + uri
                          ).Wrap(ex);
            }

            _model  = _connection.CreateModel();
            _cancel = new CancellationTokenSource();

            if (string.IsNullOrEmpty(_queue) && string.IsNullOrEmpty(_exchange))
            {
                throw new ConfigException(
                          correlationId,
                          "NO_QUEUE",
                          "Queue or exchange are not defined in connection parameters"
                          );
            }

            // Automatically create queue, exchange and binding
            if (_autoCreate)
            {
                if (!string.IsNullOrEmpty(_exchange))
                {
                    _model.ExchangeDeclare(
                        _exchange,
                        _exchangeType,
                        _persistent,
                        _autoDelete,
                        null
                        );
                }

                if (!connection.GetAsBoolean("no_queue"))
                {
                    if (string.IsNullOrEmpty(_queue))
                    {
                        _queue = _model.QueueDeclare(
                            "",
                            _persistent,
                            true,
                            true
                            ).QueueName;
                    }
                    else
                    {
                        _model.QueueDeclare(
                            _queue,
                            _persistent,
                            _exclusive,
                            _autoDelete,
                            null
                            );
                    }

                    if (!string.IsNullOrEmpty(_exchange))
                    {
                        _model.QueueBind(
                            _queue,
                            _exchange,
                            _routingKey
                            );
                    }
                }
            }

            await Task.Delay(0);
        }
        private string ComposeUri(List <ConnectionParams> connections, CredentialParams credential)
        {
            // If there is a uri then return it immediately
            foreach (var connection in connections)
            {
                var fullUri = connection.GetAsNullableString("uri");//connection.Uri;
                if (fullUri != null)
                {
                    return(fullUri);
                }
            }

            // Define hosts
            var hosts = "";

            foreach (var connection in connections)
            {
                var host = connection.Host;
                var port = connection.Port;

                if (hosts.Length > 0)
                {
                    hosts += ",";
                }
                hosts += host + (port == 0 ? "" : ":" + port);
            }

            // Define database
            var database = "";

            foreach (var connection in connections)
            {
                database = connection.GetAsNullableString("database") ?? database;
            }
            if (database.Length > 0)
            {
                database = "/" + database;
            }

            // Define authentication part
            var auth = "";

            if (credential != null)
            {
                var username = credential.Username;
                if (username != null)
                {
                    var password = credential.Password;
                    if (password != null)
                    {
                        auth = username + ":" + password + "@";
                    }
                    else
                    {
                        auth = username + "@";
                    }
                }
            }

            // Define additional parameters parameters
            var options = ConfigParams.MergeConfigs(connections.ToArray()).Override(credential);

            options.Remove("uri");
            options.Remove("host");
            options.Remove("port");
            options.Remove("database");
            options.Remove("username");
            options.Remove("password");
            var parameters = "";
            var keys       = options.Keys;

            foreach (var key in keys)
            {
                if (parameters.Length > 0)
                {
                    parameters += "&";
                }

                parameters += key;

                var value = options.GetAsString(key);
                if (value != null)
                {
                    parameters += "=" + value;
                }
            }
            if (parameters.Length > 0)
            {
                parameters = "?" + parameters;
            }

            // Compose uri
            var uri = "mongodb://" + auth + hosts + database + parameters;

            return(uri);
        }
        public async Task OpenAsync(string correlationId, ConnectionParams connection, CredentialParams credential)
        {
            if (connection == null)
            {
                throw new ConfigException(correlationId, "NO_CONNECTION", "Database connection is not set");
            }

            var uri          = connection.Uri;
            var host         = connection.Host;
            var port         = connection.Port;
            var databaseName = connection.GetAsNullableString("database");

            if (uri != null)
            {
                databaseName = MongoUrl.Create(uri).DatabaseName;
            }
            else
            {
                if (host == null)
                {
                    throw new ConfigException(correlationId, "NO_HOST", "Connection host is not set");
                }

                if (port == 0)
                {
                    throw new ConfigException(correlationId, "NO_PORT", "Connection port is not set");
                }

                if (databaseName == null)
                {
                    throw new ConfigException(correlationId, "NO_DATABASE", "Connection database is not set");
                }
            }

            _logger.Trace(correlationId, "Connecting to mongodb database {0}, collection {1}", databaseName, _collectionName);

            try
            {
                if (uri != null)
                {
                    _connection = new MongoClient(uri);
                }
                else
                {
                    var settings = new MongoClientSettings
                    {
                        Server = new MongoServerAddress(host, port),
                        MaxConnectionPoolSize = _options.GetAsInteger("poll_size"),
                        ConnectTimeout        = _options.GetAsTimeSpan("connect_timeout"),
                        //SocketTimeout =
                        //    new TimeSpan(options.GetInteger("server.socketOptions.socketTimeoutMS")*
                        //                 TimeSpan.TicksPerMillisecond)
                    };

                    if (credential.Username != null)
                    {
                        settings.Credential = MongoCredential.CreateCredential(databaseName, credential.Username, credential.Password);
                    }

                    _connection = new MongoClient(settings);
                }

                _database   = _connection.GetDatabase(databaseName);
                _collection = _database.GetCollection <T>(_collectionName);

                _logger.Debug(correlationId, "Connected to mongodb database {0}, collection {1}", databaseName, _collectionName);
            }
            catch (Exception ex)
            {
                throw new ConnectionException(correlationId, "ConnectFailed", "Connection to mongodb failed", ex);
            }

            await Task.Delay(0);
        }
Пример #16
0
 /// <summary>
 /// Opens the component with given connection and credential parameters.
 /// </summary>
 /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
 /// <param name="connection">connection parameters</param>
 /// <param name="credential">credential parameters</param>
 public abstract Task OpenAsync(string correlationId, ConnectionParams connection, CredentialParams credential);
Пример #17
0
 /// <summary>
 /// Opens the component with given connection and credential parameters.
 /// </summary>
 /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
 public virtual Task OpenAsync(string correlationId, List <ConnectionParams> connections, CredentialParams credential)
 {
     throw new NotImplementedException();
 }
Пример #18
0
        public override async Task OpenAsync(string correlationId, List <ConnectionParams> connections, CredentialParams credential)
        {
            try
            {
                var connection = connections?.FirstOrDefault();
                if (connection == null)
                {
                    throw new ArgumentNullException(nameof(connections));
                }

                _queueName = connection.GetAsNullableString("queue") ?? Name;

                _connectionString = ConfigParams.FromTuples(
                    "Endpoint", connection.GetAsNullableString("uri") ?? connection.GetAsNullableString("Endpoint"),
                    "SharedAccessKeyName", credential.AccessId ?? credential.GetAsNullableString("SharedAccessKeyName"),
                    "SharedAccessKey", credential.AccessKey ?? credential.GetAsNullableString("SharedAccessKey")
                    ).ToString();

                _logger.Info(null, "Connecting queue {0} to {1}", Name, _connectionString);

                _queueClient      = new QueueClient(_connectionString, _queueName);
                _namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);
                _messageReceiver  = new MessageReceiver(_connectionString, _queueName);
            }
            catch (Exception ex)
            {
                _queueClient      = null;
                _namespaceManager = null;
                _messageReceiver  = null;

                _logger.Error(correlationId, ex, $"Failed to open queue '{Name}'.");
            }

            await Task.CompletedTask;
        }
Пример #19
0
        public async override Task OpenAsync(string correlationId, ConnectionParams connection, CredentialParams credential)
        {
            var awsConnection = new AwsConnectionParams(connection, credential);

            // Assign service name
            awsConnection.Service = "sqs";

            // Assign queue name
            var queueName = awsConnection.Resource ?? awsConnection.Get("queue") ?? Name;

            awsConnection.Resource = queueName;
            var deadQueueName = awsConnection.Get("dead_queue");

            // Determine if a fifo queue is being used
            _fifoQueue = queueName.EndsWith(".fifo", StringComparison.OrdinalIgnoreCase) ? true : false;

            // Validate connection params
            var err = awsConnection.Validate(correlationId);

            if (err != null)
            {
                throw err;
            }

            _logger.Info(null, "Connecting queue {0} to {1}", Name, awsConnection.Arn);

            var region = RegionEndpoint.GetBySystemName(awsConnection.Region);
            var config = new AmazonSQSConfig()
            {
                RegionEndpoint = region,
                UseHttp        = true
            };

            _client = new AmazonSQSClient(awsConnection.AccessId, awsConnection.AccessKey, config);

            try
            {
                try
                {
                    // Create queue if it doesn't exist
                    var queueRequest = new CreateQueueRequest(queueName);

                    if (_fifoQueue)
                    {
                        queueRequest.Attributes.Add("FifoQueue", "true");
                    }

                    await _client.CreateQueueAsync(queueRequest);
                }
                catch (QueueNameExistsException)
                {
                    // Ignore exception.
                }

                try
                {
                    // Create dead queue if it doesn't exist
                    if (!string.IsNullOrEmpty(deadQueueName))
                    {
                        var deadQueueRequest = new CreateQueueRequest(deadQueueName);

                        if (_fifoQueue)
                        {
                            deadQueueRequest.Attributes.Add("FifoQueue", "true");
                        }

                        await _client.CreateQueueAsync(deadQueueRequest);
                    }
                }
                catch (QueueNameExistsException)
                {
                    // Ignore exception.
                }

                var response = await _client.GetQueueUrlAsync(queueName);

                _queue = response.QueueUrl;

                if (_fifoQueue)
                {
                    var temp = await GetQueueAttributesAsync(correlationId, new List <string>() { "ContentBasedDeduplication" }, _queue);

                    _contentBasedDupication = BooleanConverter.ToBooleanWithDefault(temp["ContentBasedDeduplication"], _contentBasedDupication);
                }

                if (!string.IsNullOrEmpty(deadQueueName))
                {
                    response = await _client.GetQueueUrlAsync(deadQueueName);

                    _deadQueue = response.QueueUrl;

                    if (_fifoQueue)
                    {
                        var temp = await GetQueueAttributesAsync(correlationId, new List <string>() { "ContentBasedDeduplication" }, _deadQueue);

                        _contentBasedDupicationDlq = BooleanConverter.ToBooleanWithDefault(temp["ContentBasedDeduplication"], _contentBasedDupicationDlq);
                    }
                }
                else
                {
                    _deadQueue = null;
                }
            }
            catch (Exception ex)
            {
                throw new ConnectionException(correlationId, "CANNOT_ACCESS_QUEUE", "Failed to access SQS queue", ex)
                      .WithDetails("queue", _queue);
            }
        }
        /// <summary>
        /// Composes Composite connection options from connection and credential parameters.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        /// <param name="connections">connection parameters</param>
        /// <param name="credential">credential parameters</param>
        /// <param name="parameters">optional parameters</param>
        /// <returns>resolved options or throw error</returns>
        public ConfigParams Compose(string correlationId, IList <ConnectionParams> connections, CredentialParams credential, ConfigParams parameters)
        {
            // Validate connection parameters
            foreach (var connection in connections)
            {
                ValidateConnection(correlationId, connection);
            }

            // Validate credential parameters
            ValidateCredential(correlationId, credential);

            var options = ComposeOptions(connections, credential, parameters);

            return(options);
        }
 /// <summary>
 /// Validates credential parameters.
 /// This method can be overriden in child classes.
 /// Throw error if validation failed.
 /// </summary>
 /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
 /// <param name="credential">credential parameters to be validated</param>
 protected void ValidateCredential(string correlationId, CredentialParams credential)
 {
     return;
 }
        public async override Task OpenAsync(string correlationId, ConnectionParams connection, CredentialParams credential)
        {
            try
            {
                var connectionString = ConfigParams.FromTuples(
                    "DefaultEndpointsProtocol", connection.Protocol ?? connection.GetAsNullableString("DefaultEndpointsProtocol") ?? "https",
                    "AccountName", credential.AccessId ?? credential.GetAsNullableString("account_name") ?? credential.GetAsNullableString("AccountName"),
                    "AccountKey", credential.AccessKey ?? credential.GetAsNullableString("account_key") ?? credential.GetAsNullableString("AccountKey")
                    ).ToString();

                _logger.Info(null, "Connecting queue {0} to {1}", Name, connectionString);

                var storageAccount = CloudStorageAccount.Parse(connectionString);
                var client         = storageAccount.CreateCloudQueueClient();

                var queueName = connection.Get("queue") ?? Name;
                _queue = client.GetQueueReference(queueName);
                await _queue.CreateIfNotExistsAsync();

                var deadName = connection.Get("dead");
                _deadQueue = deadName != null?client.GetQueueReference(deadName) : null;
            }
            catch (Exception ex)
            {
                _queue = null;
                _logger.Error(correlationId, ex, $"Failed to open queue {Name}.");
            }

            await Task.Delay(0);
        }
Пример #23
0
 /// <summary>
 /// Opens the component with given connection and credential parameters.
 /// </summary>
 /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
 /// <param name="connection">connection parameters</param>
 /// <param name="credential">credential parameters</param>
 public async override Task OpenAsync(string correlationId, ConnectionParams connection, CredentialParams credential)
 {
     _opened = true;
     await Task.Delay(0);
 }
        /// <summary>
        /// Merges connection options with credential parameters
        /// This method can be overriden in child classes.
        /// </summary>
        /// <param name="options">connection options</param>
        /// <param name="credential">credential parameters to be merged</param>
        /// <returns>merged connection options.</returns>
        protected ConfigParams MergeCredential(ConfigParams options, CredentialParams credential)
        {
            var mergedOptions = options.Override(credential);

            return(mergedOptions);
        }
        public override async Task OpenAsync(string correlationId, List <ConnectionParams> connections, CredentialParams credential)
        {
            try
            {
                var connection = connections?.FirstOrDefault();
                if (connection == null)
                {
                    throw new ArgumentNullException(nameof(connections));
                }

                _topicName        = connection.GetAsNullableString("topic") ?? Name;
                _tempSubscriber   = connection.Get("subscription") == null || connection.Get("Subscription") == null;
                _subscriptionName = connection.GetAsNullableString("subscription") ?? connection.Get("Subscription") ?? IdGenerator.NextLong(); // "AllMessages";

                _connectionString = ConfigParams.FromTuples(
                    "Endpoint", connection.GetAsNullableString("uri") ?? connection.GetAsNullableString("Endpoint"),
                    "SharedAccessKeyName", credential.AccessId ?? credential.GetAsNullableString("shared_access_key_name") ?? credential.GetAsNullableString("SharedAccessKeyName"),
                    "SharedAccessKey", credential.AccessKey ?? credential.GetAsNullableString("shared_access_key") ?? credential.GetAsNullableString("SharedAccessKey")
                    ).ToString();

                _namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);
                _messageReceiver  = new MessageReceiver(_connectionString, EntityNameHelper.FormatSubscriptionPath(_topicName, _subscriptionName));
            }
            catch (Exception ex)
            {
                _namespaceManager = null;

                _logger.Error(correlationId, ex, $"Failed to open message topic '{Name}'.");
            }

            await Task.CompletedTask;
        }
Пример #26
0
        /// <summary>
        ///  Compose method are composes Nats connection options from connection and credential parameters.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        /// <param name="connections">Connection parameters</param>
        /// <param name="credential">Credential parameters</param>
        /// <returns>Composed connection parameters</returns>
        public ConfigParams Compose(string correlationId, List <ConnectionParams> connections, CredentialParams credential)
        {
            // Validate connections
            foreach (var connection in connections)
            {
                ValidateConnection(correlationId, connection);
            }

            var options = ComposeOptions(connections, credential);

            return(options);
        }
        private void ValidateConnection(string correlationId, ConnectionParams connection, CredentialParams credential)
        {
            if (connection == null)
            {
                throw new ConfigException(correlationId, "NO_CONNECTION", "HTTP connection is not set");
            }

            var uri = connection.Uri;

            if (!string.IsNullOrEmpty(uri))
            {
                return;
            }

            var protocol = connection.GetProtocolWithDefault("http");

            if ("http" != protocol && "https" != protocol)
            {
                throw new ConfigException(
                          correlationId, "WRONG_PROTOCOL", "Protocol is not supported by REST connection")
                      .WithDetails("protocol", protocol);
            }

            var host = connection.Host;

            if (host == null)
            {
                throw new ConfigException(correlationId, "NO_HOST", "Connection host is not set");
            }

            var port = connection.Port;

            if (port == 0)
            {
                throw new ConfigException(correlationId, "NO_PORT", "Connection port is not set");
            }

            // Check HTTPS credentials
            if (protocol == "https")
            {
                // Check for credential
                if (credential == null)
                {
                    throw new ConfigException(
                              correlationId, "NO_CREDENTIAL", "SSL certificates are not configured for HTTPS protocol");
                }

                // Sometimes when we use https we are on an internal network and do not want to have to deal with security.
                // When we need a https connection and we don't want to pass credentials, set the value 'no_credentials_needed' in the config yml credentials section
                if (credential.GetAsNullableString("internal_network") == null)
                {
                    if (credential.GetAsNullableString("ssl_password") == null)
                    {
                        throw new ConfigException(
                                  correlationId, "NO_SSL_PASSWORD", "SSL password is not configured in credentials");
                    }

                    if (credential.GetAsNullableString("ssl_pfx_file") == null)
                    {
                        throw new ConfigException(
                                  correlationId, "NO_SSL_PFX_FILE", "SSL pfx file is not configured in credentials");
                    }
                }
            }
        }
        private ConfigParams ComposeOptions(List <ConnectionParams> connections, CredentialParams credential)
        {
            credential = credential ?? new CredentialParams();

            // Construct options and copy over credentials
            var options = new ConfigParams().SetDefaults(credential);

            var globalUri      = "";
            var serversBuilder = new StringBuilder();

            // Process connections, find or construct uri
            foreach (var connection in connections)
            {
                options = options.SetDefaults(connection);

                if (globalUri != "")
                {
                    continue;
                }

                var uri = connection.Uri;
                if (!string.IsNullOrEmpty(uri))
                {
                    globalUri = uri;
                    continue;
                }

                if (serversBuilder.Length > 0)
                {
                    serversBuilder.Append(",");
                }

                var host = connection.Host;
                serversBuilder.Append(host);

                var port = connection.GetAsIntegerWithDefault("port", 1883);
                serversBuilder.Append(":");
                serversBuilder.Append(port.ToString());
            }

            // Set connection uri
            if (globalUri != "")
            {
                var pos = globalUri.IndexOf("://");
                if (pos > 0)
                {
                    globalUri = globalUri.Substring(pos + 3);
                }

                pos = globalUri.IndexOf("@");
                if (pos > 0)
                {
                    var userPass = globalUri.Substring(0, pos);
                    globalUri = globalUri.Substring(pos + 1);
                    pos       = userPass.IndexOf(":");
                    if (pos > 0)
                    {
                        var username = userPass.Substring(0, pos);
                        options.SetAsObject("username", username);
                        var password = userPass.Substring(pos + 1);
                        options.SetAsObject("password", password);
                    }
                    else
                    {
                        options.SetAsObject("username", userPass);
                    }
                }

                pos = globalUri.IndexOf("?");
                if (pos > 0)
                {
                    globalUri = globalUri.Substring(0, pos);
                }

                options.SetAsObject("servers", globalUri);
            }
            else
            {
                options.SetAsObject("servers", serversBuilder.ToString());
            }

            return(options);
        }