コード例 #1
0
    public static void CreateDatabase(string connectionString)
    {
        try
        {
            var builder = new DbConnectionStringBuilder
            {
                ConnectionString = connectionString
            };

            object catalog;

            if (builder.ContainsKey("database"))
            {
                catalog = builder["database"];
                builder.Remove("database");
            }
            else if (builder.ContainsKey("initial catalog"))
            {
                catalog = builder["initial catalog"];
                builder.Remove("initial catalog");
            }
            else
            {
                return;
            }

            var master = builder.ToString();
            ExecuteScript(master, $"IF NOT exists(select * from sys.databases where name='{catalog}') CREATE DATABASE [{catalog}]");
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Could not create database.", ex);
        }
    }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="settings"></param>
        /// <exception cref="ConnectionElementNotFoundException"></exception>
        public void ReadConnectionParameters(ConnectionStringSettings settings)
        {
            var connectionString = new DbConnectionStringBuilder();

            connectionString.ConnectionString = settings.ConnectionString;

            if (connectionString.ContainsKey("DriverClass"))
            {
                ConnectionDriverClass = (string)connectionString["DriverClass"];
                connectionString.Remove("DriverClass");
            }
            else
            {
                throw new ConnectionElementNotFoundException("DriverClass");
            }

            if (connectionString.ContainsKey("Dialect"))
            {
                Dialect = (string)connectionString["Dialect"];
                connectionString.Remove("Dialect");
            }
            else
            {
                throw new ConnectionElementNotFoundException("Dialect");
            }

            ConnectionConnectionString = connectionString.ConnectionString;
        }
コード例 #3
0
        public string GetConnectionString(SqlDbConfig config, string user, string password)
        {
            if (String.IsNullOrEmpty(user) || String.IsNullOrEmpty(password))
            {
                if (!(String.IsNullOrEmpty(user) && String.IsNullOrEmpty(password)))
                {
                    throw new Exception("BUG: user and password must both be empty when one is.");
                }

                if (String.IsNullOrEmpty(config.Database.Connection.DefaultUser) || String.IsNullOrEmpty(config.Database.Connection.DefaultPassword))
                {
                    throw new Exception("Please add DefaultUser and DefaultPassword");
                }

                return(GetConnectionString(config, config.Database.Connection.DefaultUser, config.Database.Connection.DefaultPassword));
            }
            else
            {
                var    db   = config.Database;
                string tmp1 = string.Copy(db.Connection.ConnectionString);
                DbConnectionStringBuilder connBuilder = new DbConnectionStringBuilder();
                connBuilder.ConnectionString = tmp1;
                if (connBuilder.ContainsKey(db.Connection.KeyForPassword))
                {
                    connBuilder.Remove(db.Connection.KeyForPassword);
                    connBuilder.Add(db.Connection.KeyForPassword, password);
                }
                if (connBuilder.ContainsKey(db.Connection.KeyForUser))
                {
                    connBuilder.Remove(db.Connection.KeyForUser);
                    connBuilder.Add(db.Connection.KeyForUser, user);
                }
                return(connBuilder.ConnectionString);
            }
        }
コード例 #4
0
        // <Snippet1>
        static void Main()
        {
            DbConnectionStringBuilder builder =
                new DbConnectionStringBuilder();

            builder.ConnectionString = @"Data Source=c:\MyData\MyDb.mdb";
            builder.Add("Provider", "Microsoft.Jet.Oledb.4.0");
            builder.Add("Jet OLEDB:Database Password", "*******");
            builder.Add("Jet OLEDB:System Database",
                        @"c:\MyData\Workgroup.mdb");
            // Set up row-level locking.
            builder.Add("Jet OLEDB:Database Locking Mode", 1);

            // The DbConnectionStringBuilder class
            // is database agnostic, so it's possible to
            // build any type of connection string using
            // this class.

            // The ConnectionString property may have been
            // formatted by the DbConnectionStringBuilder class.
            OleDbConnection oledbConnect = new
                                           OleDbConnection(builder.ConnectionString);

            Console.WriteLine(oledbConnect.ConnectionString);

            // Use the same DbConnectionStringBuilder to create
            // a SqlConnection object.
            builder.Clear();
            builder.Add("integrated security", true);
            builder.Add("Initial Catalog", "AdventureWorks");
            builder.Add("Data Source", "(local)");

            SqlConnection sqlConnect = new
                                       SqlConnection(builder.ConnectionString);

            Console.WriteLine(sqlConnect.ConnectionString);

            // Pass the DbConnectionStringBuilder an existing
            // connection string, and you can retrieve and
            // modify any of the elements.
            builder.ConnectionString = "server=(local);user id=*******;" +
                                       "password=*******;initial catalog=AdventureWorks";
            builder["Server"] = ".";
            builder.Remove("User ID");

            // Note that calling Remove on a nonexistent item doesn't
            // throw an exception.
            builder.Remove("BadItem");

            // Setting the indexer adds the value if
            // necessary.
            builder["Integrated Security"] = true;
            builder.Remove("password");
            builder["User ID"] = "Hello";
            Console.WriteLine(builder.ConnectionString);

            Console.WriteLine("Press Enter to finish.");
            Console.ReadLine();
        }
コード例 #5
0
        public string GetWithoutPassword()
        {
            var conn = new DbConnectionStringBuilder(false);

            conn.ConnectionString = this.connectionString;
            conn.Remove("Password");
            conn.Remove("Pwd");
            return(conn.ToString());
        }
コード例 #6
0
ファイル: PostgreSQLProvider.cs プロジェクト: vindamle/openiz
        /// <summary>
        /// Gets a readonly connection
        /// </summary>
        public DataContext GetReadonlyConnection()
        {
            var conn = this.GetProviderFactory().CreateConnection();

            DbConnectionStringBuilder dbst = new DbConnectionStringBuilder();

            dbst.ConnectionString = this.ReadonlyConnectionString;

            if (this.ReadonlyConnectionString != this.ConnectionString)
            {
                Object host = String.Empty;
                if (this.m_readonlyIpAddresses == null && dbst.TryGetValue("host", out host) || dbst.TryGetValue("server", out host))
                {
                    IPAddress ip = null;
                    if (IPAddress.TryParse(host.ToString(), out ip)) // server is an IP, no need to dns
                    {
                        this.m_readonlyIpAddresses = new IPAddress[] { ip }
                    }
                    ;
                    else if (host.ToString() == "localhost")
                    {
                        conn.ConnectionString = this.ReadonlyConnectionString;
                        return(new DataContext(this, conn, true));
                    }
                    else
                    {
                        this.m_readonlyIpAddresses = Dns.GetHostAddresses(host.ToString());
                    }
                    dbst.Remove("host");
                    dbst.Remove("server");
                    this.ReadonlyConnectionString = dbst.ConnectionString;
                }

                // Readonly IP address
                if (this.m_readonlyIpAddresses?.Length > 1)
                {
                    dbst["server"] = this.m_readonlyIpAddresses[this.m_lastRrHost++ % this.m_readonlyIpAddresses.Length].ToString();
                    if (this.m_lastRrHost > this.m_readonlyIpAddresses.Length)
                    {
                        this.m_lastRrHost = 0;
                    }
                    conn.ConnectionString = dbst.ConnectionString;
                }
                else
                {
                    conn.ConnectionString = this.ReadonlyConnectionString;
                }
            }
            else
            {
                conn.ConnectionString = this.ReadonlyConnectionString;
            }

            return(new DataContext(this, conn, true));
        }
コード例 #7
0
        public string GetProviderCompatibleConnectionString()
        {
            var csb = new DbConnectionStringBuilder {
                ConnectionString = _csb.ConnectionString
            };

            csb.Remove(CharSetKey);
            csb.Remove(CollationKey);

            return(csb.ConnectionString);
        }
コード例 #8
0
 public void Clean(DbConnectionStringBuilder builder)
 {
     builder.Remove(Keyword);
     if (Synonyms == null)
     {
         return;
     }
     foreach (var syn in Synonyms)
     {
         builder.Remove(syn);
     }
 }
コード例 #9
0
        /// <summary>
        /// Creates connection from config settings stored in SPWeb.
        /// </summary>
        /// <returns>The new SqlConnection instance.</returns>
        public SqlConnection CreateConnection(SPWeb web)
        {
            if (web == null)
            {
                throw new ArgumentNullException(nameof(web));
            }

            if (!AllowDatabaseConnections(web))
            {
                throw new InvalidOperationException($"PPMFeature is not installed ({web.Site.Url})");
            }

            var basePath         = GetBasePath(web);
            var connectionString = Utilities.GetPFEDBConnectionString(basePath);

            // convert sql connection string to proper format
            var connectionStringBuilder = new DbConnectionStringBuilder {
                ConnectionString = connectionString
            };

            connectionStringBuilder.Remove("Provider");
            connectionStringBuilder.Add("Application Name", "EPMLiveCore");
            connectionString = connectionStringBuilder.ToString();

            var connection = new SqlConnection(connectionString);

            connection.Open();
            return(connection);
        }
コード例 #10
0
        public static void Save(ConnectionProperties connectionProperties, ConfigurationNode configurationNode)
        {
            var attributes = configurationNode.Attributes;

            attributes.SetAttributeValue("ConnectionName", connectionProperties.ConnectionName);
            attributes.SetAttributeValue("ProviderName", connectionProperties.ProviderName);
            attributes.SetAttributeValue(ConnectionStringKeyword.DataSource, connectionProperties.DataSource);
            attributes.SetAttributeValue(ConnectionStringKeyword.InitialCatalog, connectionProperties.InitialCatalog);
            attributes.SetAttributeValue(ConnectionStringKeyword.IntegratedSecurity, connectionProperties.IntegratedSecurity);
            attributes.SetAttributeValue(ConnectionStringKeyword.UserId, connectionProperties.UserId);

            if (connectionProperties.Password != null)
            {
                attributes.SetAttributeValue(ConnectionStringKeyword.Password, ProtectPassword(connectionProperties.Password.Value));
            }
            else
            {
                attributes.Remove(ConnectionStringKeyword.Password);
            }

            var connectionStringBuilder = new DbConnectionStringBuilder();

            connectionStringBuilder.ConnectionString = connectionProperties.ConnectionString;
            connectionStringBuilder.Remove(ConnectionStringKeyword.Password);
            attributes.SetAttributeValue("ConnectionString", connectionStringBuilder.ConnectionString);
        }
コード例 #11
0
        /// <summary>
        /// Records the SQL information on the current subsegment,
        /// </summary>
        private static void CollectSqlInformation(DbCommand command, bool?collectSqlQueriesOverride)
        {
            // Get database type from DbCommand
            string databaseType = GetDataBaseType(command);

            _recorder.AddSqlInformation("database_type", databaseType);

            DbConnectionStringBuilder connectionStringBuilder = new DbConnectionStringBuilder
            {
                ConnectionString = command.Connection.ConnectionString
            };

            // Remove sensitive information from connection string
            connectionStringBuilder.Remove("Password");

            _recorder.AddSqlInformation("connection_string", connectionStringBuilder.ToString());

            // Do a pre-check for UserID since in the case of TrustedConnection, a UserID may not be available.
            var user_id = GetUserId(connectionStringBuilder);

            if (user_id != null)
            {
                _recorder.AddSqlInformation("user", user_id.ToString());
            }

            if (ShouldCollectSqlText(collectSqlQueriesOverride))
            {
                _recorder.AddSqlInformation("sanitized_query", command.CommandText);
            }

            _recorder.AddSqlInformation("database_version", command.Connection.ServerVersion);
        }
コード例 #12
0
        /// <summary>
        /// Records the SQL information on the current subsegment,
        /// </summary>
        protected virtual void CollectSqlInformation(CommandEventData eventData)
        {
            // Get database type from DbContext
            string databaseType = EFUtil.GetDataBaseType(eventData.Context);

            _recorder.AddSqlInformation("database_type", databaseType);

            _recorder.AddSqlInformation("database_version", eventData.Command.Connection.ServerVersion);

            DbConnectionStringBuilder connectionStringBuilder = new DbConnectionStringBuilder
            {
                ConnectionString = eventData.Command.Connection.ConnectionString
            };

            // Remove sensitive information from connection string
            connectionStringBuilder.Remove("Password");

            // Do a pre-check for UserID since in the case of TrustedConnection, a UserID may not be available.
            var user_id = EFUtil.GetUserId(connectionStringBuilder);

            if (user_id != null)
            {
                _recorder.AddSqlInformation("user", user_id.ToString());
            }

            _recorder.AddSqlInformation("connection_string", connectionStringBuilder.ToString());

            if (ShouldCollectSqlText())
            {
                _recorder.AddSqlInformation("sanitized_query", eventData.Command.CommandText);
            }
        }
コード例 #13
0
        static void GetProjectEXTID(string basepath, SPWeb web, string projectid, out int projectextid)
        {
            try
            {
                projectextid = 0;
                var connectionString = Utilities.GetPFEDBConnectionString(basepath);
                // convert sql connection string to proper format
                var connectionStringBuilder = new DbConnectionStringBuilder {
                    ConnectionString = connectionString
                };
                connectionStringBuilder.Remove("Provider");
                connectionStringBuilder.Add("Application Name", "EPMLiveCore TimeSheet");
                connectionString = connectionStringBuilder.ToString();
                using (SqlConnection cn = new SqlConnection(connectionString))
                {
                    cn.Open();

                    using (SqlCommand cmd = new SqlCommand(PfeProjectSQL, cn))
                    {
                        cmd.Parameters.AddWithValue("@projectID", projectid);
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            if (dr.Read())
                            {
                                projectextid = dr.GetInt32(0);
                            }
                        }
                    }
                }
            }
            catch
            {
                projectextid = 0;
            }
        }
コード例 #14
0
        private static void SetDataHelperNamesLegacyConnectionString(DbConnectionStringBuilder connectionStringBuilder)
        {
            // get the data layer type and parse it
            var datalayerType = String.Empty;

            if (connectionStringBuilder.ContainsKey(ConnectionStringDataLayerIdentifier))
            {
                datalayerType = connectionStringBuilder[ConnectionStringDataLayerIdentifier].ToString();
                connectionStringBuilder.Remove(ConnectionStringDataLayerIdentifier);
            }

            _connectionString = connectionStringBuilder.ConnectionString;

            var datalayerTypeParts = datalayerType.Split(",".ToCharArray());

            _dataHelperTypeName     = datalayerTypeParts[0].Trim();
            _dataHelperAssemblyName = datalayerTypeParts.Length < 2
                                          ? string.Empty
                                          : datalayerTypeParts[1].Trim();

            if (datalayerTypeParts.Length > 2 || (_dataHelperTypeName.Length == 0 && _dataHelperAssemblyName.Length > 0))
            {
                throw new ArgumentException("Illegal format of data layer property. Should be 'DataLayer = Full_Type_Name [, Assembly_Name]'.", "connectionString");
            }
        }
コード例 #15
0
        public virtual string ToDisplayString()
        {
            var sensitiveProperties = Properties.Values.Where(x => x.IsSensitive);

            var removedProperties = new List <Tuple <string, object> >();

            foreach (var sensitiveProperty in sensitiveProperties)
            {
                var propertyName = sensitiveProperty.Name;
                if (!_connectionStringBuilder.ShouldSerialize(propertyName))
                {
                    continue;
                }

                removedProperties.Add(new Tuple <string, object>(propertyName, _connectionStringBuilder[propertyName]));
                _connectionStringBuilder.Remove(propertyName);
            }
            var displayConnectionString = _connectionStringBuilder.ConnectionString;

            foreach (var prop in removedProperties.Where(prop => prop.Item2 != null))
            {
                _connectionStringBuilder[prop.Item1] = prop.Item2;
            }

            return(displayConnectionString);
        }
コード例 #16
0
        public static DbProviderInfo ParseArg(string target)
        {
            // check to see if target is a named connection string
            ConnectionStringSettings css = ConfigurationManager.ConnectionStrings[target];

            if (css != null)
            {
                DbProviderInfo provider =
                    Instance.Find(p => string.Compare(css.ProviderName, p.InvariantName, true) == 0);
                provider.ConnectionString = css.ConnectionString;
                return(provider);
            }

            // check to see if a valid connection string
            DbConnectionStringBuilder csb = new DbConnectionStringBuilder {
                ConnectionString = target
            };
            string providerName = csb["Provider"] as string;

            if (!string.IsNullOrEmpty(providerName))
            {
                DbProviderInfo provider = Instance.Find(p => string.Compare(providerName, p.InvariantName, true) == 0);
                csb.Remove("provider");
                provider.ConnectionString = csb.ConnectionString;
                return(provider);
            }
            return(null);
        }
コード例 #17
0
        public void SaveApplicationData()
        {
            var folder = ConnectionsConfigurationNode;

            foreach (var subFolder in folder.ChildNodes)
            {
                var connectionProperties = new ConnectionProperties();
                connectionProperties.Load(subFolder);

                var dbConnectionStringBuilder = new DbConnectionStringBuilder();
                dbConnectionStringBuilder.ConnectionString = connectionProperties.ConnectionString;
                object obj;
                var    contains = dbConnectionStringBuilder.TryGetValue(ConnectionStringKeyword.UserId, out obj);

                if (contains)
                {
                    var password = dbConnectionStringBuilder.GetValue(ConnectionStringKeyword.Password);
                    dbConnectionStringBuilder.Remove(ConnectionStringKeyword.Password);
                    connectionProperties.ConnectionString = dbConnectionStringBuilder.ConnectionString;
                    password = ConnectionProperties.ProtectPassword(password);
                    subFolder.Attributes.SetAttributeValue(ConnectionStringKeyword.Password, password);
                }

                connectionProperties.Save(subFolder);
            }

            var tempFileName = FileName + ".temp";

            ApplicationData.Save(tempFileName, _sectionName);
            var succeeded = NativeMethods.MoveFileEx(tempFileName, FileName,
                                                     NativeMethods.MoveFileExFlags.ReplaceExisiting);

            Log.Write(LogLevel.Trace, "MoveFileEx succeeded: {0}", succeeded);
        }
コード例 #18
0
        /// <summary>
        /// Records the SQL information on the current subsegment.
        /// </summary>
        private static void CollectSqlInformationDefault(DbCommand command)
        {
            var recorder     = AWSXRayRecorder.Instance;
            var databaseType = AgentUtil.GetDataBaseType(command);

            recorder.AddSqlInformation("database_type", databaseType);

            recorder.AddSqlInformation("database_version", command.Connection.ServerVersion);

            DbConnectionStringBuilder connectionStringBuilder = new DbConnectionStringBuilder
            {
                ConnectionString = command.Connection.ConnectionString
            };

            // Remove sensitive information from connection string
            connectionStringBuilder.Remove("Password");

            var userId = AgentUtil.GetUserId(connectionStringBuilder);

            // Do a pre-check for user ID since in the case of TrustedConnection, a user ID may not be available.
            if (userId != null)
            {
                recorder.AddSqlInformation("user", userId.ToString());
            }

            recorder.AddSqlInformation("connection_string", connectionStringBuilder.ToString());

            if (ShouldCollectSqlText())
            {
                recorder.AddSqlInformation("sanitized_query", command.CommandText);
            }
        }
コード例 #19
0
        /// <summary>
        /// Replaces any existing 'enlist' parameter in the connection string
        /// with a value indicating that manual enlist is necessary.
        /// </summary>
        /// <remarks>
        /// ODP.NET supports 3 values for 'enlist'; 'true', 'false' and 'dynamic'.
        ///  'dynamic' effectively works the same as 'false' in System.Data.OracleClient.
        /// </remarks>
        protected override void ReplaceEnlistInConnectionString(DbConnectionStringBuilder dbConnectionStringBuilder)
        {
            if (dbConnectionStringBuilder.ContainsKey("enlist"))
            {
                dbConnectionStringBuilder.Remove("enlist");
            }

            dbConnectionStringBuilder.Add("enlist", "dynamic");
        }
コード例 #20
0
        /// <summary>
        /// Replaces any existing 'enlist' parameter in the connection String
        /// with a value indicating that manual enlist is necessary.
        /// </summary>
        protected virtual void ReplaceEnlistInConnectionString(DbConnectionStringBuilder dbConnectionStringBuilder)
        {
            if (dbConnectionStringBuilder.ContainsKey("enlist"))
            {
                dbConnectionStringBuilder.Remove("enlist");
            }

            dbConnectionStringBuilder.Add("enlist", false);
        }
コード例 #21
0
        void CheckMsSqlConnectionString()
        {
            string[] customKeys = { "Queue Schema" };

            try
            {
                //Check  validity of connection string. This will throw if invalid
                var builder = new DbConnectionStringBuilder {
                    ConnectionString = connectionString
                };

                //The NSB SQL Transport can have custom key/value pairs in the connection string
                // that won't make sense to SQL. Remove these from the string we want to validate.
                foreach (var customKey in customKeys)
                {
                    if (builder.ContainsKey(customKey))
                    {
                        builder.Remove(customKey);
                    }
                }

                //Check that localsystem is not used when integrated security is enabled
                if (builder.ContainsKey("Integrated Security"))
                {
                    var integratedSecurity = (string)builder["Integrated Security"];
                    var enabledValues      = new[]
                    {
                        "true",
                        "yes",
                        "sspi"
                    };
                    if (enabledValues.Any(p => p.Equals(integratedSecurity, StringComparison.OrdinalIgnoreCase)))
                    {
                        var account = UserAccount.ParseAccountName(serviceAccount);
                        if (account.IsLocalSystem())
                        {
                            throw new EngineValidationException("Invalid service account for this connection string. The connection string has integrated security enabled but localsystem service has been selected.");
                        }
                    }
                }

                //Attempt to connect to DB
                using (var s = new SqlConnection(builder.ConnectionString))
                {
                    s.Open();
                }
            }
            catch (ArgumentException argumentException)
            {
                throw new EngineValidationException($"Connection String is invalid - {argumentException.Message}");
            }
            catch (SqlException sqlEx)
            {
                throw new EngineValidationException($"SQL connection failed - {sqlEx.Message}");
            }
        }
コード例 #22
0
        public static string GetConnectionString(string databaseName = null)
        {
            if (databaseName != null)
            {
                conStrBuilder.Remove("Database");
                conStrBuilder.Add("Database", databaseName);
            }

            return(conStrBuilder.ConnectionString);
        }
コード例 #23
0
        public static string GetConnectionStringWithoutProvider(string connStr)
        {
            var builder = new DbConnectionStringBuilder();

            builder.ConnectionString = connStr;
            if (builder.ContainsKey("provider"))
            {
                builder.Remove("provider");
            }
            return(builder.ConnectionString);
        }
コード例 #24
0
        private static string GetConnectionStringForServiceDatabase(DbConnectionStringBuilder connectionStringBuilder, string serviceDbName)
        {
            var cloneConnectionString = new DbConnectionStringBuilder
            {
                ConnectionString = connectionStringBuilder.ConnectionString
            };

            cloneConnectionString.Remove("database");
            cloneConnectionString.Add("database", serviceDbName);
            return(cloneConnectionString.ConnectionString);
        }
コード例 #25
0
ファイル: source.cs プロジェクト: yashbajra/samples
 static void TryRemove(DbConnectionStringBuilder builder, string itemToRemove)
 {
     if (builder.Remove(itemToRemove))
     {
         Console.WriteLine(@"Removed '{0}'", itemToRemove);
     }
     else
     {
         Console.WriteLine(@"Unable to remove '{0}'", itemToRemove);
     }
     Console.WriteLine(builder.ConnectionString);
 }
コード例 #26
0
        private async Task Run()
        {
            // setup connection
            var connectionString = GetConvar($"{m_name}_connection_string", "");

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException($"No connection string configured for {m_name}. " +
                                                    $"Please set the `{m_name}_connection_string` convar in your server startup script.");
            }

            var csBuilder = new DbConnectionStringBuilder();

            csBuilder.ConnectionString = connectionString;

            if (!csBuilder.TryGetValue("dbProvider", out object provider))
            {
                provider = "mysql";
            }

            csBuilder.Remove("dbProvider");

            var factory = m_factoryList.GetFactory(provider.ToString());

            if (factory == null)
            {
                throw new InvalidOperationException($"Invalid database provider name {provider} in connection string for {m_name}. " +
                                                    $"Supported providers: [{string.Join(", ", m_factoryList.GetNames())}].");
            }

            m_dataAbstraction = m_factoryList.GetDataAbstraction(provider.ToString());

            m_connectionString = csBuilder.ConnectionString;

            using (var connection = await OpenConnection(factory))
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT 1";

                    var r = await command.ExecuteScalarAsync();

                    if (Convert.ToInt32(r) == 1)
                    {
                        m_factory = factory;
                    }
                    else
                    {
                        throw new InvalidOperationException($"SELECT 1 failed for {m_name} - it returned {r} instead.");
                    }
                }
            }
        }
コード例 #27
0
        /// <summary>
        /// Extracts the provider from the connection string or uses the default.
        /// </summary>
        /// <param name="csb">The DbConnectionStringBuilder object to use.</param>
        /// <returns>the string type of the provider.</returns>
        private static string GetProvider(DbConnectionStringBuilder csb)
        {
            string provider = "System.Data.SqlClient"; // default factory provider

            if (csb.ContainsKey("provider"))
            {
                provider = csb["provider"].ToString();
                csb.Remove("provider");
            }

            return(provider);
        }
コード例 #28
0
        public override bool Perform()
        {
            try
            {
                using (SPWeb mySite = Web.Site.OpenWeb())
                {
                    string basePath = CoreFunctions.getConfigSetting(mySite, "epkbasepath");
                    if (!string.IsNullOrEmpty(basePath))
                    {
                        RegistryKey rk = Registry.LocalMachine.OpenSubKey(const_subKey + basePath);
                        if (rk != null)
                        {
                            if (rk.GetValue("QMActive", "no").ToString().ToLower() == "yes")
                            {
                                var dbConnectionStringBuilder = new DbConnectionStringBuilder {
                                    ConnectionString = rk.GetValue("ConnectionString", string.Empty).ToString().Trim()
                                };
                                dbConnectionStringBuilder.Remove("Provider");
                                string connection = dbConnectionStringBuilder.ToString();
                                if (!string.IsNullOrEmpty(connection))
                                {
                                    using (SqlConnection pfecn = new SqlConnection(connection))
                                    {
                                        pfecn.Open();
                                        var definition = pfecn.IndexDefinition("I_COST_BREAKDOWN_ATTRIBS_CB_ID_BA_BC_UID_BA_PRD_ID_BA_RATETYPE_UID_BA_CODE_UID");
                                        if (definition == null)
                                        {
                                            pfecn.ExecuteNonQuery(@"Create Index I_COST_BREAKDOWN_ATTRIBS_CB_ID_BA_BC_UID_BA_PRD_ID_BA_RATETYPE_UID_BA_CODE_UID
                                                                    ON EPGP_COST_BREAKDOWN_ATTRIBS(CB_ID,BA_BC_UID,BA_PRD_ID,BA_RATETYPE_UID,BA_CODE_UID)");
                                            LogMessage("I_COST_BREAKDOWN_ATTRIBS_CB_ID_BA_BC_UID_BA_PRD_ID_BA_RATETYPE_UID_BA_CODE_UID index has been created.", MessageKind.SUCCESS, 4);
                                        }
                                        else
                                        {
                                            LogMessage("I_COST_BREAKDOWN_ATTRIBS_CB_ID_BA_BC_UID_BA_PRD_ID_BA_RATETYPE_UID_BA_CODE_UID index already exists.", MessageKind.SKIPPED, 4);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception exception)
            {
                string message = exception.InnerException != null
                      ? exception.InnerException.Message
                      : exception.Message;

                LogMessage(message, MessageKind.FAILURE, 4);
            }
            return(false);
        }
コード例 #29
0
        static string RemoveXpoProviderKey(string connectionString)
        {
            const string xpoProviderKey = "XpoProvider";

            var builder = new DbConnectionStringBuilder()
            {
                ConnectionString = connectionString
            };

            builder.Remove(xpoProviderKey);

            return(builder.ToString());
        }
コード例 #30
0
        private static string GenerateConnectionString(string edsSqlSchemaVersion, string connectionString)
        {
            string value = Guid.NewGuid().ToString();
            DbConnectionStringBuilder dbConnectionStringBuilder = new DbConnectionStringBuilder();

            dbConnectionStringBuilder.ConnectionString = connectionString;
            object obj;

            if (dbConnectionStringBuilder.TryGetValue("Site", out obj))
            {
                dbConnectionStringBuilder.Remove("Site");
            }
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(dbConnectionStringBuilder.ConnectionString);
            object obj2;

            if (!sqlConnectionStringBuilder.TryGetValue("Password", out obj2))
            {
                throw new ArgumentException("The connection string must contain a password.");
            }
            string password;

            if (!ManageEdsConnectionStrings.DkmEncryptString(obj2.ToString(), out password))
            {
                throw new ApplicationException("Unable to encrypt password");
            }
            sqlConnectionStringBuilder.Password = password;
            object obj3;

            if (!sqlConnectionStringBuilder.TryGetValue("User ID", out obj3) || string.IsNullOrEmpty(obj3.ToString()))
            {
                throw new ArgumentException("The connection string must contains a User ID");
            }
            if (!sqlConnectionStringBuilder.TryGetValue("Initial Catalog", out obj3) || string.IsNullOrEmpty(obj3.ToString()))
            {
                throw new ArgumentException("The connection string must contains an Initial Catalog");
            }
            if (!sqlConnectionStringBuilder.TryGetValue("Data Source", out obj3) || string.IsNullOrEmpty(obj3.ToString()))
            {
                throw new ArgumentException("The connection string must contains a Data Source");
            }
            DbConnectionStringBuilder dbConnectionStringBuilder2 = new DbConnectionStringBuilder();

            dbConnectionStringBuilder2.ConnectionString = sqlConnectionStringBuilder.ConnectionString;
            if (!string.IsNullOrEmpty((string)obj))
            {
                dbConnectionStringBuilder2.Add("Site", obj);
            }
            dbConnectionStringBuilder2.Add("Guid", value);
            dbConnectionStringBuilder2.Add("EdsSqlSchemaVersion", edsSqlSchemaVersion);
            return(dbConnectionStringBuilder2.ToString());
        }