예제 #1
0
 private static bool IsOleDb(DbConnectionStringBuilder builder)
 {
     return(builder
            .GetType()
            .GetTypesInHierarchy()
            .Any(t => string.Equals(t.FullName, "System.Data.OleDb.OleDbConnectionStringBuilder")));
 }
예제 #2
0
 public static IImplementation GetImplementation(DbConnectionStringBuilder connectionStringBuilder)
 {
     return(GetImplementation(i => i.IsFor(connectionStringBuilder),
                              string.Format(
                                  FAnsiStrings
                                  .ImplementationManager_GetImplementation_No_implementation_found_for_ADO_Net_object_of_Type__0_,
                                  connectionStringBuilder.GetType())));
 }
예제 #3
0
        /// <summary>
        /// Creates a <seealso cref="DbConnection"/> of a type specific to that of the connection string builder.
        /// </summary>
        /// <param name="connectionStringBuilder">The connection string builder.</param>
        /// <returns>DbConnection.</returns>
        public static DbConnection CreateConnection(this DbConnectionStringBuilder connectionStringBuilder)
        {
            DbConnection connection = null;

            if (connectionStringBuilder != null)
            {
                connection = DbProviderFactories.GetFactory(connectionStringBuilder.GetType().Namespace).CreateConnection();
                connection.ConnectionString = connectionStringBuilder.ConnectionString;
            }
            return(connection);
        }
예제 #4
0
        private void TestConnectionStringForMicrosoftExcelOrAccess()
        {
            var useSquareBrackets = false;
            var name = _connectionStringBuilder.GetType().FullName ?? string.Empty;

            if (name.StartsWith("System.Data.OleDb"))
            {
                //this is a OleDb connection
                var s = _connectionStringBuilder["Extended Properties"] as string;
                if (!string.IsNullOrEmpty(s) && s.ToLower().Contains("excel"))
                {
                    //we found MS Excel
                    useSquareBrackets = true;
                }
                else
                {
                    //check for MS Acess
                    s = _connectionStringBuilder["Provider"] as string ?? string.Empty;
                    useSquareBrackets = s.Contains("MS Remote");
                    if (!useSquareBrackets)
                    {
                        s = (_connectionStringBuilder["Data Source"]
                             as string ?? string.Empty).ToLower();
                        useSquareBrackets = s.EndsWith(".accdb") || s.EndsWith(".mdb");
                    }
                }
            }
            else
            {
                if (name.StartsWith("System.Data.Odbc"))
                {
                    //this is an Odbc Connection
                    var s = _connectionStringBuilder["driver"] as string;
                    if (!string.IsNullOrEmpty(s))
                    {
                        s = s.ToLower();
                        //test for either excel or access
                        useSquareBrackets =
                            s.Contains("*.xls") || s.Contains("*.mdb");
                    }
                }
            }
            if (useSquareBrackets)
            {
                _quotePrefix = "[";
                _quoteSuffix = "]";
            }
        }
예제 #5
0
        public static IDatabaseProvider GetDatabaseProvider(this DbConnectionStringBuilder connectionStringBuilder)
        {
            var connectionStringBuilderTypeName = connectionStringBuilder.GetType().FullName;

            if (!connectionStringBuilderProviderNameDictionary.ContainsKey(connectionStringBuilderTypeName))
            {
                var message = $"The provider {connectionStringBuilderTypeName} is not known. Use the RegisterDatabaseProvider method.";

                throw new ArgumentException(message);
            }

            var providerName = connectionStringBuilderProviderNameDictionary[connectionStringBuilderTypeName];

            return
                (databaseProviderDictionary[providerName]
                 .DynamicInvoke(connectionStringBuilder)
                 .Convert <IDatabaseProvider>());
        }
예제 #6
0
        /// <summary>
        /// Generic database connection method using OS user (Trusted Security)
        /// </summary>
        /// <param name="strProviderName">Provider Name</param>
        /// <param name="strDBServer">Server Name</param>
        /// <returns></returns>
        private ConnectionState connectToDatabase
            (out DbConnection oDbConnection, string strProviderName, string strDBServer, string strInitialCatalog)
        {
            Debug.Assert(strProviderName != null);
            Stopwatch       sw    = new Stopwatch();
            ConnectionState state = ConnectionState.Closed;

            oDbConnection = null;
            try {
                DbProviderFactory oDbFactory           = null;
                string            strOLEProviderString = null;
                foreach (string strDefaultOleDbProviderName in Enum.GetNames(typeof(oleDBProvider)))
                {
                    if (strDefaultOleDbProviderName.Equals(strProviderName))
                    {
                        oDbFactory = DbProviderFactories.GetFactory(@"System.Data.OleDb");
                        if (strDefaultOleDbProviderName.Equals(oleDBProvider.ASEOLEDBProvider.ToString()))
                        {
                            strOLEProviderString = @"Sybase.ASEOLEDBProvider";
                        }
                        else
                        {
                            strOLEProviderString = strDefaultOleDbProviderName;
                        }
                        break;
                    }
                }
                if (oDbFactory == null)
                {
                    oDbFactory = DbProviderFactories.GetFactory(strProviderName);
                }
                oDbConnection = oDbFactory.CreateConnection();
                DbConnectionStringBuilder oDbConnStrBuilder = oDbFactory.CreateConnectionStringBuilder();
                // Provider is only used for Ole DB Connection
                if (oDbConnStrBuilder.GetType().Equals(typeof(System.Data.OleDb.OleDbConnectionStringBuilder)))
                {
                    oDbConnStrBuilder[@"Provider"] = strOLEProviderString;
                    if (strOLEProviderString.Equals("DB2OLEDB"))
                    {
                        oDbConnStrBuilder[@"Network Transport Library"] = @"TCPIP";
                    }
                }
                if (!string.IsNullOrEmpty(strDBServer))
                {
                    if (strDBServer.Contains(@"\MSSQLSERVER(DEFAULT)"))
                    {
                        strDBServer.Replace(@"\MSSQLSERVER(DEFAULT)", string.Empty);
                    }
                }
                oDbConnStrBuilder[@"Data Source"]         = strDBServer;
                oDbConnStrBuilder[@"Initial Catalog"]     = strInitialCatalog;
                oDbConnStrBuilder[@"Integrated Security"] = @"SSPI";
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Attempting to connect to database using connectionString {1}.",
                                      m_taskId,
                                      oDbConnStrBuilder.ConnectionString);
                string connString = oDbConnStrBuilder.ConnectionString;
                oDbConnection.ConnectionString = oDbConnStrBuilder.ConnectionString;
                sw.Start();
                oDbConnection.Open();
                sw.Stop();
                state = oDbConnection.State;
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Connection result {1}.  Elapsed time {2}.",
                                      m_taskId,
                                      oDbConnection.State.ToString(),
                                      sw.Elapsed.ToString());
            } catch (DbException sqlEx) {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Database connection failed!  Elapsed time {1}.\n{2}",
                                      m_taskId,
                                      sw.Elapsed.ToString(),
                                      FormatDbException(sqlEx));
            } catch (Exception ex) {
                Lib.LogException(m_taskId, sw, "Database connection failed", ex);
            }
            return(state);
        }
예제 #7
0
        /// <summary>
        /// SQL実行イベント
        /// </summary>
        private void ExecuteSqlEvent(object sender, EventArgs e)
        {
            StringBuilder output = new StringBuilder();

            // カーソルを待機カーソルにする
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                this._factory = DbProviderFactories.GetFactory(((DataRowView)comboDbProvider.SelectedItem).Row);

                output.AppendFormat("データベースプロバイダファクトリのクラス型: {0}", this._factory.GetType().ToString());
                output.AppendLine().AppendLine();


                // 接続文字列を生成する
                DbConnectionStringBuilder csb = this._factory.CreateConnectionStringBuilder();

                output.AppendFormat("接続文字列ビルダのクラス型: {0}", csb.GetType().ToString());
                output.AppendLine();

                foreach (ListViewItem item in listViewConnectionString.CheckedItems)
                {
                    csb[item.Text] = item.SubItems[1].Text;
                }

                output.AppendFormat("接続文字列: {0}", csb.ConnectionString);
                output.AppendLine().AppendLine();


                // データベースからデータを取得する
                DbConnection conn      = this._factory.CreateConnection();
                DbCommand    cmd       = conn.CreateCommand();
                DataTable    dataTable = new DataTable();
                this._adapter = this._factory.CreateDataAdapter();

                output.AppendFormat("データベース接続オブジェクトのクラス型: {0}", conn.GetType().ToString());
                output.AppendLine();
                output.AppendFormat("データアダプタのクラス型: {0}", this._adapter.GetType().ToString());
                output.AppendLine().AppendLine();

                conn.ConnectionString = csb.ConnectionString;

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = textSql.Text;

                foreach (DataGridViewRow row in dataGridViewParameter.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        DbParameter param = this._factory.CreateParameter();
                        DbType      type  = (DbType)row.Cells["type"].Value;

                        param.ParameterName = (string)row.Cells["name"].Value;
                        param.DbType        = type;
                        param.Value         = DbTypeUtil.Parse((string)row.Cells["value"].Value, type);

                        cmd.Parameters.Add(param);
                    }
                }

                this._adapter.SelectCommand = cmd;
                this._adapter.Fill(dataTable);

                dataGridViewTable.Columns.Clear();
                dataGridViewTable.DataSource = dataTable;
                dataGridViewTable.DataMember = string.Empty;


                output.AppendFormat("< {0} > データ取得は正常に完了しました。", System.DateTime.Now);
                output.AppendLine();

                textOutput.Text = output.ToString();

                buttonRollback.Enabled           = true;
                buttonCheckUpdateCommand.Enabled = true;
                buttonExecuteUpdate.Enabled      = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                output.AppendLine();
                output.AppendLine(ex.ToString());
                textOutput.Text = output.ToString();
                buttonCheckUpdateCommand.Enabled = false;
                buttonExecuteUpdate.Enabled      = false;
            }
        }
예제 #8
0
 public static IImplementation GetImplementation(DbConnectionStringBuilder connectionStringBuilder)
 {
     return(GetImplementation(i => i.IsFor(connectionStringBuilder), "No implementation found for Type " + connectionStringBuilder.GetType()));
 }