Inheritance: DataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
Ejemplo n.º 1
0
 public DBCAD(string sDBKey, string sTable, string sColum)
 {
     this.sDbKey = sDBKey;
     this.sTable = sTable;
     this.sColum = sColum;
     this.adaProxy = this.CrearAdaptador(this.sTable, this.sColum);
 }
Ejemplo n.º 2
0
        public TableInform( string tableName )
        {
            try
            {
                dataAdapter = TableInform.dbProviderFactory.CreateDataAdapter();

                command = TableInform.dbProviderFactory.CreateCommand();
                command.Connection = TableInform.Connection;

                DbCommandBuilder commandBuilder = TableInform.dbProviderFactory.CreateCommandBuilder();
                commandBuilder.ConflictOption = ConflictOption.OverwriteChanges;
                commandBuilder.DataAdapter = dataAdapter;

                dataTable = new DataTable();
                dataTable.TableName = tableName;

                command.CommandText = "Select * from " + Table.TableName;

                dataAdapter.SelectCommand = command;
                dataAdapter.InsertCommand = commandBuilder.GetInsertCommand();

                dataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand();
                dataAdapter.DeleteCommand = commandBuilder.GetDeleteCommand();

                dataAdapter.Fill( dataTable );
            }
            catch ( Exception ex )
            { }
        }
Ejemplo n.º 3
0
        public List <CountyList> FillCountryDropDownList()
        {
            ShomaRMEntities   db      = new ShomaRMEntities();
            List <CountyList> lstData = new List <CountyList>();

            System.Data.DataTable dtTable = new System.Data.DataTable();
            try
            {
                using (var cmd = db.Database.Connection.CreateCommand())
                {
                    db.Database.Connection.Open();
                    cmd.CommandText = "usp_GetCountryList";
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                    System.Data.Common.DbDataAdapter da = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient").CreateDataAdapter();
                    da.SelectCommand = cmd;
                    da.Fill(dtTable);
                    db.Database.Connection.Close();
                }
                foreach (System.Data.DataRow dr in dtTable.Rows)
                {
                    CountyList model = new CountyList();
                    model.ID          = Convert.ToInt64(dr["ID"].ToString());
                    model.CountryName = dr["CountryName"].ToString();
                    lstData.Add(model);
                }
                db.Dispose();
                return(lstData.ToList());
            }
            catch (Exception ex)
            {
                db.Database.Connection.Close();
                throw ex;
            }
        }
Ejemplo n.º 4
0
 internal TableManager(string tableName)
 {
     try
     {
         _da = TableManager._DbProviderFactory.CreateDataAdapter();
         _cmd = TableManager._DbProviderFactory.CreateCommand();
         DbCommandBuilder cb =
            TableManager._DbProviderFactory.CreateCommandBuilder();
         cb.QuotePrefix = "[";
         cb.QuoteSuffix = "]";
         _cmd.Connection = TableManager.Connection;
         cb.ConflictOption = ConflictOption.OverwriteChanges;
         cb.DataAdapter = _da;
         _dt = new DataTable();
         _temp = new DataTable();
         _dt.TableName = _temp.TableName = tableName;
         _cmd.CommandText = "Select * from " + Table.TableName;
         _da.SelectCommand = _cmd;
         _da.InsertCommand = cb.GetInsertCommand();
         _da.DeleteCommand = cb.GetDeleteCommand();
         _da.UpdateCommand = cb.GetUpdateCommand();
         Recharge("1 = 2");
     }
     catch { GlobalErrorCode = 13; }
     if (GlobalErrorCode == 13)
         MessageBox.Show("ОШИБКА");
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets one email address item for a recipient list.
        /// </summary>
        /// <param name="recipientListId">The recipient list id.</param>
        /// <param name="emailAddress">The email address.</param>
        /// <returns>One row of data with email address information</returns>
        public DataRow RecipientListGetItem(int recipientListId, string emailAddress)
        {
            DataTable emailAddresses = new DataTable();

            return(Executor.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterRecipientListGetItem");
                cmd.Parameters.Add(base.CreateParameter("recipientlistid", recipientListId));
                cmd.Parameters.Add(base.CreateParameter("emailaddress", emailAddress));

                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(emailAddresses);

                if (emailAddresses.Rows.Count > 1)
                {
                    throw new ApplicationException("More than one (" + emailAddresses.Rows.Count.ToString() +
                                                   ") email address item rows returned for recipient list " + recipientListId.ToString() + " and email '" + emailAddress +
                                                   "'). This is unexpected and might imply data corruption.");
                }

                if (emailAddresses.Rows.Count == 1)
                {
                    return emailAddresses.Rows[0];
                }

                return null;
            }));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets one work item based on job id and email address.
        /// </summary>
        /// <param name="jobId">The job id.</param>
        /// <param name="emailAddress">The email address.</param>
        /// <returns>A DataRow with the work item if successfull, null if not found</returns>
        public DataRow WorkItemGet(int jobId, string emailAddress)
        {
            DataTable workItem = new DataTable();

            Database.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterWorkItemGet");
                cmd.Parameters.Add(base.CreateParameter("jobid", jobId));
                cmd.Parameters.Add(base.CreateParameter("emailaddress", emailAddress));

                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(workItem);

                if (workItem.Rows.Count > 1)
                {
                    throw new ApplicationException("More than one (" + workItem.Rows.Count.ToString() +
                                                   ") work item rows returned for job " + jobId.ToString() + " and email '" + emailAddress +
                                                   "'). This is unexpected and might imply data corruption.");
                }

                if (workItem.Rows.Count == 1)
                {
                    return(workItem.Rows[0]);
                }
                return(null);
            });
            return(null);
        }
Ejemplo n.º 7
0
 protected DataAccessLayer(string connectionString)
 {
     CommandTimeout = 120;
     Com = null;
     Adapter = null;
     Constr = connectionString;
 }
Ejemplo n.º 8
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string[] df = comboBox1.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                string fid = df[df.Count() - 1].Trim();
                df = comboBox2.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string sid = df[df.Count() - 1].Trim();
                Adapter = DbProvider.GetDataAdapter("SELECT subject1, subject2, subject3, subject4, subject5 FROM Subjects WHERE (Faculty_ID='" + fid + "'AND Spec_ID='" + sid + "'AND SesionNo='" + int.Parse(textBox1.Text).ToString() + "')", ORM.DB_University.connection);
                Table = new DataTable();
                Adapter.Fill(Table);
                if (Table.Rows.Count == 0)
                {
                    for (int i = 0; i < 5; i++)
                        dataGridView1[i, 0].Value = "";
                    MessageBox.Show("0 rows");
                    return;
                }
                for (int i = 0; i < 5; i++)
                    dataGridView1[i, 0].Value = Table.Rows[0][i].ToString().Trim();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 9
0
        protected void Initialize (string databaseName, string querySelectRowString)
        {
            string providerName = GetProviderNameByDBName(databaseName);
            string connectionString = GetConnectionStringByDBName(databaseName);

            // Create the DbProviderFactory and DbConnection.
            factory = DbProviderFactories.GetFactory(providerName);

            connection = factory.CreateConnection();
            connection.ConnectionString = connectionString;

            // Create the DbCommand.
            DbCommand SelectTableCommand = factory.CreateCommand();
            SelectTableCommand.CommandText = querySelectRowString;
            SelectTableCommand.Connection = connection;

            adapter = factory.CreateDataAdapter();
            adapter.SelectCommand = SelectTableCommand;

            // Create the DbCommandBuilder.
            builder = factory.CreateCommandBuilder();
            builder.DataAdapter = adapter;

            adapter.ContinueUpdateOnError = true;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 执行查询,将结果集返回到一个DataTable
        /// </summary>
        /// <param name="cmdText">sql语句</param>
        /// <param name="sqlDA">DbDataAdapter对象</param>
        /// <returns>结果集</returns>
        public System.Data.DataTable QueryDataTable(string cmdText, out System.Data.Common.DbDataAdapter sqlDA)
        {
            System.Data.DataSet   ds      = new System.Data.DataSet();
            System.Data.DataTable dt      = null;
            DbDataAdapter         adapter = null;

            try
            {
                DbConnection connection = (DbConnection)this.Session.Connection;
                ITransaction trans      = this.Session.Transaction;
                DbCommand    command    = connection.CreateCommand();
                command.CommandText = cmdText;
                command.CommandType = System.Data.CommandType.Text;
                // DSSessionFactoryObject sessionfactory = this.SessionFactory as Spring.Data.NHibernate.DSSessionFactoryObject;
                adapter = IDbProvider.CreateDataAdapter() as DbDataAdapter;
                adapter.SelectCommand = command;
                trans.Enlist(command);
                adapter.Fill(ds);
            }
            catch (DbException e)
            {
                ExceptionHandler.AsynchronousThreadExceptionHandler = new DbExceptionHandler();
                ExceptionHandler.AsynchronousThreadExceptionHandler.HandleException(e);
            }
            if (ds != null && ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            sqlDA = adapter;
            return(dt);
        }
Ejemplo n.º 11
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                Adapter = DbProvider.GetDataAdapter("SELECT subject1, subject2, subject3, subject4, subject5 FROM Subjects WHERE (Faculty_ID='" + Faculty_ID.ToString()+ "'AND Spec_ID='" + Spec_ID.ToString() + "'AND SesionNo='" + int.Parse(textBox1.Text).ToString() + "')", ORM.DB_University.connection);
                Table = new DataTable();
                Adapter.Fill(Table);
                if (Table.Rows.Count == 0)
                {
                    throw new Exception("Invalid SesionNo");
                }

                for (int i = 0; i < 5; i++)
                    dataGridView1.Columns[i].HeaderText = Table.Rows[0][i].ToString().Trim();

                Adapter = DbProvider.GetDataAdapter("SELECT Mark1, Mark2, Mark3, Mark4, Mark5 FROM Marks WHERE (Student_ID='" + Stud_ID.ToString() + "' AND SesionNo='" + int.Parse(textBox1.Text).ToString() + "')", ORM.DB_University.connection);
                Table = new DataTable();
                Adapter.Fill(Table);
                if (Table.Rows.Count == 0)
                {
                    for (int i = 0; i < 5; i++)
                        dataGridView1[i, 0].Value = "";
                    MessageBox.Show("0 rows");
                    return;
                }
                for (int i = 0; i < 5; i++)
                    dataGridView1[i, 0].Value = Table.Rows[0][i].ToString().Trim();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 private void CloneFrom(DbDataAdapter from)
 {
     IDbDataAdapter adapter = from._IDbDataAdapter;
     this._IDbDataAdapter.SelectCommand = this.CloneCommand(adapter.SelectCommand);
     this._IDbDataAdapter.InsertCommand = this.CloneCommand(adapter.InsertCommand);
     this._IDbDataAdapter.UpdateCommand = this.CloneCommand(adapter.UpdateCommand);
     this._IDbDataAdapter.DeleteCommand = this.CloneCommand(adapter.DeleteCommand);
 }
Ejemplo n.º 13
0
		// Called just before the Save() is truly executed
		override protected void HookupRowUpdateEvents(DbDataAdapter adapter)
		{
			// We only bother hooking up the event if we have an AutoKey
			if (this.GetAutoKeyColumn().Length > 0)
			{
				OleDbDataAdapter da = adapter as OleDbDataAdapter;
				da.RowUpdated += new OleDbRowUpdatedEventHandler(OnRowUpdated);
			}
		}
Ejemplo n.º 14
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fonteDeDados">Tipo entre Excel, SQLServer ou arquivo TXT.</param>
        /// <param name="Local">Esse atributo representa o endereço do servidor do banco de dados, o local de grvação do arquivo Excel ou txt.</param>
        /// <param name="Arquivo">Esse atributo representa o nome do Banco de dados em caso de um SGDB,o nome da planilha Excel ou o nome do arquivo TXT.</param>
        /// <param name="Login">Login para SQLServer.</param>
        /// <param name="Senha">Senha para o SQLServer.</param>
        public FonteDeDadosOld(TipoFonteDados fonteDeDados, string Local, string Arquivo, string Login, string Senha)
        {
            try
            {

                _local = Local;
                _arquivo = Arquivo;
                _login = Login;
                _senha = Senha;
                _tipoFonteDados = fonteDeDados;

                if (_tipoFonteDados == TipoFonteDados.SQLServer)
                {
                    _stringConexao = "Data Source=" + _local + ";Initial Catalog=" + _arquivo + ";User Id=" + _login + ";Password="******"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + _local + "\\" + _arquivo;

                    if (_primeiraLinhaCabecalho)
                    {

                        _stringConexao += ";Extended Properties='Excel 8.0; HDR=YES'";

                    }
                    else
                    {

                        _stringConexao += ";Extended Properties='Excel 8.0; HDR=NO'";

                    }

                    _conexao = new OleDbConnection(_stringConexao);
                    _comando = new OleDbCommand();
                    _adaptador = new OleDbDataAdapter();
                }

                if (_tipoFonteDados == TipoFonteDados.TXT)
                {

                    ConectaArquivoTXT();

                }

            }
            catch (Exception ex)
            {
                //clsUtil.Gravalog("IsicLibrary.dll", "clsBancoDeDados.clsBancoDeDados()", Environment.StackTrace.ToString(), ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 15
0
        internal TableMapForm(DbDataAdapter dbAdapter)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            this.dbAdapter = dbAdapter;
        }
Ejemplo n.º 16
0
		public BaseAdapter (string database) 
                {
			con = null;
			cmd = null;
			dataAdapter = null;
			dataset = null;
			setOfChanges = null;
			configDoc = (XmlNode) ConfigurationSettings.GetConfig (database);
		}
Ejemplo n.º 17
0
        public ConnexionOracle()
        {
            connec = new OracleConnection();
            connec.ConnectionString = string.Format("User Id=om141055; Password=om141055; Data Source=//{0}", Properties.Settings.Default.connexion);
            dbpf = DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
            connec.Open();

            // initialisation de la connexion conn et de dbpf
            dba = dbpf.CreateDataAdapter();
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Excel 或Access 檔存放位置(虛擬路徑)
 /// </summary>
 /// <param name="ConnectString">連結字串</param>
 public OleDb(ConnectionString ConnectString)
 {
     constring = ConnectString;
     string connstr =
         string.Format("{0}{1}",
                                  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=",
                                  System.Web.HttpContext.Current.Server.MapPath(ConnectString.ConString));
     Connection = new OleDbConnection(connstr);
     adapter = new OleDbDataAdapter();
 }
Ejemplo n.º 19
0
    public async Task DataAdapter_command_access()
    {
        using var conn = await OpenConnectionAsync();

        using var command = new NpgsqlCommand("SELECT CAST('1 hour' AS interval) AS dauer", conn);
        var da = new NpgsqlDataAdapter();

        da.SelectCommand = command;
        System.Data.Common.DbDataAdapter common = da;
        Assert.IsNotNull(common.SelectCommand);
    }
Ejemplo n.º 20
0
        protected void CreateFile(string database, string tableName, IDbCommand cmd, DbDataAdapter da)
        {
            cmd.CommandText = string.Format(TableInfoSQL, database.ToLower(), tableName.ToLower());
            DataTable dt = new DataTable();
            da.Fill(dt);

            cmd.CommandText = string.Format(TableCommentSQL, database.ToLower(), tableName.ToLower());
            string tableComments = (cmd.ExecuteScalar() ?? string.Empty).ToString();

            CreateFile(tableName.ToUpper(), tableComments, dt);
        }
Ejemplo n.º 21
0
 public override void TearDown()
 {
   if (m_adapter != null) {
     m_adapter.Dispose();
     m_adapter = null;
   }
   if (m_reader != null) {
     m_reader.Close();
     m_reader = null;
   }
   base.TearDown();
 }
Ejemplo n.º 22
0
 public DataSource(
     string name, DataProvider provider, string connectionString,
     string commandDir, string commandFileMask)
 {
     _name = name;
     _provider = provider;
     _connectionString = connectionString;
     _commandFactory = new DataCommandFactory(this, commandDir, commandFileMask);
     _templateConnection = (IDbConnection)Activator.CreateInstance(_provider.ConnectionObjectType);
     _templateCommand = (IDbCommand)Activator.CreateInstance(_provider.CommandObjectType);
     _templateDataAdapter = (DbDataAdapter)Activator.CreateInstance(_provider.DataAdapterObjectType);
 }
Ejemplo n.º 23
0
 public DbCommandBuilder Builder(DbDataAdapter adapter)
 {
     switch (provider)
     {
         case "System.Data.SqlClient":
             return new SqlCommandBuilder ((SqlDataAdapter)adapter);
         case "MySql.Data.MySqlClient":
             return new MySqlCommandBuilder ((MySqlDataAdapter)adapter);
         default:
             throw new NotSupportedException ("The provider "+provider+" is not supported in this library.");
     }
 }
Ejemplo n.º 24
0
 private void frmanimals_Load(object sender, EventArgs e)
 {
     DbCommand idbCommand = Connection.provideConnection().CreateCommand();
     idbCommand.CommandText = "select * from `animals`";
     ad = returnAdapter();
     DbCommandBuilder builder = returnBuilder();
     builder.DataAdapter = ad;
     ad.SelectCommand = idbCommand;
     ad.Fill(this.newDataSet.animals);
     ad.DeleteCommand = builder.GetDeleteCommand();
     ad.UpdateCommand = builder.GetUpdateCommand();
     ad.InsertCommand = builder.GetInsertCommand();
 }
Ejemplo n.º 25
0
 public DataSet GetData(DbDataAdapter adapter, string CommandText, CommandType cmdType, DbParameter[] parameters = null)
 {
     DataSet ds = new DataSet();
     _cmd.CommandText = CommandText;
     _cmd.CommandType = cmdType;
     if (parameters != null && parameters.Count() > 0)
     {
         _cmd.Parameters.AddRange(parameters);
     }
     adapter.SelectCommand = _cmd;
     adapter.Fill(ds);
     return ds;
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets one recipient list from the database
        /// </summary>
        /// <returns></returns>
        public DataTable RecipientListGetById(int recipientListId)
        {
            DataTable recipientList = new DataTable();

            Executor.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterRecipientListGet");
                cmd.Parameters.Add(base.CreateParameter("recipientlistid", recipientListId));

                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(recipientList);
            });
            return(recipientList);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets all recipient lists from the database for sepcified user email
        /// </summary>
        /// <returns>All recipient lists</returns>
        public DataTable RecipientListGetAllByEmail(string email)
        {
            DataTable recipientLists = new DataTable();

            Executor.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterRecipientListGetAllByEmail");
                cmd.Parameters.Add(base.CreateParameter("email", email));
                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(recipientLists);
            });

            return(recipientLists);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Gets all work items for a job.
        /// </summary>
        /// <param name="jobId">The job id</param>
        /// <returns></returns>
        public DataTable WorkItemGetAllForJob(int jobId)
        {
            DataTable workItems = new DataTable();

            Database.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterWorkItemGetAllForJob");
                cmd.Parameters.Add(base.CreateParameter("jobid", jobId));

                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(workItems);
            });

            return(workItems);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Searches for work items doing a LIKE query on the
        /// email address.
        /// </summary>
        /// <param name="jobId">The job id.</param>
        /// <param name="searchFor">The email to search for.</param>
        /// <returns>A DataTable with the results</returns>
        public DataTable WorkItemSearch(int jobId, string searchFor)
        {
            DataTable workItems = new DataTable();

            Database.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterWorkItemSearch");
                cmd.Parameters.Add(base.CreateParameter("jobid", jobId));
                cmd.Parameters.Add(base.CreateParameter("searchfor", searchFor));

                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(workItems);
            });
            return(workItems);
        }
Ejemplo n.º 30
0
    //Constructor: intiliazes dbfactory and its connection
    public DALBlog(string connectionString)
    {
        // set object connection string to the one provided
        this.connectionString = ConfigurationManager.ConnectionStrings[connectionString].ConnectionString;

        // create new factory based on provider
        dbFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");

        // create a connection to the desired database
        connection = dbFactory.CreateConnection();
        connection.ConnectionString = this.connectionString;

        // initialize DataSet and DataAdapter objects
        ds = new DataSet();
        da = dbFactory.CreateDataAdapter();
    }
Ejemplo n.º 31
0
 public DataLayer(string dbType = "mySQL")
 {
     if (dbType == "mySQL")
     {
         connectionString = ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString;
         connection = new MySqlConnection(connectionString);
         adapter = new MySqlDataAdapter();
     }
     else
     {
         connectionString = ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString;
         connection = new System.Data.SqlClient.SqlConnection(connectionString);
         adapter = new System.Data.SqlClient.SqlDataAdapter();
     }
     dataContext = new DataContext(1);
 }
Ejemplo n.º 32
0
        private System.Data.Common.DbDataAdapter getDbDataAdapter(string providerName)
        {
            System.Data.Common.DbDataAdapter returnValue = null;

            if (!String.IsNullOrEmpty(providerName))
            {
                System.Data.Common.DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory(providerName);

                if (factory != null)
                {
                    returnValue = factory.CreateDataAdapter();
                }
            }

            return(returnValue);
        }
Ejemplo n.º 33
0
        static internal DbDataAdapter GetDataAdapterClone(
            System.Data.Common.DbDataAdapter origDbDataAdapter)
        {
            if (origDbDataAdapter == null)
            {
                return(null);
            }

            // Make a copy of the DataAdapter, Command, and Connection
            // objects to avoid accidentally overriding fields in them.
            DbDataAdapter dbAdapter =
                (DbDataAdapter)((ICloneable)origDbDataAdapter).Clone();
            IDbDataAdapter dataAdapter =
                (IDbDataAdapter)dbAdapter;
            IDbCommand dbCommand =
                dataAdapter.SelectCommand;

            // return if missing Command
            if (dbCommand == null)
            {
                return(dbAdapter);
            }

            // make copy of Command
            dbCommand =
                (IDbCommand)((ICloneable)dbCommand).Clone();

            // return if missing Connection
            if (dbCommand.Connection == null)
            {
                return(dbAdapter);
            }

            // make copy of Connection and plug in Command copy into adapter
            dbCommand.Connection =
                (IDbConnection)((ICloneable)dbCommand.Connection).Clone();
            dataAdapter.SelectCommand = dbCommand;

            // simplify the user's DataAdapter actions for our internal use
            dataAdapter.MissingSchemaAction = MissingSchemaAction.Add;
            if (dataAdapter.MissingMappingAction == MissingMappingAction.Error)
            {
                dataAdapter.MissingMappingAction = MissingMappingAction.Ignore;
            }

            return(dbAdapter);
        }  // GetDataAdapterClone
Ejemplo n.º 34
0
        /// <summary>
        /// Gets a batch of work items ready for processing. All work items
        /// will be updated with the status given
        /// </summary>
        /// <param name="jobId">The job id</param>
        /// <param name="status">The status all the work items in the batch should be set to</param>
        /// <returns></returns>
        public DataTable WorkItemGetBatchForProcessing(int jobId, JobWorkStatus getStatus, JobWorkStatus setStatus, int count)
        {
            DataTable workItems = new DataTable();

            Database.Execute(() =>
            {
                DbCommand cmd = base.CreateCommand("NewsletterWorkItemGetBatchForProcessing");
                cmd.Parameters.Add(base.CreateParameter("jobid", jobId));
                cmd.Parameters.Add(base.CreateParameter("selectStatus", getStatus));
                cmd.Parameters.Add(base.CreateParameter("updatedStatus", setStatus));
                cmd.Parameters.Add(base.CreateParameter("count", count));

                System.Data.Common.DbDataAdapter adapter = base.CreateDataAdapter(cmd);
                adapter.Fill(workItems);
            });

            return(workItems);
        }
Ejemplo n.º 35
0
		public void LoadDataPanelCAControlo(DbDataAdapter da, string ID) 
		{
			string QueryFilter = "IDControloAut=" + ID;
			string WhereQueryFilter = "WHERE " + QueryFilter;

			DataBaseLayer.ConnectionHolder ch = null;

			try 
			{
				ch = DBDataLayer.GetDBLayer().HoldConnection();
//				DBDataLayer.GetControloAutDataDeDescricaoDataAdapter(WhereQueryFilter, null, null).Fill(DBDataLayer.GetInstance().ControloAutDataDeDescricao);
//				DBDataLayer.GetTrusteeDataAdapter(null,null,null).Fill(DBDataLayer.GetInstance().Trustee);
//				DBDataLayer.GetTrusteeUserDataAdapter("WHERE IsAuthority=1",null,null).Fill(DBDataLayer.GetInstance().TrusteeUser);
			}
			finally
			{
				DataBaseLayer.DisposeConnection(ch);
			}
		}
Ejemplo n.º 36
0
        public SubjectsForm()
        {
            InitializeComponent();
            dataGridView1.Rows.Add(1);

            Adapter = DbProvider.GetDataAdapter("SELECT Name, Object_ID FROM UObjects WHERE Class_ID='20'", ORM.DB_University.connection);
            Table = new DataTable();
            Adapter.Fill(Table);
            Fac = (from DataRow c in Table.AsEnumerable()
                   select (c[0].ToString().Trim() + " " + c[1].ToString().Trim())).ToList();
            comboBox1.DataSource = Fac;

            Adapter = DbProvider.GetDataAdapter("SELECT Spec, Spec_ID FROM Spec", ORM.DB_University.connection);
            Table = new DataTable();
            Adapter.Fill(Table);
            Spc = (from DataRow c in Table.AsEnumerable()
                   select (c[0].ToString().Trim() + " " + c[1].ToString().Trim())).ToList();
            comboBox2.DataSource = Spc;
        }
Ejemplo n.º 37
0
        public virtual DataTable Fill(DataTable dataTable, string commandText, IDbDataParameter[] dbParameters, CommandType commandType)
        {
            int tickCount = Environment.TickCount;

            Trace.WriteLine(DateTime.Now.ToString(SystemInfo.TimeFormat) + " :Begin: " + MethodBase.GetCurrentMethod().ReflectedType.Name + "." + MethodBase.GetCurrentMethod().Name);
            if (this.AutoOpenClose)
            {
                this.Open();
            }
            else if (this.DbConnection == null)
            {
                this.AutoOpenClose = true;
                this.Open();
            }
            using (this.dbCommand_0 = this.DbConnection.CreateCommand())
            {
                this.dbCommand_0.CommandTimeout = this.DbConnection.ConnectionTimeout;
                this.dbCommand_0.CommandText    = commandText;
                this.dbCommand_0.CommandType    = commandType;
                if (this.InTransaction)
                {
                    this.dbCommand_0.Transaction = this.dbTransaction_0;
                }
                this.dbDataAdapter_0 = this.GetInstance().CreateDataAdapter();
                this.dbDataAdapter_0.SelectCommand = this.dbCommand_0;
                if ((dbParameters != null) && (dbParameters.Length > 0))
                {
                    this.dbCommand_0.Parameters.AddRange(dbParameters);
                }
                this.dbDataAdapter_0.Fill(dataTable);
                this.dbDataAdapter_0.SelectCommand.Parameters.Clear();
            }
            if (this.AutoOpenClose)
            {
                this.Close();
            }
            int num2 = Environment.TickCount;

            Trace.WriteLine(DateTime.Now.ToString(SystemInfo.TimeFormat) + " Ticks: " + TimeSpan.FromMilliseconds((double)(num2 - tickCount)).ToString() + " :End: " + MethodBase.GetCurrentMethod().ReflectedType.Name + "." + MethodBase.GetCurrentMethod().Name);
            this.WriteLog(commandText);
            return(dataTable);
        }
Ejemplo n.º 38
0
Archivo: DAL.cs Proyecto: morimizu/repo
        public static DataTable ReadTable(string sproc, List <ParamStruct> paramList)
        {
            DataTable dt = new DataTable();

            SDC.DbProviderFactory factory = SDC.DbProviderFactories.GetFactory(Properties.Settings.Default.provider);

            SDC.DbCommand comm = factory.CreateCommand();
            comm = BuildCommand(sproc, paramList);
            SDC.DbDataAdapter da   = factory.CreateDataAdapter();
            SDC.DbConnection  conn = Connection(factory);
            comm.Connection        = conn;
            da.SelectCommand       = comm;
            da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            using (conn)
            {
                conn.Open();
                da.Fill(dt);
                return(dt);
            }
        }
Ejemplo n.º 39
0
 public UpdatingOfDataOfInformation(string StringOfConnection)
 {
     //
     // Creating Of Connection
     //
     try
     {
         ConnectionToBase = CreatingConnection(StringOfConnection);
         try
         {
             ConnectionToBase.Open();
             ConnectionToBase.Close();
         }
         catch (Exception E) { throw new Exception(String.Format("Ошибка при открытии подключения обновления: {0}", E)); }
     }
     catch (Exception E) { throw new Exception(String.Format("Ошибка при создании подключения обновления: {0}", E)); }
     //
     // Initializing UpdatingOfData
     //
     _UpdatingOfData = CreatingDataAdapter();
 }
Ejemplo n.º 40
0
        void CreateDataAdapter()
        {
            _dataAdapter                = _query.CreateDataAdapter();
            _commandBuilder             = _query.CreateCommandBuilder();
            _commandBuilder.DataAdapter = _dataAdapter;

            // Select * from the entity table
            if (SelectCommand == null)
            {
                _dataAdapter.SelectCommand = _query.CreateTextCommand("SELECT * FROM " + this.EntityTableName);
            }
            else
            {
                _dataAdapter.SelectCommand = SelectCommand;
            }
            // Set the connection string on the select so that CommandBuilder GetxxCommand() calls work
            if (_dataAdapter.SelectCommand.Connection == null)
            {
                _dataAdapter.SelectCommand.Connection = _query.CreateConnection();
            }
        }
Ejemplo n.º 41
0
        public DbHelper(string provider, string connStr)
        {
            if (provider == null || connStr == null) { throw new ArgumentNullException(); }

            this.BaseDate = new DateTime(2010, 1, 1, 0, 0, 0);

            this.provider = provider;
            this.connectionString = connStr;

            //Соединение и объекты для работы с базой

            this.dbFactory = DbProviderFactories.GetFactory(this.Provider);
            this.dbConnection = this.dbFactory.CreateConnection();
            this.dbAdapter = this.dbFactory.CreateDataAdapter();
            this.dbConnection.ConnectionString = this.ConnectionString;

            this.dbAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

            //Кешируем базу

            this.ReadDataBase();
        }
Ejemplo n.º 42
0
        public DataSet GetDataSet(string sql)
        {
            // Description: fill DataSet via OleDbDataAdapter, connect Firebird, Interbase
            using (var ds = new DataSet())
            {
                try
                {
                    OpenFbData();

                    //Using not work with transaction
                    Com = GetCommandDb(sql);

                    Adapter = GetAdapterDb(Com);

                    Adapter.Fill(ds);
                }
                finally
                {
                    ReleaseResource();
                }

                return ds;
            }
        }
Ejemplo n.º 43
0
 public override DbCommandBuilder GetDbCommandBuilder(DbDataAdapter da)
 {
     if (da is SQLiteDataAdapter)
     {
         return new SQLiteCommandBuilder((SQLiteDataAdapter)da);
     }
     else
     {
         return base.GetDbCommandBuilder(da);
     }
 }
Ejemplo n.º 44
0
 public override DbCommandBuilder GetDbCommandBuilder(DbDataAdapter da)
 {
     if (da is OdbcDataAdapter)
     {
         return new OdbcCommandBuilder((OdbcDataAdapter)da);
     }
     else
     {
         return base.GetDbCommandBuilder(da);
     }
 }
Ejemplo n.º 45
0
 /// <summary>
 /// 设置 <paramref name="adapter"/> 对象的 RowUpdated 事件回调函数。
 /// </summary>
 /// <param name="adapter">需要设置 RowUpdated 事件的 <see cref="System.Data.Common.DbDataAdapter"/> 对象实例。</param>
 protected override void SetUpRowUpdatedEvent(System.Data.Common.DbDataAdapter adapter)
 {
     base.SetUpRowUpdatedEvent(adapter);
     ((MySqlDataAdapter)adapter).RowUpdated += MySqlDatabase_RowUpdated;
 }
Ejemplo n.º 46
0
 public override System.Data.Common.DbCommandBuilder GetDbCommandBuilder(System.Data.Common.DbDataAdapter Adapter)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 47
0
 /// <summary>
 /// 设置 <paramref name="adapter"/> 对象的 RowUpdated 事件回调函数。
 /// </summary>
 /// <param name="adapter">需要设置 RowUpdated 事件的 <see cref="System.Data.Common.DbDataAdapter"/> 对象实例。</param>
 protected override void SetUpRowUpdatedEvent(System.Data.Common.DbDataAdapter adapter)
 {
     ((DB2DataAdapter)adapter).RowUpdated += DB2Database_RowUpdated;
     base.SetUpRowUpdatedEvent(adapter);
 }
Ejemplo n.º 48
0
 /// <summary>
 /// See <see cref="IProvider">IProvider interface</see>.
 /// </summary>
 public abstract object NewCommandBuilder(System.Data.Common.DbDataAdapter dataAdapter);
Ejemplo n.º 49
0
 public abstract System.Data.Common.DbCommandBuilder CreateDbCommandBuilder(System.Data.Common.DbDataAdapter adapter);
Ejemplo n.º 50
0
 protected DbDataAdapter(DbDataAdapter adapter) : base(adapter)
 {
 }
Ejemplo n.º 51
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // --- Database initialization ---
        string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath);

        System.Data.IDbConnection        Conn = null;
        System.Data.Common.DbDataAdapter Sql  = null;
        string SqlStr = "SELECT * FROM TableData";

        System.Reflection.Assembly SQLite = null; // Required only for SQLite database

        if (UseMDB)                               // For MS Acess database
        {
            Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1");
            Sql  = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn);
        }
        else // For SQLite database
        {
            SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL");
            Conn   = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db");
            Sql    = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/
        }
        System.Data.DataTable D = new System.Data.DataTable();
        Sql.Fill(D);

        // --- Response initialization ---
        Response.ContentType = "text/html";
        Response.Charset     = "utf-8";
        Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate");
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

        System.Xml.XmlDocument X = new System.Xml.XmlDocument();

        // --- Save data to database ---
        string XML = TGData.Value;

        if (XML != "" && XML != null)
        {
            X.LoadXml(HttpUtility.HtmlDecode(XML));
            System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes");
            if (Ch.Count > 0)
            {
                foreach (System.Xml.XmlElement I in Ch[0])
                {
                    string id = I.GetAttribute("id");
                    System.Data.DataRow R;
                    if (I.GetAttribute("Added") == "1")
                    {
                        R       = D.NewRow();
                        R["ID"] = id;
                        D.Rows.Add(R);
                    }
                    else
                    {
                        R = D.Select("[ID]='" + id + "'")[0];
                    }

                    if (I.GetAttribute("Deleted") == "1")
                    {
                        R.Delete();
                    }
                    else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1")
                    {
                        if (I.HasAttribute("Project"))
                        {
                            R["Project"] = I.GetAttribute("Project");
                        }
                        if (I.HasAttribute("Resource"))
                        {
                            R["Resource"] = I.GetAttribute("Resource");
                        }
                        if (I.HasAttribute("Week"))
                        {
                            R["Week"] = System.Double.Parse(I.GetAttribute("Week"));
                        }
                        if (I.HasAttribute("Hours"))
                        {
                            R["Hours"] = System.Double.Parse(I.GetAttribute("Hours"));
                        }
                    }
                }
            }
            if (UseMDB)
            {
                new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql);      // For MS Acess database
            }
            else
            {
                Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database
            }
            Sql.Update(D);                                                                                // Updates changed to database
            D.AcceptChanges();
            X.RemoveAll();
        }

        // --- Load data from database ---
        {
            System.Xml.XmlElement G, BB, B, I;
            G  = X.CreateElement("Grid"); X.AppendChild(G);
            BB = X.CreateElement("Body"); G.AppendChild(BB);
            B  = X.CreateElement("B"); BB.AppendChild(B);
            foreach (System.Data.DataRow R in D.Rows)
            {
                I = X.CreateElement("I");
                B.AppendChild(I);
                I.SetAttribute("id", R[0].ToString());
                I.SetAttribute("Project", R[1].ToString());
                I.SetAttribute("Resource", R[2].ToString());
                I.SetAttribute("Week", R[3].ToString());
                I.SetAttribute("Hours", R[4].ToString());
            }
            TGData.Value = X.InnerXml;
        }
    }
Ejemplo n.º 52
0
 protected abstract void SetRowUpdatingHandler(DbDataAdapter adapter);
Ejemplo n.º 53
0
 private void Base_InitializeAdapter(ref System.Data.Common.DbDataAdapter Value)
 {
     Value = new MySqlDataAdapter();
 }
Ejemplo n.º 54
0
        public virtual DataTable GetSchema(string collectionName, string[] restrictionValues)
        {
            if (collectionName == null)
            {
                //LAMESPEC: In MS.NET, if collectionName is null, it throws ArgumentException.
                throw new ArgumentException();
            }

            String    cName       = null;
            DataTable schemaTable = MetaDataCollections.Instance;
            int       length      = restrictionValues == null ? 0 : restrictionValues.Length;

            foreach (DataRow row in schemaTable.Rows)
            {
                if (String.Compare((string)row ["CollectionName"], collectionName, true) == 0)
                {
                    if (length > (int)row ["NumberOfRestrictions"])
                    {
                        throw new ArgumentException("More restrictions were provided " +
                                                    "than the requested schema ('" +
                                                    row ["CollectionName"].ToString() + "') supports");
                    }
                    cName = row ["CollectionName"].ToString();
                }
            }
            if (cName == null)
            {
                throw new ArgumentException("The requested collection ('" + collectionName + "') is not defined.");
            }

            DbCommand command   = null;
            DataTable dataTable = new DataTable();

            switch (cName)
            {
            case "Databases":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select name as database_name, dbid, crdate as create_date " +
                                      "from master.sys.sysdatabases where (name = @Name or (@Name " +
                                      "is null))";
                AddParameter(command, "@Name", DbType.StringFixedLength, 4000);
                break;

            case "ForeignKeys":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, " +
                                      "TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, " +
                                      "IS_DEFERRABLE, INITIALLY_DEFERRED from " +
                                      "INFORMATION_SCHEMA.TABLE_CONSTRAINTS where (CONSTRAINT_CATALOG" +
                                      " = @Catalog or (@Catalog is null)) and (CONSTRAINT_SCHEMA = " +
                                      "@Owner or (@Owner is null)) and (TABLE_NAME = @Table or (" +
                                      "@Table is null)) and (CONSTRAINT_NAME = @Name or (@Name is null))" +
                                      " and CONSTRAINT_TYPE = 'FOREIGN KEY' order by CONSTRAINT_CATALOG," +
                                      " CONSTRAINT_SCHEMA, CONSTRAINT_NAME";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Table", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Name", DbType.StringFixedLength, 4000);
                break;

            case "Indexes":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select distinct db_name() as constraint_catalog, " +
                                      "constraint_schema = user_name (o.uid), " +
                                      "constraint_name = x.name, table_catalog = db_name (), " +
                                      "table_schema = user_name (o.uid), table_name = o.name, " +
                                      "index_name  = x.name from sysobjects o, sysindexes x, " +
                                      "sysindexkeys xk where o.type in ('U') and x.id = o.id and " +
                                      "o.id = xk.id and x.indid = xk.indid and xk.keyno = x.keycnt " +
                                      "and (db_name() = @Catalog or (@Catalog is null)) and " +
                                      "(user_name() = @Owner or (@Owner is null)) and (o.name = " +
                                      "@Table or (@Table is null)) and (x.name = @Name or (@Name is null))" +
                                      "order by table_name, index_name";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Table", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Name", DbType.StringFixedLength, 4000);
                break;

            case "IndexColumns":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select distinct db_name() as constraint_catalog, " +
                                      "constraint_schema = user_name (o.uid), constraint_name = x.name, " +
                                      "table_catalog = db_name (), table_schema = user_name (o.uid), " +
                                      "table_name = o.name, column_name = c.name, " +
                                      "ordinal_position = convert (int, xk.keyno), keyType = c.xtype, " +
                                      "index_name = x.name from sysobjects o, sysindexes x, syscolumns c, " +
                                      "sysindexkeys xk where o.type in ('U') and x.id = o.id and o.id = c.id " +
                                      "and o.id = xk.id and x.indid = xk.indid and c.colid = xk.colid " +
                                      "and xk.keyno <= x.keycnt and permissions (o.id, c.name) <> 0 " +
                                      "and (db_name() = @Catalog or (@Catalog is null)) and (user_name() " +
                                      "= @Owner or (@Owner is null)) and (o.name = @Table or (@Table is" +
                                      " null)) and (x.name = @ConstraintName or (@ConstraintName is null)) " +
                                      "and (c.name = @Column or (@Column is null)) order by table_name, " +
                                      "index_name";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 8);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Table", DbType.StringFixedLength, 13);
                AddParameter(command, "@ConstraintName", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Column", DbType.StringFixedLength, 4000);
                break;

            case "Procedures":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, " +
                                      "ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, " +
                                      "CREATED, LAST_ALTERED from INFORMATION_SCHEMA.ROUTINES where " +
                                      "(SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and " +
                                      "(SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME" +
                                      " = @Name or (@Name is null)) and (ROUTINE_TYPE = @Type or (@Type " +
                                      "is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Name", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Type", DbType.StringFixedLength, 4000);
                break;

            case "ProcedureParameters":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, " +
                                      "ORDINAL_POSITION, PARAMETER_MODE, IS_RESULT, AS_LOCATOR, " +
                                      "PARAMETER_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, " +
                                      "CHARACTER_OCTET_LENGTH, COLLATION_CATALOG, COLLATION_SCHEMA, " +
                                      "COLLATION_NAME, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, " +
                                      "CHARACTER_SET_NAME, NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, " +
                                      "NUMERIC_SCALE, DATETIME_PRECISION, INTERVAL_TYPE, " +
                                      "INTERVAL_PRECISION from INFORMATION_SCHEMA.PARAMETERS where " +
                                      "(SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and " +
                                      "(SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME = " +
                                      "@Name or (@Name is null)) and (PARAMETER_NAME = @Parameter or (" +
                                      "@Parameter is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA," +
                                      " SPECIFIC_NAME, PARAMETER_NAME";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Name", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Parameter", DbType.StringFixedLength, 4000);
                break;

            case "Tables":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE " +
                                      "from INFORMATION_SCHEMA.TABLES where" +
                                      " (TABLE_CATALOG = @catalog or (@catalog is null)) and " +
                                      "(TABLE_SCHEMA = @owner or (@owner is null))and " +
                                      "(TABLE_NAME = @name or (@name is null)) and " +
                                      "(TABLE_TYPE = @table_type or (@table_type is null))";
                AddParameter(command, "@catalog", DbType.StringFixedLength, 8);
                AddParameter(command, "@owner", DbType.StringFixedLength, 3);
                AddParameter(command, "@name", DbType.StringFixedLength, 11);
                AddParameter(command, "@table_type", DbType.StringFixedLength, 10);
                break;

            case "Columns":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, " +
                                      "ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, " +
                                      "CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, " +
                                      "NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE, " +
                                      "DATETIME_PRECISION, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, " +
                                      "CHARACTER_SET_NAME, COLLATION_CATALOG from INFORMATION_SCHEMA.COLUMNS" +
                                      " where (TABLE_CATALOG = @Catalog or (@Catalog is null)) and (" +
                                      "TABLE_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @table" +
                                      " or (@Table is null)) and (COLUMN_NAME = @column or (@Column is null" +
                                      ")) order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Table", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Column", DbType.StringFixedLength, 4000);
                break;

            case "Users":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select uid, name as user_name, createdate, updatedate from sysusers" +
                                      " where (name = @Name or (@Name is null))";
                AddParameter(command, "@Name", DbType.StringFixedLength, 4000);
                break;

            case "Views":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CHECK_OPTION, " +
                                      "IS_UPDATABLE from INFORMATION_SCHEMA.VIEWS where (TABLE_CATALOG" +
                                      " = @Catalog or (@Catalog is null)) TABLE_SCHEMA = @Owner or " +
                                      "(@Owner is null)) and (TABLE_NAME = @table or (@Table is null))" +
                                      " order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Table", DbType.StringFixedLength, 4000);
                break;

            case "ViewColumns":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME, TABLE_CATALOG, " +
                                      "TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from " +
                                      "INFORMATION_SCHEMA.VIEW_COLUMN_USAGE where (VIEW_CATALOG = " +
                                      "@Catalog (@Catalog is null)) and (VIEW_SCHEMA = @Owner (@Owner" +
                                      " is null)) and (VIEW_NAME = @Table or (@Table is null)) and " +
                                      "(COLUMN_NAME = @Column or (@Column is null)) order by " +
                                      "VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME";
                AddParameter(command, "@Catalog", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Owner", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Table", DbType.StringFixedLength, 4000);
                AddParameter(command, "@Column", DbType.StringFixedLength, 4000);
                break;

            case "UserDefinedTypes":
                command             = CreateCommand();
                command.Connection  = this;
                command.CommandText = "select assemblies.name as assembly_name, types.assembly_class " +
                                      "as udt_name, ASSEMBLYPROPERTY(assemblies.name, 'VersionMajor') " +
                                      "as version_major, ASSEMBLYPROPERTY(assemblies.name, 'VersionMinor') " +
                                      "as version_minor, ASSEMBLYPROPERTY(assemblies.name, 'VersionBuild') " +
                                      "as version_build, ASSEMBLYPROPERTY(assemblies.name, 'VersionRevision') " +
                                      "as version_revision, ASSEMBLYPROPERTY(assemblies.name, 'CultureInfo') " +
                                      "as culture_info, ASSEMBLYPROPERTY(assemblies.name, 'PublicKey') " +
                                      "as public_key, is_fixed_length, max_length, Create_Date, " +
                                      "Permission_set_desc from sys.assemblies as assemblies join " +
                                      "sys.assembly_types as types on assemblies.assembly_id = types.assembly_id" +
                                      " where (assemblies.name = @AssemblyName or (@AssemblyName is null)) and " +
                                      "(types.assembly_class = @UDTName or (@UDTName is null))";
                AddParameter(command, "@AssemblyName", DbType.StringFixedLength, 4000);
                AddParameter(command, "@UDTName", DbType.StringFixedLength, 4000);
                break;

            case "MetaDataCollections":
                return(MetaDataCollections.Instance);

            case "DataSourceInformation":
                throw new NotImplementedException();

            case "DataTypes":
                return(DataTypes.Instance);

            case "ReservedWords":
                return(ReservedWords.Instance);

            case "Restrictions":
                return(Restrictions.Instance);
            }
            for (int i = 0; i < length; i++)
            {
                command.Parameters [i].Value = restrictionValues [i];
            }
            DbDataAdapter dataAdapter = DbProviderFactory.CreateDataAdapter();

            dataAdapter.SelectCommand = command;
            dataAdapter.Fill(dataTable);
            return(dataTable);
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Sets the RowUpdated event for the data adapter.
 /// </summary>
 /// <param name="adapter">The <see cref="DbDataAdapter"/> to set the event.</param>
 protected override void SetUpRowUpdatedEvent(DbDataAdapter adapter)
 {
     ((SqlDataAdapter)adapter).RowUpdated += OnSqlRowUpdated;
 }
Ejemplo n.º 56
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // By default (false) it uses SQLite database (Database.db). You can switch to MS Access database (Database.mdb) by setting UseMDB = true
            // The SQLite loads dynamically its DLL from TreeGrid distribution, it chooses 32bit or 64bit assembly
            // The MDB can be used only on 32bit IIS mode !!! The ASP.NET service program must have write access to the Database.mdb file !!!
            bool UseMDB = false;

            // --- Response initialization ---
            Response.ContentType = "text/xml";
            Response.Charset     = "utf-8";
            Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate");
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

            // --- Database initialization ---
            string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath);
            System.Data.IDbConnection           Conn = null;
            System.Data.Common.DbDataAdapter    Sql  = null;
            System.Data.Common.DbCommandBuilder Bld  = null;
            string SqlStr = "SELECT * FROM TableData";
            System.Reflection.Assembly SQLite = null; // Required only for SQLite database

            if (UseMDB)                               // For MS Acess database
            {
                Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1");
                Sql  = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn);
            }
            else // For SQLite database
            {
                SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL");
                Conn   = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db");
                Sql    = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/
            }

            System.Data.DataTable D = new System.Data.DataTable();
            Sql.Fill(D);

            // --- Save data to database ---
            System.Xml.XmlDocument X = new System.Xml.XmlDocument();
            string XML = Request["TGData"];
            if (XML != "" && XML != null)
            {
                X.LoadXml(HttpUtility.HtmlDecode(XML));
                System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes");
                if (Ch.Count > 0)
                {
                    foreach (System.Xml.XmlElement I in Ch[0])
                    {
                        string id = I.GetAttribute("id");
                        System.Data.DataRow R;
                        if (I.GetAttribute("Added") == "1")
                        {
                            R       = D.NewRow();
                            R["ID"] = id;
                            D.Rows.Add(R);
                        }
                        else
                        {
                            R = D.Select("[ID]='" + id + "'")[0];
                        }

                        if (I.GetAttribute("Deleted") == "1")
                        {
                            R.Delete();
                        }
                        else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1")
                        {
                            if (I.HasAttribute("Project"))
                            {
                                R["Project"] = I.GetAttribute("Project");
                            }
                            if (I.HasAttribute("Resource"))
                            {
                                R["Resource"] = I.GetAttribute("Resource");
                            }
                            if (I.HasAttribute("Week"))
                            {
                                R["Week"] = System.Double.Parse(I.GetAttribute("Week"));
                            }
                            if (I.HasAttribute("Hours"))
                            {
                                R["Hours"] = System.Double.Parse(I.GetAttribute("Hours"));
                            }
                        }
                    }
                }

                if (UseMDB)
                {
                    new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql);     // For MS Acess database
                }
                else
                {
                    Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database
                }
                Sql.Update(D);                                                                                // Updates changed to database
                D.AcceptChanges();
                X.RemoveAll();
                Response.Write("<Grid><IO Result='0'/></Grid>");
            }

            // --- Load data from database ---
            else
            {
                System.Xml.XmlElement G, BB, B, I;
                G  = X.CreateElement("Grid"); X.AppendChild(G);
                BB = X.CreateElement("Body"); G.AppendChild(BB);
                B  = X.CreateElement("B"); BB.AppendChild(B);
                foreach (System.Data.DataRow R in D.Rows)
                {
                    I = X.CreateElement("I");
                    B.AppendChild(I);
                    I.SetAttribute("id", R[0].ToString());
                    I.SetAttribute("Project", R[1].ToString());
                    I.SetAttribute("Resource", R[2].ToString());
                    I.SetAttribute("Week", R[3].ToString());
                    I.SetAttribute("Hours", R[4].ToString());
                }
                Response.Write(X.InnerXml);
            }
        }  catch (Exception E)
        {
            Response.Write("<Grid><IO Result=\"-1\" Message=\"Error in TreeGrid example:&#x0a;&#x0a;" + E.Message.Replace("&", "&amp;").Replace("<", "&lt;").Replace("\"", "&quot;") + "\"/></Grid>");
        }
    }
Ejemplo n.º 57
0
 public override System.Data.Common.DbCommandBuilder GetCommandBuilder(System.Data.Common.DbDataAdapter Adapter)
 {
     return(new OracleCommandBuilder(((OracleDataAdapter)Adapter)));
 }
Ejemplo n.º 58
0
 public GlimpseDbDataAdapter(DbDataAdapter innerDataAdapter)
 {
     InnerDataAdapter = innerDataAdapter;
 }
Ejemplo n.º 59
0
 public override System.Data.Common.DbCommandBuilder CreateDbCommandBuilder(System.Data.Common.DbDataAdapter adapter)
 {
     return(new SqlCommandBuilder(adapter as SqlDataAdapter));
 }