Ejemplo n.º 1
0
        private void ConfigureShards(IServiceScope serviceScope)
        {
            var databaseManager      = serviceScope.ServiceProvider.GetService <IDatabaseManager>();
            var shardsConfiguration  = serviceScope.ServiceProvider.GetService <ShardsConfiguration>();
            var shardProvider        = serviceScope.ServiceProvider.GetService <IShardFactory <int> >();
            var shardMapProvider     = serviceScope.ServiceProvider.GetService <IShardMapProvider <int> >();
            var shardMappingProvider = serviceScope.ServiceProvider.GetService <IShardMappingFactory <int> >();

            databaseManager.CreateIfNotExtists(ShardMapConnectionString);

            foreach (var shardConfiguration in shardsConfiguration.Shards)
            {
                databaseManager.CreateIfNotExtists(shardConfiguration.Server, shardConfiguration.UserName, shardConfiguration.Password.ToSecureString(), shardConfiguration.Database);
                var shardMap = shardMapProvider.CreateOrGetListShardMap(ShardMapConnectionString, ShardMapName);
                var shard    = shardProvider.CreateOrGet(shardMap, shardConfiguration.Server, shardConfiguration.Database);

                foreach (var shardingKey in shardConfiguration.ShardingKeys)
                {
                    shardMappingProvider.CreateIfNotExists(shardMap, shard, shardingKey);
                }

                var optionsBuilder         = new DbContextOptionsBuilder <SchoolsDbContext>();
                var connectionStringBuiler = new SqlConnectionStringBuilder();
                connectionStringBuiler.Add("Server", shardConfiguration.Server);
                connectionStringBuiler.Add("Data Source", shardConfiguration.Database);
                connectionStringBuiler.Add("User Id", shardConfiguration.UserName);
                connectionStringBuiler.Add("Password", shardConfiguration.Password);
                optionsBuilder.UseSqlServer(connectionStringBuiler.ConnectionString,
                                            sqlServerOptions => sqlServerOptions.MigrationsAssembly(_migrationsAssembly));
                var schoolsDbContext = new SchoolsDbContext(optionsBuilder.Options);
                schoolsDbContext.Database.EnsureCreated();
            }
        }
Ejemplo n.º 2
0
        public void TestSqlConnectionStringBuilderShouldSerialize(SqlConnectionColumnEncryptionSetting sqlConnectionColumnEncryptionSetting)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            connectionStringBuilder.Add(@"Column Encryption Setting", sqlConnectionColumnEncryptionSetting);

            // Query the ShouldSerialize method to check if the above add was effective.
            Assert.True(connectionStringBuilder.ShouldSerialize(@"Column Encryption Setting"));

            // Use the Remove function to Remove the Column Encryption Setting from the dictionary.
            connectionStringBuilder.Remove(@"Column Encryption Setting");

            // Query the property to check if the above add was effective.
            Assert.False(connectionStringBuilder.ShouldSerialize(@"Column Encryption Setting"));

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            string url = "www.foo.com";

            connectionStringBuilder.Add(@"Enclave Attestation Url", url);

            // Query the ShouldSerialize method to check if the above add was effective.
            Assert.True(connectionStringBuilder.ShouldSerialize(@"Enclave Attestation Url"));

            // Use the Remove function to Remove the Column Encryption Setting from the dictionary.
            connectionStringBuilder.Remove(@"Enclave Attestation Url");

            // Query the property to check if the above add was effective.
            Assert.False(connectionStringBuilder.ShouldSerialize(@"Enclave Attestation Url"));
        }
Ejemplo n.º 3
0
        public static string ModifyConnString(string connString)
        {
            OleDbConnectionStringBuilder oleConnBuilder = new OleDbConnectionStringBuilder(connString);
            SqlConnectionStringBuilder   sqlConnBuilder = new SqlConnectionStringBuilder();

            object tokenValue;

            if (oleConnBuilder.TryGetValue("Application Name", out tokenValue))
            {
                sqlConnBuilder.ApplicationName = tokenValue.ToString();
            }
            if (oleConnBuilder.TryGetValue("Server", out tokenValue))
            {
                sqlConnBuilder.Add("Server", tokenValue.ToString());
            }
            if (oleConnBuilder.TryGetValue("Database", out tokenValue))
            {
                sqlConnBuilder.Add("Database", tokenValue.ToString());
            }
            if (oleConnBuilder.TryGetValue("Trusted_Connection", out tokenValue))
            {
                sqlConnBuilder.IntegratedSecurity = (string.Compare(tokenValue.ToString(), "yes", true) == 0);
            }
            if (!sqlConnBuilder.IntegratedSecurity)
            {
                sqlConnBuilder.UserID   = oleConnBuilder["User Id"].ToString();
                sqlConnBuilder.Password = oleConnBuilder["Password"].ToString();
            }
            if (oleConnBuilder.TryGetValue("MARS Connection", out tokenValue))
            {
                sqlConnBuilder.MultipleActiveResultSets = (string.Compare(tokenValue.ToString(), "true", true) == 0);
            }

            return(sqlConnBuilder.ToString());
        }
Ejemplo n.º 4
0
        public void TestSqlConnectionStringBuilderAdd(SqlConnectionColumnEncryptionSetting sqlConnectionColumnEncryptionSetting)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            connectionStringBuilder.Add(@"Column Encryption Setting", sqlConnectionColumnEncryptionSetting);

            // Query the property to check if the above add was effective.
            Assert.Equal(sqlConnectionColumnEncryptionSetting, connectionStringBuilder.ColumnEncryptionSetting);

            //define value for Attestation Url and Attestation Protocol
            string url = "www.foo.com";
            SqlConnectionAttestationProtocol protocol = SqlConnectionAttestationProtocol.HGS;

            // Use the Add function to update the Enclave Attestation Url in the dictionary.
            connectionStringBuilder.Add(@"Enclave Attestation Url", url);

            // Query the property to check if the above add was effective.
            Assert.Equal(url, connectionStringBuilder.EnclaveAttestationUrl);

            // Use the Add function to update the Attestation Protocol in the dictionary.
            connectionStringBuilder.Add(@"Attestation Protocol", protocol);

            // Query the property to check if the above add was effective.
            Assert.Equal(protocol, connectionStringBuilder.AttestationProtocol);
        }
Ejemplo n.º 5
0
        public void TestSqlConnectionStringBuilderRemove(SqlConnectionColumnEncryptionSetting sqlConnectionColumnEncryptionSetting)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            connectionStringBuilder.Add(@"Column Encryption Setting", sqlConnectionColumnEncryptionSetting);

            // Query the property to check if the above add was effective.
            Assert.Equal(sqlConnectionColumnEncryptionSetting, connectionStringBuilder.ColumnEncryptionSetting);

            // Use the Remove function to remove the Column Encryption Setting from the dictionary.
            connectionStringBuilder.Remove(@"Column Encryption Setting");

            // Query the property to check if the above add was effective.
            object outputValue;

            connectionStringBuilder.TryGetValue(@"Column Encryption Setting", out outputValue);
            Assert.Equal(SqlConnectionColumnEncryptionSetting.Disabled, outputValue);

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            string url = "www.foo.com";

            connectionStringBuilder.Add(@"Enclave Attestation Url", url);

            // Query the property to check if the above add was effective.
            Assert.Equal(url, connectionStringBuilder.EnclaveAttestationUrl);

            // Use the Remove function to remove the Column Encryption Setting from the dictionary.
            connectionStringBuilder.Remove(@"Enclave Attestation Url");

            // Query the property to check if the above add was effective.
            connectionStringBuilder.TryGetValue(@"Enclave Attestation Url", out outputValue);
            Assert.Equal(string.Empty, outputValue);
        }
Ejemplo n.º 6
0
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            SettingHelper parentForm = (SettingHelper)this.Owner;

            try {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                builder.Add("Server", this.textBoxServerName.Text);
                if (this.comboBoxAuth.SelectedIndex == 0)
                {
                    builder.Add("Integrated Security", "SSPI");
                }
                else if (this.comboBoxAuth.SelectedIndex == 1)
                {
                    builder.Add("UID", this.textBoxUserName.Text);
                    builder.Add("PWD", this.textBoxPassword.Text);
                    builder.Add("Network Library", "DBMSSOCN");
                }

                parentForm.dbConn = new SqlConnection(builder.ConnectionString);
                parentForm.dbConn.Open();
                parentForm.dbCmd             = parentForm.dbConn.CreateCommand();
                parentForm.dbCmd.CommandType = CommandType.Text;

                // write settings back
                parentForm.connSetting["Server"]   = this.textBoxServerName.Text;
                parentForm.connSetting["AuthType"] = this.comboBoxAuth.SelectedIndex;
                parentForm.connSetting["UID"]      = this.textBoxUserName.Text;
                parentForm.connSetting["PWD"]      = this.textBoxPassword.Text;
                this.Close();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 7
0
        public void insertHKDRATE(string hkdrate)
        {
            SqlConnectionStringBuilder builder2 = new SqlConnectionStringBuilder();

            builder2.Add("User id", DBUser.Trim());
            builder2.Add("Initial Catalog", DBStr.Trim());
            builder2.Add("Data Source", DBHostStr.Trim());
            builder2.Add("Password", DBPasd.Trim());
            SqlConnection cn2  = new SqlConnection(builder2.ConnectionString);
            SqlCommand    cmd2 = cn2.CreateCommand();

            cmd2.Parameters.Add(new SqlParameter("@From_Currency_code", "HKD"));
            cmd2.Parameters.Add(new SqlParameter("@To_Currency_code", "TWD"));
            cmd2.Parameters.Add(new SqlParameter("@Rate_YYYYMMDD", DateTime.Now.ToString("yyyyMMdd")));
            cmd2.Parameters.Add(new SqlParameter("@Exchange_rate", Convert.ToSingle(hkdrate)));
            cmd2.Parameters.Add(new SqlParameter("@Creation_date", DateTime.Now));
            cmd2.Parameters.Add(new SqlParameter("@Created_by", 195));
            cmd2.CommandText = "insert into Exchange_date_rate(From_Currency_code,To_Currency_code,Rate_YYYYMMDD,Exchange_rate,Creation_date,Created_by) values (@From_Currency_code,@To_Currency_code,@Rate_YYYYMMDD,@Exchange_rate,@Creation_date,@Created_by) ";
            try
            {
                cn2.Open();
                cmd2.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }
            finally
            {
                cn2.Close();
                cn2.Dispose();
            }
            return;
        }
        public string BuildForWindowsAuthentication(string serverName)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            connectionStringBuilder.Add("Data Source", serverName);
            connectionStringBuilder.Add("Integrated Security", "True");

            return(connectionStringBuilder.ConnectionString);
        }
        private static string AddCredentials(string connectionString)
        {
            var databaseConfiguration = (NameValueCollection)ConfigurationManager.GetSection("DatabaseConfig");
            var builder = new SqlConnectionStringBuilder(connectionString);

            builder.Add("User Id", databaseConfiguration["UserId"]);
            builder.Add("Password", databaseConfiguration["Password"]);
            return(builder.ConnectionString);
        }
        public string BuildForSqlAuthentication(string serverName, string login, string password)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            connectionStringBuilder.Add("Data Source", serverName);
            connectionStringBuilder.Add("User Id", login);
            connectionStringBuilder.Add("Password", password);

            return(connectionStringBuilder.ConnectionString);
        }
Ejemplo n.º 11
0
        // Init
        static SqlConn()
        {
            SqlConnectionStringBuilder lConnStr = new SqlConnectionStringBuilder();

            lConnStr.Add("Data Source", "paweladamczuk.com.pl,4100");
            lConnStr.Add("Initial Catalog", "FOKA");
            lConnStr.Add("User Id", "sa");
            lConnStr.Add("Password", "foka");

            mSC = new SqlConnection(lConnStr.ConnectionString);
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            string domain = System.Environment.UserDomainName;

            Console.WriteLine(domain);

            //this need to be wrapped
            string       password     = "******";
            SecureString secureString = new SecureString();

            Array.ForEach(password.ToArray(), (z) => secureString.AppendChar(z));
            //end

            secureString.MakeReadOnly();
            try
            {
                //use sql crederntial and password
                SqlCredential sql = new SqlCredential(Environment.UserName, secureString);
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.Add("Data Source", domain);
                builder.Add("Initial Catalog", "Example");
                SqlCredential sqlCredential = new SqlCredential("roman", secureString);
                using (SqlConnection sqlConnectio = new SqlConnection(builder.ConnectionString, sqlCredential))
                {
                    sqlConnectio.Open();
                    SqlCommand sqlCommand = new SqlCommand("select SYSTEM_USER", sqlConnectio);
                    string     result     = (string)sqlCommand.ExecuteScalar();
                    Console.WriteLine(result);
                    sqlConnectio.Close();
                }

                //use windows authentication
                builder.Clear();
                builder.Add("Data Source", domain);
                builder.Add("Initial Catalog", "Example");
                builder.Add("Integrated Security", "SSPI");
                using (SqlConnection sqlConnectionSecond = new SqlConnection(builder.ConnectionString))
                {
                    sqlConnectionSecond.Open();
                    SqlCommand sqlCommand = new SqlCommand("select SYSTEM_USER", sqlConnectionSecond);
                    string     result     = (string)sqlCommand.ExecuteScalar();
                    Console.WriteLine(result);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                secureString.Dispose();
            }
        }
Ejemplo n.º 13
0
        private void FormFestivos_Load(object sender, EventArgs e)
        {
            SqlConnectionStringBuilder ParametrosConexion = new SqlConnectionStringBuilder();

            dt.Columns.Add("Fecha", Type.GetType("System.DateTime"));
            dt.Columns.Add("Fiesta", Type.GetType("System.String"));

            ParametrosConexion.Add("Data Source", "SEGUNDO150");
            ParametrosConexion.Add("Initial Catalog", "AVAN_iban");
            ParametrosConexion.Add("Integrated Security", "SSPI");

            //ParametrosConexion.Add("Data Source", "xxxxxxx,80");
            //ParametrosConexion.Add("Initial Catalog", "Agencia");
            //ParametrosConexion.Add("user", "sa");
            //ParametrosConexion.Add("password", "xxxxxxx");


            cn.ConnectionString = ParametrosConexion.ConnectionString;

            SqlParameter p_anio  = new SqlParameter();
            SqlCommand   Comando = cn.CreateCommand();

            Comando.CommandType  = System.Data.CommandType.Text;
            Comando.CommandText  = "select CAST(CAST(Agno AS varchar(4)) + '-' + CAST(Mes AS varchar(2)) + '-' + CAST(DiaMes AS varchar(2)) AS date) Fecha, DescFestivo from Agencia.Calendario where Festivo = 1 and Agno = @anio";
            p_anio.SqlDbType     = SqlDbType.SmallInt;
            p_anio.Direction     = ParameterDirection.Input;
            p_anio.ParameterName = "@anio";
            p_anio.Value         = DateTime.Now.Year;
            Comando.Parameters.Add(p_anio);

            try
            {
                cn.Open();
                SqlDataReader lector = Comando.ExecuteReader();

                while (lector.Read())
                {
                    agrega_fecha((DateTime)((IDataRecord)lector)["Fecha"], (String)((IDataRecord)lector)["DescFestivo"]);
                }
                lector.Close();
            }
            catch (Exception ex)
            {
                //////
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cn.Close();
            }
        }
Ejemplo n.º 14
0
    /// <summary>
    /// static constructor to determine the state of the environment and set defaults
    /// </summary>
    static CurrentEnvironment()
    {
        // Not on cloud foundry filling in the blanks.
        if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME)))
        {
            Environment.SetEnvironmentVariable(BOUND_SERVICES_ENV_VARIABLE_NAME, "{}");
            Environment.SetEnvironmentVariable(PORT_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
            Environment.SetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
            Environment.SetEnvironmentVariable(INSTANCE_INDEX_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
        }

        // check to see if DB is bound, if so...what type
        // SQL server first
        if (BoundServices.GetValue("azure-sqldb") != null) // Azure SQL Database (Azure Broker)
        {
            DbEngine = DatabaseEngine.SqlServer;
            SqlConnectionStringBuilder csbuilder = new SqlConnectionStringBuilder();
            csbuilder.Add("server", BoundServices["azure-sqldb"][0]["credentials"]["hostname"].ToString());
            csbuilder.Add("uid", BoundServices["azure-sqldb"][0]["credentials"]["username"].ToString());
            csbuilder.Add("pwd", BoundServices["azure-sqldb"][0]["credentials"]["password"].ToString());
            csbuilder.Add("database", BoundServices["azure-sqldb"][0]["credentials"]["name"].ToString());
            _connectionString = csbuilder.ToString();
        }
        else if (BoundServices.GetValue("azure-mysqldb") != null || BoundServices.GetValue("p-mysql") != null || BoundServices.GetValue("cleardb") != null) // MySQL for PCF or Mysql for AZURE
        {
            string label = "p-mysql";                                                                                                                       // MySQL Database.

            if (BoundServices.GetValue("azure-mysqldb") != null)
            {
                label = "azure-mysqldb"; //Mysql Database on Azure (Mysql For Azure)
            }
            if (BoundServices.GetValue("cleardb") != null)
            {
                label = "cleardb"; //Mysql cleardb
            }
            DbEngine = DatabaseEngine.MySql;
            MySqlConnectionStringBuilder csbuilder = new MySqlConnectionStringBuilder();
            csbuilder.Add("server", BoundServices[label][0]["credentials"]["hostname"].ToString());
            csbuilder.Add("port", BoundServices[label][0]["credentials"]["port"].ToString());
            csbuilder.Add("uid", BoundServices[label][0]["credentials"]["username"].ToString());
            csbuilder.Add("pwd", BoundServices[label][0]["credentials"]["password"].ToString());
            csbuilder.Add("database", BoundServices[label][0]["credentials"]["name"].ToString());
            _connectionString = csbuilder.ToString();
        }
        else
        {
            DbEngine = DatabaseEngine.None;
        }
    }
Ejemplo n.º 15
0
        public static string GetProviderConnectionString(string connectionString, out bool isEntity)
        {
            isEntity = false;
            if (string.Compare(connectionString, "metadata=", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(connectionString);
                connectionString = ecsb.ProviderConnectionString;
                isEntity         = true;
            }
            var builder = new SqlConnectionStringBuilder(connectionString);

            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
Ejemplo n.º 16
0
        public static string GetConnstringFromDBSource(DBSource dbSource, string connDB)
        {
            if (dbSource == null)
            {
                return(null);
            }
            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();

            sb.DataSource     = dbSource.ServerName;
            sb.InitialCatalog = connDB;
            sb.Pooling        = true;
            sb.MaxPoolSize    = 20;
            sb.MinPoolSize    = 10;
            sb.ConnectTimeout = 30;
            if (dbSource.IDType == IDType.sqlserver)
            {
                sb.UserID   = dbSource.LoginName;
                sb.Password = dbSource.LoginPassword;
                return(sb.ConnectionString);
            }
            else
            {
                sb.Add("Trusted_Connection", "SSPI");
                return(sb.ConnectionString);
            }
        }
Ejemplo n.º 17
0
        private static string BuildConnectionString(string server, string database, string username, string password)
        {
            // Create a connection string builder
            SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder
            {
                DataSource = server
            };

            // Define connection string attributes using three techniques
            csb.Add("Initial Catalog", database);
            csb.Add("User Id", username);
            csb.Add("Password", password);
            //csb["Integrated Security"] = true;

            return(csb.ConnectionString);
        }
Ejemplo n.º 18
0
        public string GetConnectionString(string name)
        {
            // Try to find entity connection.
            var cs = ConfigurationManager.ConnectionStrings[name];

            // If configuration section with not found then return.
            if (cs == null)
            {
                return(null);
            }
            var connectionString = cs.ConnectionString;

            if (string.Compare(cs.ProviderName, "System.Data.EntityClient", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(cs.ConnectionString);
                connectionString = ecsb.ProviderConnectionString;
            }
            var builder = new SqlConnectionStringBuilder(connectionString);

            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
Ejemplo n.º 19
0
        private SqlConnection CreateSQLConnection()
        {
            string serverName = SQLServerText.Text,
                   userName   = Username.Text,
                   password   = Password.Text,
                   dataBase   = DBName.Text;

            bool          isIntegratedSecurity          = AuthenticationTypeComboBox.SelectedIndex != 0;
            SqlConnection connection                    = new SqlConnection();
            SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();

            if (isIntegratedSecurity)
            {
                connectionString.Add("Integrated Security", "SSPI");
            }
            else
            {
                connectionString.UserID   = userName;
                connectionString.Password = password;
            }
            if (!String.IsNullOrEmpty(dataBase))
            {
                connectionString.InitialCatalog = dataBase;
            }
            connectionString.DataSource = serverName;

            connection.ConnectionString = connectionString.ToString();
            return(connection);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// This builds a connection string to hit this connection
        /// </summary>
        /// <returns></returns>
        public string BuildConnectionString()
        {
            SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();

            if (!string.IsNullOrEmpty(Server))
            {
                csb.DataSource = Server;
            }
            if (!string.IsNullOrEmpty(Database))
            {
                csb.InitialCatalog = Database;
            }
            csb.IntegratedSecurity = (SecurityType == SecurityType.WindowsAuthentication);

            if (csb.IntegratedSecurity == false && !string.IsNullOrEmpty(Username))
            {
                csb.UserID = Username;
                if (!string.IsNullOrEmpty(Password))
                {
                    csb.Password = Password;
                }
            }

            // Turn on MARS
            csb.Add("MultipleActiveResultSets", true);

            return(csb.ConnectionString);
        }
Ejemplo n.º 21
0
        public static string GetProviderConnectionString(string connectionString, out bool isEntity)
        {
            isEntity = false;
#if NETSTANDARD  // .NET Standard
#elif NETCOREAPP // .NET Core
            // EF Core does not support EF specific connection strings (metadata=res:... < this kind of connection strings).
#else // .NET Framework
            if (string.Compare(connectionString, "metadata=", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(connectionString);
                connectionString = ecsb.ProviderConnectionString;
                isEntity         = true;
            }
#endif
            var builder = new SqlConnectionStringBuilder(connectionString);
            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
Ejemplo n.º 22
0
        public static SqlConnection GetSQLConnection()
        {
            string connString = ConfigurationManager.ConnectionStrings["appConnectionString"].ConnectionString;
            SqlConnectionStringBuilder connStringBuilder = new SqlConnectionStringBuilder(connString);

            connStringBuilder.Add("Password", "niemvui");
            return(new SqlConnection(connStringBuilder.ToString()));
        }
Ejemplo n.º 23
0
        public void TestSqlConnectionStringBuilderAdd(SqlConnectionColumnEncryptionSetting sqlConnectionColumnEncryptionSetting)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            connectionStringBuilder.Add(@"Column Encryption Setting", sqlConnectionColumnEncryptionSetting);

            // Query the property to check if the above add was effective.
            Assert.Equal(sqlConnectionColumnEncryptionSetting, connectionStringBuilder.ColumnEncryptionSetting);

            // Use the Add function to update the Column Encryption Setting in the dictionary.
            string url = "www.foo.com";

            connectionStringBuilder.Add(@"Enclave Attestation Url", url);

            // Query the property to check if the above add was effective.
            Assert.Equal(url, connectionStringBuilder.EnclaveAttestationUrl);
        }
        static Connect()
        {
            try
            {
                SqlConnectionStringBuilder stringConn = new SqlConnectionStringBuilder();
                stringConn.Add("Data Source", @"VLADIMIR\SQLEXPRESS");
                stringConn.Add("Initial Catalog", "projekt_bazy_danych");
                stringConn.Add("Trusted_Connection", "True");

                conn = new SqlConnection(stringConn.ConnectionString);
                conn.Open();
                connected = true;
            }
            catch
            {
                conn.Dispose();
                connected = false;
            }
        }
Ejemplo n.º 25
0
        public static string SeachConnectionString()
        {
            SqlConnectionStringBuilder SCSB = new SqlConnectionStringBuilder();

            SCSB.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework";
            //if (Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Contains("assembly"))
            //    return @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\BankNetEntity\BankNetEntity\BankNetEntityDB\BankNetEntityDB.mdf;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework";
            SCSB.Add("AttachDbFilename", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\BankNetEntityDB.mdf");
            return(SCSB.ConnectionString);
        }
Ejemplo n.º 26
0
        private string getConnStr()
        {
            // 参数详见 https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.110%29.aspx

            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

            builder.Add("Server", dbIP.Text + "," + dbPort.Value.ToString());
            if (modeWin.Checked)
            {
                builder.Add("Integrated Security", "SSPI");
            }
            else
            {
                builder.Add("UID", userName.Text);
                builder.Add("PWD", password.Text);
                builder.Add("Network Library", "DBMSSOCN");
            }

            return(builder.ConnectionString);
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            var builder = new SqlConnectionStringBuilder()
            {
                ["Server"] = ".",
                ["Integrated Security"] = "Тrue"
            };
            var connection = new SqlConnection(builder.ToString());

            connection.Open();
            using (connection)
            {
                string createDbQuery = "CREATE DATABASE MinionsDB";
                ExecuteNonQueryCommand(createDbQuery, connection);
            }

            builder.Add("Database", "MinionsDb");
            connection = new SqlConnection(builder.ToString());

            using (connection)
            {
                connection.Open();
                string createCountriesSql       = "CREATE TABLE Countries (Id INT PRIMARY KEY IDENTITY,Name VARCHAR(50))";
                string createTownsSql           = "CREATE TABLE Towns(Id INT PRIMARY KEY IDENTITY,Name VARCHAR(50), CountryCode INT FOREIGN KEY REFERENCES Countries(Id))";
                string createMinionsSql         = "CREATE TABLE Minions(Id INT PRIMARY KEY IDENTITY,Name VARCHAR(30), Age INT, TownId INT FOREIGN KEY REFERENCES Towns(Id))";
                string createEvilnesFactorSql   = "CREATE TABLE EvilnessFactors(Id INT PRIMARY KEY IDENTITY, Name VARCHAR(50))";
                string createVillainsSql        = "CREATE TABLE Villains (Id INT PRIMARY KEY IDENTITY, Name VARCHAR(50), EvilnessFactorId INT FOREIGN KEY REFERENCES EvilnessFactors(Id))";
                string createMinionsVillainsSql = "CREATE TABLE MinionsVillains (MinionId INT FOREIGN KEY REFERENCES Minions(Id),VillainId INT FOREIGN KEY REFERENCES Villains(Id),CONSTRAINT PK_MinionsVillains PRIMARY KEY (MinionId, VillainId))";

                ExecuteNonQueryCommand(createCountriesSql, connection);
                ExecuteNonQueryCommand(createTownsSql, connection);
                ExecuteNonQueryCommand(createMinionsSql, connection);
                ExecuteNonQueryCommand(createEvilnesFactorSql, connection);
                ExecuteNonQueryCommand(createVillainsSql, connection);
                ExecuteNonQueryCommand(createMinionsVillainsSql, connection);

                string insertCountries       = "INSERT INTO Countries ([Name]) VALUES ('Bulgaria'),('England'),('Cyprus'),('Germany'),('Norway')";
                string insertTowns           = "INSERT INTO Towns ([Name], CountryCode) VALUES ('Plovdiv', 1),('Varna', 1),('Burgas', 1),('Sofia', 1),('London', 2),('Southampton', 2),('Bath', 2),('Liverpool', 2),('Berlin', 3),('Frankfurt', 3),('Oslo', 4)";
                string insertMinions         = "INSERT INTO Minions (Name,Age, TownId) VALUES('Bob', 42, 3),('Kevin', 1, 1),('Bob ', 32, 6),('Simon', 45, 3),('Cathleen', 11, 2),('Carry ', 50, 10),('Becky', 125, 5),('Mars', 21, 1),('Misho', 5, 10),('Zoe', 125, 5),('Json', 21, 1)";
                string insertEvilnessFactor  = "INSERT INTO EvilnessFactors (Name) VALUES ('Super good'),('Good'),('Bad'), ('Evil'),('Super evil')";
                string insertVillains        = "INSERT INTO Villains (Name, EvilnessFactorId) VALUES ('Gru',2),('Victor',1),('Jilly',3),('Miro',4),('Rosen',5),('Dimityr',1),('Dobromir',2)";
                string insertMinionsVillains = "INSERT INTO MinionsVillains (MinionId, VillainId) VALUES (4,2),(1,1),(5,7),(3,5),(2,6),(11,5),(8,4),(9,7),(7,1),(1,3),(7,3),(5,3),(4,3),(1,2),(2,1),(2,7)";

                ExecuteNonQueryCommand(insertCountries, connection);
                ExecuteNonQueryCommand(insertTowns, connection);
                ExecuteNonQueryCommand(insertMinions, connection);
                ExecuteNonQueryCommand(insertEvilnessFactor, connection);
                ExecuteNonQueryCommand(insertVillains, connection);
                ExecuteNonQueryCommand(insertMinionsVillains, connection);
                connection.Close();
            }
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            var builder = new SqlConnectionStringBuilder()
            {
                ["Server"] = "RZR\\SQLEXPRESS",
                ["Integrated Security"] = "True"
            };
            var connection = new SqlConnection(builder.ToString());

            connection.Open();

            using (connection)
            {
                try
                {
                    var createDbQuery = "CREATE DATABASE MinionsDB";
                    ExecuteCommand(createDbQuery, connection);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            builder.Add("DATABASE", "MinionsDB");
            connection = new SqlConnection(builder.ToString());
            connection.Open();
            using (connection)
            {
                try
                {
                    string cTCCountries       = "CREATE TABLE Countries ( Id INT PRIMARY KEY IDENTITY, Name NVARCHAR(50))";
                    string cTCTowns           = "CREATE TABLE Towns ( Id INT PRIMARY KEY IDENTITY, Name NVARCHAR(50), CountryId INT NOT NULL, CONSTRAINT FK_TownCountry FOREIGN KEY (CountryId) REFERENCES Countries(Id))";
                    string cTCEvilnessFactors = "CREATE TABLE EvilnessFactors ( Id INT PRIMARY KEY,	Name NVARCHAR(10) UNIQUE NOT NULL )";
                    string cTCVillains        = "CREATE TABLE Villains (	Id INT PRIMARY KEY IDENTITY, Name NVARCHAR(50), EvilnessFactorId INT CONSTRAINT FK_VillainEvilnessFactor FOREIGN KEY (EvilnessFactorId) REFERENCES EvilnessFactors(Id) )";
                    string cTCMinions         = "CREATE TABLE Minions ( Id INT PRIMARY KEY IDENTITY,	Name NVARCHAR(50), Age INT,	TownId INT, CONSTRAINT FK_Towns FOREIGN KEY (TownId) REFERENCES Towns(Id) )";
                    string cTCMinionsVillains = "CREATE TABLE MinionsVillains ( MinionId INT,	VillainId INT, CONSTRAINT FK_Minions FOREIGN KEY (MinionId) REFERENCES Minions(Id), CONSTRAINT FK_Villains FOREIGN KEY (VillainId) REFERENCES Villains(Id) )";

                    ExecuteCommand(cTCCountries, connection);
                    ExecuteCommand(cTCTowns, connection);
                    ExecuteCommand(cTCEvilnessFactors, connection);
                    ExecuteCommand(cTCVillains, connection);
                    ExecuteCommand(cTCMinions, connection);
                    ExecuteCommand(cTCMinionsVillains, connection);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Ejemplo n.º 29
0
        private static DbContextOptions <DeviceContext> GetModifedOptions(DbContextOptions <DeviceContext> options,
                                                                          IHttpContextAccessor httpContentAccessor, IOptions <ConnectionSettings> connectionOptions)
        {
            ValidateDefaultConnection(connectionOptions);
            var connectionBuilder = new SqlConnectionStringBuilder(connectionOptions.Value.DefaultConnection);

            connectionBuilder.Remove(Constants.Database);
            connectionBuilder.Add(Constants.Database, GetDataBaseName(GetTenantId(httpContentAccessor.HttpContext)));
            var contextOptionsBuilder = new DbContextOptionsBuilder <DeviceContext>();

            contextOptionsBuilder.UseSqlServer(connectionBuilder.ConnectionString);

            return(contextOptionsBuilder.Options);
        }
Ejemplo n.º 30
0
        private SqlConnectionStringBuilder ChangeNameDatabase()
        {
            var sqlConnectionBuilder = new SqlConnectionStringBuilder(this._connectionOptions.Value.DefaultConnection);
            var tenant = this._databaseManager.GetTenantById(this.TenantId);

            if (tenant == null)
            {
                throw new ArgumentNullException(nameof(tenant));
            }
            // Remove old DataBase name from connection string AND add new one
            sqlConnectionBuilder.Remove(DatabaseFieldKeyword);
            sqlConnectionBuilder.Add(DatabaseFieldKeyword, tenant.Name);

            return(sqlConnectionBuilder);
        }