Ejemplo n.º 1
0
        private static void DoAdd(IServiceCollection services, PostgresServiceInfo info, IConfiguration config, ServiceLifetime contextLifetime)
        {
            PostgresProviderConnectorOptions PostgresConfig = new PostgresProviderConnectorOptions(config);
            PostgresProviderConnectorFactory factory        = new PostgresProviderConnectorFactory(info, PostgresConfig);

            services.Add(new ServiceDescriptor(typeof(NpgsqlConnection), factory.Create, contextLifetime));
        }
Ejemplo n.º 2
0
        private static void DoAdd(IServiceCollection services, PostgresServiceInfo info, IConfiguration config, ServiceLifetime contextLifetime)
        {
            var postgresConfig = new PostgresProviderConnectorOptions(config);
            var factory        = new PostgresProviderConnectorFactory(info, postgresConfig, PostgreSqlTypeLocator.NpgsqlConnection);

            services.Add(new ServiceDescriptor(typeof(IHealthContributor), ctx => new RelationalHealthContributor((IDbConnection)factory.Create(ctx), ctx.GetService <ILogger <RelationalHealthContributor> >()), contextLifetime));
        }
        internal void UpdateConfiguration(PostgresServiceInfo si, PostgresProviderConnectorOptions configuration)
        {
            if (si == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(si.Uri))
            {
                configuration.Port = si.Port;
                if (configuration.UrlEncodedCredentials)
                {
                    configuration.Username = WebUtility.UrlDecode(si.UserName);
                    configuration.Password = WebUtility.UrlDecode(si.Password);
                }
                else
                {
                    configuration.Username = si.UserName;
                    configuration.Password = si.Password;
                }

                configuration.Host     = si.Host;
                configuration.Database = si.Path;
            }
        }
Ejemplo n.º 4
0
        internal void UpdateConfiguration(PostgresServiceInfo si, PostgresProviderConnectorOptions configuration)
        {
            if (si == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(si.Uri))
            {
                if (si.Port > 0)
                {
                    configuration.Port = si.Port;
                }

                if (configuration.UrlEncodedCredentials)
                {
                    configuration.Username = WebUtility.UrlDecode(si.UserName);
                    configuration.Password = WebUtility.UrlDecode(si.Password);
                }
                else
                {
                    configuration.Username = si.UserName;
                    configuration.Password = si.Password;
                }

                configuration.Host     = si.Host;
                configuration.Database = si.Path;
                if (si.Query != null)
                {
                    foreach (var kvp in UriExtensions.ParseQuerystring(si.Query))
                    {
                        if (kvp.Key.Equals("sslmode", StringComparison.InvariantCultureIgnoreCase))
                        {
                            // Npgsql parses SSL Mode into an enum, the first character must be capitalized
                            configuration.SslMode = FirstCharToUpper(kvp.Value);
                        }
                        else if (kvp.Key.Equals("sslcert"))
                        {
                            // TODO: Map this client cert into the npgsql client cert callback
                            configuration.ClientCertificate = kvp.Value;
                        }
                        else if (kvp.Key.Equals("sslkey"))
                        {
                            // TODO: Map this client cert into the npgsql client cert callback
                            configuration.ClientKey = kvp.Value;
                        }
                        else if (kvp.Key.Equals("sslrootcert"))
                        {
                            // TODO: Map this client cert into the npgsql remote cert validation callback
                            configuration.SslRootCertificate = kvp.Value;
                        }
                        else
                        {
                            configuration.Options.Add(kvp.Key, kvp.Value);
                        }
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void Constructor_ThrowsIfConfigNull()
        {
            PostgresProviderConnectorOptions config = null;
            PostgresServiceInfo si = null;

            var ex = Assert.Throws <ArgumentNullException>(() => new PostgresProviderConnectorFactory(si, config, typeof(NpgsqlConnection)));

            Assert.Contains(nameof(config), ex.Message);
        }
Ejemplo n.º 6
0
        private static void DoAdd(IServiceCollection services, PostgresServiceInfo info, IConfiguration config, ServiceLifetime contextLifetime)
        {
            Type postgresConnection = ConnectorHelpers.FindType(PostgreSqlTypeLocator.Assemblies, PostgreSqlTypeLocator.ConnectionTypeNames);
            var  postgresConfig     = new PostgresProviderConnectorOptions(config);
            var  factory            = new PostgresProviderConnectorFactory(info, postgresConfig, postgresConnection);

            services.Add(new ServiceDescriptor(typeof(IDbConnection), factory.Create, contextLifetime));
            services.Add(new ServiceDescriptor(postgresConnection, factory.Create, contextLifetime));
            services.Add(new ServiceDescriptor(typeof(IHealthContributor), ctx => new RelationalHealthContributor((IDbConnection)factory.Create(ctx), ctx.GetService <ILogger <RelationalHealthContributor> >()), ServiceLifetime.Singleton));
        }
        public PostgresProviderConnectorFactory(PostgresServiceInfo sinfo, PostgresProviderConnectorOptions config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            _info   = sinfo;
            _config = config;
        }
        public void Constructor_ThrowsIfConfigNull()
        {
            // Arrange
            PostgresProviderConnectorOptions config = null;
            PostgresServiceInfo si = null;

            // Act and Assert
            var ex = Assert.Throws <ArgumentNullException>(() => new PostgresProviderConnectorFactory(si, config));

            Assert.Contains(nameof(config), ex.Message);
        }
        /// <summary>
        /// Postgre连接字符串构建
        /// </summary>
        /// <param name="config"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static string BuildePostgreConnectionString(this IConfiguration config, string serviceName = null)
        {
            PostgresServiceInfo info = string.IsNullOrEmpty(serviceName)
                    ? config.GetSingletonServiceInfo <PostgresServiceInfo>()
                    : config.GetRequiredServiceInfo <PostgresServiceInfo>(serviceName);

            PostgresProviderConnectorOptions mySqlConfig = new PostgresProviderConnectorOptions(config);
            PostgresProviderConnectorFactory factory     = new PostgresProviderConnectorFactory(info, mySqlConfig, null);

            return(factory.CreateConnectionString());
        }
Ejemplo n.º 10
0
        private Connection GetConnection(PostgresServiceInfo info, IConfiguration configuration)
        {
            var postgresConfig = new PostgresProviderConnectorOptions(configuration);
            var configurer     = new PostgresProviderConfigurer();
            var connection     = new Connection(configurer.Configure(info, postgresConfig), "Postgres", info);

            connection.Properties.Add("ClientCertificate", postgresConfig.ClientCertificate);
            connection.Properties.Add("ClientKey", postgresConfig.ClientKey);
            connection.Properties.Add("SslRootCertificate", postgresConfig.SslRootCertificate);

            return(connection);
        }
Ejemplo n.º 11
0
        private static void DoAdd(IServiceCollection services, PostgresServiceInfo info, IConfiguration config, ServiceLifetime contextLifetime, bool addSteeltoeHealthChecks)
        {
            var postgresConnection = ReflectionHelpers.FindType(PostgreSqlTypeLocator.Assemblies, PostgreSqlTypeLocator.ConnectionTypeNames);
            var postgresConfig     = new PostgresProviderConnectorOptions(config);
            var factory            = new PostgresProviderConnectorFactory(info, postgresConfig, postgresConnection);

            services.Add(new ServiceDescriptor(typeof(IDbConnection), factory.Create, contextLifetime));
            services.Add(new ServiceDescriptor(postgresConnection, factory.Create, contextLifetime));
            if (!services.Any(s => s.ServiceType == typeof(HealthCheckService)) || addSteeltoeHealthChecks)
            {
                services.Add(new ServiceDescriptor(typeof(IHealthContributor), ctx => new RelationalDbHealthContributor((IDbConnection)factory.Create(ctx), ctx.GetService <ILogger <RelationalDbHealthContributor> >()), ServiceLifetime.Singleton));
            }
        }
        public void PostgreSql_Is_Connected_Returns_Up_Status()
        {
            var implementationType = PostgreSqlTypeLocator.NpgsqlConnection;
            var sqlConfig          = new PostgresProviderConnectorOptions();
            var sInfo       = new PostgresServiceInfo("MyId", "postgres://*****:*****@localhost:5432/postgres");
            var logrFactory = new LoggerFactory();
            var connFactory = new PostgresProviderConnectorFactory(sInfo, sqlConfig, implementationType);
            var h           = new RelationalDbHealthContributor((IDbConnection)connFactory.Create(null), logrFactory.CreateLogger <RelationalDbHealthContributor>());

            var status = h.Health();

            Assert.Equal(HealthStatus.UP, status.Status);
        }
        public void Constructor_CreatesExpected()
        {
            var uri = "postgres://*****:*****@192.168.0.90:3306/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355?reconnect=true";
            var r1  = new PostgresServiceInfo("myId", uri);

            Assert.Equal("myId", r1.Id);
            Assert.Equal("postgres", r1.Scheme);
            Assert.Equal("192.168.0.90", r1.Host);
            Assert.Equal(3306, r1.Port);
            Assert.Equal("7E1LxXnlH2hhlPVt", r1.Password);
            Assert.Equal("Dd6O1BPXUHdrmzbP", r1.UserName);
            Assert.Equal("cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355", r1.Path);
            Assert.Equal("reconnect=true", r1.Query);
        }
        private static void DoAdd(IServiceCollection services, PostgresServiceInfo info, IConfiguration config, ServiceLifetime contextLifetime)
        {
            Type postgresConnection = ConnectorHelpers.FindType(postgresAssemblies, postgresTypeNames);

            if (postgresConnection == null)
            {
                throw new ConnectorException("Unable to find NpgsqlConnection, are you missing Postgres ADO.NET assembly");
            }

            PostgresProviderConnectorOptions postgresConfig = new PostgresProviderConnectorOptions(config);
            PostgresProviderConnectorFactory factory        = new PostgresProviderConnectorFactory(info, postgresConfig, postgresConnection);

            services.Add(new ServiceDescriptor(typeof(IDbConnection), factory.Create, contextLifetime));
            services.Add(new ServiceDescriptor(postgresConnection, factory.Create, contextLifetime));
        }
Ejemplo n.º 15
0
        public void Create_ReturnsPostgresConnection()
        {
            var config = new PostgresProviderConnectorOptions()
            {
                Host     = "localhost",
                Port     = 3306,
                Password = "******",
                Username = "******",
                Database = "database"
            };
            var si         = new PostgresServiceInfo("MyId", "postgres://*****:*****@192.168.0.90:5432/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355");
            var factory    = new PostgresProviderConnectorFactory(si, config, typeof(NpgsqlConnection));
            var connection = factory.Create(null);

            Assert.NotNull(connection);
        }
        internal void UpdateConfiguration(PostgresServiceInfo si, PostgresProviderConnectorOptions configuration)
        {
            if (si == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(si.Uri))
            {
                configuration.Port     = si.Port;
                configuration.Username = si.UserName;
                configuration.Password = si.Password;
                configuration.Host     = si.Host;
                configuration.Database = si.Path;
            }
        }
Ejemplo n.º 17
0
        public void PostgreSql_Not_Connected_Returns_Down_Status()
        {
            // arrange
            Type implementationType = PostgreSqlTypeLocator.NpgsqlConnection;
            var  sqlConfig          = new PostgresProviderConnectorOptions();
            var  sInfo       = new PostgresServiceInfo("MyId", "postgres://localhost:5432/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355");
            var  logrFactory = new LoggerFactory();
            var  connFactory = new PostgresProviderConnectorFactory(sInfo, sqlConfig, implementationType);
            var  h           = new RelationalHealthContributor((IDbConnection)connFactory.Create(null), logrFactory.CreateLogger <RelationalHealthContributor>());

            // act
            var status = h.Health();

            // assert
            Assert.Equal(HealthStatus.DOWN, status.Status);
            Assert.Contains(status.Details.Keys, k => k == "error");
        }
Ejemplo n.º 18
0
        public static IServiceCollection AddPostgresConnection(this IServiceCollection services, IConfiguration config, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ILoggerFactory logFactory = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

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

            PostgresServiceInfo info = config.GetSingletonServiceInfo <PostgresServiceInfo>();

            DoAdd(services, info, config, contextLifetime);
            return(services);
        }
        private static NpgsqlConnection GetConnection(IConfiguration config, string serviceName = null)
        {
            PostgresServiceInfo info = null;

            if (string.IsNullOrEmpty(serviceName))
            {
                info = config.GetSingletonServiceInfo <PostgresServiceInfo>();
            }
            else
            {
                info = config.GetRequiredServiceInfo <PostgresServiceInfo>(serviceName);
            }

            PostgresProviderConnectorOptions postgresConfig = new PostgresProviderConnectorOptions(config);

            PostgresProviderConnectorFactory factory = new PostgresProviderConnectorFactory(info, postgresConfig);

            return(factory.Create(null) as NpgsqlConnection);
        }
        public void UpdateConfiguration_WithPostgresServiceInfo_ReturnsExpected()
        {
            PostgresProviderConfigurer       configurer = new PostgresProviderConfigurer();
            PostgresProviderConnectorOptions config     = new PostgresProviderConnectorOptions()
            {
                Host     = "localhost",
                Port     = 1234,
                Username = "******",
                Password = "******",
                Database = "database"
            };
            PostgresServiceInfo si = new PostgresServiceInfo("MyId", "postgres://*****:*****@192.168.0.90:5432/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355");

            configurer.UpdateConfiguration(si, config);

            Assert.Equal("192.168.0.90", config.Host);
            Assert.Equal(5432, config.Port);
            Assert.Equal("Dd6O1BPXUHdrmzbP", config.Username);
            Assert.Equal("7E1LxXnlH2hhlPVt", config.Password);
            Assert.Equal("cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355", config.Database);
        }
        public void ConnectionTypeLocatorFindsTypeFromServiceInfo()
        {
            var cosmosInfo   = new CosmosDbServiceInfo("id");
            var mongoInfo    = new MongoDbServiceInfo("id", "mongodb://host");
            var mysqlInfo    = new MySqlServiceInfo("id", "mysql://host");
            var oracleInfo   = new OracleServiceInfo("id", "oracle://host");
            var postgresInfo = new PostgresServiceInfo("id", "postgres://host");
            var rabbitMqInfo = new RabbitMQServiceInfo("id", "rabbitmq://host");
            var redisInfo    = new RedisServiceInfo("id", "redis://host");
            var sqlInfo      = new SqlServerServiceInfo("id", "sqlserver://host");
            var manager      = new ConnectionStringManager(new ConfigurationBuilder().Build());

            Assert.StartsWith("CosmosDb", manager.GetFromServiceInfo(cosmosInfo).Name);
            Assert.StartsWith("MongoDb", manager.GetFromServiceInfo(mongoInfo).Name);
            Assert.StartsWith("MySql", manager.GetFromServiceInfo(mysqlInfo).Name);
            Assert.StartsWith("Oracle", manager.GetFromServiceInfo(oracleInfo).Name);
            Assert.StartsWith("Postgres", manager.GetFromServiceInfo(postgresInfo).Name);
            Assert.StartsWith("RabbitMQ", manager.GetFromServiceInfo(rabbitMqInfo).Name);
            Assert.StartsWith("Redis", manager.GetFromServiceInfo(redisInfo).Name);
            Assert.StartsWith("SqlServer", manager.GetFromServiceInfo(sqlInfo).Name);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Add an IHealthContributor to a ServiceCollection for PostgreSQL
        /// </summary>
        /// <param name="services">Service collection to add to</param>
        /// <param name="config">App configuration</param>
        /// <param name="serviceName">cloud foundry service name binding</param>
        /// <param name="contextLifetime">Lifetime of the service to inject</param>
        /// <param name="logFactory">logger factory</param>
        /// <returns>IServiceCollection for chaining</returns>
        public static IServiceCollection AddPostgresHealthContributor(this IServiceCollection services, IConfiguration config, string serviceName, ServiceLifetime contextLifetime = ServiceLifetime.Singleton, ILoggerFactory logFactory = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentNullException(nameof(serviceName));
            }

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

            PostgresServiceInfo info = config.GetRequiredServiceInfo <PostgresServiceInfo>(serviceName);

            DoAdd(services, info, config, contextLifetime);
            return(services);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Add NpgsqlConnection and its IHealthContributor to a ServiceCollection
        /// </summary>
        /// <param name="services">Service collection to add to</param>
        /// <param name="config">App configuration</param>
        /// <param name="serviceName">cloud foundry service name binding</param>
        /// <param name="contextLifetime">Lifetime of the service to inject</param>
        /// <param name="logFactory">logger factory</param>
        /// <param name="addSteeltoeHealthChecks">Add Steeltoe healthChecks</param>
        /// <returns>IServiceCollection for chaining</returns>
        /// <remarks>NpgsqlConnection is retrievable as both NpgsqlConnection and IDbConnection</remarks>
        public static IServiceCollection AddPostgresConnection(this IServiceCollection services, IConfiguration config, string serviceName, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ILoggerFactory logFactory = null, bool addSteeltoeHealthChecks = false)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentNullException(nameof(serviceName));
            }

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

            PostgresServiceInfo info = config.GetRequiredServiceInfo <PostgresServiceInfo>(serviceName);

            DoAdd(services, info, config, contextLifetime, addSteeltoeHealthChecks);
            return(services);
        }
        public void Configure_ServiceInfoOveridesConfig_ReturnsExpected()
        {
            PostgresProviderConnectorOptions config = new PostgresProviderConnectorOptions()
            {
                Host     = "localhost",
                Port     = 1234,
                Username = "******",
                Password = "******",
                Database = "database"
            };

            PostgresProviderConfigurer configurer = new PostgresProviderConfigurer();
            PostgresServiceInfo        si         = new PostgresServiceInfo("MyId", "postgres://*****:*****@192.168.0.90:5432/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355");

            var opts = configurer.Configure(si, config);

            Assert.True(opts.Contains("Host=192.168.0.90;"));
            Assert.True(opts.Contains("Port=5432;"));
            Assert.True(opts.Contains("Username=Dd6O1BPXUHdrmzbP;"));
            Assert.True(opts.Contains("Password=7E1LxXnlH2hhlPVt;"));
            Assert.True(opts.Contains("Database=cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355;"));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Adds NpgsqlConnection (as IDbConnection and NpgsqlConnection) to your Autofac Container
        /// </summary>
        /// <param name="container">Your Autofac Container Builder</param>
        /// <param name="config">Application configuration</param>
        /// <param name="serviceName">Cloud Foundry service name binding</param>
        /// <returns>the RegistrationBuilder for (optional) additional configuration</returns>
        public static IRegistrationBuilder <object, SimpleActivatorData, SingleRegistrationStyle> RegisterPostgreSqlConnection(this ContainerBuilder container, IConfiguration config, string serviceName = null)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

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

            PostgresServiceInfo info = serviceName == null
                ? config.GetSingletonServiceInfo <PostgresServiceInfo>()
                : config.GetRequiredServiceInfo <PostgresServiceInfo>(serviceName);

            Type postgreSqlConnection = PostgreSqlTypeLocator.NpgsqlConnection;
            var  postgreSqlConfig     = new PostgresProviderConnectorOptions(config);
            var  factory = new PostgresProviderConnectorFactory(info, postgreSqlConfig, postgreSqlConnection);

            container.RegisterType <RelationalHealthContributor>().As <IHealthContributor>();
            return(container.Register(c => factory.Create(null)).As(typeof(IDbConnection), postgreSqlConnection));
        }
 internal string Configure(PostgresServiceInfo si, PostgresProviderConnectorOptions configuration)
 {
     UpdateConfiguration(si, configuration);
     return(configuration.ToString());
 }
 public PostgresProviderConnectorFactory(PostgresServiceInfo sinfo, PostgresProviderConnectorOptions config, Type type)
 {
     _info   = sinfo;
     _config = config ?? throw new ArgumentNullException(nameof(config));
     _type   = type;
 }