Exemple #1
0
 /// <summary>
 /// Attempts to cancels the execution of an <see cref="System.Data.IDbCommand"></see>.
 /// </summary>
 void IDbCommand.Cancel()
 {
     innerDbCommand.Cancel();
 }
 /// <summary>
 /// Cancel the command.
 /// </summary>
 public void Cancel() => _command.Cancel();
Exemple #3
0
 public void Cancel()
 {
     wrappedCommand.Cancel();
 }
 public void Cancel()
 {
     _cmd.Cancel();
 }
Exemple #5
0
 public void Cancel()
 {
     _Command.Cancel();
 }
Exemple #6
0
 /// <summary>
 /// Attempts to cancels the execution of a <see cref="DbCommand"/>.
 /// </summary>
 public override void Cancel()
 {
     _command.Cancel();
 }
Exemple #7
0
        public virtual DataTable Select(string SQL, ODAParameter[] ParamList, int StartIndex, int MaxRecord, string Orderby)
        {
            IDbCommand  Cmd = OpenCommand();
            IDataReader Dr  = null;

            try
            {
                Cmd.CommandType = CommandType.Text;
                SetCmdParameters(ref Cmd, SQL, ParamList);
                Dr = Cmd.ExecuteReader();
                DataTable dt = new DataTable("RECORDSET");
                if (Dr.FieldCount > 0)
                {
                    for (int num = 0; num < Dr.FieldCount; num++)
                    {
                        DataColumn column = new DataColumn();
                        if (dt.Columns.Contains(Dr.GetName(num)))
                        {
                            column.ColumnName = Dr.GetName(num) + num.ToString();
                        }
                        else
                        {
                            column.ColumnName = Dr.GetName(num);
                        }
                        column.DataType = Dr.GetFieldType(num);
                        dt.Columns.Add(column);
                    }
                    while (StartIndex > 0)
                    {
                        if (!Dr.Read())
                        {
                            return(dt);
                        }
                        StartIndex--;
                    }
                    int ReadRecord = MaxRecord;
                    while (ReadRecord > 0 || MaxRecord == -1)
                    {
                        if (Dr.Read())
                        {
                            object[] rVal = new object[Dr.FieldCount];
                            Dr.GetValues(rVal);
                            dt.Rows.Add(rVal);
                            ReadRecord--;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                return(dt);
            }
            finally
            {
                if (Dr != null)
                {
                    try
                    {
                        Cmd.Cancel();
                    }
                    catch { }
                    Dr.Close();
                    Dr.Dispose();
                }
                CloseCommand(Cmd);
            }
        }
Exemple #8
0
 public void Cancel()
 {
     @base.Cancel();
 }
 private void CancelCommand()
 {
     _command.Cancel();
 }
Exemple #10
0
        private static IEnumerable QueryInternal(Type type, Mapping.Table table, System.Data.IDbConnection connection, String sql, Object param, IDbTransaction transaction, CommandType?commandType, Int32?commandTimeout)
        {
            var command  = new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered);
            var identity = new SqlMapper.Identity(sql, commandType, connection, type, param == null ? null : param.GetType(), null);
            var info     = SqlMapper.GetCacheInfo(identity, param, command.AddToCache);

            IDbCommand  cmd    = null;
            IDataReader reader = null;

            Boolean wasClosed = connection.State == ConnectionState.Closed;

            try
            {
                cmd = command.SetupCommand(connection, info.ParamReader);

                if (wasClosed)
                {
                    connection.Open();
                }
                reader    = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess : CommandBehavior.SequentialAccess);
                wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
                // with the CloseConnection flag, so the reader will deal with the connection; we
                // still need something in the "finally" to ensure that broken SQL still results
                // in the connection closing itself
                var tuple = info.Deserializer;
                int hash  = SqlMapper.GetColumnHash(reader);
                if (tuple.Func == null || tuple.Hash != hash)
                {
                    if (reader.FieldCount == 0) //https://code.google.com/p/dapper-dot-net/issues/detail?id=57
                    {
                        yield break;
                    }
                    tuple = info.Deserializer = new SqlMapper.DeserializerState(hash, GetDeserializer(type, reader, 0, -1, false, table));
                    if (command.AddToCache)
                    {
                        SqlMapper.SetQueryCache(identity, info);
                    }
                }

                var func = tuple.Func;
                while (reader.Read())
                {
                    yield return(func(reader));
                }
                while (reader.NextResult())
                {
                }
                // happy path; close the reader cleanly - no
                // need for "Cancel" etc
                reader.Dispose();
                reader = null;

                command.OnCompleted();
            }
            finally
            {
                if (reader != null)
                {
                    if (!reader.IsClosed)
                    {
                        try { cmd.Cancel(); }
                        catch { /* don't spoil the existing exception */ }
                    }
                    reader.Dispose();
                }
                if (wasClosed)
                {
                    connection.Close();
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                }
            }
        }
Exemple #11
0
 public void Cancel()
 {
     _com.Cancel();
 }
        internal override IEnumerable QueryDataReader(IDataDefine source, IDbCommand dbcommand, Region region, SafeLevel level)
        {
            int start;
            int size;

            if (region != null)
            {
                start = region.Start;
                size  = region.Size;
            }
            else
            {
                start = 0;
                size  = int.MaxValue;
            }
            if (_isTransaction)
            {
                _trconnection.SetupCommand(dbcommand);
                using (IDataReader reader = dbcommand.ExecuteReader()) {
                    int index = 0;
                    int count = 0;
                    while (reader.Read())
                    {
                        if (index >= start)
                        {
                            count++;
                            object item = source.LoadData(this, reader);
                            yield return(item);

                            if (count >= size)
                            {
                                dbcommand.Cancel();
                                break;
                            }
                        }
                        index++;
                    }
                }
            }
            else
            {
                TransactionConnection transaction = GetTransactionConnection();
                transaction.ResetTransaction(level);
                transaction.SetupCommand(dbcommand);
                using (IDataReader reader = dbcommand.ExecuteReader()) {
                    int index = 0;
                    int count = 0;
                    while (reader.Read())
                    {
                        if (index >= start)
                        {
                            count++;
                            object item = source.LoadData(this, reader);
                            yield return(item);

                            if (count >= size)
                            {
                                dbcommand.Cancel();
                                break;
                            }
                        }
                        index++;
                    }
                }
                transaction.Commit();
            }
        }
Exemple #13
0
 public void Cancel()
 {
     real.Cancel();
 }
Exemple #14
0
 public void Cancel()
 {
     Target.Cancel();
 }
Exemple #15
0
        }                     // GetCatalogTableIndexes

        /*
        ** GetCatalogTablePrimaryKey
        **
        ** Description:
        **	Find the fields that make up the table's primary key.
        **
        ** History:
        **	10-Feb-03 (thoda04)
        **	    Created.
        */

        /// <summary>
        /// Find the fields that make up the table's primary key.
        /// </summary>
        public Catalog.Table GetCatalogTablePrimaryKey(Catalog.Table catTable)
        {
            string sql_lvl = AdvanConnect.conn.dbCaps.getDbCap("COMMON/SQL_LEVEL");
            int    cs_lvl  = 0;
            int    key_id;
            int    key_id_prior = -1;
            Object obj;

            if (sql_lvl != null)                // get the Ingres or Gateway support level
            {
                try { cs_lvl = Int32.Parse(sql_lvl); }
                catch (Exception /*ignore*/) {}
            }
            ;

            IDbCommand     cmd = AdvanConnect.Connection.CreateCommand();
            IDataParameter parm;

            parm        = cmd.CreateParameter();
            parm.Value  = catTable.SchemaName;
            parm.DbType = DbType.AnsiString;              // don't send Unicode
            cmd.Parameters.Add(parm);

            parm        = cmd.CreateParameter();
            parm.Value  = catTable.TableName;
            parm.DbType = DbType.AnsiString;              // don't send Unicode
            cmd.Parameters.Add(parm);

            IDataReader rdr             = null;
            bool        PrimaryKeyFound = false;

            // if Ingres server and iikeys is supported
            if (AdvanConnect.conn.is_ingres && cs_lvl > 601)
            {
                cmd.CommandText =
                    "SELECT DISTINCT k.column_name, k.key_position " +
                    "FROM iikeys k, iiconstraints c " +
                    "WHERE k.schema_name = ? AND k.table_name = ? AND " +
                    "c.constraint_type = 'P'  AND " +
                    "k.constraint_name = c.constraint_name ";

                // send the query to the database catalog to get keys
                rdr = null;

                try
                {
                    // read the primary key columns of table from iikeys
                    rdr = cmd.ExecuteReader();
                    while (rdr.Read())                      // process list of columns
                    {
                        if (rdr.IsDBNull(0))                // skip if somehow null
                        {
                            continue;
                        }
                        String columnName = rdr.GetString(0).TrimEnd();
                        // find the primary key column in the table's columns
                        foreach (Catalog.Column col in catTable.Columns)
                        {
                            if (col.ColumnName.Equals(columnName))
                            {
                                if (rdr.IsDBNull(1))
                                {
                                    col.PrimaryKeySequence = 0;
                                }
                                else
                                {
                                    obj = rdr.GetValue(1);                                     // int32 or Oracle NUMERIC float
                                    col.PrimaryKeySequence = Convert.ToInt32(obj);
                                    PrimaryKeyFound        = true;
                                }
                                break;
                            }
                        }                  // end loop through columns
                    }                      // end while loop reading through columns in catalog
                }
                catch (SqlEx)              // ex)
                {
                    //Console.WriteLine(ex);
                    throw;
                }
                finally
                {
                    if (rdr != null)
                    {
                        rdr.Close();
                    }
                }

                if (PrimaryKeyFound)
                {
                    return(catTable); // no need to look further
                }
            }                         // end if Ingres server


            // Primary key not found in iikeys; try iialt_columns.
            // Use the primary key or first unique key.

            cmd.CommandText =
                "SELECT DISTINCT k.column_name, k.key_sequence, k.key_id " +
                "FROM iialt_columns k " +
                "WHERE table_owner = ? AND table_name = ? AND " +
                "key_sequence <> 0 " +
                "ORDER BY 3";

            // send the query to the database catalog to get keys
            rdr = null;

            try
            {
                // read the first unique key columns of table from iialt_columns
                rdr = cmd.ExecuteReader();
                while (rdr.Read())                  // process list of columns
                {
                    if (rdr.IsDBNull(0))            // skip if somehow null
                    {
                        continue;
                    }

                    if (rdr.IsDBNull(2))
                    {
                        key_id = 0;
                    }
                    else
                    {
                        obj    = rdr.GetValue(2);                      // int32 or Oracle NUMERIC float
                        key_id = Convert.ToInt32(obj);
                    }
                    if (PrimaryKeyFound && key_id != key_id_prior)
                    {
                        break;                          // break out if found new index key
                    }
                    String columnName = rdr.GetString(0).TrimEnd();
                    // find the primary key column in the table's columns
                    foreach (Catalog.Column col in catTable.Columns)
                    {
                        if (col.ColumnName.Equals(columnName))
                        {
                            if (rdr.IsDBNull(1))
                            {
                                col.PrimaryKeySequence = 0;
                            }
                            else
                            {
                                obj = rdr.GetValue(1);                                 // int32 or Oracle NUMERIC float
                                col.PrimaryKeySequence = Convert.ToInt32(obj);
                                PrimaryKeyFound        = true;
                                key_id_prior           = key_id; // save key_id of first key
                            }
                            break;                               // break out of table's columns search
                        }
                    }                                            // end loop through columns
                }                                                // end while loop reading through columns in catalog
            }
            catch (SqlEx)                                        // ex)
            {
                //Console.WriteLine(ex);
                throw;
            }
            finally
            {
                if (rdr != null)
                {
                    cmd.Cancel();                      // cancel the remainder to avoid spurious msg
                    rdr.Close();
                }
            }

            if (PrimaryKeyFound)
            {
                return(catTable);
            }

            // Primary key not found in iikeys nor iialt_columns
            // Fall back to trying to use the physical underlying key
            foreach (Catalog.Column col in catTable.Columns)
            {
                col.PrimaryKeySequence = col.KeySequence;
            }

            return(catTable);
        }          // GetCatalogTablePrimaryKey
        /// <summary>
        /// Cancels the command.
        /// </summary>
        public override void Cancel()
        {
            base.Cancel();

            command.Cancel();
        }
        /// <summary>
        /// Executes an SQL query and populates a given <see cref="QueryResults" /> instance with the results.
        /// </summary>
        /// <param name="results"><see cref="QueryResults" /> instance to populate with results.</param>
        /// <param name="command">SQL command to execute.</param>
        /// <param name="result"><see cref="AsyncResult"/> instance to use to mark state changes.</param>
        /// <param name="messages"><see cref="StringBuilder" /> instance to which to append messages.</param>
        /// <param name="IncludeExecutionPlan">If true indciates that the query execution plans are expected to be contained
        /// in the results sets; otherwise, false.</param>
        private static void PopulateResults(QueryResults results, IDbCommand command, AsyncQueryRunner.AsyncResult result, StringBuilder messages, bool IncludeExecutionPlan)
        {
            QueryPlan plan = new QueryPlan();
            using (var reader = command.ExecuteReader())
            {

                do
                {
                    // Check to see if the resultset is an execution plan
                    if (IncludeExecutionPlan && reader.FieldCount == 1 && reader.GetName(0) == "Microsoft SQL Server 2005 XML Showplan")
                    {
                        if (reader.Read())
                        {
                            result.HasOutput = true;
                            plan.AppendStatementPlan(reader[0].ToString());
                        }
                    }
                    else
                    {
                        if (reader.FieldCount == 0)
                        {
                            if (reader.RecordsAffected >= 0)
                            {
                                messages.AppendFormat("({0} row(s) affected)\n\n", reader.RecordsAffected);
                            }
                            continue;
                        }

                        var resultSet = new ResultSet();
                        resultSet.MessagePosition = messages.Length;
                        results.ResultSets.Add(resultSet);

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            var columnInfo = new ResultColumnInfo();
                            columnInfo.Name = reader.GetName(i);
                            ResultColumnType colType;
                            if (ResultColumnInfo.ColumnTypeMap.TryGetValue(reader.GetFieldType(i), out colType))
                            {
                                columnInfo.Type = colType;
                            }

                            resultSet.Columns.Add(columnInfo);
                        }

                        int currentRow = 0;
                        while (reader.Read())
                        {
                            result.HasOutput = true;
                            if (currentRow++ >= MAX_RESULTS)
                            {
                                results.Truncated = true;
                                results.MaxResults = MAX_RESULTS;
                                break;
                            }
                            var row = new List<object>();
                            resultSet.Rows.Add(row);

                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                object col = reader.GetValue(i);
                                if (col is DateTime)
                                {
                                    var date = (DateTime)col;
                                    col = date.ToJavascriptTime();
                                }
                                row.Add(col);
                            }
                        }
                        if (results.Truncated)
                        {
                            // next result would force ado.net to fast forward
                            //  through the result set, which is way too slow
                            break;
                        }

                        if (reader.RecordsAffected >= 0)
                        {
                            messages.AppendFormat("({0} row(s) affected)\n\n", reader.RecordsAffected);
                        }

                        messages.AppendFormat("({0} row(s) affected)\n\n", resultSet.Rows.Count);
                    }
                } while (reader.NextResult());
                command.Cancel();
            }
            results.ExecutionPlan = plan.PlanXml;
        }
Exemple #18
0
 void IDbCommand.Cancel()
 {
     _command.Cancel();
 }
Exemple #19
0
        private DataTable GetColumns(string[] TableViewNames, string TableName)
        {
            IDbConnection Conn = (IDbConnection)GetConnection();

            if (Conn.State != ConnectionState.Open)
            {
                Conn.ConnectionString = ConnString;
                Conn.Open();
            }
            try
            {
                string[]   UserView    = TableViewNames;
                DataTable  Dt          = new DataTable(TableName);
                DataColumn dcTableName = new DataColumn("TABLE_NAME");
                Dt.Columns.Add(dcTableName);
                DataColumn dcColumnName = new DataColumn("COLUMN_NAME");
                Dt.Columns.Add(dcColumnName);
                DataColumn dcColSeq = new DataColumn("COL_SEQ");
                Dt.Columns.Add(dcColSeq);
                DataColumn dcOdaDatatype = new DataColumn("ODA_DATATYPE");
                Dt.Columns.Add(dcOdaDatatype);
                DataColumn dcLength = new DataColumn("LENGTH");
                Dt.Columns.Add(dcLength);
                DataColumn dcScale = new DataColumn("SCALE");
                Dt.Columns.Add(dcScale);
                DataColumn dcDirection = new DataColumn("DIRECTION");
                Dt.Columns.Add(dcDirection);
                DataColumn NotNull = new DataColumn("NOT_NULL");
                Dt.Columns.Add(NotNull);

                for (int i = 0; i < UserView.Length; i++)
                {
                    IDbCommand Cmd = Conn.CreateCommand();
                    Cmd.CommandText = "select * from  " + UserView[i] + " where 1=0 ";
                    Cmd.CommandType = CommandType.Text;

                    IDataReader idr = Cmd.ExecuteReader();
                    DataTable   sch = idr.GetSchemaTable();
                    if (sch != null && sch.Rows.Count > 0)
                    {
                        for (int j = 0; j < sch.Rows.Count; j++)
                        {
                            DataRow dr_tmp = Dt.NewRow();
                            dr_tmp["TABLE_NAME"]  = UserView[i];
                            dr_tmp["COLUMN_NAME"] = (string)sch.Rows[j]["ColumnName"];
                            int ln = (int)sch.Rows[j]["ColumnSize"];
                            ln = ln <= 0 ? 2000 : ln > 2000 ? 2000 : ln;
                            dr_tmp["LENGTH"]    = ln;
                            dr_tmp["SCALE"]     = 0;
                            dr_tmp["DIRECTION"] = "";
                            dr_tmp["NOT_NULL"]  = ((bool)sch.Rows[j]["AllowDBNull"]) ? "N" : "Y";
                            dr_tmp["COL_SEQ"]   = j;

                            string ColumnDataType = "ODA_DATATYPE";
                            Type   Columntype     = (Type)sch.Rows[j]["DataType"];
                            if (Columntype == typeof(string))
                            {
                                dr_tmp[ColumnDataType] = "OVarchar";
                                dr_tmp["SCALE"]        = 0;
                            }
                            else if (Columntype == typeof(int))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.OInt;
                                dr_tmp["LENGTH"]       = 31;
                                dr_tmp["SCALE"]        = 0;
                            }
                            else if (Columntype == typeof(long))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.ODecimal;
                                dr_tmp["LENGTH"]       = 31;
                                dr_tmp["SCALE"]        = 0;
                            }
                            else if (Columntype == typeof(double))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.ODecimal;
                                dr_tmp["LENGTH"]       = 31;
                                dr_tmp["SCALE"]        = 12;
                            }
                            else if (Columntype == typeof(float))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.ODecimal;
                                dr_tmp["LENGTH"]       = 31;
                                dr_tmp["SCALE"]        = 12;
                            }
                            else if (Columntype == typeof(decimal))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.ODecimal;
                                dr_tmp["LENGTH"]       = 31;
                                dr_tmp["SCALE"]        = 12;
                            }
                            else if (Columntype == typeof(System.DateTime))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.ODatetime;
                            }
                            else if (Columntype == typeof(byte[]))
                            {
                                dr_tmp[ColumnDataType] = ODAdbType.OBinary;
                            }
                            else
                            {
                                dr_tmp[ColumnDataType] = "OVarchar";
                                dr_tmp["SCALE"]        = 0;
                            }
                            Dt.Rows.Add(dr_tmp);
                        }
                    }
                    if (idr.Read())
                    {
                        Cmd.Cancel();
                    }
                    idr.Close();
                }
                return(Dt);
            }
            finally
            {
                Conn.Close();
            }
        }
Exemple #20
0
        private DataTable ReadData(IDbCommand Cmd)
        {
            IDataReader Dr = null;

            try
            {
                int StartIndex = 0;
                int MaxRecord  = 100;
                Dr = Cmd.ExecuteReader();
                DataTable dt = new DataTable("RECORDSET");
                if (Dr.FieldCount > 0)
                {
                    for (int num = 0; num < Dr.FieldCount; num++)
                    {
                        DataColumn column = new DataColumn();
                        if (dt.Columns.Contains(Dr.GetName(num)))
                        {
                            column.ColumnName = Dr.GetName(num) + num.ToString();
                        }
                        else
                        {
                            column.ColumnName = Dr.GetName(num);
                        }
                        column.DataType = Dr.GetFieldType(num);
                        dt.Columns.Add(column);
                    }
                    while (StartIndex > 0)
                    {
                        if (!Dr.Read())
                        {
                            return(dt);
                        }
                        StartIndex--;
                    }
                    int ReadRecord = MaxRecord;
                    while (ReadRecord > 0 || MaxRecord == -1)
                    {
                        if (Dr.Read())
                        {
                            object[] rVal = new object[Dr.FieldCount];
                            Dr.GetValues(rVal);
                            dt.Rows.Add(rVal);
                            ReadRecord--;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                return(dt);
            }
            finally
            {
                if (Dr != null)
                {
                    Cmd.Cancel();
                    Dr.Close();
                    Dr.Dispose();
                }
                Cmd.Dispose();
            }
        }
Exemple #21
0
        public virtual DataSet ExecuteProcedure(string SQL, ODAParameter[] ParamList)
        {
            IDbCommand Cmd       = OpenCommand();
            DataSet    ds_rtl    = new DataSet("ReturnValues");
            DataTable  dt_values = new DataTable("ValuesCollection");

            dt_values.Columns.Add("ParamName");
            dt_values.Columns.Add("ReturnValue");
            IDataReader datareader = null;

            try
            {
                Cmd.CommandType = CommandType.StoredProcedure;
                SetCmdParameters(ref Cmd, SQL, ParamList);
                datareader = Cmd.ExecuteReader();

                int rtlcount = 0;
                do
                {
                    if (datareader.FieldCount > 0)
                    {
                        DataTable dt = new DataTable("RECORDSET" + rtlcount.ToString());
                        rtlcount++;
                        for (int num = 0; num < datareader.FieldCount; num++)
                        {
                            DataColumn column = new DataColumn();
                            if (dt.Columns.Contains(datareader.GetName(num)))
                            {
                                column.ColumnName = datareader.GetName(num) + num.ToString();
                            }
                            else
                            {
                                column.ColumnName = datareader.GetName(num);
                            }
                            column.DataType = datareader.GetFieldType(num);
                            dt.Columns.Add(column);
                        }
                        while (datareader.Read())
                        {
                            DataRow row = dt.NewRow();
                            for (int num = 0; num < datareader.FieldCount; num++)
                            {
                                row[num] = datareader[num];
                            }
                            dt.Rows.Add(row);
                        }
                        ds_rtl.Tables.Add(dt);
                    }
                }while (datareader.NextResult());
                datareader.Close();
                datareader.Dispose();

                foreach (DbParameter param in Cmd.Parameters)
                {
                    if (param.Direction == System.Data.ParameterDirection.InputOutput || param.Direction == System.Data.ParameterDirection.Output)
                    {
                        DataRow dr = dt_values.NewRow();
                        dr["ParamName"]   = param.ParameterName;
                        dr["ReturnValue"] = param.Value;
                        dt_values.Rows.Add(dr);
                    }
                }
                ds_rtl.Tables.Add(dt_values);
                return(ds_rtl);
            }
            finally
            {
                dt_values.Dispose();
                ds_rtl.Dispose();
                if (datareader != null)
                {
                    try
                    {
                        Cmd.Cancel();
                    }
                    catch { }
                    datareader.Close();
                    datareader.Dispose();
                }
                CloseCommand(Cmd);
            }
        }
Exemple #22
0
        private static IEnumerable <T> internalQuery <T>(this IDbConnection conn, CommandDefinition command)
        {
            // 缓存
            var         parameter   = command.Parameters;
            Certificate certificate = new Certificate(command.CommandText, command.CommandType, conn, typeof(T), parameter?.GetType());
            CacheInfo   cacheInfo   = CacheInfo.GetCacheInfo(certificate, parameter);
            // 读取
            IDbCommand  cmd       = null;
            IDataReader reader    = null;
            var         wasClosed = conn.State == ConnectionState.Closed;

            try {
                cmd = command.SetupCommand(conn, cacheInfo.ParameterReader);
                if (wasClosed)
                {
                    conn.Open();
                }
                reader = ExecuteReaderWithFlagsFallback(cmd, wasClosed, CommandBehavior.SingleResult);
                if (cacheInfo.Deserializer == null)
                {
                    cacheInfo.Deserializer = BuildDeserializer <T>(reader);
                }
                while (reader.Read())
                {
                    var val = cacheInfo.Deserializer(reader);
                    yield return(GetValue <T>(val));
                }
            } finally {
                // dispose
                if (reader != null)
                {
                    if (!reader.IsClosed)
                    {
                        try {
                            cmd.Cancel();
                        } catch {
                        }
                    }
                    reader.Dispose();
                }
                if (wasClosed)
                {
                    conn.Close();
                }
                cmd?.Dispose();
            }

            IDataReader ExecuteReaderWithFlagsFallback(IDbCommand c, bool close, CommandBehavior behavior)
            {
                try {
                    return(c.ExecuteReader(GetBehavior(close, behavior)));
                } catch (ArgumentException ex) {
                    throw;
                }
            }

            CommandBehavior GetBehavior(bool close, CommandBehavior @default)
            {
                return(close ? (@default | CommandBehavior.CloseConnection) : @default);
            }
        }
        //private DataTable GetSchemaTable(IDbCommand sqlSelectCommand)
        protected virtual DataTable GetSchemaTable(IDbCommand sqlSelectCommand)
        {
            DataTable dataTableSchema = new DataTable();
            bool isClosed = ConnectionState.Closed == _sqlConnection.State;

            try
            {
                if (isClosed)
                {
                    _sqlConnection.Open();
                }

                IDataReader sqlDataReader = sqlSelectCommand.ExecuteReader(CommandBehavior.KeyInfo);
                dataTableSchema = sqlDataReader.GetSchemaTable();
                sqlSelectCommand.Cancel();
                sqlDataReader.Close();
            }
            catch (NotSupportedException)
            {
                //swallow this since .Close() op isn't supported on all DB targets (e.g., SQLCE)
            }
            finally
            {
                //Only close connection if connection was not passed to constructor
                if (!_passedconnection)
                {
                    if (_sqlConnection.State != ConnectionState.Closed)
                    {
                        _sqlConnection.Close();
                    }
                }
            }

            return dataTableSchema;
        }
Exemple #24
0
        internal Cover MaybeGetCover(BaseFile file)
        {
            if (connection == null)
            {
                return(null);
            }

            var info = file.Item;

            byte[] data;
            lock (connection)
            {
                try
                {
                    selectCoverKey.Value  = info.FullName;
                    selectCoverSize.Value = info.Length;
                    selectCoverTime.Value = info.LastWriteTimeUtc.Ticks;
                    try
                    {
                        data = selectCover.ExecuteScalar() as byte[];
                    }
                    catch (DbException ex)
                    {
                        Error("Failed to lookup file cover from store", ex);
                        return(null);
                    }
                }
                finally
                {
                    selectCover.Cancel();
                }
            }

            if (data == null)
            {
                return(null);
            }
            try
            {
                using (var s = new MemoryStream(data))
                {
                    var ctx = new StreamingContext(
                        StreamingContextStates.Persistence,
                        new DeserializeInfo(null, info, DlnaMime.ImageJPEG)
                        );
                    var formatter = new BinaryFormatter(null, ctx)
                    {
                        TypeFormat     = FormatterTypeStyle.TypesWhenNeeded,
                        AssemblyFormat = FormatterAssemblyStyle.Simple
                    };
                    var rv = formatter.Deserialize(s) as Cover;
                    return(rv);
                }
            }
            catch (SerializationException ex)
            {
                Debug("Failed to deserialize a cover", ex);
                return(null);
            }
            catch (Exception ex)
            {
                Fatal("Failed to deserialize a cover", ex);
                throw;
            }
        }
Exemple #25
0
 public void Cancel()
 {
     dbCmd.Cancel();
 }
Exemple #26
0
        internal BaseFile MaybeGetFile(FileServer server, FileInfo info,
                                       DlnaMime type)
        {
            if (connection == null)
            {
                return(null);
            }
            byte[] data;
            lock (connection)
            {
                try
                {
                    selectKey.Value  = info.FullName;
                    selectSize.Value = info.Length;
                    selectTime.Value = info.LastWriteTimeUtc.Ticks;
                    try
                    {
                        data = select.ExecuteScalar() as byte[];
                    }
                    catch (DbException ex)
                    {
                        Error("Failed to lookup file from store", ex);
                        return(null);
                    }
                }
                finally
                {
                    select.Cancel();
                }
            }

            if (data == null)
            {
                return(null);
            }
            try
            {
                using (var s = new MemoryStream(data))
                {
                    var ctx = new StreamingContext(
                        StreamingContextStates.Persistence,
                        new DeserializeInfo(server, info, type));
                    var formatter = new BinaryFormatter(null, ctx)
                    {
                        TypeFormat     = FormatterTypeStyle.TypesWhenNeeded,
                        AssemblyFormat = FormatterAssemblyStyle.Simple
                    };
                    var rv = formatter.Deserialize(s) as BaseFile;
                    if (rv == null)
                    {
                        throw new SerializationException("Deserialized as null");
                    }
                    rv.Item = info;
                    return(rv);
                }
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException || ex is SerializationException)
                {
                    Debug("Failed to deserialize an item", ex);
                    return(null);
                }

                throw;
            }
        }
Exemple #27
0
 public void Cancel()
 {
     inner.Cancel();
 }
Exemple #28
0
 public override void Cancel() => _cmd.Cancel();
Exemple #29
0
 public void Cancel()
 {
     command.Cancel();
 }
Exemple #30
0
 /// <summary>
 /// Attempts to cancels the execution of an System.Data.IDbCommand.
 /// </summary>
 public void Cancel()
 {
     BaseCommand.Cancel();
 }
Exemple #31
0
        public override DataTable Select(string SQL, ODAParameter[] ParamList)
        {
            IDbCommand  Cmd = OpenCommand();
            IDataReader Dr  = null;

            try
            {
                Cmd.CommandType = CommandType.Text;
                SetCmdParameters(ref Cmd, SQL, ParamList);
                Dr = Cmd.ExecuteReader();
                DataTable dt = new DataTable("RECORDSET");

                List <int> mysqlDtIdx = new List <int>();
                if (Dr.FieldCount > 0)
                {
                    for (int num = 0; num < Dr.FieldCount; num++)
                    {
                        DataColumn column = new DataColumn();
                        if (dt.Columns.Contains(Dr.GetName(num)))
                        {
                            column.ColumnName = Dr.GetName(num) + num.ToString();
                        }
                        else
                        {
                            column.ColumnName = Dr.GetName(num);
                        }

                        var dtype = Dr.GetFieldType(num);

                        if (dtype == typeof(MySqlDateTime))
                        {
                            mysqlDtIdx.Add(num);
                            column.DataType = typeof(DateTime);
                        }
                        else
                        {
                            column.DataType = dtype;
                        }
                        dt.Columns.Add(column);
                    }
                    while (Dr.Read())
                    {
                        object[] val = new object[dt.Columns.Count];
                        Dr.GetValues(val);

                        for (int i = 0; i < mysqlDtIdx.Count; i++)
                        {
                            if (val[mysqlDtIdx[i]] is MySqlDateTime &&
                                ((MySqlDateTime)val[mysqlDtIdx[i]]).IsValidDateTime)
                            {
                                val[mysqlDtIdx[i]] = ((MySqlDateTime)val[mysqlDtIdx[i]]).Value;
                            }
                            else
                            {
                                val[mysqlDtIdx[i]] = null;
                            }
                        }
                        dt.Rows.Add(val);
                    }
                }
                return(dt);
            }
            finally
            {
                if (Dr != null)
                {
                    try
                    {
                        Cmd.Cancel();
                    }
                    catch { }
                    Dr.Close();
                    Dr.Dispose();
                }
                CloseCommand(Cmd);
            }
        }
Exemple #32
0
        public UserSearchOrder(AdvanConnect advanConnect)
        {
            AdvanConnect = advanConnect;
            bool   isGateway       = false;
            string Username        = null;
            string DBAname         = null;
            string SystemOwnername = "$ingres";

            if (!advanConnect.conn.is_ingres)
            {
                string str;
                if ((str = AdvanConnect.conn.dbCaps.getDbCap("DBMS_TYPE")) != null)
                {
                    str = str.ToUpper(
                        System.Globalization.CultureInfo.InvariantCulture);
                    // certain gateways don't have iidbconstants(system_owner)
                    if (str.Equals("VSAM") ||
                        str.Equals("IMS"))
                    {
                        isGateway = true;
                    }
                }
            }

            IDbCommand cmd = AdvanConnect.Connection.CreateCommand();

            if (isGateway)
            {
                cmd.CommandText =
                    "SELECT user_name, dba_name, dba_name FROM iidbconstants";
            }
            else             // Ingres and other full-service gateways
            {
                cmd.CommandText =
                    "SELECT user_name, dba_name, system_owner FROM iidbconstants";
            }

            // send the query to the database catalog to get columns
            IDataReader rdr = null;

            try
            {
                // read the user search order
                rdr = cmd.ExecuteReader();
                while (rdr.Read())                  // dummy loop for break convenience
                {
                    if (!rdr.IsDBNull(0))
                    {
                        Username = rdr.GetString(0).TrimEnd();
                    }
                    if (!rdr.IsDBNull(1))
                    {
                        DBAname = rdr.GetString(1).TrimEnd();
                    }
                    if (!rdr.IsDBNull(2))
                    {
                        SystemOwnername = rdr.GetString(2).TrimEnd();
                    }
                    break;         // read just the first row
                }                  // end dummy while loop
            }
            catch (SqlEx /*ex*/)
            {
                //Console.WriteLine(ex);
                throw;
            }
            finally
            {
                if (rdr != null)
                {
                    cmd.Cancel();                      // cancel the remainder to avoid spurious msg
                    rdr.Close();                       // close the data reader
                }
            }

            // eliminate duplicates
            if (Username != null)
            {
                if (DBAname != null)
                {
                    if (DBAname.Equals(Username))
                    {
                        DBAname = null;
                    }
                }
                if (SystemOwnername != null)
                {
                    if (SystemOwnername.Equals(Username))
                    {
                        SystemOwnername = null;
                    }
                }
            }
            if (DBAname != null)
            {
                if (SystemOwnername != null)
                {
                    if (SystemOwnername.Equals(DBAname))
                    {
                        SystemOwnername = null;
                    }
                }
            }

            if (Username != null)
            {
                base.Add(Username);
            }
            if (DBAname != null)
            {
                base.Add(DBAname);
            }
            if (SystemOwnername != null)
            {
                base.Add(SystemOwnername);
            }
        }