Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
コード例 #1
0
ファイル: Form1.cs プロジェクト: SaschaP1802/Csharp-Login
        public bool trylogin(string username, string passwort)
        {
            MySqlConnection con = new MySqlConnection("host=5.135.97.241;user=lesen;password=test234;database=test;");
            MySqlCommand cmd = new MySqlCommand("select * FROM login WHERE user = '******' AND pass = '******' AND datum >= CURRENT_DATE() - INTERVAL 0 DAY ;");
            cmd.Connection = con;
            con.Open();

            MySqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read() != false)
            {

                if (reader.IsDBNull(0) == true)
                {
                    cmd.Connection.Close();
                    reader.Dispose();
                    cmd.Dispose();
                    return false;

                }
                else
                {
                    cmd.Connection.Close();
                    reader.Dispose();
                    cmd.Dispose();
                    return true;

                }
            }
            else
            {
                return false;
            }
        }
コード例 #2
0
ファイル: DataService.cs プロジェクト: andyshao/aushelper
        /// <summary>
        /// 一个公用interface执行所有非 select语句
        /// </summary>
        /// <param name="non_query_type"></param>
        /// <returns>返回影响数据库几行</returns>
        public int GeneralNonSelectQuery(MySqlCommand cmd)
        {
            int iReturn = 0;
            string connStr = sql.GetSQL(sql.SQL.S_CONNECTION_STR);
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;

                iReturn = cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
            catch (Exception ex)
            {
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
            }

            return iReturn;
        }
コード例 #3
0
 public static string getFirstRow(string strSql)
 {
     MySqlConnection connection = Getconn();
     if (connection == null) throw new ArgumentNullException("connection");
     connection.Open();
     MySqlCommand cmd = new MySqlCommand(strSql, connection);
     MySqlDataAdapter da = new MySqlDataAdapter(cmd);
     DataSet ds = new DataSet();
     da.Fill(ds);
     DataTable dt = ds.Tables[0];
     for (int i = 0; i < dt.Rows.Count; i++)
     {
         if (dt.Rows[i][0] != null)
         {
             da.Dispose();
             cmd.Dispose();
             connection.Close();
             return dt.Rows[i][0].ToString();
         }
     }
     da.Dispose();
     cmd.Dispose();
     connection.Close();
     return null;
 }
コード例 #4
0
ファイル: MySqlHelper.cs プロジェクト: 0611163/DaQin
 /// <summary>
 /// 执行SQL语句,返回影响的记录数
 /// </summary>
 /// <param name="SQLString">SQL语句</param>
 /// <returns>影响的记录数</returns>
 public int ExecuteSql(string SQLString)
 {
     using (MySqlConnection connection = new MySqlConnection(connectionString))
     {
         using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
         {
             try
             {
                 connection.Open();
                 int rows = cmd.ExecuteNonQuery();
                 return rows;
             }
             catch (MySql.Data.MySqlClient.MySqlException e)
             {
                 connection.Close();
                 throw new Exception(e.Message);
             }
             finally
             {
                 cmd.Dispose();
                 connection.Close();
             }
         }
     }
 }
コード例 #5
0
        public static int GetNumberOfRowsInATable()
        {
            int numberOfRows = 0;
            try
            {
                string mySqlConnectionString = MakeMySqlConnectionString();
                var conn = new MySqlConnection {ConnectionString = mySqlConnectionString};

                using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM " + Program.selectedEventName, conn))
                {
                    conn.Open();
                    numberOfRows = int.Parse(cmd.ExecuteScalar().ToString());
                    conn.Close();
                    cmd.Dispose();
                    return numberOfRows;
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine(ex.Message);
                ConsoleWindow.WriteLine("Error Code: " + ex.ErrorCode);
                ConsoleWindow.WriteLine(ex.Message);
            }
            return numberOfRows;
        }
コード例 #6
0
ファイル: LoginManager.cs プロジェクト: MeVini/MyProjects
 public Login1 CheckExternalEmail(String Email)
 {
     MySqlCommand cmd = new MySqlCommand("CheckExternalEmail", connection);
     cmd.CommandType = System.Data.CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@MEmail", Email);
     MySqlDataReader reader = cmd.ExecuteReader();
     if (reader.HasRows)
     {
         Login1 login1 = new Login1();
         if (reader.Read())
         {
             login1.Id = reader.GetInt32("Id");
             login1.FirstName = reader.GetString("FirstName");
             login1.LastName = reader.GetString("LastName");
             login1.Email = reader.GetString("Email");
             login1.Password = reader.GetString("Password");
             login1.FavouriteGenre = reader.GetString("FavouriteGenre");
         }
         return login1;
     }
     else
     {
         reader.Dispose();
         cmd.Dispose();
         return null;
     }
 }
コード例 #7
0
ファイル: DBHelper.cs プロジェクト: CasBill/Hearthstone2048
 protected MySqlDataReader executeSqlCommandDataReader(String sqlCommandStr, List<MySqlParameter> paramList)
 {
     MySqlConnection sqlCon = this.getMySqlConnection();
     try
     {
         sqlCon.Open();
         MySqlCommand sqlCommand = new MySqlCommand(sqlCommandStr, sqlCon);
         if (paramList != null && paramList.Count > 0)
         {
             foreach (MySqlParameter param in paramList)
             {
                 sqlCommand.Parameters.Add(param);
             }
         }
         MySqlDataReader sqlReader = sqlCommand.ExecuteReader();
         sqlCommand.Dispose();
         return sqlReader;
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         sqlCon.Close();
         sqlCon.Dispose();
     }
 }
コード例 #8
0
ファイル: StateForm.cs プロジェクト: GuardAngelY/wowitemmaker
 public void DBAdapter(object SQL)
 {
     MyInvoke mi = new MyInvoke(miCMDSQL);
     MyInvoke end = new MyInvoke(miEND);
     MainForm f1 = new MainForm();
     UpdateItemInfo uii = new UpdateItemInfo(f1.GetItemInfo);
     DataSet ds = new DataSet();
     MySqlConnection Conn = new MySqlConnection(MainForm.GetConnStr());
     MySqlCommand setname = new MySqlCommand("set names 'gbk';", Conn);
     MySqlDataAdapter adp = new MySqlDataAdapter(SQL.ToString(), Conn);
     try
     {
         Conn.Open();
         setname.ExecuteNonQuery();
         setname.Dispose();
         adp.Fill(ds);
         this.Invoke(uii, ds);
         this.Invoke(mi, "执行成功!");
         Thread.Sleep(1000);
         this.Invoke(end, "true");
     }
     catch (Exception err)
     {
         ItemInfo.Stat = false;
         this.Invoke(mi, "执行失败!");
         this.Invoke(end, err.Message);
     }
 }
コード例 #9
0
        public void editarRegistros()
        {
            this.comenzarConexion();

            Console.Write("Ingrese el ID del registro a modificar: ");
            id=int.Parse(Console.ReadLine());

            MySqlCommand micomando = new MySqlCommand(this.queryBuscar(),this.EscuelaConexion);
            MySqlDataReader myReader = micomando.ExecuteReader();

            if(myReader.Read())
            {
                Console.WriteLine("Nombre"); nombre = Console.ReadLine();
                Console.WriteLine("Codigo"); codigo = int.Parse(Console.ReadLine());
                Console.WriteLine("Telefono"); telefono = int.Parse(Console.ReadLine());
                Console.WriteLine("Email"); email = Console.ReadLine ();

                string sql = "UPDATE `Persona` SET `nombre`='" + nombre + "',`codigo`='" + codigo + "',`telefono`='"+ telefono +"'" +
                             ",`email`='"+ email +"' WHERE (`id`='" + id + "')";
                myReader.Close();
                myReader =null;
                micomando.Dispose();
                micomando=null;

                this.ejecutarComando(sql);
                Console.WriteLine("Registro con ID "+id+" modificado con EXITO");

            }
            else
            Console.WriteLine("ID "+ id +" NO EXISTE");
        }
コード例 #10
0
ファイル: MysqlConn.cs プロジェクト: dream-young-soul/soul
        //创建军团 成功返回军团id,失败返回-1
        public static int CreateLegion(LegionInfo info)
        {
            MySqlCommand command;
            info.name = Coding.GB2312ToLatin1(info.name);
            info.notice = Coding.GB2312ToLatin1(info.notice);
            String leader_name = Coding.GB2312ToLatin1(info.leader_name);
            String sql = String.Format(MysqlString.CREATE_LEGION, info.name, info.title, info.leader_id, leader_name, info.money, info.notice);
            String utf_sql = sql;
            command = new MySqlCommand(utf_sql, MysqlConn.GetConn());
            MysqlConn.Conn_Open();
            command.ExecuteNonQuery();
            MysqlConn.Conn_Close();
            command.Dispose();

            //取主键-- 不能用于多线程或者多个程序操作该数据库。。切记
            String _key = "select max(id) from cq_legion";
            command = new MySqlCommand(_key, MysqlConn.GetConn());
            MysqlConn.Conn_Open();
            MySqlDataReader reader = command.ExecuteReader();
            int ret = -1;
            reader.Read();
            if (reader.HasRows)
            {
                ret =Convert.ToInt32(reader[0].ToString());
            }
            MysqlConn.Conn_Close();
            command.Dispose();
            return ret;
        }
コード例 #11
0
 private void GetItemsDataSet(object mangosDB)
 {
     string SQL = "SELECT entry,name FROM item_template;";
     MyReceiverInvoke mi = new MyReceiverInvoke(invokeDataGridView);
     MySqlConnection Conn = new MySqlConnection(sManager.GetConnStr());
     MySqlCommand chgDB = new MySqlCommand("USE " + mangosDB.ToString() + ";", Conn);
     MySqlCommand setname = new MySqlCommand("set names 'gbk';", Conn);
     MySqlDataAdapter adp = new MySqlDataAdapter(SQL, Conn);
     try
     {
         this.Invoke(mi, new object[] { 1, "正在读取物品信息..." });
         Conn.Open();
         setname.ExecuteNonQuery();
         setname.Dispose();
         chgDB.ExecuteNonQuery();
         chgDB.Dispose();
         ItemsSet = new DataSet();
         adp.Fill(ItemsSet);
         adp.Dispose();
         if (ItemsSet.Tables[0].Rows.Count == 0)
         {
             throw new Exception("没有找到任何物品!");
         }
         this.Invoke(mi, new object[] { 2, string.Empty });
     }
     catch (Exception err)
     {
         this.Invoke(mi, new object[] { 0, err.Message });
     }
     finally
     {
         Conn.Close();
     }
 }
コード例 #12
0
        public ArrayList ObtenerDatos()
        {
            this.IniciarConeccion();
            MySqlCommand Comando = new MySqlCommand(this.Query(),this.Conectado);

            MySqlDataReader LeerSQL = Comando.ExecuteReader();

            ArrayList DatosTabla = new ArrayList();

            while (LeerSQL.Read())
            {
                Datos datos = new Datos();
                datos.nombre = LeerSQL["Nombre"].ToString();
                datos.apellido = LeerSQL["Apellido"].ToString();
                datos.domicilio = LeerSQL["Domicilio"].ToString();
                datos.fecha = LeerSQL["Fecha"].ToString();

                DatosTabla.Add(datos);
            }
            Comando.Dispose();
            Comando = null;

            LeerSQL.Close();
            LeerSQL = null;

            this.CerrarConeccion();

            return DatosTabla;
        }
コード例 #13
0
ファイル: UserManager.cs プロジェクト: sujiantao/Su.BaoLinks
        /// <summary>
        /// 创建账户
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static Account CreateAccount(Account account)
        {

            // 检查邮箱是否有重复
            var existEmailAccounts = SearchAccountsByEmail(account.Email);
            if(existEmailAccounts.Any())
                throw new Exception("邮箱已经被注册过了,请换一个邮箱注册");
            var existNameAccounts = SearchAccountsByName(account.Name);
            if(existNameAccounts.Any())
                throw new Exception("用户名已经被注册过了,请换一个用户名注册");

            string query = "INSERT INTO account(Name,Email,Password,IsActive,EnumDataEntityStatus) values('" +
                           account.Name + "','" + account.Email + "','" + account.Password + "'," + account.IsActive +
                           "," + (int)account.EnumDataEntityStatus + ")";

            MySqlCommand myCommand = new MySqlCommand(query, MyConnection);
            MyConnection.Open();
            int exeCount = myCommand.ExecuteNonQuery();
            try
            {
                if (exeCount > 0)
                {
                    return account;
                }
            }
            finally
            {
                myCommand.Dispose();
                MyConnection.Close();
            }
            return null;
        }
コード例 #14
0
ファイル: Database.cs プロジェクト: samfromdeath/CSharpServer
 public static void DisposeMysql(MySqlCommand obj)
 {
     if (obj != null)
     {
         obj.Dispose();
     }
 }
コード例 #15
0
ファイル: ImageDAO.cs プロジェクト: vincentpaca/diia
 public int count(string pTags, int pTagCount, DateTime pFrom, DateTime pTo)
 {
     try
     {
         int _count = 0;
         MySqlCommand _adapter = new MySqlCommand("call spCountImages(\"" + pTags + "\"," + pTagCount + ",'" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", pFrom) + "','" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", pTo) + "')", GlobalVariables.goMySqlConnection);
         try
         {
             try
             {
                 _count = int.Parse(_adapter.ExecuteScalar().ToString());
             }
             catch
             {
                 _count = 0;
             }
             return _count;
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             _adapter.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #16
0
ファイル: ANS_GROUP_INVITE.cs プロジェクト: harleyknd1/rAPB
 public ANS_GROUP_INVITE(String charName, WorldClient client)
     : base((UInt32)Opcodes.ANS_GROUP_INVITE)
 {
     MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM `characters` WHERE `name`= @name", WorldServer.Database.Connection.Instance);
     try
     {
         cmd.Prepare();
         cmd.Parameters.AddWithValue("@name", charName);
         Byte rows = Convert.ToByte(cmd.ExecuteScalar());
         if (client.Name == charName) WriteUInt32Reverse((uint)ResponseCodes.RC_GROUP_INVITE_SELF);
         else if (client.Name != charName)
         {
             if (rows < 1) WriteUInt32Reverse((uint)ResponseCodes.RC_GROUP_INVITE_NOT_FOUND);
             else if (rows >= 1)
             {
                 WriteUInt32((uint)ResponseCodes.RC_SUCCESS);
                 WriteParsedString(charName);
             }
         }
     }
     finally
     {
         cmd.Dispose();
     }
 }
コード例 #17
0
        public int ExecuteNonQuery(List<string> sqlList)
        {
            int rowsUpdated = 0;
            try
            {
                var con = CONNECTION.OpenCon();

                foreach (var sql in sqlList)
                {
                    var cmd = new MySqlCommand(sql, con);
                    rowsUpdated += cmd.ExecuteNonQuery();

                    cmd.Dispose();
                }

                CONNECTION.CloseCon(con);
            }
            catch (Exception ex)
            {
                SLLog.WriteError(new LogData
                {
                    Source = ToString(),
                    FunctionName = "ExecuteNonQuery Error!",
                    Ex = ex,
                });
                return -1;
            }

            return rowsUpdated;
        }
コード例 #18
0
ファイル: Log.cs プロジェクト: rolignu2/MyPlumon
        /// <summary>
        /// guarda cualquier error producido en algun proceso del programa
        /// </summary>
        /// <param name="error">descripcion del error</param>
        /// <param name="sector">sector donde se produjo</param>
        /// <param name="id_user">uaurio a quien se le produjo (opcional)</param>
        public static void Set_Log_Error( string error, string sector, string id_user = null)
        {
            string fecha = null;
            fecha = Seguridad.FormatoFecha(DateTime.Now.Year.ToString()
                , DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString());

            try
            {
                Conexion conn = new Conexion();
                conn.IniciarConexion();
                if (conn == null)
                           return;

                if (id_user == null) id_user = "******";
                string mysql = "INSERT INTO log_ (id_user , error , sector , fecha) VALUES ('" + id_user + "','" + error + "','" + sector + "','" + fecha + "')";
                MySqlCommand cmd = new MySqlCommand(mysql, conn.GetConexion);
                MySqlDataReader read = cmd.ExecuteReader();
                if(read.RecordsAffected < 1)
                    TempLog.Add(error + "," + sector + "," + id_user + "," + fecha);
                cmd.Dispose();
                read.Dispose();
                conn.CerrarConexion();
            }
            catch
            {
                TempLog.Add(error + "," + sector + "," + id_user + "," + fecha);
            }
        }
コード例 #19
0
ファイル: ImageTagDAO.cs プロジェクト: vincentpaca/diia
 public bool delete(object poImageTag)
 {
     try
     {
         loImageTag = poImageTag;
         loadAttributes();
         MySqlCommand _delete = new MySqlCommand("call spDeleteImageTag('" + lTag + "','" + lImageId + "','" + GlobalVariables.goLoggedInUser + "')", GlobalVariables.goMySqlConnection);
         try
         {
             int _rowsAffected = _delete.ExecuteNonQuery();
             if (_rowsAffected > 0)
                 return true;
             return false;
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             _delete.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #20
0
ファイル: registro.cs プロジェクト: RosarioOAguilar/Practica8
        public void mostrarconexion()
        {
            this.abrirConexion();
            MySqlCommand myCommand = new MySqlCommand(this.querySelect(),
                                                      myConnection);
            MySqlDataReader myReader = myCommand.ExecuteReader();
            while (myReader.Read()){
                string id = myReader["id"].ToString();
                string nombre = myReader["Nombre"].ToString();
                string codigo = myReader["Codigo"].ToString();
                string telefono = myReader["Telefono"].ToString();
                string email = myReader["Email"].ToString();
                Console.WriteLine("ID: " + id +
                                  " Nombre: " + nombre +
                                  " Codigo: " + codigo +
                                  " Telefono:" + telefono +
                                  " Email:" + email);
            }

            myReader.Close();
            myReader = null;
            myCommand.Dispose();
            myCommand = null;
            this.cerrarConexion();
        }
コード例 #21
0
        public void eliminarRegistro()
        {
            this.comenzarConexion();

            Console.Write("ID del registro a eliminar: ");
            id=int.Parse(Console.ReadLine ());

            MySqlCommand micomando = new MySqlCommand(this.queryBuscar(),this.EscuelaConexion);
            MySqlDataReader myReader = micomando.ExecuteReader();

            if(myReader.Read ())
            {
                string sql = "DELETE  FROM `Persona` WHERE id="+id;

                myReader.Close();
                myReader =null;
                micomando.Dispose();
                micomando=null;

                this.ejecutarComando(sql);
                Console.WriteLine("SE ELIMINO EL ID "+id+" CON EXITO");

            }
            else
            Console.WriteLine ("ID "+id+" NO EXISTE");

            this.cerrarConexion();
        }
コード例 #22
0
ファイル: DBWorker.cs プロジェクト: PavelSk1997/KPIproj
        /// <summary>
        /// Inputs a new row with file and iformation about it to DB 
        /// </summary>
        /// <param name="filePath">Path to file</param>
        /// <param name="table">Table in DB</param>
        public static void SetValue(Dictionary<string, object> info)
        {
            Init();

            string queryString = string.Format(@"INSERT INTO new_table (Color, Mark, Number, Owner) VALUES ('{0}','{1}','{2}','{3}')",
                info["Color"], info["Mark"], info["Number"], info["Owner"]);
                
            using (MySqlConnection con = new MySqlConnection())
            {
                con.ConnectionString = mysqlCSB.ConnectionString;

                MySqlCommand mainCommand = new MySqlCommand(queryString, con);
                MySqlCommand timeoutCommand = new MySqlCommand("set net_write_timeout = 99999999; set net_read_timeout = 9999999", con);

                try
                {
                    con.Open();
                    timeoutCommand.ExecuteNonQuery();
                    mainCommand.CommandText = queryString;
                    mainCommand.ExecuteNonQuery();

                    con.Close();
                    mainCommand.Dispose();
                }
                catch (Exception e)
                {
                    
                }
            }
        }
コード例 #23
0
ファイル: Update.aspx.cs プロジェクト: mrhanti/getiteasy
    protected void Page_Load(object sender, EventArgs e)
    {
        topics_ids = new ArrayList();

        dbConnection = new MySqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
        dbConnection.Open();

        slctTopics = new MySqlCommand("SELECT t_id FROM topics", dbConnection);
        dReaderTopics = slctTopics.ExecuteReader();

        while (dReaderTopics.Read())
        {
            topics_ids.Add(dReaderTopics[0].ToString());
            counter++;
        }

        dReaderTopics.Close();
        slctTopics.Dispose();

        while (i < counter)
        {
            updtTopicsNumberOfVideos = new MySqlCommand("UPDATE topics SET t_nb_videos=(SELECT count(*) FROM videos WHERE t_id=" + topics_ids[i].ToString() + ") WHERE t_id=" + topics_ids[i].ToString(), dbConnection);
            updtTopicsNumberOfVideos.ExecuteNonQuery();
            updtTopicsNumberOfVideos.Dispose();
            i++;
        }
    }
コード例 #24
0
ファイル: ImageDAO.cs プロジェクト: vincentpaca/diia
 public bool delete(string pImageID)
 {
     try
     {
         MySqlCommand _delete = new MySqlCommand("call spDeleteImage('" + pImageID + "')", GlobalVariables.goMySqlConnection);
         try
         {
             int _rowsAffected = _delete.ExecuteNonQuery();
             if (_rowsAffected > 0)
                 return true;
             return false;
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             _delete.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #25
0
        public static ResponseStruct DeleteAllImages()
        {
            ResponseStruct Result;
            try
            {
                MySqlConnection DBConnection = new MySqlConnection(OverallInformations.TradingSystemDBConnectionString);
                DBConnection.Open();
                string SQLQuery = "TRUNCATE TABLE images_from_players";
                MySqlCommand DBCommand = new MySqlCommand(SQLQuery, DBConnection);
                DBCommand.ExecuteNonQuery();
                DBCommand.Dispose();
                DBConnection.Dispose();

                string[] ImageFileNames = Directory.GetFiles(OverallInformations.ImagePath, "*.*", SearchOption.AllDirectories);
                foreach (string anImageFileName in ImageFileNames)
                {
                    File.Delete(anImageFileName);
                }

                Result = new ResponseStruct() { Status = ResponseStatusType.Done, Broadcast = new List<string>() { "Đã xóa." } };
            }
            catch (Exception ex)
            {
                LauncherServer.OutputMessage(String.Format("[Server]: DeleteAllImages() | Error: {0}", ex.Message), LauncherServer.MessageType.Error);
                Result = new ResponseStruct() { Status = ResponseStatusType.Fail, Error = new List<string>() { ex.Message }, Broadcast = new List<string>() { "Kiểm tra hệ thống để xác định nguyên nhân." } };
            }
            return Result;
        }
コード例 #26
0
        public bool _Adicionar(Lojas _loja, string stringConnect)
        {
            try
            {
                MySqlConnection conexao = new MySqlConnection(stringConnect);
                var sql = new MySqlCommand("INSERT INTO `Loja` (`L_Loja` , `L_Responsavel` , `L_Telefone` , `L_Email` ) VALUES (@L_Loja, @L_Responsavel, @L_Telefone, @L_Email);", conexao);

                sql.Parameters.AddWithValue("@L_Loja", _loja.l_loja);
                sql.Parameters.AddWithValue("@L_Responsavel", _loja.l_responsavel);
                sql.Parameters.AddWithValue("@L_Telefone", _loja.l_telefone);
                sql.Parameters.AddWithValue("@L_Email", _loja.l_email);

                conexao.Open();
                sql.ExecuteScalar();
                if (conexao.State == ConnectionState.Open)
                {
                    conexao.Close();
                    conexao.Dispose();
                }
                sql.Dispose();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
コード例 #27
0
        public static Session GetSession(string SessionToken)
        {
            MySqlConnection dbcon = new MySqlConnection(connectionString);
            MySqlCommand command = new MySqlCommand();
            dbcon.Open();

            command.CommandText = "SELECT * FROM sessions WHERE SessionToken=@SessionToken";
            command.Parameters.AddWithValue("@SessionToken", Program.sessionToken);
            command.Connection = dbcon;
            command.ExecuteNonQuery();

            Session session = new Session();
            MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                session.DateCreated = (int)reader["DateCreated"];
                session.LastHeartbeat = (int)reader["LastHeartbeat"];
            }

            dbcon.Close();
            dbcon.Dispose();
            command.Dispose();

            return session;
        }
コード例 #28
0
ファイル: DB.cs プロジェクト: glebmillenium/projects
        public static int addHistoryId(string reason)
        {
            MySqlConnection Connection = new MySqlConnection("Data Source=" + MySQL_host + ";" +
                                                         "Port=" + MySQL_port + ";" +
                                                         "User Id=" + MySQL_uid + ";" +
                                                         "Password="******";" +
                                                         "database=" + MySQL_db + ";");
            MySqlCommand Query = new MySqlCommand();
            Query.Connection = Connection;

            try
            {
                Connection.Open();
            }
            catch (MySqlException SSDB_Exception)
            {
                return -1;
            }

            Query.CommandText = "INSERT INTO `history` (`reason`) VALUES('" + reason + "'); SELECT last_insert_id();";
            MySqlDataReader MyReader = Query.ExecuteReader();// Запрос, подразумевающий чтение данных из таблиц.
            string str = "";;

            while (MyReader.Read())
            {
                str += (MyReader.GetValue(0));
            }

            MyReader.Close();
            Query.Dispose();
            Connection.Close();
            int res;
            if(Int32.TryParse(str, out res)) return res; else return -1;
        }
コード例 #29
0
        public static int GetNumberOfRowsThatContainAValue(int teamNumber)
        {
            int numberOfRows = 0;
            try
            {
                string mySqlConnectionString = MakeMySqlConnectionString();
                var conn = new MySqlConnection {ConnectionString = mySqlConnectionString};

                string mySQLCommantText = String.Format("SELECT COUNT(*) FROM {0} WHERE TeamNumber={1}", Program.selectedEventName, teamNumber);
                using (var cmd = new MySqlCommand(mySQLCommantText, conn))
                {
                    conn.Open();
                    numberOfRows = int.Parse(cmd.ExecuteScalar().ToString());
                    conn.Close();
                    cmd.Dispose();
                    return numberOfRows;
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine(ex.Message);
            }
            return numberOfRows;
        }
コード例 #30
0
ファイル: Database.cs プロジェクト: halo779/EoEmu
 /// <summary>
 /// Used to set password if the password set on first login is active
 /// </summary>
 /// <param name="Account">Account name</param>
 /// <param name="Pass">given password</param>
 public static void SetPass(string Account, string Pass)
 {
     MySqlCommand Cmd = new MySqlCommand("UPDATE `accounts` SET `Password` = \"" + Pass + "\" WHERE `AccountID` = \"" + Account + "\"", DatabaseConnection.NewConnection());
     Cmd.ExecuteNonQuery();
     Cmd.Connection.Close();
     Cmd.Dispose();
 }
コード例 #31
0
    //new code from crackstation

    private void registerUserWithSlowHash()
    {
        try
        {

            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString();
            con = new MySql.Data.MySqlClient.MySqlConnection(connString);
            con.Open();
            querystr = "";

            querystr = "INSERT INTO mydatabase.registertable(Username,DOB,Mobile,slowHashSalt)" +
               "VALUES(?username,?datebirth,?mob,?slowhashsalt)";
            cmd = new MySqlCommand(querystr, con);
            cmd.Parameters.AddWithValue("?username", Username.Text);
            cmd.Parameters.AddWithValue("?datebirth", dob.Text);
            cmd.Parameters.AddWithValue("?mob", mob.Text);

            string saltHashReturned = PasswordStorage.CreateHash(passwd.Text);
            int commaIndex = saltHashReturned.IndexOf(":");
            string extractedString = saltHashReturned.Substring(0, commaIndex);
            commaIndex = saltHashReturned.IndexOf(":");
            extractedString = saltHashReturned.Substring(commaIndex + 1);
            commaIndex = extractedString.IndexOf(":");
            string salt = extractedString.Substring(0, commaIndex);

            commaIndex = extractedString.IndexOf(":");
            extractedString = extractedString.Substring(commaIndex + 1);
            string hash = extractedString;
            //from the first : to the second : is the salt
            //from the second : to the end is the hash
            cmd.Parameters.AddWithValue("?slowhashsalt", saltHashReturned);
            cmd.ExecuteReader();
            con.Close();
            //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('You have been Succesfully Registered! Click O.K to navigate to Homepage.');window.location.replace('Default.aspx');</script>");
            cmd.Dispose();
            clearfields();
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >alertMX('Registered Succesfully! Click OK');</script>");
            //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >myalert('Test', 'This is a test modal dialog');</script>");
        }
        catch (MySqlException reg)
        {
            Console.WriteLine("{0}+MySql Exceptions", reg);
        }
        finally
        {
            if (!(con == null))
            {
                con.Dispose();
            }
        }

    }
コード例 #32
0
    private void activateuser()
    {
        try
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString();
            con = new MySql.Data.MySqlClient.MySqlConnection(connString);
            con.Open();
            querystr = "";
            querystr = "SELECT * FROM mydatabase.activation_table WHERE Email_id=?email AND Activation_Code=?code";
            cmd      = new MySqlCommand(querystr, con);
            cmd.Parameters.AddWithValue("?email", email.Text);
            cmd.Parameters.AddWithValue("?code", code.Text);
            reader = cmd.ExecuteReader();
            name   = "";
            while (reader.HasRows && reader.Read())
            {
                name = reader.GetString(reader.GetOrdinal("Activation_Code"));
            }
            if (reader.HasRows)
            {
                Session["uname"]      = name;
                Response.BufferOutput = true;
                Response.Redirect("Registration.aspx", false);
            }
            else
            {
                email.Text = "";
                code.Text  = "";
                ClientScript.RegisterStartupScript(Page.GetType(), "disablevalidation", "<script language='javascript' >disableall();</script>");
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >alertMX('Invalid Email / Activation Code!');</script>");
            }

            reader.Close();
            con.Close();
        }
        catch (MySqlException ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }
        finally
        {
            if (cmd != null)
            {
                cmd.Dispose();
            }
            if (con != null)
            {
                con.Close();
            }
        }
    }
コード例 #33
0
    public static bool Ejecutar2_Mysql(string Consulta, ref string Resultado)
    {
        bool Ejecutar2_Mysql = false;

        WSQLAux_My = "";
        Conecta_My = Conexion_My("", "");
        WSQLAux_My = Consulta;
        try
        {
            CmdAux_My                = new MySql.Data.MySqlClient.MySqlCommand();
            CmdAux_My.Connection     = Conecta_My;
            CmdAux_My.CommandTimeout = 0;
            CmdAux_My.CommandType    = CommandType.Text;
            CmdAux_My.CommandText    = WSQLAux_My;

            Conecta_My.Open();
            try
            {
                Resultado = CmdAux_My.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {
                Resultado = "XXXXX";
            }
            if (Resultado == "XXXXX")
            {
                Resultado       = "";
                Ejecutar2_Mysql = false;
            }
            else
            {
                Ejecutar2_Mysql = true;
            }
            Conecta_My.Close();
            CmdAux_My.Dispose();
        }
        catch (Exception ex)
        {
            if (Conecta_My.State == ConnectionState.Open)
            {
                Conecta_My.Close();
            }
            MessageBox.Show("Error en la Cosulta: " + WSQLAux_My + " / " + ex.Message, "SISTEMA V 2.0", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        return(Ejecutar2_Mysql);
    }
コード例 #34
0
ファイル: Pub.cs プロジェクト: lesleyjames/CSF-TICKETING
        public static bool isIT_Support()
        {
            try
            {
                bool _Result = false;

                //if (!string.IsNullOrEmpty(_isIT_Support))
                //    return _isIT_Support.Equals("YES", StringComparison.OrdinalIgnoreCase) ? true : false;

                if (MySQL_ITIS.openConnection() == false)
                {
                    throw new Exception("MySQL Connection not open!");
                }

                MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT count(*) as COUNT FROM IT_WORKSTATIONS.IT_USERS WHERE IT_USERS.NAME = @Param1;");
                cmd.Parameters.AddWithValue("@Param1", Pub.MyDisplayName());
                cmd.Connection = MySQL_ITIS.conn;
                MySqlDataReader r = cmd.ExecuteReader();

                if (r.Read())
                {
                    _isIT_Support = r.GetInt16("COUNT") == 1 ? "YES" : "NO";
                    _Result       = r.GetInt16("COUNT") == 1 ? true : false;
                }

                //cmd.Connection.Close();
                //cmd.Connection.Dispose();
                cmd.Dispose();

                MySQL_ITIS.conn.Close();
                MySQL_ITIS.conn.Dispose();

                return(_Result);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Error : " + ex.Message);
                return(false);
            }
        }
コード例 #35
0
 public static int execS(String sql)
 {
     if (MainClass.usedb)
     {
         int lines = 0;
         MySql.Data.MySqlClient.MySqlCommand    cmd  = null;
         MySql.Data.MySqlClient.MySqlConnection conn = null;
         try
         {
             conn = createConnection();
             cmd  = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
             cmd.CommandTimeout = (60 * 1000) * 3;
             lines = cmd.ExecuteNonQuery();
         }
         catch (Exception ex)
         {
             Console.WriteLine("execS" + ex.Message + ex.StackTrace);
             return(-1);
         }
         finally
         {
             if (cmd != null)
             {
                 cmd.Dispose();
                 cmd = null;
             }
             if (conn != null)
             {
                 conn.Close();
                 conn.Dispose();
                 conn = null;
             }
         }
         return(lines);
     }
     else
     {
         return(0);
     }
 }
コード例 #36
0
    //new code for hash login with password

    private void LoginWithPasswordHashFunction()
    {
        List <string> salthashList = null;
        List <string> namesList    = null;

        try
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString();
            con = new MySql.Data.MySqlClient.MySqlConnection(connString);
            con.Open();
            querystr = "SELECT slowHashSalt, Username FROM mydatabase.registertable WHERE Username=?uname";
            cmd      = new MySqlCommand(querystr, con);
            cmd.Parameters.AddWithValue("?uname", username.Text);
            reader = cmd.ExecuteReader();
            string name = "";
            if (reader.HasRows && reader.Read())
            {
                if (salthashList == null)
                {
                    salthashList = new List <string>();
                    namesList    = new List <string>();
                }

                string saltHashes = reader.GetString(reader.GetOrdinal("slowHashSalt"));
                salthashList.Add(saltHashes);

                name = reader.GetString(reader.GetOrdinal("Username"));
                namesList.Add(name);
            }



            reader.Close();



            if (salthashList != null)
            {
                for (int i = 0; i < salthashList.Count; i++)
                {
                    querystr = "";
                    bool validuser = PasswordStorage.VerifyPassword(password.Text, salthashList[i]);

                    {
                        if (validuser == true)
                        {
                            if (name == "hardeepsinghnegi")
                            {
                                //Session["uname"] = name; old code
                                Session["uname"] = name;

                                Response.BufferOutput = true;
                                Response.Redirect("Login.aspx", false);
                            }

                            else
                            {
                                Session["uname"]      = name;
                                Response.BufferOutput = true;
                                Response.Redirect("Guest.aspx", false);
                            }
                        }
                        else
                        {
                            username.Text = "";
                            if (!(chkBoxRememberMe.Checked))
                            {
                                chkBoxRememberMe.Checked = false;
                            }

                            ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >alertMX('Invalid Username/Password!');</script>");

                            //ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "myfunctionclick()",true);
                            //ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >myfunction();</script>");
                            //new code for ui dialog
                            //ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "myfunctionclick();",true);
                            //usererror.Text = "Invalid Username/Password!";
                        }

                        con.Close();
                    }
                }

                if (chkBoxRememberMe.Checked)
                {
                    Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
                    Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30);
                }
                else
                {
                    Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
                }
                Response.Cookies["UserName"].Value = username.Text.Trim();
                Response.Cookies["Password"].Value = password.Text.Trim();
            }
            else
            {
                username.Text = "";
                if ((chkBoxRememberMe.Checked == true))
                {
                    chkBoxRememberMe.Checked = false;
                }
                //DisableForm(Page.Controls);

                ClientScript.RegisterStartupScript(Page.GetType(), "validationuser2", "<script language='javascript' >disableall();</script>");
                ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >alertMX('Invalid Username/Password !');</script>");
                //ClientScript.RegisterStartupScript(Page.GetType(), "validationuser2", "<script language='javascript' >disableall();</script>");

                //DisableControls();
            }
        }



        catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }


        finally
        {
            if (cmd != null)
            {
                cmd.Dispose();
            }
            if (con != null)
            {
                con.Close();
            }
        }
    }