Beispiel #1
0
        public static UsuariosBO UpdateUsuario(UsuariosBO Usuario, ADODB.Connection cn)
        {
            var RsUsuarios = new ADODB.Recordset();
            var LibORGM    = new SQL();
            var Serializer = new SerializerFO();

            try
            {
                RsUsuarios.Open(String.Format("SELECT * FROM dbo.Usuarios WHERE Usuario = '{0}'", Usuario.Usuario), cn, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic);
                if (RsUsuarios.EOF)
                {
                    RsUsuarios.AddNew();
                    RsUsuarios.Fields["Usuario"].Value     = Usuario.Usuario;
                    RsUsuarios.Fields["SenhaAcesso"].Value = Usuario.SenhaAcesso;
                    RsUsuarios.Fields["TokenAcesso"].Value = CriptografiaFO.EncriptarMD5(Usuario.TokenAcesso);
                }
                RsUsuarios.Fields["Inativo"].Value = Usuario.Inativo;


                RsUsuarios.Update();
                RsUsuarios.Close();

                Usuario = UsuariosDA.GetUsuarios(Usuario.Usuario, cn);
            }
            catch (Exception)
            {
                throw;
            }

            return(Usuario);
        }
Beispiel #2
0
        public static UsuariosBO GetUsuarios(string Usuario, ADODB.Connection Cn)
        {
            var Usuarios   = new UsuariosBO();
            var RsUsuarios = new Recordset();

            try
            {
                RsUsuarios.Open(String.Format("SELECT * FROM dbo.Usuarios WHERE Usuario = '" + Usuario + "'"), Cn, CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockReadOnly);
                if (!RsUsuarios.EOF)
                {
                    Usuarios.Usuario     = RsUsuarios.Fields["Usuario"].Value.ToString();
                    Usuarios.SenhaAcesso = RsUsuarios.Fields["SenhaAcesso"].Value.ToString();
                    Usuarios.TokenAcesso = RsUsuarios.Fields["TokenAcesso"].Value.ToString();
                    return(Usuarios);
                }
                else
                {
                    return(new UsuariosBO());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Підключення до Касового Апарату
        /// Number
//Номер аппарата.
//Тип: строка
//Умолчание: "1"
//Позволяет указать кассовый аппарат для работы в виде:
//Логический номер (в виде "число")
//Комбинация номер порта, сетевой номер кассы (в виде "порт;сетевойномер")
//Комбинация номер порта, сетевой номер кассы, скорость обмена (в виде "порт;сетевойномер;скорость")
//Если в момент установки значения свойства сеанс связи с аппаратом был установлен, он закрывается.
//При использовании логического номера он должен совпадать с логическим номером, запрограммированным в кассе в параметрах связи с компьютером.
//Если используется сетевой номер, то он должен совпадать с сетевым номером, запрограммированным в кассе в параметрах связи с компьютером.
//Возможные значения скорости: 9600, 19200, 38400, 57600, 115200. Однако некоторые модели касс не поддерживают скорости 57600 и 115200. Указанная скорость должна совпадать со скоростью обмена с компьютером, запрограммированной в кассе.
//Если касса подключена к компьютеру и в её настройках разрешён обмен с компьютером, то с помощью утилиты comtest.exe вы можете выяснить, на какой скорости работает касса, какой протокол она использует для обмена (упрощённый или полный) и какой имеет сетевой номер. Эти данные помогут вам правильно сформировать строку для свойства Number. Иконка comtest.exe устанавливается на рабочем столе Windows большинством инсталляторов, которые устанавливают драйверы EQL..
        /// </summary>
        public void Connect(string Port, string LogicNumber, string UserId, string Password)
        {
            connection = new Connection();
            string strCnn = "Provider=EQL OLE DB Provider;";

            strCnn = strCnn + "Data Source='" + Port + ";" + LogicNumber + "'";
            //strCnn = strCnn + "Data Source=’" + Port + ";" + LogicNumber + "’";
            strCnn = strCnn + ";User Id=" + UserId + ";Password="******";";
            strCnn = strCnn + "Extended Properties = \"Protocol=" + "L2Com.HcComSessionCreator\"";
            connection.Open(strCnn);

            srv = new Recordset();
            //відкриття службової таблиці
            srv.Open("EQL_service", connection, CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 512);
            //отримання процедурного інтерфейсу
            proc                = srv.Fields[1].Value;
            fp                  = (IHcFReg)proc;
            fpext               = (IHcFRegEx)proc;
            report              = (IHcReport)proc;
            display             = (IHcDisplay)proc;
            fiscPrinter         = (IHcFiscPrnt)proc;
            fiscPrinterLastInfo = (IHmLastInfo)proc;
            fiscPrinterSound    = (IHcSound)proc;

            this.OutTone(1000, 100);
        }
Beispiel #4
0
        /// <summary>
        /// Create access database table; True = Success, False = Fail
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table_name"></param>
        /// <returns></returns>
        public bool CreateTable <T>(string table_name)
        {
            bool         r   = true;
            CatalogClass cat = openDatabase();

            //Get properties of T
            Type itemType   = typeof(T);
            var  properties = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            try {
                //Create the table and it's fields.
                ADOX.Table table = new ADOX.Table();
                table.Name = table_name;

                //Add column to the table.
                foreach (var p in properties)
                {
                    table.Columns.Append(tableField(p.Name, cat, myConverter.FromVSTypeToTableAccessDataType(p.PropertyType.Name.ToString())));
                }

                //Add the table to our database
                cat.Tables.Append(table);

                // Close the connection to the database after we are done creating it and adding the table to it.
                con = (ADODB.Connection)cat.ActiveConnection;
                if (con != null && con.State != 0)
                {
                    con.Close();
                }
            } catch { r = false; }
            cat = null;
            return(r);
        }
Beispiel #5
0
        /// <summary>
        /// Підключення до Касового Апарату
        /// Number
//Номер аппарата.
//Тип: строка
//Умолчание: "1"
//Позволяет указать кассовый аппарат для работы в виде:
//Логический номер (в виде "число")
//Комбинация номер порта, сетевой номер кассы (в виде "порт;сетевойномер")
//Комбинация номер порта, сетевой номер кассы, скорость обмена (в виде "порт;сетевойномер;скорость")
//Если в момент установки значения свойства сеанс связи с аппаратом был установлен, он закрывается.
//При использовании логического номера он должен совпадать с логическим номером, запрограммированным в кассе в параметрах связи с компьютером.
//Если используется сетевой номер, то он должен совпадать с сетевым номером, запрограммированным в кассе в параметрах связи с компьютером.
//Возможные значения скорости: 9600, 19200, 38400, 57600, 115200. Однако некоторые модели касс не поддерживают скорости 57600 и 115200. Указанная скорость должна совпадать со скоростью обмена с компьютером, запрограммированной в кассе.
//Если касса подключена к компьютеру и в её настройках разрешён обмен с компьютером, то с помощью утилиты comtest.exe вы можете выяснить, на какой скорости работает касса, какой протокол она использует для обмена (упрощённый или полный) и какой имеет сетевой номер. Эти данные помогут вам правильно сформировать строку для свойства Number. Иконка comtest.exe устанавливается на рабочем столе Windows большинством инсталляторов, которые устанавливают драйверы EQL..
        /// </summary>
        public void Connect(string Port, string LogicNumber, string UserId, string Password)
        {
            connection = new Connection();
            string strCnn = "Provider=EQL OLE DB Provider;";
            strCnn = strCnn + "Data Source='" + Port + ";" + LogicNumber + "'";
            //strCnn = strCnn + "Data Source=’" + Port + ";" + LogicNumber + "’";
            strCnn = strCnn + ";User Id=" + UserId + ";Password="******";";
            strCnn = strCnn + "Extended Properties = \"Protocol=" + "L2Com.HcComSessionCreator\"";
            connection.Open(strCnn);

            srv = new Recordset();
            //відкриття службової таблиці
            srv.Open("EQL_service", connection, CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 512);
            //отримання процедурного інтерфейсу
            proc = srv.Fields[1].Value;
            fp = (IHcFReg)proc;
            fpext = (IHcFRegEx)proc;
            report = (IHcReport)proc;
            display = (IHcDisplay)proc;
            fiscPrinter = (IHcFiscPrnt)proc;
            fiscPrinterLastInfo = (IHmLastInfo)proc;
            fiscPrinterSound = (IHcSound)proc;

            this.OutTone(1000, 100);
        }
        public object[] db_access(string strSQL)
        {
            ADODB.Connection objCon;
            ADODB.Recordset  objRec;
            object[,] dataRows;
            object[] dataSuite;
            string   strCon;

            objCon = new ADODB.Connection();
            objRec = new ADODB.Recordset();

            //establish the connection string and open the database connection
            strCon = "driver={MySQL ODBC 5.1 Driver};server=107.22.232.228;uid=qa_people;pwd=thehandcontrols;" +
                     "database=functional_test_data;option=3";

            objCon.Open(strCon);

            //execute the SQL and return the recrodset of results
            objRec = objCon.Execute(strSQL, out missing, 0);

            //populate a two dinmensional object array with the results
            dataRows = objRec.GetRows();

            //get a onedimensional array that can be placed into the Test Suite dropdown
            dataSuite = thinArray(dataRows);

            //close the recordset
            objRec.Close();

            //close the database connection
            objCon.Close();

            return(dataSuite);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool CreateNewAccessDatabase(string fileName)
        {
            bool result = false;

            ADOX.Catalog cat = new ADOX.Catalog();
            //ADOX.Table table = new ADOX.Table();

            //Create the table and it's fields.
            //table.Name = "Table1";
            //table.Columns.Append("Field1");
            //table.Columns.Append("Field2");

            try
            {
                cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5");
                //cat.Tables.Append(table);

                //Now Close the database
                ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                if (con != null)
                {
                    con.Close();
                }

                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            cat = null;
            return(result);
        }
Beispiel #8
0
        public void DtaDbCre()
        {
            if (!File.Exists(@"Data\Data.accdb"))
            {
                ADOX.Catalog cat   = new ADOX.Catalog();
                ADOX.Table   table = new ADOX.Table();

                try
                {
                    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Data\\Data.accdb; Jet OLEDB:Engine Type=5");

                    //Now Close the database
                    ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                    if (con != null)
                    {
                        con.Close();
                    }

                    //result = true;
                }
                catch //(Exception ex)
                {
                }
                cat = null;
                TblCre();
            } //End if
        }     //End dbCre
Beispiel #9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="conn"></param>
 protected void OnDbClosedByUser(ADODB.Connection conn)
 {
     if (this.DbClosedByUser != null)
     {
         this.DbClosedByUser(conn, new EventArgs());
     }
 }
Beispiel #10
0
        private void cmbTableUn_SelectedIndexChanged(object sender, EventArgs e)
        {
            grdData.Rows.Clear();
            grdData.Columns.Clear();

            mycon = new ADODB.Connection();
            mycon.Open("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + clsDataStorage.db.Name);
            recordSet = new ADODB.Recordset();
            recordSet.Open("SELECT * FROM " + cmbTableUn.Text, mycon, CursorTypeEnum.adOpenStatic);

            //clsDataStorage.db.OpenTable(cmbTableUn.Text);

            foreach (ADODB.Field field in recordSet.Fields)
            {
                grdData.Columns.Add("clm" + field.Name, field.Name);
            }

            while (!recordSet.EOF)
            {
                grdData.Rows.Add();

                for (int i = 0; i < recordSet.Fields.Count; i++)
                {
                    grdData.Rows[r].Cells[i].Value = recordSet.Fields[i].Value;
                }
                r++;
                recordSet.MoveNext();
            }
            r = 0;
            recordSet.Close();
        }
Beispiel #11
0
        /// <summary>
        /// Classe cria um objeto do tipo usuário que contém informações de um determinado usuário do sistema
        /// </summary>
        /// <param name="conexao">Recebe um objeto do tipo ADODB.Connection para linkar ao banco de dados</param>
        /// <param name="usuario">Filtra os dados de um determinado Usuário</param>
        public Usuarios(Connection conexaoArg, String usuarioArg)
        {
            conexao = conexaoArg;
            usuario = usuarioArg;
            if (dados.State == 0)
            {
                dados.LockType       = LockTypeEnum.adLockOptimistic;
                dados.CursorLocation = CursorLocationEnum.adUseClient;
                dados.CursorType     = CursorTypeEnum.adOpenDynamic;
            }
            SQL = "SELECT usuarios.* FROM usuarios WHERE (((usuarios.matricula)='" + usuario + "')) ORDER BY usuarios.matricula;";
            abreConexao();

            if (dados.RecordCount == 0)
            {
                throw new ArgumentException("Usuário não encontrado.");
            }


            usuario     = usuarioArg;
            senha       = dados.Fields["senha"].Value;
            codUsuario  = dados.Fields["cod"].Value;
            tipoUsuario = Convert.ToInt16(dados.Fields["Tipo"].Value);


            if (tipoUsuario == 1)
            {
                fechaConexao();
                SQL = "SELECT usuarios.* FROM usuarios ORDER BY usuarios.matricula;";
                abreConexao();
            }

            criaListaUsuarios();
            fechaConexao();
        }
Beispiel #12
0
        /// <summary>
        /// 关闭一个数据库连接
        /// </summary>
        /// <param name="conn"></param>
        public void CloseDatabase(ADODB.Connection conn)
        {
            if (conn == null)
            {
                return;
            }
            int orgState = 0;

            try
            {
                orgState = conn.State;
                if (orgState == 1)
                {
                    conn.Close();
                    OnDbClosedByUser(conn);
                }
            }
            catch (Exception ex)
            {
                if (orgState == 1)
                {
                    log.Error(ex);
                }
                else
                {
                    log.Error(ex.Message);
                }
            }
        }
Beispiel #13
0
 public ADOConnection(string connectionString) : base()
 {
     _connection = new ADODB.Connection();
     _connection.Open(connectionString, String.Empty, String.Empty, -1);
     _connection.CursorLocation = ADODB.CursorLocationEnum.adUseServer;
     SetState(SQLConnectionState.Idle);
 }
Beispiel #14
0
        public static bool session_valid(string sdate)
        {
            try
            {
                ADODB.Connection ADOconn = new ADODB.Connection();
                ADODB.Recordset  tmp     = new ADODB.Recordset();

                SqlConnectionStringBuilder decoder = new SqlConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["Con"].ConnectionString);


                ADOconn.Open("Provider=SQLOLEDB;Initial Catalog= " + decoder.InitialCatalog + ";Data Source=" + decoder.DataSource + ";", decoder.UserID, decoder.Password, 0);

                ADODB.Recordset rec = new ADODB.Recordset();
                string          sql = "SELECT FINANCE_ID FROM FINANCE_SESSION  WHERE FINANCE_STATUS=1 AND '" + sdate + "' between finance_start_date and finance_end_date";

                Recordset TMP = new Recordset();
                TMP.Open(sql, ADOconn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, -1);
                if (TMP.RecordCount == 0)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
 public Datasource(string conStr, string conName)
 {
     try {
         conectionString = conStr;
         connectionName  = conName;
         if (conectionString.Contains("Provider=") == true)
         {
             adocon = new ADODB.Connection(conStr);
             adocon.Open();
         }
         else if (conectionString.Contains("Driver=") == true)
         {
             con = new OdbcConnection(conStr);
             con.Open();
         }
         else
         {
             mycon = new MySqlConnection(conStr);
             mycon.Open();
         }
         this.getSchema();
     } catch (Exception e) {
         error = e.Message.ToString();
     }
 }
Beispiel #16
0
        public bool CreateDatabase()
        {
            bool result = false;

            ADOX.Catalog cat = new ADOX.Catalog();
            try
            {
                string connection = this.GetConnectionString();
                cat.Create(connection);

                Table assignment = this.CreateAssignmentTable(cat);
                cat.Tables.Append(assignment);
                Table folders = this.CreateFoldersTable(cat);
                cat.Tables.Append(folders);
                Table image = this.CreateImageTable(cat);
                cat.Tables.Append(image);

                //Now Close the database
                ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                if (con != null)
                {
                    con.Close();
                }

                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            cat = null;
            return(result);
        }
 public bool switchDatabase(string databasename)
 {
     try {
         disconnect();
         string conStr = conectionString.Replace(database, databasename);
         database = databasename;
         if (conectionString.Contains("Provider=") == true)
         {
             adocon = new ADODB.Connection(conStr);
             adocon.Open();
         }
         else if (conectionString.Contains("Driver=") == true)
         {
             con = new OdbcConnection(conStr);
             con.Open();
         }
         else
         {
             mycon = new MySqlConnection(conStr);
             mycon.Open();
         }
         connect();
         this.getSchema();
         return(true);
     } catch (Exception e) {
         error = e.Message.ToString();
         return(false);
     }
 }
Beispiel #18
0
        private void DisplayResults()
        {
            //SS:01/03/2018:2018-R1:ABSEXCH-19796: When Running the ExchDVT.exe, SQL Admin Passwords are visible in dump file.
            ADODB.Connection conn = new ADODB.Connection();
            ADODB.Command    cmd  = new ADODB.Command();
            cmd.CommandText = "SELECT RCount = COUNT(*) " +
                              "FROM [common].[SQLDataValidation] " +
                              "WHERE UPPER(Severity) = 'HIGH' " +
                              "AND SchemaName = '" + CompanyCode + "'";
            cmd.CommandTimeout = 10000;

            if (conn.State == 0)
            {
                if (connPassword.Trim() == "")
                {
                    conn.Open();
                }
                else
                {
                    conn.Open(ExchequerCommonSQLConnection, "", connPassword.Trim(),
                              (int)ADODB.ConnectModeEnum.adModeUnknown);
                }
            }
            conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient;

            DataTable dataTable = new DataTable();

            cmd.CommandType      = ADODB.CommandTypeEnum.adCmdText;
            cmd.ActiveConnection = conn;
            ADODB.Recordset recordSet = null;
            object          objRecAff;

            try
            {
                recordSet = (ADODB.Recordset)cmd.Execute(out objRecAff, Type.Missing, (int)ADODB.CommandTypeEnum.adCmdText);
            }
            catch
            {
                throw;
            }

            for (int i = 0; i < recordSet.RecordCount; i++)
            {
                if (Convert.ToInt32(recordSet.Fields["RCount"].Value) == 0)
                {
                    // Posting Enabled
                    PostingEnabledDisabled(true, false);
                }
                else
                {
                    // Posting Disabled
                    PostingEnabledDisabled(false, false);
                }
            }

            File.Delete(fileString);

            Application.Exit();
        }
Beispiel #19
0
 public void Dispose()
 {
     if (conn != null)
     {
         conn.Close();
         conn = null;
     }
 }
Beispiel #20
0
        public static bool Gf_ExecSql(ADODB.Connection Conn, string sQuery)
        {
            bool returnValue = false;

            //Dim iCount As Integer
            object[,] OutParam = new object[3, 5];

            ADODB.Command adoCmd;

            try
            {
                //Db Connection Check
                if (GeneralCommon.M_CN1.State == 0)
                {
                    if (GeneralCommon.GF_DbConnect() == false)
                    {
                        return(returnValue);
                    }
                }

                Cursor.Current = Cursors.WaitCursor;

                //Ado Setting
                GeneralCommon.M_CN1.CursorLocation = ADODB.CursorLocationEnum.adUseServer;
                adoCmd = new ADODB.Command();

                Conn.BeginTrans();

                adoCmd.ActiveConnection = GeneralCommon.M_CN1;
                adoCmd.CommandText      = "UPDATE  GP_USTRESULT SET  UST_LOC= '',UST_REMARTS   = '' WHERE  PLATE_NO  = '05201206040102'";

                object null_object  = "";
                object null_object2 = "";
                adoCmd.Execute(out null_object, ref null_object2, -1);
                Conn.CommitTrans();
                adoCmd         = null;
                Cursor.Current = Cursors.Default;

                if (GeneralCommon.M_CN1.State != 0)
                {
                    GeneralCommon.M_CN1.Close();
                }
            }
            catch (Exception ex)
            {
                adoCmd = null;
                Conn.RollbackTrans();
                returnValue    = false;
                Cursor.Current = Cursors.Default;
                if (GeneralCommon.M_CN1.State != 0)
                {
                    GeneralCommon.M_CN1.Close();
                }
                GeneralCommon.Gp_MsgBoxDisplay((string)("Gf_ExecProcedure Error : " + ex.Message), "", "");
            }

            return(returnValue);
        }
Beispiel #21
0
        private void save_form()
        {
            try
            {
                //ADOconn.BeginTrans();
                ADODB.Recordset cus = new ADODB.Recordset();
                //ADOconn.BeginTrans();

                if (cmbgrp.Text == "")
                {
                    MessageBox.Show("Invalid User Group", "Invalid Entry");
                    return;
                }
                dgv1.EndEdit();
                ADODB.Connection ADOconn = new ADODB.Connection();
                ADOconn.Open("Provider=SQLOLEDB;Initial Catalog= " + decoder.InitialCatalog + ";Data Source=" + decoder.DataSource + ";", decoder.UserID, decoder.Password, 0);

                for (int i = 1; i < dgv1.RowCount; i++)
                {
                    if (dgv1["id", i].Value == null)
                    {
                        continue;
                    }
                    cus = new ADODB.Recordset();
                    sql = "SELECT * FROM userpriv where GROUP_NAME ='" + cmbgrp.Text + "' and form_id=" + dgv1["id", i].Value;
                    cus.Open(sql, ADOconn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, -1);
                    if (cus.RecordCount == 0)
                    {
                        cus.AddNew();
                    }
                    cus.Fields["GROUP_NAME"].Value = cmbgrp.Text;
                    cus.Fields["form_id"].Value    = dgv1["id", i].Value;
                    cus.Fields["ins"].Value        = dgv1["ins", i].Value;
                    cus.Fields["upd"].Value        = dgv1["upd", i].Value;
                    //cus.Fields["qry"].Value = dgv1["qry",i].Value;
                    cus.Fields["del"].Value       = dgv1["del", i].Value;
                    cus.Fields["dsp"].Value       = dgv1["dsp", i].Value;
                    cus.Fields["Menu_Name"].Value = dgv1["Menu_Name", i].Value;
                    cus.Update();
                }

                string grp = cmbgrp.Text;
                sql = "SELECT   distinct group_name  FROM UserPriv ";
                SqlDataAdapter adagrp = new SqlDataAdapter(sql, Conn);
                ///ada.TableMappings.Add("Table", "Leaders");
                DataSet grpds = new DataSet();

                adagrp.Fill(grpds, "UserPriv");
                cmbgrp.DisplayMember = "group_name";
                cmbgrp.DataSource    = grpds.Tables[0];
                cmbgrp.Text          = grp;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #22
0
 public void TestCreateConectionTheSaneWay()
 {
     ADODB.Connection connection = new ADODB.Connection();
     connection.Provider         = "sqloledb";
     connection.ConnectionString = String.Format("Server={0};Database={1};User Id={2};Password={3}",
                                                 this.server, this.database, this.user, this.password);
     connection.ConnectComplete += new ADODB.ConnectionEvents_ConnectCompleteEventHandler(TheConnectionComplete);
     connection.Open();
 }
Beispiel #23
0
 public void Return_SpreadSheet(string strSQL, string strPath)
 {
     ADODB.Connection adoConnection = new ADODB.Connection();
     ADODB.Recordset  objRecordset  = ReturnRecordset(strSQL, ref adoConnection);
     if (objRecordset.RecordCount > 0)
     {
         CreateSpreadSheet(objRecordset, strPath);
     }
 }
 private void ADODB_Close(ADODB.Connection _ad_Con)
 {
     try
     {
         _ad_Con.Close();
     }
     catch
     {
     }
 }
Beispiel #25
0
        /// <summary>
        /// 物料清单
        /// 保存、删除事件接口方法
        /// </summary>
        /// <param name="ds">传入的数据集</param>
        /// <param name="errmsg">用于返回的错误信息</param>
        /// <returns>true=操作成功;false=操作失败</returns>
        public bool DoAPI_DataSet(ref DataSet ds, ref string errmsg)
        {
            try
            {
                //获取插件上下文
                MomCallContext context = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取帐套库连接对象
                ADODB.Connection conn = context.BizDbConnection as ADODB.Connection;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = context.U8Login as U8Login.clsLogin;

                string eventIdentity = context.EventIdentity;

                if (ds is StandardBomDs)
                {
                    //(ds as StandardBomDs).WriteXml("C:\\" + eventIdentity.Replace("/", ".") + ".xml");
                }

                Biz.BizBase oper;
                switch (eventIdentity.ToLower())
                {
                //删除后
                case "u8api/bom/delete_after":
                    //DataSet delDs = ds.Copy();
                    //delDs.RejectChanges();
                    //oper = new U8.Interface.Bus.Event.SyncAdapter.Biz.StandBom(ref conn,delDs, login.UFDataConnstringForNet.ToString());
                    //oper.LinkDelete();
                    break;

                //保存前  制造参数设为保存并默认审核时,不会设审核事件。所以在添加保存前事件
                case "u8api/bom/save_before":
                //保存后
                case "u8api/bom/save_after":
                    oper = (Biz.BizBase)System.Reflection.Assembly.Load(U8.Interface.Bus.Config.ConfigUtility.EventBizDllName).CreateInstance(U8.Interface.Bus.Config.ConfigUtility.EventBizNamespace + "." + "Bom_bom",
                                                                                                                                              true, System.Reflection.BindingFlags.CreateInstance, null,
                                                                                                                                              new object[] { conn, ds, login.UFDataConnstringForNet.ToString(), "a" }, null, null);
                    //oper = new U8.Interface.Bus.Event.SyncAdapter.Biz.Factory.HM.Bom_bom(ref conn, ref ds, login.UFDataConnstringForNet.ToString());
                    using (System.Transactions.TransactionScope tra = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Suppress))
                    {
                        oper.Insert();
                    }
                    break;
                }

                return(true);
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
                return(false);
            }
        }
Beispiel #26
0
        public void DisConnect()
        {
            //
            if (con == null)
            {
                return;
            }

            con.Close();
            con = null;
        }
Beispiel #27
0
        public void Connect(string path)
        {
            //
            if (con != null)
            {
                return;
            }

            con = new ADODB.Connection();
            con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";", "", "", 0);
        }
Beispiel #28
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        CatalogClass openDatabase()
        {
            CatalogClass catalog = new CatalogClass();

            con = new Connection();
            try {
                con.Open(this.conString);
                catalog.ActiveConnection = con;
            } catch { catalog.Create(this.conString); }
            return(catalog);
        }
Beispiel #29
0
 public static DataTable GetDataTable(string strFileName)
 {
     ADODB.Connection oConn = new ADODB.Connection();
     oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
     string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
     ADODB.Recordset rs = new ADODB.Recordset();
     System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
     DataTable dt = new DataTable();
     rs.Open(strQuery, "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
         ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
     adapter.Fill(dt, rs);
     return dt;
 }
Beispiel #30
0
 /// <summary>
 /// Classe cria um objeto do tipo usuário que contém informações de um determinado usuário do sistema
 /// </summary>
 /// <param name="conexao">recebe um objeto do tipo ADODB.Connection para linkar ao banco de dados</param>
 public Usuarios(Connection conexaoArg)
 {
     conexao = conexaoArg;
     if (dados.State == 0)
     {
         dados.LockType       = LockTypeEnum.adLockOptimistic;
         dados.CursorLocation = CursorLocationEnum.adUseClient;
         dados.CursorType     = CursorTypeEnum.adOpenDynamic;
     }
     SQL = "SELECT usuarios.* FROM usuarios ORDER BY usuarios.matricula;";
     abreConexao();
     criaListaUsuarios();
     fechaConexao();
 }
Beispiel #31
0
 public DevADODBConn(string DSN)
 {
     try
     {
         if (conn == null)
         {
             conn = new ADODB.Connection();
             conn.Open(DSN, null, null, 0);
         }
     }
     catch (Exception ex)
     {
         //PublicLib.handleError("", this.GetType().Name, ex.Message);
     }
 }
Beispiel #32
0
        public static double Get_Currency_rate(double acc_no, string currency)
        {
            try
            {
                SqlConnectionStringBuilder decoder = new SqlConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["Con"].ConnectionString);

                SqlConnection Conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
                Conn.Close();
                Conn.Open();
                ADODB.Connection ADOconn = new ADODB.Connection();
                ADOconn.Open("Provider=SQLOLEDB;Initial Catalog= " + decoder.InitialCatalog + ";Data Source=" + decoder.DataSource + ";", decoder.UserID, decoder.Password, 0);

                string sql;


                sql = "SELECT C.currency_code as ac_currency,C.currency_rate as ac_rate,c1.currency_code, c1.currency_rate FROM currency_master AS C " +
                      "inner join accounts on def_currency=currency_CODE inner join currency_master as c1 on c1.currency_code='" + currency + "'  WHERE acc_no=" + acc_no;


                ADODB.Recordset tmp  = new Recordset();
                ADODB.Recordset tmp1 = new Recordset();
                tmp.Open(sql, ADOconn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic, -1);


                do
                {
                    if (tmp.Fields["ac_currency"].Value.ToString() == tmp.Fields["currency_code"].Value.ToString())
                    {
                        //return 1;
                        return(Convert.ToDouble(tmp.Fields["ac_rate"].Value));
                    }
                    else
                    {
                        return(Convert.ToDouble(tmp.Fields["ac_rate"].Value));
                    }

                    tmp.MoveNext();
                } while (!tmp.EOF);

                return(1);
            }


            catch (Exception ex)
            {
                return(1);
            }
        }
        public object[] db_access(string strSQL)
        {
            ADODB.Connection objCon;
            ADODB.Recordset objRec;
            object[,] dataRows;
            object[] dataSuite;
            string strCon;

            objCon = new ADODB.Connection();
            objRec = new ADODB.Recordset();

            //establish the connection string and open the database connection
            strCon = "driver={MySQL ODBC 5.1 Driver};server=107.22.232.228;uid=qa_people;pwd=thehandcontrols;" +
                "database=functional_test_data;option=3";

            objCon.Open(strCon);

            //execute the SQL and return the recrodset of results
            objRec = objCon.Execute(strSQL, out missing, 0);

            //populate a two dinmensional object array with the results
            dataRows = objRec.GetRows();

            //get a onedimensional array that can be placed into the Test Suite dropdown
            dataSuite = thinArray(dataRows);

            //close the recordset
            objRec.Close();

            //close the database connection
            objCon.Close();

            return dataSuite;
        }
 private bool Connect(out string errorMessage)
 {
     try
     {
         errorMessage = "";
         dbConn = new ConnectionClass();
         dbConn.Open(connectionString, txtUser, txtPassword, 0);
         dbConn.DefaultDatabase = strCatalogName;
         return true;
     }
     catch (Exception e)
     {
         errorMessage = e.Source + " " + e.Message;
         //MessageBox.Show(e.Source + " " + e.Message);
         // Disconnect();
         return false;
     }
 }
        private object[] db_access(string strSQL, ref int fndExcep)
        {
            ADODB.Connection objCon;
                ADODB.Recordset objRec;
                object[,] dataRows;
                object[] dataSuite;
                string strCon;
                string tmpString;

                dataSuite = null;
                objCon = new ADODB.Connection();
                objRec = new ADODB.Recordset();
                try
                {
                    //establish the connection string and open the database connection
                    strCon = "driver={MySQL ODBC 5.1 Driver};server=107.22.232.228;uid=qa_people;pwd=thehandcontrols;" +
                        "database=functional_test_data;option=3";

                    objCon.Open(strCon);

                    //execute the SQL and return the recrodset of results
                    objRec = objCon.Execute(strSQL, out missing, 0);

                    //populate a two dinmensional object array with the results
                    dataRows = objRec.GetRows();

                    //get a one dimensional array that can be placed into the Test Suite dropdown
                    dataSuite = thinArray(dataRows);

                    //close the recordset
                    objRec.Close();

                    //close the database connection
                    objCon.Close();
                }
                catch (Exception e)
                {
                    tmpString = e.Message;

                    //set the variable to ternibate the script
                    fndExcep = -1;

                }

                return dataSuite;
        }
Beispiel #36
0
        public void DisConnect()
        {
            //
            if (con == null)
                return;

            con.Close();
            con = null;
        }
Beispiel #37
0
        public void Connect(string path)
        {
            //
            if (con != null)
                return;

            con = new ADODB.Connection();
            con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";", "", "", 0);
        }
 public MiniManagerJetDB()
 {
     _myAccessConn = new ADODB.Connection();
     _myAccessConn.ConnectionString = _cnstr;
 }
        private void btnExtract_Click(object sender, EventArgs e)
        {
            object[] rtnList;
                string[] lstArray;
                string argID;
                string itmList;
                string strCon;
                string steID;
                string thsFuncID;
                string tstID;
                int itmCount;
                int argNum;
                int numSteps;
                int numTests;
                ArrayList slctList;
                ADODB.Connection objCon;
                DialogResult valExtract;

                itmList = "";
                itmCount = lstCaseSelect.Items.Count;
                lstArray = new string[itmCount];
                strCon = "driver={MySQL ODBC 5.1 Driver};server=107.22.232.228;uid=qa_people;pwd=thehandcontrols;" +
                    "database=functional_test_data;option=3";

                objCon = new ADODB.Connection();

                //set lstArray to all items in the lstCaseSelect box
                for (int x = 0; x < itmCount; x++)
                    lstArray[x] = lstCaseSelect.Items[x].ToString();

                slctList = new ArrayList(itmCount);

                for (int x = 0; x < itmCount; x++)
                {
                    //get a carriage return delimited string of all entries in lstCaseSelect
                    itmList = itmList + lstArray[x] + "\r\n";

                    //add the items to slctList whiule iterating through the lstCaseSelect items
                    slctList.Add(lstCaseSelect.Items[x]);
                }

                //show an information message box with an escape option
                valExtract = MessageBox.Show("You will be extracting the following tests from the database \r\n\r\n" + itmList + "\r\nSelect Yes to continue. Select No to return to TestDriver ",
                        "Database Test Extractor", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                if (valExtract == DialogResult.Yes)
                {
                    for (int cnt = 0; cnt < itmCount; cnt++)
                    {
                        string strSQL;

                        //get the function ID aznd number of steps from the test table
                        strSQL = "SELECT id, number_of_steps FROM test WHERE name = '" + lstArray[cnt] + "'";
                        rtnList = db_access(strSQL, ref fndExcep);
                        tstID = rtnList[0].ToString();

                        if (rtnList[1].ToString() != "")
                        {
                            numSteps = Convert.ToInt32(rtnList[1]);
                        }
                        else
                        {
                            numSteps = 0;
                        }

                        //open a connection  to the database
                        objCon.Open(strCon);

                        //set a for loop with x + 1 being the current step number being processed
                        //renmove all steps that are not used in any other tests (recCount = 1)
                        for (int x = 0; x < numSteps; x++)
                        {
                            //get the function id and arg set id using the
                            strSQL = "SELECT function_id, argument_set_id FROM step WHERE (test_id = '" + tstID + "' AND number = '" + (x + 1).ToString() + "')" ;
                            rtnList = db_access(strSQL, ref fndExcep);
                            thsFuncID = rtnList[0].ToString();
                            argID = rtnList[1].ToString();

                            strSQL = "DELETE FROM step WHERE argument_set_id = '" + argID + "' AND function_id = '" + thsFuncID +
                                    "' AND test_id = '" + tstID + "' AND number = '" + (x + 1).ToString() + "'";
                            objCon.Execute(strSQL, out missing, 0);

                            //if an argument set is no longer used, gert rid of it
                            strSQL = "SELECT COUNT(*) FROM step WHERE argument_set_id = '" + argID + "'";
                            rtnList = db_access(strSQL, ref fndExcep);
                            argNum = Convert.ToInt32(rtnList[0]);

                            if (argNum == 0)
                            {
                                strSQL = "DELETE FROM argument WHERE argument_set_id = '" + argID + "'";
                                objCon.Execute(strSQL, out missing, 0);

                                //delete t
                                strSQL = "DELETE FROM argument_set WHERE id = '" + argID + "'";
                                objCon.Execute(strSQL, out missing, 0);
                            }
                        }

                        //get the regression suite id from the test being extracted
                        strSQL= "SELECT regression_suite_id FROM test WHERE id = '" + tstID + "'";
                        rtnList = db_access(strSQL, ref fndExcep);
                        steID = rtnList[0].ToString();

                        //delete the test from the test rable
                        strSQL = "DELETE FROM test WHERE  id = '" + tstID + "'";
                        objCon.Execute(strSQL, out missing, 0);

                        //get the number of tests from in the regression suite. If delete the regression suite
                        strSQL = "SELECT COUNT(*) FROM test WHERE regression_suite_id = '" + steID + "'";
                        rtnList = db_access(strSQL, ref fndExcep);
                        numTests = Convert.ToInt32(rtnList[0]);

                        //if there are no tests left in the database delete the suite
                        if (numTests == 0)
                        {
                            strSQL = "DELETE FROM regression_suite WHERE id = '" + steID + "'";
                            objCon.Execute(strSQL, out missing, 0);
                        }

                        //close the database connection
                        objCon.Close();

                        //get the list of
                        for (int x = 0; x < slctList.Count; x++)
                        {
                            if (Convert.ToString(slctList[x]) == lstArray[cnt])
                            {
                                slctList.Remove(lstArray[cnt]);
                                break;
                            }
                        }
                    }

                    lstCaseSelect.Items.Clear();
                }
        }