Example #1
0
        public DataSource(
			string name, DataProvider provider, string connectionStringName, 
			string dataOperationsPath, 
			string parameterNamePrefix,
			int commandTimeout)
        {
            _name = name;
            _provider = provider;

            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionStringName];

            if (settings == null)
                throw new DataAccessException(ResourceStringLoader.GetResourceString(
                    "connection_string_not_found", connectionStringName));

            _connectionStringName = connectionStringName;

            _templateConnection = (IDbConnection)Activator.CreateInstance(
                _provider.ConnectionObjectType);
            _templateCommand = (IDbCommand)Activator.CreateInstance(
                _provider.CommandObjectType);
            if(_provider.DataAdapterObjectType != null)
                _templateDataAdapter = (IDbDataAdapter)Activator.CreateInstance(
                    _provider.DataAdapterObjectType);

            _parameterNamePrefix = provider.ParameterNamePrefix;
            _commandTimeout = commandTimeout;

            _operationFactory = new DataOperationFactory(this, dataOperationsPath);
        }
        internal LsSumario_Antimicrobiano Listar()
        {
            try
              {
              var m_oSumario_Antimicrobiano = new LsSumario_Antimicrobiano();
              sbSQL.Length = 0;
              sbSQL.Append("SELECT IDINT064, IDINT058, DSANTI, DSPERI");
              sbSQL.Append(" FROM TBINT064 WHERE IDINT058 = " + Convert.ToInt32(UtSessao.Sessao["Id058"]));

              oAdapter = ObterDataAdapter(sbSQL.ToString());

              ITableMapping objMapping = oAdapter.TableMappings.Add("Table" , LsSumario_Antimicrobiano.tbSumario_Antimicrobiano);
              objMapping.ColumnMappings.Add("IDINT064",LsSumario_Antimicrobiano.cpCodigo);
              objMapping.ColumnMappings.Add("IDINT058",LsSumario_Antimicrobiano.cpidint058);
              objMapping.ColumnMappings.Add("DSANTI",LsSumario_Antimicrobiano.cpnome);
              objMapping.ColumnMappings.Add("DSPERI",LsSumario_Antimicrobiano.cpdsperi);

              oAdapter.Fill(m_oSumario_Antimicrobiano);

              return m_oSumario_Antimicrobiano;
              }
              catch (Exception en)
              {
              throw new Dor.Util.OperacaoInvalidaBD(en);
              }
        }
Example #3
0
        internal LsMenu Listar()
        {
            try
            {
                var m_oMenu = new LsMenu();
                sbSQL.Length = 0;
                sbSQL.Append("SELECT IDPRO018, IDPRO039, IDSUBMENU, NMMENU, NMPAGN");
                sbSQL.Append(" FROM TBPRO039 ");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsMenu.tbMenu);
                objMapping.ColumnMappings.Add("IDPRO018", LsMenu.cpCodigoProjeto);
                objMapping.ColumnMappings.Add("IDPRO039", LsMenu.cpCodigo);
                objMapping.ColumnMappings.Add("IDSUBMENU", LsMenu.cpSubMenu);
                objMapping.ColumnMappings.Add("NMMENU", LsMenu.cpNome);
                objMapping.ColumnMappings.Add("NMPAGN", LsMenu.cpPagina);

                oAdapter.Fill(m_oMenu);

                return m_oMenu;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
		public SQLCommandBuilderExample ()
		{
			var connectionDetails = 
				ConfigurationManager.ConnectionStrings ["MyDatabase"];

			var providerName = connectionDetails.ProviderName;
			var connectionString = connectionDetails.ConnectionString;
			var dbFactory = DbProviderFactories.GetFactory (providerName);   

			Adapter = dbFactory.CreateDataAdapter ();

			// Create and configure a connection
			using (var connection = dbFactory.CreateConnection ()) {

				connection.ConnectionString = connectionString;

				// Create Select Command
				var selCmd = dbFactory.CreateCommand ();
				selCmd.CommandText = "SELECT idMyTable, FieldA FROM MyTable";
				selCmd.Connection = connection;
				Adapter.SelectCommand = selCmd;

				// Create and configure DbCommandBuilder
				var builder = dbFactory.CreateCommandBuilder ();
				builder.DataAdapter = (DbDataAdapter)Adapter;

				// Create and fill a DataTable
				Adapter.Fill (DS);
			}
		}
Example #5
0
        internal LsDireito Listar()
        {
            try
            {
                var m_oDireito = new LsDireito();
                sbSQL.Length = 0;
                sbSQL.Append("SELECT DSAPLDDIRT, IDPRO017, NMDIRT");
                sbSQL.Append(" FROM TBPRO017");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsDireito.tbDireito);
                objMapping.ColumnMappings.Add("DSAPLDDIRT", LsDireito.cpApelido);
                objMapping.ColumnMappings.Add("IDPRO017", LsDireito.cpCodigo);
                objMapping.ColumnMappings.Add("NMDIRT", LsDireito.cpNome);

                oAdapter.Fill(m_oDireito);

                return m_oDireito;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
Example #6
0
        internal LsUf Listar()
        {
            try
            {
                var m_oUf = new LsUf();
                sbSQL.Length = 0;
                sbSQL.Append("SELECT CDUNDDFEDR, IDPRO021, NMUNDDFEDR");
                sbSQL.Append(" FROM TBPRO021");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsUf.tbUf);
                objMapping.ColumnMappings.Add("CDUNDDFEDR", LsUf.cpSigla);
                objMapping.ColumnMappings.Add("IDPRO021", LsUf.cpCodigo);
                objMapping.ColumnMappings.Add("NMUNDDFEDR", LsUf.cpNome);

                oAdapter.Fill(m_oUf);

                return m_oUf;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
        internal LsUsuarioPerfilEmpresa Listar()
        {
            try
            {
                var m_oUsuarioPerfilEmpresa = new LsUsuarioPerfilEmpresa();
                sbSQL.Length = 0;
                sbSQL.Append("SELECT IDPRO012, IDPRO013, IDPRO015, IDPRO016");
                sbSQL.Append(" FROM TBPRO013");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsUsuarioPerfilEmpresa.tbUsuarioPerfilEmpresa);
                objMapping.ColumnMappings.Add("IDPRO012", "CodigoEmpresa");
                objMapping.ColumnMappings.Add("IDPRO013", "Codigo");
                objMapping.ColumnMappings.Add("IDPRO015", "CodigoUsuario");
                objMapping.ColumnMappings.Add("IDPRO016", "CodigoPerfil");

                oAdapter.Fill(m_oUsuarioPerfilEmpresa);

                return m_oUsuarioPerfilEmpresa;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
Example #8
0
        internal LsOperacao Listar()
        {
            try
              {
              var m_oOperacao = new LsOperacao();
              sbSQL.Length = 0;
              sbSQL.Append("SELECT DSAPLDOPRC, IDPRO020, NMOPRC");
              sbSQL.Append(" FROM TBPRO020");

              oAdapter = ObterDataAdapter(sbSQL.ToString());

              ITableMapping objMapping = oAdapter.TableMappings.Add("Table" , LsOperacao.tbOperacao);
              objMapping.ColumnMappings.Add("DSAPLDOPRC","Apelido");
              objMapping.ColumnMappings.Add("IDPRO020","Codigo");
              objMapping.ColumnMappings.Add("NMOPRC","Nome");

              oAdapter.Fill(m_oOperacao);

              return m_oOperacao;
              }
              catch (Exception ex)
              {
              throw new Dor.Util.OperacaoInvalidaBD(ex);
              }
        }
Example #9
0
        internal LsPerfil Listar()
        {
            try
            {
                var m_oPerfil = new LsPerfil();
                sbSQL.Length = 0;
                sbSQL.Append("SELECT DSAPLDPERF, IDPRO016, NMPERF");
                sbSQL.Append(" FROM TBPRO016");
                sbSQL.Append(" ORDER BY NMPERF");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsPerfil.tbPerfil);
                objMapping.ColumnMappings.Add("DSAPLDPERF", LsPerfil.cpApelido);
                objMapping.ColumnMappings.Add("IDPRO016", LsPerfil.cpCodigo);
                objMapping.ColumnMappings.Add("NMPERF", LsPerfil.cpNome);

                oAdapter.Fill(m_oPerfil);

                return m_oPerfil;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
        internal LsSumario_Procedimento Listar()
        {
            try
              {
              var m_oSumario_Procedimento = new LsSumario_Procedimento();
              sbSQL.Length = 0;

              //sbSQL.Append("SELECT IDINT063, IDINT058, DSPRC, DTPRC");
              //sbSQL.Append(" FROM TBINT063");

              sbSQL.Append("SELECT IDINT063, IDINT058, DSPRC, DTPRC");
              sbSQL.Append(" FROM TBINT063 WHERE IDINT058 = " + Convert.ToInt32(UtSessao.Sessao["Id058"]));

              oAdapter = ObterDataAdapter(sbSQL.ToString());

              ITableMapping objMapping = oAdapter.TableMappings.Add("Table" , LsSumario_Procedimento.tbSumario_Procedimento);
              objMapping.ColumnMappings.Add("IDINT063",LsSumario_Procedimento.cpCodigo);
              objMapping.ColumnMappings.Add("IDINT058",LsSumario_Procedimento.cpidint058);
              objMapping.ColumnMappings.Add("DSPRC",LsSumario_Procedimento.cpnome);
              objMapping.ColumnMappings.Add("DTPRC",LsSumario_Procedimento.cpdtprc);

              oAdapter.Fill(m_oSumario_Procedimento);

              return m_oSumario_Procedimento;
              }
              catch (Exception en)
              {
              throw new Dor.Util.OperacaoInvalidaBD(en);
              }
        }
Example #11
0
        internal LsPerfilFuncao Listar()
        {
            try
            {
                var m_oPerfilFuncao = new LsPerfilFuncao();
                sbSQL.Length = 0;
                sbSQL.Append("SELECT IDDOR033, IDPRO016, IDPRO031");
                sbSQL.Append(" FROM TBPRO033");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsPerfilFuncao.tbPerfilFuncao);
                objMapping.ColumnMappings.Add("IDDOR033", "Codigo");
                objMapping.ColumnMappings.Add("IDPRO016", "CodigoPerfil");
                objMapping.ColumnMappings.Add("IDPRO031", "CodigoFuncao");

                oAdapter.Fill(m_oPerfilFuncao);

                return m_oPerfilFuncao;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
 public DbCommandBuilder GetDBCommandBuilder( IDbDataAdapter dbDataAdapter )
 {
     if ( dbDataAdapter is OleDbDataAdapter ) {
         return new OleDbCommandBuilder ( ( OleDbDataAdapter ) dbDataAdapter );
     } else {
         throw new Exception ( "dbDataAdapter must be OleDbDataAdapter" );
     }
 }
Example #13
0
        public DbHelper(ConnectionType conn)
        {
            if ((DatabaseType)conn.DbType == DatabaseType.SqlServer)
            {
                Connection = new SqlConnection(conn.ConnectionString);
                Adapter = new SqlDataAdapter();

            }
        }
Example #14
0
 /// <summary>
 /// Creates an instance of Schema
 /// </summary>
 /// <param name="dataProvider">The provider of the schema</param>
 /// <param name="connectString">The connection string for the provider</param>
 public Schema( ProviderType dataProvider, string connectString )
 {
     m_con = SchemaFactory.GetConnection( dataProvider, connectString );
     m_adap = SchemaFactory.CreateDataAdapter( dataProvider );
     m_com = SchemaFactory.CreateCommand( ProviderType.SqlServer );
     m_com.Connection = m_con;
     m_provider = dataProvider;
     m_dataset = new DataSet( m_con.Database );
     m_name = m_con.Database;
 }
Example #15
0
        /// <summary>
        /// Initialises a new instance of the <see cref="ProfiledDbDataAdapter"/> class.
        /// </summary>
        /// <param name="wrappedAdapter">The wrapped adapter.</param>
        /// <param name="profiler">The profiler.</param>
        public ProfiledDbDataAdapter(IDbDataAdapter wrappedAdapter, IDbProfiler profiler = null)
        {
            if (wrappedAdapter == null)
            {
                throw new ArgumentNullException("wrappedAdapter");
            }

            _adapter = wrappedAdapter;
            _profiler = profiler ?? MiniProfiler.Current;
        }
        public TransactionalExecutionState(IDbConnection connection, IDbDataAdapter adapter)
        {
            if (connection.State != ConnectionState.Closed)
            {
                throw new ArgumentOutOfRangeException("connection", "Connection cannot be open!");
            }

            _connection = connection;
            _adapter = adapter;
        }
        public SQLAnywhereDataAdapter()
        {
            m_asmSqlClient      = Assembly.LoadWithPartialName(m_sAssemblyName);
            if ( m_asmSqlClient == null )
                throw(new Exception("Could not load " + m_sAssemblyName));
            m_typSqlDataAdapter = m_asmSqlClient.GetType(m_sDataAdapterName);

            ConstructorInfo info = m_typSqlDataAdapter.GetConstructor(new Type[0]);
            m_dbDataAdapter = info.Invoke(null) as IDbDataAdapter;
            if ( m_dbDataAdapter == null )
                throw(new Exception("Failed to invoke database adapter constructor."));
        }
Example #18
0
File: SqlServer.cs Project: xqgzh/Z
        public void ExtractTableParameters(string TableName, IDbDataAdapter adapter, 
            out DatabaseCache InsertCache, 
            out DatabaseCache DeleteCache,
            out DatabaseCache UpdateCache,
            out DatabaseCache IsExistCache,
            out DataTable dt
            )
        {
            adapter.SelectCommand.CommandText = "select top 1 * from " + TableName;

            DataSet ds = new DataSet();

            dt = adapter.FillSchema(ds, SchemaType.Source)[0];

            dt.TableName = TableName;

            SqlCommandBuilder builder = new SqlCommandBuilder(adapter as SqlDataAdapter);

            builder.ConflictOption = ConflictOption.OverwriteChanges;
            //builder.SetAllValues = false;
            SqlCommand InsertCmd = builder.GetInsertCommand(true);
            builder.ConflictOption = ConflictOption.OverwriteChanges;

            InsertCache = new DatabaseCache(InsertCmd.CommandText, InsertCmd.Parameters);
            InsertCache.CurrentTable = dt;

            foreach (DataColumn c in dt.Columns)
            {
                if (c.AutoIncrement)
                {
                    InsertCache.IsHaveAutoIncrement = true;
                    InsertCache.SQL += ";Select @@IDENTITY;";
                    break;
                }
            }

            SqlCommand UpdateCmd = builder.GetUpdateCommand(true);
            UpdateCache = new DatabaseCache(UpdateCmd.CommandText, UpdateCmd.Parameters);
            UpdateCache.CurrentTable = dt;

            SqlCommand DeleteCmd = builder.GetDeleteCommand(true);
            DeleteCache = new DatabaseCache(DeleteCmd.CommandText, DeleteCmd.Parameters);
            DeleteCache.CurrentTable = dt;

            IsExistCache = new DatabaseCache(DeleteCmd.CommandText, DeleteCmd.Parameters);
            IsExistCache.CurrentTable = dt;
            IsExistCache.SQL = IsExistCache.SQL.Replace("DELETE FROM [" + TableName + "]", "Select count(1) from [" + TableName + "] with(nolock) ");
        }
Example #19
0
        public DataSetAdapter(
			string adapterName, 
			IDbDataAdapter dbDataAdapter,
			DataSource dataSource,
			IDataCommand selectCommand,
			IDataCommand updateCommand,
			IDataCommand insertCommand,
			IDataCommand deleteCommand)
            : this(adapterName, dataSource)
        {
            _dbDataAdapter = dbDataAdapter;
            _selectCommand = selectCommand;
            _updateCommand = updateCommand;
            _insertCommand = insertCommand;
            _deleteCommand = deleteCommand;
        }
Example #20
0
 public object ExecuteBatchUpdate(ConfigSettings configuration, DataSet ds)
 {
     Connection(configuration);
     ((IDbCommand)configuration.DBCommand).Connection = GenericConnection;
     switch (configuration.DataStore)
     {
         case DataProviderType.Sql: GenericDataAdapter = new SqlDataAdapter((SqlCommand)configuration.DBCommand); break;
         case DataProviderType.OleDb: GenericDataAdapter = new OleDbDataAdapter((OleDbCommand)configuration.DBCommand); break;
         case DataProviderType.Odbc: GenericDataAdapter = new OdbcDataAdapter((OdbcCommand)configuration.DBCommand); break;
     }
     GenericDataAdapter.UpdateCommand = (IDbCommand)configuration.DBCommand;
     int i = GenericDataAdapter.Update(ds);
     GenericConnection.Close();
     GenericConnection.Dispose();
     return (object)i;
 }
Example #21
0
        public IDbDataAdapter CriarAdapter(string xQuery)
        {
            switch (banco)
            {
                case Banco.SQLSERVER:
                    dbAdapter = new SqlDataAdapter(xQuery,(SqlConnection) dbConnection);
                    break;
                case Banco.ORACLE:
                    //dbAdapter = new OracleDataAdapter(xQuery, (OracleConnection)dbConnection);
                    dbAdapter = new SqlDataAdapter(xQuery, (SqlConnection)dbConnection);
                    break;
                default:
                    break;
            }

            return dbAdapter;
        }
Example #22
0
 private void InitCommands(IDbDataAdapter wrappedAdapter)
 {
     if (wrappedAdapter.SelectCommand != null)
     {
         _selectCommand = wrappedAdapter.SelectCommand;
     }
     if (wrappedAdapter.DeleteCommand != null)
     {
         _deleteCommand = wrappedAdapter.DeleteCommand;
     }
     if (wrappedAdapter.UpdateCommand != null)
     {
         _updateCommand = wrappedAdapter.UpdateCommand;
     }
     if (wrappedAdapter.InsertCommand != null)
     {
         _insertCommand = wrappedAdapter.InsertCommand;
     }
 }
Example #23
0
	    public static void DisposeDataAdapterCommands(IDbDataAdapter adapter)
        {
            if (adapter.SelectCommand != null)
            {
                DoDisposeCommand(adapter.SelectCommand);
            }
	        if (adapter.InsertCommand != null)
	        {
	            DoDisposeCommand(adapter.InsertCommand);
	        }
            if (adapter.UpdateCommand != null)
            {
                DoDisposeCommand(adapter.UpdateCommand);
            }
	        if (adapter.DeleteCommand != null)
	        {
	            DoDisposeCommand(adapter.DeleteCommand);
	        }

        }
Example #24
0
        private int DoUpdateDataSet(UpdateBehavior behavior, IDbConnection connection,
                                    DataSet dataSet, string tableName, DBCommandWrapper insertCommand,
                                    DBCommandWrapper updateCommand, DBCommandWrapper deleteCommand)
        {
            if (insertCommand == null && updateCommand == null && deleteCommand == null)
            {
                throw new ArgumentException("UpdateDataSetArgumentFailure");
            }

            using (DbDataAdapter adapter = GetDataAdapter(behavior, connection))
            {
                IDbDataAdapter explicitAdapter = (IDbDataAdapter)adapter;
                if (insertCommand != null)
                {
                    explicitAdapter.InsertCommand = insertCommand.Command;
                }
                if (updateCommand != null)
                {
                    explicitAdapter.UpdateCommand = updateCommand.Command;
                }
                if (deleteCommand != null)
                {
                    explicitAdapter.DeleteCommand = deleteCommand.Command;
                }

                try
                {
                    DateTime startTime = DateTime.Now;
                    int      rows      = adapter.Update(dataSet.Tables[tableName]);
                    return(rows);
                }
                catch
                {
                    throw;
                }
            }
        }
        protected override DataSet ColumnSchema(Table table, DataAccessProviderFactory dataProvider, IDbConnection connection)
        {
            DataSet ds          = new DataSet();
            String  schemaQuery = "SELECT atc.OWNER, " +
                                  "atc.TABLE_NAME, " +
                                  "atc.COLUMN_NAME, " +
                                  "atc.DATA_TYPE, " +
                                  "atc.DATA_LENGTH, " +
                                  "atc.DATA_PRECISION, " +
                                  "atc.DATA_SCALE, " +
                                  "atc.NULLABLE, " +
                                  "atc.COLUMN_ID, " +
                                  "acc.CONSTRAINT_NAME, " +
                                  "ac.CONSTRAINT_TYPE, " +
                                  "ac.R_CONSTRAINT_NAME, " +
                                  "ac.INDEX_NAME " +
                                  "FROM ALL_TAB_COLUMNS atc " +
                                  "LEFT OUTER JOIN ALL_CONS_COLUMNS acc " +
                                  "ON acc.OWNER = atc.OWNER " +
                                  "AND acc.TABLE_NAME = atc.TABLE_NAME " +
                                  "AND acc.COLUMN_NAME = atc.COLUMN_NAME " +
                                  "LEFT OUTER JOIN ALL_CONSTRAINTS ac " +
                                  "ON ac.OWNER = acc.OWNER " +
                                  "AND ac.CONSTRAINT_NAME = acc.CONSTRAINT_NAME " +
                                  "WHERE atc.OWNER = '" + table.ParentDatabase.Name + "' " +
                                  "AND atc.TABLE_NAME = '" + table.Name + "' " +
                                  "ORDER BY TABLE_NAME asc";

            IDbCommand sqlCommand = dataProvider.CreateCommand(schemaQuery, connection);

            sqlCommand.CommandType = CommandType.Text;
            IDbDataAdapter da = dataProvider.CreateDataAdapter();

            da.SelectCommand = sqlCommand;
            da.Fill(ds);
            return(ds);
        }
Example #26
0
        public static ITableScheme CreateSqlTableScheme(string sql, string tableName,
                                                        string keyFields, TkDbContext context)
        {
            TkDebug.AssertArgumentNullOrEmpty(sql, "sql", null);
            TkDebug.AssertArgumentNullOrEmpty(tableName, "tableName", null);
            TkDebug.AssertArgumentNullOrEmpty(keyFields, "keyFields", null);
            TkDebug.AssertArgumentNull(context, "context", null);

            IDbDataAdapter adapter = context.CreateDataAdapter();
            DataSet        dataSet = new DataSet {
                Locale = ObjectUtil.SysCulture
            };

            using (dataSet)
            {
                IDbCommand command = context.CreateCommand();
                adapter.SelectCommand = command;
                using (adapter as IDisposable)
                    using (command)
                    {
                        string newSql = string.Format(ObjectUtil.SysCulture,
                                                      "SELECT * FROM ({0}) {1} WHERE 1 = 0", sql, tableName);
                        command.CommandText = newSql;
                        try
                        {
                            FillDataSet(null, adapter, dataSet, tableName);
                        }
                        catch (Exception ex)
                        {
                            TkDebug.ThrowToolkitException(string.Format(ObjectUtil.SysCulture,
                                                                        "无法选取数据库表{0},请确认该表是否存在于数据库中", tableName), ex, null);
                        }
                    }
                return(new InternalTableScheme(tableName, keyFields, dataSet.Tables[tableName]));
            }
        }
Example #27
0
        public T Execute <T>(string query_procedure, Hashtable parameters, CommandType queryType, int?timeOut)
        {
            object objData = null;

            _objDBCmd = Command(queryType, query_procedure, parameters);
            if (timeOut.HasValue)
            {
                _objDBCmd.CommandTimeout = timeOut.Value;
            }
            _dataAdapter = DataAdapter();
            if (typeof(T) == typeof(DataSet))
            {
                objData = new DataSet(); _dataAdapter.Fill((DataSet)objData);
            }
            else if (typeof(T) == typeof(DataTable))
            {
                DataSet dt = new DataSet(); _dataAdapter.Fill(dt); dt.Tables[0].TableName = Guid.NewGuid().ToString(); objData = dt.Tables[0].Copy();
            }
            else
            {
                objData = Convert.ChangeType(null, typeof(T));
            }
            return((T)objData);
        }
Example #28
0
        public DataSet ReadData()
        {
            try {
                if (this.connectionObject.Connection.State == ConnectionState.Closed)
                {
                    this.connectionObject.Connection.Open();
                }

                IDbCommand command = this.connectionObject.Connection.CreateCommand();

                if (String.IsNullOrEmpty(this.connectionObject.QueryString))
                {
                    command.CommandText = reportSettings.CommandText;
                }
                else
                {
                    command.CommandText = this.connectionObject.QueryString;
                }

                command.CommandType = reportSettings.CommandType;
                // We have to check if there are parameters for this Query, if so
                // add them to the command

                BuildQueryParameters(command, reportSettings.SqlParameters);
                IDbDataAdapter adapter = connectionObject.CreateDataAdapter(command);
                DataSet        ds      = new DataSet();
                ds.Locale = CultureInfo.CurrentCulture;
                adapter.Fill(ds);
                return(ds);
            } finally {
                if (this.connectionObject.Connection.State == ConnectionState.Open)
                {
                    this.connectionObject.Connection.Close();
                }
            }
        }
Example #29
0
        public void FillDataSet(string storedProcedure, List <IDbDataParameter> parameters, ref DataSet ds)
        {
            //Dataset specific initialization
            if (ds == null)
            {
                ds = new DataSet();
            }

            try
            {
                //Establish Connection
                IDbCommand     dbCmd = InitializeCommandAndConnection(ref parameters, storedProcedure);
                IDbDataAdapter da    = GetAdapter();
                da.SelectCommand = dbCmd;

                _connection.Open();
                da.Fill(ds);
                _connection.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error occured in getting the data.", ex);
            }
        }
Example #30
0
        /// <summary>
        /// method to execute the dataset property of the command object
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <returns></returns>
        public DataSet ExecuteDataSet(CommandType commandType, string commandText)
        {
            try
            {
                // get the command object from the DBManagerFactory
                this.idbCommand = DBManagerFactory.GetCommand(this.ProviderType);

                // method to prepare the oommand object
                PrepareCommand(idbCommand, this.Connection, this.Transaction, commandType, commandText, this.Parameters);
                // get the data adapter from DBManagerFactory
                IDbDataAdapter dataAdapter = DBManagerFactory.GetDataAdapter(this.ProviderType);
                // assign the selected command property
                dataAdapter.SelectCommand = idbCommand;

                DataSet dataSet = new DataSet();
                // fill the dataset
                dataAdapter.Fill(dataSet);
                // clear the command parameters
                idbCommand.Parameters.Clear();
                return(dataSet);
            }
            catch (Exception ex)
            { throw ex; }
        }
Example #31
0
    public DataTable GetTable(string selectsql)
    {
        DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(_factoryType);
        IDbConnection     dbConnection      = dbProviderFactory.CreateConnection();

        dbConnection.ConnectionString = _connectionString;

        IDbCommand dbCommand = dbProviderFactory.CreateCommand();

        dbCommand.CommandText = selectsql;
        dbCommand.Connection  = dbConnection;

        IDbDataAdapter dataAdapter = dbProviderFactory.CreateDataAdapter();

        dataAdapter.SelectCommand = dbCommand;

        DataSet dataSet = new DataSet();

        try
        {
            dataAdapter.Fill(dataSet);
        }
        catch (Exception errMsg)
        {
            _errorString = errMsg.Message;
            return(ErrorTable);
        }
        if (dataSet.Tables.Count != 1)
        {
            return(ErrorTable);
        }
        else
        {
            return(dataSet.Tables[0]);
        }
    }
Example #32
0
        public virtual void Insert(IDbConnection conn, IDbTransaction transaction)
        {
            ExcpHelper.ThrowIf(this.Table == null, "TableSpec is not specified for type {0}", this.GetType());

            using (DataTable dtInsert = DataCopyTables.GetEmptyDataTableByName(conn, transaction, this.Table.TableName))
            {
                using (IDbCommand cmdInsert = DataCopy.GenerateInsertCommand(conn, transaction, dtInsert, this.Table))
                {
                    using (IDisposable dsp = SqlObjectFactory.CreateDbAdapter(null) as IDisposable)
                    {
                        IDbDataAdapter daInsert = dsp as IDbDataAdapter;
                        Debug.Assert(daInsert != null);

                        daInsert.InsertCommand = cmdInsert;

                        dtInsert.AcceptChanges();

                        DataRow dr = this.CreateDataRow(dtInsert);

                        dtInsert.Rows.Add(dr);

                        using (DataSet ds = new DataSet())
                        {
                            ds.Tables.Add(dtInsert);
                            daInsert.Update(ds);
                        }

                        if (this.Table.IsAutoGeneratedIdentity)
                        {
                            Debug.Assert(this.Table.IdentityNames.Count > 0);
                            m_objJustInsertedIdentity = ConnectionManager.GetLastInsertId(conn, transaction, this.Table.IdentityNames[0]);
                        }
                    }
                }
            }
        }
Example #33
0
        /// <summary>
        ///     Fills a dataset
        /// </summary>
        /// <param name="executableQuery">SELECT ExecutionQuery based on which data is selected</param>
        /// <param name="ds">Resulting DataSet</param>
        public void ExecuteDataSet(ExecutionQuery executableQuery, ref DataSet ds)
        {
            IDbDataAdapter idap = null;

            DataFactory factory = new DataFactory();

            factory.InitializeDataAdapter(database, ref idap, command);
            command.CommandType = CommandType.Text;
            command.CommandText = executableQuery.Query;

            command.Parameters.Clear();

            if (executableQuery.Parameters != null)
            {
                foreach (IDataParameter var in executableQuery.Parameters)
                {
                    command.Parameters.Add(var);
                }
            }

            (new ExecutionEngineLogger()).LogContext(executableQuery);

            idap.Fill(ds);
        }
Example #34
0
        public bool ExistsFileInOs(string hash, long osId)
        {
            IDbCommand       dbcmd  = dbCon.CreateCommand();
            IDbDataParameter param1 = dbcmd.CreateParameter();

            param1.ParameterName = "@hash";
            param1.DbType        = DbType.String;
            param1.Value         = hash;
            dbcmd.Parameters.Add(param1);
            dbcmd.CommandText = $"SELECT * FROM `os_{osId}` WHERE sha256 = @hash";
            DataSet        dataSet     = new DataSet();
            IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();

            dataAdapter.SelectCommand = dbcmd;
            dataAdapter.Fill(dataSet);
            DataTable dataTable = dataSet.Tables[0];

            foreach (DataRow dRow in dataTable.Rows)
            {
                return(true);
            }

            return(false);
        }
Example #35
0
        // Execute method
        public DataSet Execute()
        {
            DataSet ds = new DataSet();

            using (IDbConnection connection = GetConnection())
            {
                IDbCommand command = connection.CreateCommand();
                command.Connection  = connection;
                command.CommandText = CmdText;
                command.CommandType = CmdType;
                foreach (IDataParameter param in GetParameters(command))
                {
                    command.Parameters.Add(param);
                }

                IDbDataAdapter adapter = GetAdapter();
                adapter.SelectCommand = command;
                try
                {
                    connection.Open();
                    adapter.Fill(ds);
                }
                catch (Exception ex)
                {
                    // throw?
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                }
                finally
                {
                    connection.Close();
                }
            }

            return(ds);
        }
Example #36
0
        /// <summary>
        /// 执行SQL语句返回结果集DataSet
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="cmdParms">参数</param>
        /// <returns></returns>
        public static DataResult GetDataSet(string sql, params IDbDataParameter[] cmdParms)
        {
            sql = DataBaseFactory.GetSQL(sql);
            DataResult result = new DataResult();

            result.Sql = sql + ";";
            result.IDbDataParameter = cmdParms;
            using (IDbConn = DataBaseFactory.GetIDbConnection())
            {
                IDbConn.Open();
                using (IDbComm = DataBaseFactory.GetIDbCommand())
                {
                    try
                    {
                        PrepareCommand(IDbComm, IDbConn, null, CommandType.Text, sql, cmdParms);
                        IDbDataAdapter dataAdapter = DataBaseFactory.GetIDbDataAdapter();
                        dataAdapter.SelectCommand = IDbComm;
                        DataSet dataSet = new DataSet();
                        dataAdapter.Fill(dataSet);
                        IDbComm.Parameters.Clear();
                        result.DataSet = dataSet;
                    }
                    catch (Exception E)
                    {
                        IDbConn.Close();
                        result.Error = E.Message;
                        return(result);
                    }
                    finally
                    {
                        IDbConn.Close();
                    }
                }
            }
            return(result);
        }
Example #37
0
        public bool ExistsOs(string mdid)
        {
            IDbCommand       dbcmd  = dbCon.CreateCommand();
            IDbDataParameter param1 = dbcmd.CreateParameter();

            param1.ParameterName = "@mdid";
            param1.DbType        = DbType.String;
            param1.Value         = mdid;
            dbcmd.Parameters.Add(param1);
            dbcmd.CommandText = "SELECT * FROM `oses` WHERE mdid = @mdid";
            DataSet        dataSet     = new DataSet();
            IDbDataAdapter dataAdapter = dbCore.GetNewDataAdapter();

            dataAdapter.SelectCommand = dbcmd;
            dataAdapter.Fill(dataSet);
            DataTable dataTable = dataSet.Tables[0];

            foreach (DataRow dRow in dataTable.Rows)
            {
                return(true);
            }

            return(false);
        }
Example #38
0
        protected override void OnInsertIdentity(DataTable dataTable, IDbCommand dbCommand, IDbTransaction dbTransaction)
        {
            IDbTransaction sqlTransaction = (IDbTransaction)dbTransaction;

            try
            {
                DisableTableConstraints(dataTable, dbTransaction);

                IDbDataAdapter sqlDataAdapter = CreateDbDataAdapter();
                sqlDataAdapter.InsertCommand             = dbCommand;
                sqlDataAdapter.InsertCommand.Connection  = sqlTransaction.Connection;
                sqlDataAdapter.InsertCommand.Transaction = sqlTransaction;

                ((DbDataAdapter)sqlDataAdapter).Update(dataTable);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                EnableTableConstraints(dataTable, dbTransaction);
            }
        }
Example #39
0
            /// <summary>
            /// Return number of rows affected.
            /// </summary>
            /// <param name="dataAdapter"></param>
            /// <returns></returns>
            public int DoInDataAdapter(IDbDataAdapter dataAdapter)
            {
                int retVal = 0;

                dataAdapter.SelectCommand.CommandType = _commandType;
                dataAdapter.SelectCommand.CommandText = _commandText;

                if (dbParameterSetter != null)
                {
                    dbParameterSetter.SetUpParameters(dataAdapter.SelectCommand.Parameters);
                    dbParameterSetter.SetUpCommand(dataAdapter.SelectCommand);
                }

                if (dataAdapter is DbDataAdapter)
                {
                    retVal = ((DbDataAdapter)dataAdapter).Fill(_dataTable);
                }
                else
                {
                    throw new DataException("Provider does not support filling DataTable directly");
                }

                return(retVal);
            }
Example #40
0
        //pooja vachhani on 20/6/15
        private DataTable GetUserGroupRights(IDbDataAdapter adapter, String UserID, ref String msg)
        {
            try
            {
                DataSet ds = new DataSet();

                adapter.SelectCommand.CommandText = "SELECT * FROM user_group_rights WHERE user_id = '" + UserID + "'";
                adapter.Fill(ds);

                if (ds.Tables[0].Rows.Count >= 1)
                {
                    return(ds.Tables[0]);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(null);
            }
        }
Example #41
0
        public void ExecuteDataSet(DBSettingEntity dbSetting, Func <DataSet, bool> funcProccessDataSet)
        {
            try
            {
                using (IDbConnection con = DBManagerFactory.BuilConnection(dbSetting.ProviderType, dbSetting.ConnectionString))
                {
                    con.Open();
                    IDbTransaction idbTransaction = null;

                    if (dbSetting.IsTransaction)
                    {
                        idbTransaction = con.BeginTransaction();
                    }

                    using (IDbCommand cmd = DBManagerFactory.BuildCommand(dbSetting.ProviderType, con, idbTransaction, dbSetting.CommandType, dbSetting.CommandText))
                    {
                        this.AttachParameters(cmd, dbSetting.Parameters, dbSetting.ProviderType);

                        IDbDataAdapter dataAdapter = DBManagerFactory.GetDataAdapter(dbSetting.ProviderType);
                        dataAdapter.SelectCommand = cmd;
                        DataSet dataSet = new DataSet();
                        dataAdapter.Fill(dataSet);
                        funcProccessDataSet.Invoke(dataSet);

                        if (idbTransaction != null)
                        {
                            idbTransaction.Commit();
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                throw this.TranslateException(ex);
            }
        }
Example #42
0
        public static DataTable ExecuteSqlReturnTable(String sql)
        {
            DataTable dt = new DataTable();

            using (IDbCommand cmd = CreateCommand(sql))
            {
                try
                {
                    cmd.CommandTimeout = 240;
                    if (cmd.Connection.State == ConnectionState.Closed)
                    {
                        cmd.Connection.Open();
                    }

                    IDbDataAdapter adapter = CreateAdapter(cmd);

                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    dt = ds.Tables[0];
                }
                catch (OleDbException ex)
                {
                    Logger.WriteSystemLog(string.Format("Error : {0}", ex.Message));
                    Logger.WriteSystemLog(sql);
                }
                finally
                {
                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                    }
                }
            }

            return(dt);
        }   // ExecuteSqlReturnTable
Example #43
0
        /// <summary>执行查询,并返回查询所返回的表</summary>
        public virtual DataTable GetDataTable(IDbCommand cmd, params IDbDataParameter[] parms)
        {
            lock (this)
            {
                if (cmd == null)
                {
                    throw new ArgumentNullException("cmd");
                }

                if (parms != null && parms.Length != 0)
                {
                    foreach (IDbDataParameter param in parms)
                    {
                        cmd.Parameters.Add(param);
                    }
                }

                OpenConnection();

                try
                {
                    cmd.Connection  = this.Connection;
                    cmd.Transaction = this.Transaction;
                    IDbDataAdapter adapter = CreateAdapter(this.DatabaseType);
                    adapter.SelectCommand = cmd;
                    DataSet result = new DataSet();
                    adapter.Fill(result);

                    return(result.Tables[0]);
                }
                finally
                {
                    CloseConnection();
                }
            }
        }
Example #44
0
        public static DataSet ExecuteDataSet(ExecuteObject sender, String DbName)
        {
            IDbCommand command;
            DataSet    set;

            CreateCommand(out command, sender, DbName);
            try
            {
                IDbDataAdapter dataAdapter = GetDataAdapter();
                dataAdapter.SelectCommand = command;
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet);
                set = dataSet;
            }
            finally
            {
                if (command.Connection.State != ConnectionState.Closed)
                {
                    command.Connection.Close();
                    command.Dispose();
                }
            }
            return(set);
        }
Example #45
0
 /// <summary>
 /// 查询数据填充到数据集DataSet中
 /// </summary>
 /// <param name="connectionString">数据库连接字符串</param>
 /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
 /// <param name="cmdText">命令文本</param>
 /// <returns>数据集DataSet对象</returns>
 public static DataSet dataSet(string connectionString, CommandType cmdType, string cmdText)
 {
     DataSet ds = new DataSet();
     IDbCommand cmd = DbFactory.CreateDbCommand();
     IDbConnection conn = DbFactory.CreateDbConnection(connectionString);
     try
     {
         PrepareCommand(cmd, conn, null, cmdType, cmdText, null);
         IDbDataAdapter sda = DbFactory.CreateDataAdapter(cmd);
         sda.Fill(ds);
         return ds;
     }
     catch
     {
         conn.Close();
         cmd.Dispose();
         throw;
     }
     finally
     {
         conn.Close();
         cmd.Dispose();
     }
 }
Example #46
0
        public static DataSet ExecuteDataSet(String SQL, String DbName)
        {
            DataSet    set;
            IDbCommand command = GetCommand(DbName);

            try
            {
                command.CommandText = SQL;
                IDbDataAdapter dataAdapter = GetDataAdapter();
                dataAdapter.SelectCommand = command;
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet);
                set = dataSet;
            }
            finally
            {
                if (command != null)
                {
                    command.Connection.Close();
                    command.Dispose();
                }
            }
            return(set);
        }
 public DataSet Execute(string SQL)
 {
     try
     {
         if (_con == null || df == null || _cmd != null)
         {
             return(null);
         }
         _cmd = df.CreateCommand(_con, SQL);
         IDbDataAdapter da = df.CreateDbAdapter(_cmd);
         if (da == null)
         {
             return(null);
         }
         DataSet ds = new DataSet();
         da.Fill(ds);
         return(ds);
     }
     catch (Exception e)
     {
         e.ToString();
         return(null);
     }
 }
Example #48
0
 public void Initialize()
 {
     Assembly assembly = null;
     Type type = null;
     try {
         assembly = Assembly.Load(this._assemblyName);
         type = assembly.GetType(this._dataAdapterClass, true);
         this.CheckPropertyType("DataAdapterClass", typeof(IDbDataAdapter), type);
         this._templateDataAdapter = (IDbDataAdapter)type.GetConstructor(Type.EmptyTypes).Invoke(null);
         type = assembly.GetType(this._connectionClass, true);
         this.CheckPropertyType("DbConnectionClass", typeof(IDbConnection), type);
         this._templateConnection = (IDbConnection)type.GetConstructor(Type.EmptyTypes).Invoke(null);
         this._commandBuilderType = assembly.GetType(this._commandBuilderClass, true);
         this._parameterDbType = assembly.GetType(this._parameterDbTypeClass, true);
         this._templateConnectionIsICloneable = this._templateConnection is ICloneable;
         this._templateDataAdapterIsICloneable = this._templateDataAdapter is ICloneable;
     }
     catch (Exception exception) {
         throw new Exception(string.Format("Could not configure providers. Unable to load provider named \"{0}\" not found, failed. Cause: {1}", this._name, exception.Message), exception);
     }
 }
Example #49
0
 public static SqlCommandBuilder GetCommandBuilder(IDbDataAdapter objAdapter)
 {
     return(new SqlCommandBuilder(objAdapter as SqlDataAdapter));
 }
Example #50
0
 public static OracleCommandBuilder GetCommandBuilder(IDbDataAdapter objAdapter)
 {
     return(new OracleCommandBuilder(objAdapter as OracleDataAdapter));
 }
Example #51
0
        private void GenDataSetForm_Load(object sender, System.EventArgs e)
        {
            if (dte == null)
            {
                MessageBox.Show(
                    "Visual Studio .NET DTE could not be found.");
                return;
            }

            if (dte.ActiveDocument == null ||
                dte.ActiveDocument.ProjectItem == null ||
                dte.ActiveDocument.ProjectItem.ContainingProject == null)
            {
                MessageBox.Show(
                    "Visual Studio .NET current project could not be found.");
                return;
            }

            currentProject         = dte.ActiveDocument.ProjectItem.ContainingProject;
            currentProjectFullPath =
                GetProperty(currentProject.Properties, "FullPath");
            if (currentProjectFullPath.Length == 0 ||
                !System.IO.Directory.Exists(currentProjectFullPath))
            {
                MessageBox.Show(
                    "Visual Studio .NET current project directory " +
                    "\"" + currentProjectFullPath + "\"" +
                    "could not be found.");
                return;
            }
            currentProjectNamespace =
                GetProperty(currentProject.Properties, "RootNamespace");
            if (currentProjectNamespace.Length == 0)
            {
                currentProjectNamespace =
                    GetProperty(currentProject.Properties, "DefaultNamespace");
            }

            existingDataSetProjectItems =
                GetAllDataSetsInProjectItems(
                    new ArrayList(), currentProject.ProjectItems);

            existingDataSetNames =
                GetProjectItemsNames(existingDataSetProjectItems);

            this.comboBoxExisting.DataSource = existingDataSetNames;

            this.textBoxNew.Text = CreateUniqueDataSetName();


            tableNames = new StringCollection();

            string         tableName      = "Table";
            IDbDataAdapter idbDataAdapter = this.dbDataAdapter as IDbDataAdapter;

            if (idbDataAdapter == null ||
                idbDataAdapter.SelectCommand == null ||
                idbDataAdapter.SelectCommand.CommandText == null ||
                idbDataAdapter.SelectCommand.CommandText.Length == 0)
            {
                MessageBox.Show("Adapter's SelectCommand is not configured",
                                "Generate " + DATASETNAME_PREFIX);
                return;
            }

            string cmdText = idbDataAdapter.SelectCommand.CommandText;

            try
            {
                // Scan the SELECT statment,
                // set the CmdTokenList token list for the SQL statement, and
                // build the column and table names lists.
                Ingres.ProviderInternals.MetaData md =
                    new Ingres.ProviderInternals.MetaData(cmdText);
                if (md != null &&
                    md.Tables != null &&
                    md.Tables.Count > 0)
                {
                    Ingres.ProviderInternals.MetaData.Table t =
                        (Ingres.ProviderInternals.MetaData.Table)md.Tables[0];
                    tableName = t.TableName;
                }
            }
            catch (FormatException)             // catch invalid syntax
            {
                MessageBox.Show("Adapter's SelectCommand is not valid syntax.",
                                "Generate " + DATASETNAME_PREFIX);
                return;
            }
            Component component = (Component)this.dbDataAdapter;

            tableName = tableName + " (" + component.Site.Name + ")";
            this.checkedListBoxTables.Items.Add(tableName, CheckState.Checked);

            // we're good to go; activate controls
            if (existingDataSetProjectItems.Count > 0)
            {
                this.radioButtonExisting.Enabled = true;
            }
            this.radioButtonNew.Enabled = true;
            this.radioButtonNew.Checked = true;
            this.buttonOK.Enabled       = true;
            this.buttonOK.Focus(); // set focus to OK button
        }                          // GenDataSetForm_Load
Example #52
0
        protected bool LoadFromRawSql(string rawSql, params object[] parameters)
        {
            bool      loaded = false;
            DataTable dt     = null;                    try

            {
                IDbCommand cmd = _LoadFromRawSql(rawSql, parameters);                          IDbDataAdapter da = this.CreateIDbDataAdapter();
                da.SelectCommand = cmd;                         TransactionMgr txMgr = TransactionMgr.ThreadTransactionMgr();                           dt = new DataTable(this.MappingName);                           txMgr.Enlist(cmd, this);
                DbDataAdapter dbDataAdapter = this.ConvertIDbDataAdapter(da);
                dbDataAdapter.Fill(dt);
                txMgr.DeEnlist(cmd, this);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.DataTable = dt;
                loaded         = (dt.Rows.Count > 0);
            }                       return(loaded);
        }
Example #53
0
        virtual public void Save()
        {
            if (_dataTable == null)
            {
                return;
            }
            if (!_canSave)
            {
                throw new Exception("Cannot call Save() after Query.AddResultColumn()");
            }
            TransactionMgr txMgr = TransactionMgr.ThreadTransactionMgr();                   try

            {
                bool needToInsert = false;
                bool needToUpdate = false;
                bool needToDelete = false;                             DataRow row;
                DataRowCollection rows = _dataTable.Rows;
                for (int i = 0; i < rows.Count; i++)
                {
                    row = rows[i];                                  switch (row.RowState)
                    {
                    case DataRowState.Added:
                        needToInsert = true;
                        break;

                    case DataRowState.Modified:
                        needToUpdate = true;
                        break;

                    case DataRowState.Deleted:
                        needToDelete = true;
                        break;
                    }
                }
                if (needToInsert || needToUpdate || needToDelete)
                {
                    IDbDataAdapter da = this.CreateIDbDataAdapter();                                        if (needToInsert)
                    {
                        da.InsertCommand = GetInsertCommand();
                    }
                    if (needToUpdate)
                    {
                        da.UpdateCommand = GetUpdateCommand();
                    }
                    if (needToDelete)
                    {
                        da.DeleteCommand = GetDeleteCommand();
                    }
                    txMgr.BeginTransaction();
                    int txCount = txMgr.NestingCount;
                    if (txCount > 1)
                    {
                        txMgr.AddBusinessEntity(this);
                    }
                    if (needToInsert)
                    {
                        txMgr.Enlist(da.InsertCommand, this);
                    }
                    if (needToUpdate)
                    {
                        txMgr.Enlist(da.UpdateCommand, this);
                    }
                    if (needToDelete)
                    {
                        txMgr.Enlist(da.DeleteCommand, this);
                    }
                    DbDataAdapter dbDataAdapter = ConvertIDbDataAdapter(da);
                    this.HookupRowUpdateEvents(dbDataAdapter);                                      dbDataAdapter.Update(_dataTable);                                       txMgr.CommitTransaction();
                    if (txCount == 1)
                    {
                        this.AcceptChanges();
                    }
                    if (needToInsert)
                    {
                        txMgr.DeEnlist(da.InsertCommand, this);
                    }
                    if (needToUpdate)
                    {
                        txMgr.DeEnlist(da.UpdateCommand, this);
                    }
                    if (needToDelete)
                    {
                        txMgr.DeEnlist(da.DeleteCommand, this);
                    }
                }
            }
            catch (Exception ex)
            {
                if (txMgr != null)
                {
                    txMgr.RollbackTransaction();
                }
                throw ex;
            }
        }
Example #54
0
        /****************
		<def
			def="b_channel"
			Caption="Channel"
			Cmd="commande sql (select * from b_channel"
			CmdType="StoredProcedure | TableDirect | Text"
			UpdateCmd="update b_channel set shortname = @shortname, longname = @longname where channel_id = @channel_id"
			UpdateCmdType="StoredProcedure | TableDirect | Text"
			Option=""
		>
			<col Name="client_id" Option="ReadOnly, Hide"/>
			<!--<col Name="code" Edit="LookUp" Display="code" Value="code" Cmd="select code, longname channel from b_channel order by isnull(order_no, 9999), longname"/>-->
		</def>
		****************/
        #endregion
        public void CreateDataSource()
        {
            if (gGridDefinition == null) return;

            //if (gbTrace) cTrace.StartNestedLevel("CreateDataSource");

            //string sOption = xe.zAttribValue("Option");
            //GridOption option = new GridOption(sOption);
            gbDynamicDataUpdate = gGridOption.DetailDynamic;

            IDbConnection con = null;

            string sCmdType, sCmd;
            IDbCommand cmd = null;
            string sTableDef = gGridDefinition.zAttribValue("TableDef");
            if (sTableDef != null)
            {
                //DataContainer data = dataList[sTableDef];
                DataContainer data = GetDataContainer(sTableDef);
                cmd = data.Command;
                gdt = data.DataTable;
                //gda = Ado.CreateDataAdapter(cmd);
                gda = _ado.CreateDataAdapter(cmd);
            }
            else
            {
                sCmdType = gGridDefinition.zAttribValue("CmdType", CommandType.Text.ToString());
                sCmd = gGridDefinition.zAttribValue("Cmd");
                con = GetConnection();
                //cmd = Ado.CreateCmd(con, sCmd, Ado.GetCommandType(sCmdType));
                cmd = _ado.CreateCmd(con, sCmd, _ado.GetCommandType(sCmdType));

                if (gbDynamicDataUpdate)
                {
                    string sMasterId = gGridDefinition.zAttribValue("MasterId");
                    DataTable dtParent = GetParentDataTable();
                    AddMasterIdParameter(cmd, dtParent, sMasterId);
                }

                string sTable = GetTableName();
                gdt = new DataTable(sTable);

                //gda = Ado.CreateDataAdapter(cmd);
                gda = _ado.CreateDataAdapter(cmd);

                //Ado.DataAdapter_FillSchema(gda, gdt);
                _ado.DataAdapter_FillSchema(gda, gdt);

                string sPrimaryKey = gGridDefinition.zAttribValue("PrimaryKey");
                SetPrimaryKey(gdt, sPrimaryKey);

                SetDataTableColumnOption(gdt, gGridDefinition);
            }

            //////////////////   Debug pb channel_id
            //if (dt.Columns.Contains("channel_id"))
            //{
            //    cTrace.Trace("PB_Grid.DataContainer.CreateDataTable() : après DataAdapter_FillSchema");
            //    DataColumn col = dt.Columns["channel_id"];
            //    cTrace.Trace("PB_Grid.cGrid.CreateDataSource() : Table {0}, col {1}, AutoIncrementSeed = {2}, AutoIncrementStep = {3}", dt.TableName, col.ColumnName, col.AutoIncrementSeed, col.AutoIncrementStep);

            //    dt.TableNewRow -= new DataTableNewRowEventHandler(Test_TableNewRow_Event);
            //    dt.TableNewRow += new DataTableNewRowEventHandler(Test_TableNewRow_Event);

            //    DataRow row = dt.NewRow();
            //    //col.AutoIncrementSeed = -20;
            //    //cTrace.Trace("PB_Grid.cGrid.CreateDataSource() : Table {0}, col {1}, AutoIncrementSeed = {2}, AutoIncrementStep = {3}", dt.TableName, col.ColumnName, col.AutoIncrementSeed, col.AutoIncrementStep);
            //    //row = dt.NewRow();
            //    //col.AutoIncrementSeed = -1;
            //    //cTrace.Trace("PB_Grid.cGrid.CreateDataSource() : Table {0}, col {1}, AutoIncrementSeed = {2}, AutoIncrementStep = {3}", dt.TableName, col.ColumnName, col.AutoIncrementSeed, col.AutoIncrementStep);
            //    //row = dt.NewRow();
            //}

            sCmdType = gGridDefinition.zAttribValue("UpdateCmdType", CommandType.Text.ToString());
            sCmd = gGridDefinition.zAttribValue("UpdateCmd");
            if (sCmd != null)
            {
                if (con == null) con = GetConnection();
                //gda.UpdateCommand = Ado.CreateCmd(con, sCmd, Ado.GetCommandType(sCmdType), gdt);
                gda.UpdateCommand = _ado.CreateCmd(con, sCmd, _ado.GetCommandType(sCmdType), gdt);
                gda.UpdateCommand.UpdatedRowSource = UpdateRowSource.Both;
            }

            bool bInsertCmdDefined = false;
            sCmdType = gGridDefinition.zAttribValue("InsertCmdType", CommandType.Text.ToString());
            sCmd = gGridDefinition.zAttribValue("InsertCmd");
            if (sCmd != null)
            {
                if (con == null) con = GetConnection();
                //gda.InsertCommand = Ado.CreateCmd(con, sCmd, Ado.GetCommandType(sCmdType), gdt);
                gda.InsertCommand = _ado.CreateCmd(con, sCmd, _ado.GetCommandType(sCmdType), gdt);
                gda.InsertCommand.UpdatedRowSource = UpdateRowSource.Both;
                bInsertCmdDefined = true;
            }

            sCmdType = gGridDefinition.zAttribValue("DeleteCmdType", CommandType.Text.ToString());
            sCmd = gGridDefinition.zAttribValue("DeleteCmd");
            if (sCmd != null)
            {
                if (con == null) con = GetConnection();
                //gda.DeleteCommand = Ado.CreateCmd(con, sCmd, Ado.GetCommandType(sCmdType), gdt);
                gda.DeleteCommand = _ado.CreateCmd(con, sCmd, _ado.GetCommandType(sCmdType), gdt);
                gda.DeleteCommand.UpdatedRowSource = UpdateRowSource.Both;
            }

            //object cb = Ado.CreateCommandBuilder(gda);
            object cb = _ado.CreateCommandBuilder(gda);
            //if (((!gGridOption.ReadOnly && !gGridOption.NoUpdate) || gGridOption.UpdateCommand) && gda.UpdateCommand == null) gda.UpdateCommand = Ado.CreateUpdateCommand(cb);
            if (((!gGridOption.ReadOnly && !gGridOption.NoUpdate) || gGridOption.UpdateCommand) && gda.UpdateCommand == null) gda.UpdateCommand = _ado.CreateUpdateCommand(cb);
            //if (((!gGridOption.ReadOnly && !gGridOption.NoInsert) || gGridOption.InsertCommand) && gda.InsertCommand == null) gda.InsertCommand = Ado.CreateInsertCommand(cb);
            if (((!gGridOption.ReadOnly && !gGridOption.NoInsert) || gGridOption.InsertCommand) && gda.InsertCommand == null) gda.InsertCommand = _ado.CreateInsertCommand(cb);
            //if (((!gGridOption.ReadOnly && !gGridOption.NoDelete) || gGridOption.DeleteCommand) && gda.DeleteCommand == null) gda.DeleteCommand = Ado.CreateDeleteCommand(cb);
            if (((!gGridOption.ReadOnly && !gGridOption.NoDelete) || gGridOption.DeleteCommand) && gda.DeleteCommand == null) gda.DeleteCommand = _ado.CreateDeleteCommand(cb);

            if (gda.InsertCommand != null && !bInsertCmdDefined)
            {
                //string sPrimaryKeyTrace;
                //if (dt.PrimaryKey == null) sPrimaryKeyTrace = "null"; else sPrimaryKeyTrace = dt.PrimaryKey.zToStringValues();
                //cTrace.Trace("PB_Grid.cGrid.CreateDataSource() : Table {0}, PrimaryKey {1}", dt.TableName, sPrimaryKeyTrace);

                IDbCommand cmdInsert = GetCommandWithReturn(gda.InsertCommand, gdt.PrimaryKey);
                gda.InsertCommand.Dispose();
                gda.InsertCommand = cmdInsert;
            }
            //if (sTableDef == null && !gGridOption.DetailDynamic) Ado.DataAdapter_Fill(gda, gdt);
            if (sTableDef == null && !gGridOption.DetailDynamic) _ado.DataAdapter_Fill(gda, gdt);

            //string sDataName = Xml.GetAttribValue(gGridDefinition, "def");
            //if (gbTrace) cTrace.StopNestedLevel("CreateDataSource");
        }
Example #55
0
 abstract internal DbDataAdapter  ConvertIDbDataAdapter(IDbDataAdapter dataAdapter);
Example #56
0
 private void ClearDataSource()
 {
     //SaveParameters();
     _ado.DataAdapter_Dispose(gda);
     gda = null;
     ClearDataTable();
     RemoveGridEvent();
     SortedList<string, RepositoryItem> editRepositoryList = GetEditRepositoryList();
     XtraGridTools.ClearGrid(gGridControl, editRepositoryList);
     if (gParentGrid != null) gParentGrid.gChildGrid.Remove(this);
 }
Example #57
0
        /// <summary>
        /// Init the provider.
        /// </summary>
        public void Initialize()
        {
            Assembly assembly = null;
            Type type = null;

            try
            {
                assembly = Assembly.Load(_assemblyName);

                // Build the DataAdapter template
                type = assembly.GetType(_dataAdapterClass, true);
                CheckPropertyType("DataAdapterClass", typeof(IDbDataAdapter), type);
                _templateDataAdapter = (IDbDataAdapter)type.GetConstructor(Type.EmptyTypes).Invoke(null);

                // Build the connection template
                type = assembly.GetType(_connectionClass, true);
                CheckPropertyType("DbConnectionClass", typeof(IDbConnection), type);
                _templateConnection = (IDbConnection)type.GetConstructor(Type.EmptyTypes).Invoke(null);

                // Get the CommandBuilder Type
                _commandBuilderType = assembly.GetType(_commandBuilderClass, true);
                if (_parameterDbTypeClass.IndexOf(',')>0)
                {
                    _parameterDbType = TypeUtils.ResolveType(_parameterDbTypeClass);
                }
                else
                {
                    _parameterDbType = assembly.GetType(_parameterDbTypeClass, true);
                }

                _templateConnectionIsICloneable = _templateConnection is ICloneable;
                _templateDataAdapterIsICloneable = _templateDataAdapter is ICloneable;
            }
            catch(Exception e)
            {
                throw new ConfigurationException(
                    string.Format("Could not configure providers. Unable to load provider named \"{0}\" not found, failed. Cause: {1}", _name, e.Message), e
                    );
            }
        }
Example #58
0
        internal LsEmpresa Listar()
        {
            try
            {
                var m_oEmpresa = new LsEmpresa();
                sbSQL.Length = 0;
                sbSQL.Append(" SELECT CDCNPJ, DSURL, IDPRO010, IDPRO011, IDPRO012, NMFANT, NMRAZASOCL,IDSUBEMPR");
                sbSQL.Append(" FROM TBPRO012");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsEmpresa.tbEmpresa);
                objMapping.ColumnMappings.Add("CDCNPJ", LsEmpresa.cpCNPJ);
                objMapping.ColumnMappings.Add("DSURL", LsEmpresa.cpUrl);
                objMapping.ColumnMappings.Add("IDPRO010", LsEmpresa.cpEndereco);
                objMapping.ColumnMappings.Add("IDPRO011", LsEmpresa.cpTelefone);
                objMapping.ColumnMappings.Add("IDPRO012", LsEmpresa.cpCodigo);
                objMapping.ColumnMappings.Add("NMFANT", LsEmpresa.cpNome);
                objMapping.ColumnMappings.Add("NMRAZASOCL", LsEmpresa.cpRazaoSocial);
                objMapping.ColumnMappings.Add("IDSUBEMPR", LsEmpresa.cpSubEmpresa);

                oAdapter.Fill(m_oEmpresa);

                return m_oEmpresa;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
Example #59
0
        internal LsEmpresa Listar(string v_sLogin)
        {
            try
            {
                var m_oEmpresa = new LsEmpresa();
                sbSQL.Length = 0;
                sbSQL.Append(" SELECT DISTINCT CDCNPJ, DSURL, IDPRO010, IDPRO011, empresa.IDPRO012, NMFANT, NMRAZASOCL,IDSUBEMPR");
                sbSQL.Append(" FROM TBPRO015 usuario, TBPRO013 usuario_perfil_empresa, TBPRO012 empresa");
                sbSQL.Append(" WHERE usuario.IDPRO015 = usuario_perfil_empresa.IDPRO015");
                sbSQL.Append(" AND usuario_perfil_empresa.IDPRO012 = empresa.IDPRO012");
                sbSQL.Append(" AND usuario.DSEMAL = :DSEMAL");

                oAdapter = ObterDataAdapter(sbSQL.ToString());

                ITableMapping objMapping = oAdapter.TableMappings.Add("Table", LsEmpresa.tbEmpresa);
                UtDbNet.AdicionarParametro(oAdapter, TratarSQLParametroBanco("DSEMAL").ToString(), v_sLogin);

                objMapping.ColumnMappings.Add("CDCNPJ", LsEmpresa.cpCNPJ);
                objMapping.ColumnMappings.Add("DSURL", LsEmpresa.cpUrl);
                objMapping.ColumnMappings.Add("IDPRO010", LsEmpresa.cpEndereco);
                objMapping.ColumnMappings.Add("IDPRO011", LsEmpresa.cpTelefone);
                objMapping.ColumnMappings.Add("IDPRO012", LsEmpresa.cpCodigo);
                objMapping.ColumnMappings.Add("NMFANT", LsEmpresa.cpNome);
                objMapping.ColumnMappings.Add("NMRAZASOCL", LsEmpresa.cpRazaoSocial);
                objMapping.ColumnMappings.Add("IDSUBEMPR", LsEmpresa.cpSubEmpresa);

                oAdapter.Fill(m_oEmpresa);

                return m_oEmpresa;
            }
            catch (Exception ex)
            {
                throw new Dor.Util.OperacaoInvalidaBD(ex);
            }
        }
Example #60
0
        /// <summary>
        /// Crée les objets Connection,AccessComanmd,DataAdapter pour connexion oleDb
        /// </summary>
        protected void CreateCnxAndObjectStandard()
        {
            MyConn = new OleDbConnection(MyConnectionString);
            myAccessCommand = new OleDbCommand();
            myDataAdapter = new OleDbDataAdapter((OleDbCommand)myAccessCommand);
            myAccessCommand.Connection = (OleDbConnection)MyConn;

        }// end