Provides a simple way to create and manage the contents of connection strings used by the NpgsqlConnection class.
Inheritance: System.Data.Common.DbConnectionStringBuilder
Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var databaseName = args.Length > 0
                ? args[0]
                : null;

            var connectionString = new NpgsqlConnectionStringBuilder
            {
                Host = ConfigurationManager.AppSettings["host"],
                Database = databaseName ?? ConfigurationManager.AppSettings["database"],
                Username = ConfigurationManager.AppSettings["user"],
                Password = ConfigurationManager.AppSettings["password"],

                SslMode = SslMode.Prefer,
                TrustServerCertificate = true
            }
            .ConnectionString;

            var upgradeEngine = DeployChanges.To
                .PostgresqlDatabase(connectionString)
                .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                .LogToConsole()
                .Build();

            var result = upgradeEngine.PerformUpgrade();
            if (!result.Successful)
            {
                Console.ReadLine();
            }
        }
Ejemplo n.º 2
0
        internal static bool TestConnectionString(string connectString)
        {
            //Connection should be fast
            var sb = new Npgsql.NpgsqlConnectionStringBuilder(connectString);

            sb.Timeout    = 15;
            connectString = sb.ToString();

            var valid = false;

            using (var conn = new NpgsqlConnection())
            {
                try
                {
                    conn.ConnectionString = connectString;
                    conn.Open();
                    valid = true;
                }
                catch (Exception ex)
                {
                    Log.Warning(ex.ToString());
                    valid = false;
                }
                finally
                {
                    conn.Close();
                }
            }
            return(valid);
        }
 public ViewModelConnectPgSql()
 {
     _connStrBuilder = new NpgsqlConnectionStringBuilder();
     _connStrBuilder.Host = "localhost";
     _connStrBuilder.Port = 5432;
     _connStrBuilder.SslMode = Npgsql.SslMode.Prefer;
 }
        public NpgsqlStartupPacket(String database_name, String user_name, NpgsqlConnectionStringBuilder  settings)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BuildStartupPacket");

            Dictionary<String, String> parameters = new Dictionary<String, String>();

            parameters.Add("DateStyle", "ISO");
            parameters.Add("client_encoding", "UTF8");
            parameters.Add("extra_float_digits", "2");

            if (! string.IsNullOrEmpty(settings.ApplicationName))
            {
                parameters.Add("application_name", settings.ApplicationName);
            }

            if (! string.IsNullOrEmpty(settings.SearchPath))
            {
                parameters.Add("search_path", settings.SearchPath);
            }

            //database
            parameterNames.Add(BackendEncoding.UTF8Encoding.GetBytes("database"));
            parameterValues.Add(BackendEncoding.UTF8Encoding.GetBytes(database_name));

            //user
            parameterNames.Add(BackendEncoding.UTF8Encoding.GetBytes("user"));
            parameterValues.Add(BackendEncoding.UTF8Encoding.GetBytes(user_name));

            //parameters
            foreach (KeyValuePair<String, String> param in parameters)
            {
                parameterNames.Add(BackendEncoding.UTF8Encoding.GetBytes(param.Key));
                parameterValues.Add(BackendEncoding.UTF8Encoding.GetBytes(param.Value));
            }
        }
Ejemplo n.º 5
0
        public void Execute(Dictionary <string, string> input)
        {
            if (!input.Any(x => x.Key == PARAMKEYS_CREATE))
            {
                return;
            }

            connectionString = DatabaseInstaller.GetSetting(input, DatabaseInstaller.PARAMKEYS_APPDB, string.Empty);
            Log.Information($"connectionstring censored: {CensorConnectionString(connectionString)}");
            masterConnectionString = DatabaseInstaller.GetSetting(input, PARAMKEYS_MASTERDB, string.Empty);
            Log.Information($"masterconnectionstring censored: {CensorConnectionString(masterConnectionString)}");
            newDatabaseName = DatabaseInstaller.GetSetting(input, PARAMKEYS_NEWNAME, string.Empty);
            Log.Information($"newDatabaseName: {newDatabaseName}");

            if (DatabaseServer.TestConnectionString(connectionString))
            {
                throw new Exception("The connection string references an existing database.");
            }

            if (string.IsNullOrEmpty(newDatabaseName))
            {
                throw new Exception("A new database name was not specified.");
            }

            var builder = new Npgsql.NpgsqlConnectionStringBuilder(connectionString);

            if (builder.Database.ToLower() != newDatabaseName.ToLower())
            {
                throw new Exception("A new database name does not match the specified connection string.");
            }

            CreateDatabase();
        }
Ejemplo n.º 6
0
        public IDocumentStore Initialize(Action<MartenRegistry> register = null)
        {
            var builder = new NpgsqlConnectionStringBuilder(_targetConnectionString);
            var targetDatabaseName = builder.Database;

            using (var connection = new NpgsqlConnection(_masterConnectionString))
            {
                connection.Open();
                var existsCommand = connection.CreateCommand();
                existsCommand.CommandText = "select (count(*) > 0)::boolean as exists from pg_database where datname=:0";
                existsCommand.Parameters.Add(new NpgsqlParameter("0", targetDatabaseName));
                var exists = (bool)existsCommand.ExecuteScalar();
                if (!exists)
                {
                    var createCommand = connection.CreateCommand();
                    createCommand.CommandText = string.Format("CREATE DATABASE \"{0}\"", targetDatabaseName);
                    createCommand.ExecuteNonQuery();
                }
            }
            var store = DocumentStore.For(cfg =>
            {
                cfg.Connection(_targetConnectionString);
                cfg.AutoCreateSchemaObjects = true;
                cfg.Schema.For<Commit>()
                    .Searchable(x => x.StreamId)
                    .Searchable(x => x.StreamVersion);
                if (register != null)
                {
                    register(cfg.Schema);
                }
            });
            return store;
        }
Ejemplo n.º 7
0
        public static void Initialize()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
            var connectionBuilder = new NpgsqlConnectionStringBuilder(connectionString);

            //connect to postgres database to create a new database
            var databaseName = connectionBuilder.Database;
            connectionBuilder.Database = "postgres";
            connectionString = connectionBuilder.ToString();

            using (var conn = new NpgsqlConnection(connectionString))
            {
                conn.Open();

                bool dbExists;
                using (var cmd = new NpgsqlCommand())
                {
                    cmd.CommandText = string.Format(@"SELECT TRUE FROM pg_database WHERE datname='{0}'", databaseName);
                    cmd.Connection = conn;

                    var result = cmd.ExecuteScalar();
                    dbExists = result != null && Convert.ToBoolean(result);
                }

                if (dbExists)
                {
                    DoClean(conn);
                }
                else
                {
                    DoCreate(conn, databaseName);
                }
            }
        }
Ejemplo n.º 8
0
        // Zu Quell- und Zieldatenbank verbinden
        private void connectFischFaunaButton_Click(object sender, EventArgs e)
        {
            DatabaseConnection sourceCon = (DatabaseConnection)sourceDatabaseConnetions.SelectedValue;
            DatabaseConnection targetCon = (DatabaseConnection)targetDatabaseConnetions.SelectedValue;

            NpgsqlConnectionStringBuilder pgConStrBuilder = new NpgsqlConnectionStringBuilder();
            pgConStrBuilder.Host = sourceCon.ServerAddress;
            pgConStrBuilder.UserName = sourceCon.UserName;
            pgConStrBuilder.Password = sourceCon.Password;
            pgConStrBuilder.Database = sourceCon.Database;

            MySqlConnectionStringBuilder mySqlConStrBuilder = new MySqlConnectionStringBuilder();
            mySqlConStrBuilder.Server = targetCon.ServerAddress;
            mySqlConStrBuilder.UserID = targetCon.UserName;
            mySqlConStrBuilder.Password = targetCon.Password;
            mySqlConStrBuilder.Database = targetCon.Database;
            mySqlConStrBuilder.AllowZeroDateTime = true;

            _sourceCon = new NpgsqlConnection(pgConStrBuilder.ToString());
            _targetCon = new MySqlConnection(mySqlConStrBuilder.ToString());

            _mainLogic = new MainLogic(_sourceCon, _targetCon);
            _mainLogic.CheckForImportedFieldInMySql();

            FillImportsCombobox();
            FillImportUsersCombobox();
            FillRecordQualityCombobox();
            FillSourceTypeCombobox();
            FillCountryCombobox();

            PreSelectTestData();

            groupBox2.Enabled = true;
        }
Ejemplo n.º 9
0
        public static NpgsqlStartupPacket BuildStartupPacket(ProtocolVersion protocol_version, String database_name, String user_name,
                                                             NpgsqlConnectionStringBuilder  settings)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BuildStartupPacket");

            if (protocol_version == ProtocolVersion.Version2)
            {
                return new NpgsqlStartupPacketV2(database_name,user_name, "", "", "");
            }
            else
            {
                Dictionary<String, String> parameters = new Dictionary<String, String>();

                parameters.Add("DateStyle", "ISO");
                parameters.Add("client_encoding", "UTF8");
                parameters.Add("extra_float_digits", "2");
                parameters.Add("lc_monetary", "C");

                if (!string.IsNullOrEmpty(settings.ApplicationName))
                {
                    parameters.Add("application_name", settings.ApplicationName);
                }

                if (!string.IsNullOrEmpty(settings.SearchPath))
                {
                    parameters.Add("search_path", settings.SearchPath);
                }

                return new NpgsqlStartupPacketV3(database_name,user_name,parameters);
            }
        }
Ejemplo n.º 10
0
 public Update(NpgsqlConnectionStringBuilder connectionInfo)
 {
     connectionInfo.PreloadReader = true;
     _dbName = connectionInfo.Database;
     _conn = new NpgsqlConnection(connectionInfo.ConnectionString);
     _conn.Open();
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 public ConnectionStringDialog()
 {
     InitializeComponent();
     this.cmbServerName.Items.Add("<Browse for more>");
     this.cmbServerName.Text = "";
     dbConnectionStringBuilder = new NpgsqlConnectionStringBuilder();
 }
Ejemplo n.º 12
0
    public static string GetPgCon()
    {
        Npgsql.NpgsqlConnectionStringBuilder csb = new Npgsql.NpgsqlConnectionStringBuilder();
        csb.Host     = "127.0.0.1";
        csb.Port     = 5432;
        csb.Database = "postgres";

        csb.IntegratedSecurity = false;

        if (!csb.IntegratedSecurity)
        {
            csb.Username = "******";
            csb.Password = "******";
        }

        csb.PersistSecurityInfo = false;
        csb.MinPoolSize         = 1;
        csb.MaxPoolSize         = 5;
        csb.Pooling             = true;

        csb.ApplicationName = "foobar Application";
        csb.Encoding        = System.Text.Encoding.UTF8.WebName;

        return(csb.ConnectionString);
    }
		public override void SetUpFixture()
		{
			PostgreSQLInsightDbProvider.RegisterProvider();

			_connectionStringBuilder = new NpgsqlConnectionStringBuilder();
			_connectionStringBuilder.ConnectionString = "Host = testserver; User Id = postgres; Password = Password1";
			_connection = _connectionStringBuilder.Open();
		}
Ejemplo n.º 14
0
        /// <summary>
        /// Сохранение активного фильтра
        /// </summary>
        public void Save(object parameter = null)
        {
            FilterSaveFrm frm = new FilterSaveFrm();

            frm.Text = "Фильтр";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int idSource = 0;
                int idTable  = 0;

                Npgsql.NpgsqlConnectionStringBuilder connect = (_source.Table.Source as PgDataRepositoryVM).Connect;
                String            sourceName = String.Format("{0}@{1}", connect.Database, connect.Host);
                String            sourceType = _source.Table.Source.Type.ToString();
                Pg_M.PgTableBaseM pgTable    = _source.Table as Pg_M.PgTableBaseM;
                String            tableName  = String.Format("\"{0}\".\"{1}\"", pgTable.SchemeName, pgTable.Name);

                bool sourceExists = (from Source src
                                     in Program.SettingsDB.Sources
                                     where src.SourceName == sourceName && src.SourceType == sourceType
                                     select src).Count() > 0;
                if (!sourceExists)
                {
                    Program.SettingsDB.Sources.AddObject(new Source()
                    {
                        SourceName = sourceName, SourceType = sourceType
                    });
                }
                idSource = Convert.ToInt32((from Source src
                                            in Program.SettingsDB.Sources
                                            where src.SourceName == sourceName && src.SourceType == sourceType
                                            select src.Id).FirstOrDefault());
                bool tableExists = (from Table tbl
                                    in Program.SettingsDB.Tables
                                    where tbl.SourceId == idSource && tbl.TableName == tableName
                                    select tbl).Count() > 0;
                if (!tableExists)
                {
                    Program.SettingsDB.Tables.AddObject(new Table()
                    {
                        TableName = tableName, SourceId = idSource
                    });
                }
                idTable = Convert.ToInt32((from Table tbl
                                           in Program.SettingsDB.Tables
                                           where tbl.TableName == tableName && tbl.SourceId == idSource
                                           select tbl.Id).FirstOrDefault());

                FilterRelationModel filterRM = GetFilterModel(_dynamicFilter);
                Program.SettingsDB.Filters.AddObject(new Filter()
                {
                    FilterName = frm.textBox1.Text,
                    WhereText  = SqlJsonParser.ToJson(filterRM),
                    IdTable    = idTable
                });
                Program.SettingsDB.SaveChanges();
                ReloadFiltersFromSqLite();
            }
        }
Ejemplo n.º 15
0
        public override void Startup(NpgsqlConnector context,NpgsqlConnectionStringBuilder settings)
        {
            NpgsqlStartupPacket startupPacket = new NpgsqlStartupPacket(context.Database, context.UserName, settings);

            startupPacket.WriteToStream(context.Stream);
            context.RequireReadyForQuery = false;

            ProcessAndDiscardBackendResponses(context);
        }
        public static NpgsqlConnection CreateConnection()
        {
            NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder(GetConnectionString());
            csb.Enlist = false;
            var connection = new NpgsqlConnection(csb.ToString());
            connection.Open();

            return connection;
        }
Ejemplo n.º 17
0
 public DatabaseWorker()
 {
     var connectionParams = new NpgsqlConnectionStringBuilder();
     connectionParams.Host = "127.0.0.1";
     connectionParams.UserName = "******";
     connectionParams.Password = "******";
     connectionParams.Database = "bbrother";
     _pgConnect = new NpgsqlConnection(connectionParams.ConnectionString);
     _pgConnect.Open();
 }
      private static void CreateDatabase()
      {
         var cxBuilder = new NpgsqlConnectionStringBuilder(ConnectionString);
         var database = cxBuilder.Database;
         cxBuilder.Database = null;

         var db = new NpgsqlConnection(cxBuilder.ToString());
         db.Execute($"DROP DATABASE IF EXISTS \"{database}\"");
         db.Execute($"CREATE DATABASE \"{database}\"");
      }
Ejemplo n.º 19
0
        public string ForceTestDB(string connectionString)
        {
            var cb = new NpgsqlConnectionStringBuilder(connectionString);
            if (!cb.Database.EndsWith("_test"))
            {
                cb.Database += "_test";
            }

            return cb.ToString();
        }
Ejemplo n.º 20
0
        private static void UsingPostgresDBConnection(NpgsqlConnection connection, Action<NpgsqlConnection> action)
        {
            var connectionBuilder = new NpgsqlConnectionStringBuilder(connection.ConnectionString);

            using (var masterConnection = new NpgsqlConnection(connectionBuilder.ConnectionString))
            {
                masterConnection.Open();
                action(masterConnection);
            }
        }
Ejemplo n.º 21
0
        public void Bug1011001()
        {
            //[#1011001] Bug in NpgsqlConnectionStringBuilder affects on cache and connection pool

            var csb1 = new NpgsqlConnectionStringBuilder(@"Server=server;Port=5432;User Id=user;Password=passwor;Database=database;");
            var cs1 = csb1.ToString();
            var csb2 = new NpgsqlConnectionStringBuilder(cs1);
            var cs2 = csb2.ToString();
            Assert.IsTrue(cs1 == cs2);
        }
Ejemplo n.º 22
0
        public static string ConnectionString()
        {
            var connectionStringBuilder = new NpgsqlConnectionStringBuilder();
            connectionStringBuilder.Host = ConfigurationManager.AppSettings["Server"];
            connectionStringBuilder.Database = ConfigurationManager.AppSettings["Database"];
            connectionStringBuilder.UserName = ConfigurationManager.AppSettings["UserId"];
            connectionStringBuilder.Password = ConfigurationManager.AppSettings["Password"];

            return connectionStringBuilder.ConnectionString;
        }
Ejemplo n.º 23
0
        public void BaseTypeResolution()
        {
            var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
            {
                ApplicationName = nameof(BaseTypeResolution),  // Prevent backend type caching in TypeHandlerRegistry
                Pooling = false
            };

            using (var conn = OpenConnection(csb))
            {
                // Resolve type by NpgsqlDbType
                using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                {
                    cmd.Parameters.AddWithValue("p", NpgsqlDbType.Integer, DBNull.Value);
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetDataTypeName(0), Is.EqualTo("int4"));
                    }
                }

                // Resolve type by DbType
                conn.ReloadTypes();
                using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter("p", DbType.Int32) { Value = DBNull.Value });
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetDataTypeName(0), Is.EqualTo("int4"));
                    }
                }

                // Resolve type by ClrType (type inference)
                conn.ReloadTypes();
                using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter { ParameterName="p", Value = 8 });
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetDataTypeName(0), Is.EqualTo("int4"));
                    }
                }

                // Resolve type by OID (read)
                conn.ReloadTypes();
                using (var cmd = new NpgsqlCommand("SELECT 8", conn))
                using (var reader = cmd.ExecuteReader())
                {
                    reader.Read();
                    Assert.That(reader.GetDataTypeName(0), Is.EqualTo("int4"));
                }
            }
        }
Ejemplo n.º 24
0
        public void EnumTypeResolutionWithGlobalMapping()
        {
            var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
            {
                ApplicationName = nameof(EnumTypeResolutionWithGlobalMapping),  // Prevent backend type caching in TypeHandlerRegistry
                Pooling = false
            };

            using (var conn = OpenConnection(csb))
            {
                conn.ExecuteNonQuery("CREATE TYPE pg_temp.mood1 AS ENUM ('sad', 'ok', 'happy')");
                NpgsqlConnection.MapEnumGlobally<Mood>("mood1");
                try
                {
                    conn.ReloadTypes();

                    // Resolve type by NpgsqlDbType
                    using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                    {
                        cmd.Parameters.Add(new NpgsqlParameter("p", NpgsqlDbType.Enum) { SpecificType = typeof(Mood), Value=DBNull.Value });
                        using (var reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            Assert.That(reader.GetDataTypeName(0), Does.StartWith("pg_temp").And.EndWith(".mood1"));
                            Assert.That(reader.IsDBNull(0), Is.True);
                        }
                    }

                    // Resolve type by ClrType (type inference)
                    conn.ReloadTypes();
                    using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                    {
                        cmd.Parameters.Add(new NpgsqlParameter { ParameterName = "p", Value = Mood.Ok });
                        using (var reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            Assert.That(reader.GetDataTypeName(0), Does.StartWith("pg_temp").And.EndWith(".mood1"));
                        }
                    }

                    // Resolve type by OID (read)
                    conn.ReloadTypes();
                    using (var cmd = new NpgsqlCommand("SELECT 'happy'::MOOD1", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetDataTypeName(0), Does.StartWith("pg_temp").And.EndWith(".mood1"));
                    }
                }
                finally
                {
                    NpgsqlConnection.UnmapEnumGlobally<Mood>("mood1");
                }
            }
        }
Ejemplo n.º 25
0
        public void CompositeTypeResolutionWithGlobalMapping()
        {
            var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
            {
                ApplicationName = nameof(CompositeTypeResolutionWithGlobalMapping),  // Prevent backend type caching in TypeHandlerRegistry
                Pooling = false
            };

            using (var conn = OpenConnection(csb))
            {
                conn.ExecuteNonQuery("CREATE TYPE pg_temp.composite1 AS (x int, some_text text)");
                NpgsqlConnection.MapCompositeGlobally<SomeComposite>("composite1");
                try
                {
                    conn.ReloadTypes();

                    // Resolve type by NpgsqlDbType
                    using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                    {
                        cmd.Parameters.Add(new NpgsqlParameter("p", NpgsqlDbType.Composite) { SpecificType = typeof(SomeComposite), Value = DBNull.Value });
                        using (var reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            Assert.That(reader.GetDataTypeName(0), Does.StartWith("pg_temp").And.EndWith(".composite1"));
                            Assert.That(reader.IsDBNull(0), Is.True);
                        }
                    }

                    // Resolve type by ClrType (type inference)
                    conn.ReloadTypes();
                    using (var cmd = new NpgsqlCommand("SELECT @p", conn))
                    {
                        cmd.Parameters.Add(new NpgsqlParameter { ParameterName = "p", Value = new SomeComposite { x = 8, SomeText = "foo" }});
                        using (var reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            Assert.That(reader.GetDataTypeName(0), Does.StartWith("pg_temp").And.EndWith(".composite1"));
                        }
                    }

                    // Resolve type by OID (read)
                    conn.ReloadTypes();
                    using (var cmd = new NpgsqlCommand("SELECT ROW(1, 'foo')::COMPOSITE1", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetDataTypeName(0), Does.StartWith("pg_temp").And.EndWith(".composite1"));
                    }
                }
                finally
                {
                    NpgsqlConnection.UnmapCompositeGlobally<SomeComposite>("composite1");
                }
            }
        }
Ejemplo n.º 26
0
 private void button1_Click(object sender, EventArgs e)
 {
     NpgsqlConnectionStringBuilder pgsCS = new NpgsqlConnectionStringBuilder();
     pgsCS.Host = @"10.211.55.2";
     pgsCS.Database = @"openbrain";
     pgsCS.UserName = @"postgres";
     pgsCS.Password = @"postgres";
     NpgsqlConnection pgCon = new NpgsqlConnection(pgsCS.ConnectionString);
     pgCon.Open();
     pgCon.Close();
 }
Ejemplo n.º 27
0
        public override void Startup(NpgsqlConnector context,NpgsqlConnectionStringBuilder settings)
        {
            NpgsqlStartupPacket startupPacket = NpgsqlStartupPacket.BuildStartupPacket(context.BackendProtocolVersion,
                                                                                       context.Database, context.UserName, settings);

            startupPacket.WriteToStream(context.Stream);
            context.RequireReadyForQuery = false;
            // This still makes part of the connection stablishment handling.
            // So we use the connectiontimeout here too.
            context.Mediator.CommandTimeout = context.ConnectionTimeout;
            ProcessAndDiscardBackendResponses(context);
        }
 public ConnectionBuilder(bool standardConnection)
 {
     _connectionStringBuilder = new NpgsqlConnectionStringBuilder();
     if (standardConnection)
     {
         this.Server("localhost")
             .Port("5432")
             .Database("App1")
             .User("App1DatabaseUser")
             .Password("pass1234");
     }
 }
        /// <summary>
        /// Initializes a new instance of the NpgsqlConnectionWithSchema class.
        /// </summary>
        /// <param name="connectionString">The connection string to wrap.</param>
        /// <param name="schema">The schema to select upon opening the connection.</param>
        public NpgsqlConnectionWithSchema(NpgsqlConnectionStringBuilder connectionString, string schema)
            : base(connectionString.Connection())
        {
            if (schema == null)
                throw new ArgumentNullException("schema");
            if (!Regex.Match(schema, String.Format(CultureInfo.InvariantCulture, "^{0}(,{0})*$", _validPostgresIdentifier)).Success)
                throw new ArgumentException("Schema contained invalid characters", "schema");

            Schema = schema;

			_switchSchemaSql = String.Format(CultureInfo.InvariantCulture, "SET SCHEMA '{0}'", Schema);
        }
Ejemplo n.º 30
0
        public NpgsqlConnectionStringBuilder ConStr()
        {
            string myConnectionString = "";
            NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder(myConnectionString);

            builder.Add("Server", textServer.Text);
            builder.Add("Port", textPort.Text);
            builder.Add("User", textUser.Text);
            builder.Add("Password", textPas.Text);
            builder.Add("Database", textBase.Text);

            return builder;
        }
Ejemplo n.º 31
0
        private string GetConnectionString()
        {
            NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder
               {
               Host = "localhost",
               Database = this.DatabaseName,
               UserName = this.UserName,
               Password = this.Password,
               ApplicationName = "MixERP Installer"
               };

               return builder.ConnectionString;
        }
Ejemplo n.º 32
0
        public virtual INpgsqlEFConnection CreateMasterConnection()
        {
            var builder = new NpgsqlConnectionStringBuilder { ConnectionString = ConnectionString };

            // TODO: See #566
            builder.Database = "postgres";

            // TODO use clone connection method once implimented see #1406
            var optionsBuilder = new DbContextOptionsBuilder();
            optionsBuilder.UseNpgsql(builder.ConnectionString).CommandTimeout(CommandTimeout);

            return new NpgsqlRelationalConnection(optionsBuilder.Options, _loggerFactory);
        }
Ejemplo n.º 33
0
        internal static string ConnectionString()
        {
            NpgsqlConnectionStringBuilder connectionStringBuilder = new NpgsqlConnectionStringBuilder
            {
                Host = Program.Server,
                Port = Program.Port,
                Database = Program.Database,
                UserName = Program.UserId,
                Password = Program.Password
            };

            return connectionStringBuilder.ConnectionString;
        }
Ejemplo n.º 34
0
        /// <summary>
        /// builds connection to database and returns npgsql connection object
        /// </summary>
        /// <returns> Npgsql connection object</returns>
        private static NpgsqlConnection Connect()
        {
            NpgsqlConnectionStringBuilder myBuilder = new NpgsqlConnectionStringBuilder()
            {
                Host = "127.0.0.1",
                Port = 5432,
                Database = "KaminariWan.Website",
                IntegratedSecurity = true
            };

            NpgsqlConnection conn = new NpgsqlConnection(myBuilder);
            return conn;
        }
Ejemplo n.º 35
0
        internal static string BuildConnectionString(bool integratedSecurity, string databaseName, string serverName, string userName, string password)
        {
            var connStr = new StringBuilder();
            var sb      = new Npgsql.NpgsqlConnectionStringBuilder();

            sb.IntegratedSecurity = integratedSecurity;
            sb.Database           = databaseName;
            sb.Host = serverName;
            if (!integratedSecurity)
            {
                sb.Username = userName;
                sb.Password = password;
            }
            return(sb.ToString());
        }
Ejemplo n.º 36
0
        public DataManager()
        {
            Npgsql.NpgsqlConnectionStringBuilder ssb = new Npgsql.NpgsqlConnectionStringBuilder();
            ssb.Host           = "localhost";
            ssb.Port           = 5432;
            ssb.Username       = "******";
            ssb.Password       = "******";
            ssb.Database       = "test_db";
            ssb.CommandTimeout = 30;
            ssb.Pooling        = true;
            ssb.MaxPoolSize    = 20;
            ssb.MinPoolSize    = 1;

            var cond = new Npgsql.NpgsqlConnection(ssb.ToString());

            database = new Database(cond.ConnectionString);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Загружает из базы SQLite названия и идентификаторы всех фильтров, относящихся к таблице _source.Table
        /// </summary>
        private void ReloadFiltersFromSqLite()
        {
            IdNameFilter.Clear();
            Npgsql.NpgsqlConnectionStringBuilder connect = (_source.Table.Source as PgDataRepositoryVM).Connect;
            Pg_M.PgTableBaseM pgTable    = _source.Table as Pg_M.PgTableBaseM;
            String            sourceName = String.Format("{0}@{1}", connect.Database, connect.Host);
            String            sourceType = pgTable.Source.Type.ToString();
            String            tableName  = String.Format("\"{0}\".\"{1}\"", pgTable.SchemeName, pgTable.Name);
            var filters = from Filter f
                          in Program.SettingsDB.Filters
                          where f.Table.TableName == tableName && f.Table.Source.SourceName == sourceName && f.Table.Source.SourceType == sourceType
                          select f;

            foreach (var filter in filters)
            {
                IdNameFilter.Add(new NameValue(filter.Id, filter.FilterName));
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Sets the `settings` ConnectionStringBuilder based on the given `connectionString`
 /// </summary>
 /// <param name="connectionString">The connection string to load the builder from</param>
 private void LoadConnectionStringBuilder(NpgsqlConnectionStringBuilder connectionString)
 {
     settings = connectionString;
     RefreshConnectionString();
     LogConnectionString();
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="NpgsqlConnection">NpgsqlConnection</see> class
 /// and sets the <see cref="NpgsqlConnection.ConnectionString">ConnectionString</see>.
 /// </summary>
 /// <param name="connectionString">The connection used to open the PostgreSQL database.</param>
 public NpgsqlConnection(NpgsqlConnectionStringBuilder connectionString)
 {
     LoadConnectionStringBuilder(connectionString);
     Init();
 }
Ejemplo n.º 40
0
 public virtual void Startup(NpgsqlConnector context, NpgsqlConnectionStringBuilder settings)
 {
     throw new InvalidOperationException("Internal Error! " + this);
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="NpgsqlConnection">NpgsqlConnection</see> class
 /// and sets the <see cref="NpgsqlConnection.ConnectionString">ConnectionString</see>.
 /// </summary>
 /// <param name="builder">The connection used to open the PostgreSQL database.</param>
 public NpgsqlConnection(NpgsqlConnectionStringBuilder builder) : this(builder.ConnectionString)
 {
 }