各个帮扶类大全,完毕图片压缩

代码:

系统剧中人物篇

前言

此篇特地记录一些常见DB援救类及其余赞助类,以便利用时毫不再行造轮子。

EF

图片 1图片 2

数据结构

DBHelper帮助类

①首当其冲的正是Sql Server帮助类,创立名称叫DbHelperSQL 的类 ,全体代码如下:

图片 3图片 4

/// <summary>
    /// 数据访问抽象基础类
    /// Copyright (C) Maticsoft 
    /// </summary>
    public abstract class DbHelperSQL
    {
        //数据库连接字符串(web.config来配置),多数据库可使用DbHelperSQLP来实现.
        public static string connectionString = PubConstant.ConnectionString;             
        public DbHelperSQL()
        {            
        }

        #region 公用方法
        /// <summary>
        /// 判断是否存在某表的某个字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">列名称</param>
        /// <returns>是否存在</returns>
        public static bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('"   tableName   "') and [name]='"   columnName   "'";
            object res = GetSingle(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max("   FieldName   ") 1 from "   TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString()); //也可能=0
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool TabExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'["   TableName   "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].["   TableName   "]') AND type in (N'U')";
            object obj = GetSingle(strsql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        public static int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行Sql和Oracle滴混合事务
        /// </summary>
        /// <param name="list">SQL命令行列表</param>
        /// <param name="oracleCmdSqlList">Oracle命令行列表</param>
        /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns>
        public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    foreach (CommandInfo myDE in list)
                    {
                        string cmdText = myDE.CommandText;
                        SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
                        PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
                        if (myDE.EffentNextType == EffentNextType.SolicitationEvent)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("违背要求" myDE.CommandText "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;
                            if (isHave)
                            {
                                //引发事件
                                myDE.OnSolicitationEvent();
                            }
                        }
                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求"   myDE.CommandText   "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求"   myDE.CommandText   "返回值必须大于0");
                                //return 0;
                            }
                            if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求"   myDE.CommandText   "返回值必须等于0");
                                //return 0;
                            }
                            continue;
                        }
                        int val = cmd.ExecuteNonQuery();
                        if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                        {
                            tx.Rollback();
                            throw new Exception("SQL:违背要求"   myDE.CommandText   "必须有影响行");
                            //return 0;
                        }
                        cmd.Parameters.Clear();
                    }
                    string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC");
                    bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList);
                    if (!res)
                    {
                        tx.Rollback();
                        throw new Exception("Oracle执行失败");
                        // return -1;
                    }
                    tx.Commit();
                    return 1;
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    tx.Rollback();
                    throw e;
                }
                catch (Exception e)
                {
                    tx.Rollback();
                    throw e;
                }
            }
        }        
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n  )
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count  = cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(SQLString, connection);
                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static object ExecuteSqlGet(string SQLString, string content)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(SQLString, connection);
                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(strSQL, connection);
                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        public static object GetSingle(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string strSQL)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(strSQL, connection);
            try
            {
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }   

        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        public static DataSet Query(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.SelectCommand.CommandTimeout = Times;
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
        public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    { int count = 0;
                        //循环
                        foreach (CommandInfo myDE in cmdList)
                        {
                            string cmdText = myDE.CommandText;
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                            {
                                if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                                {
                                    trans.Rollback();
                                    return 0;
                                }

                                object obj = cmd.ExecuteScalar();
                                bool isHave = false;
                                if (obj == null && obj == DBNull.Value)
                                {
                                    isHave = false;
                                }
                                isHave = Convert.ToInt32(obj) > 0;

                                if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                continue;
                            }
                            int val = cmd.ExecuteNonQuery();
                            count  = val;
                            if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                            {
                                trans.Rollback();
                                return 0;
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return count;
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
        public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (CommandInfo myDE in SQLStringList)
                        {
                            string cmdText = myDE.CommandText;
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
        public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
            //            finally
            //            {
            //                cmd.Dispose();
            //                connection.Close();
            //            }    

        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }


        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {


                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 存储过程操作

        /// <summary>
        /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlDataReader returnReader;
            connection.Open();
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;

        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.SelectCommand.CommandTimeout = Times;
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }

        /// <summary>
        /// 执行存储过程,返回影响的行数        
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                int result;
                connection.Open();
                SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                //Connection.Close();
                return result;
            }
        }

        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)    
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }
        #endregion

    }

View Code

只顾:依照提醒援用相关命名空间就能够。

上述代码中用到了一个PubConstant类 用来博取连接字符串,全体代码如下:

图片 5图片 6

 public class PubConstant
    {        
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string ConnectionString
        {           
            get 
            {
                string _connectionString = ConfigurationManager.AppSettings["ConnectionString"];       
                string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
                if (ConStringEncrypt == "true")
                {
                    _connectionString = DESEncrypt.Decrypt(_connectionString);
                }
                return _connectionString; 
            }
        }

        /// <summary>
        /// 得到web.config里配置项的数据库连接字符串。
        /// </summary>
        /// <param name="configName"></param>
        /// <returns></returns>
        public static string GetConnectionString(string configName)
        {
            string connectionString = ConfigurationManager.AppSettings[configName];
            string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
            if (ConStringEncrypt == "true")
            {
                connectionString = DESEncrypt.Decrypt(connectionString);
            }
            return connectionString;
        }
    }

View Code

PubConstant类中对连年字符串举办了DES加密解密操作,DES加密/解密扶持类整体代码如下:

图片 7图片 8

/// <summary>
    /// DES加密/解密类。
    /// </summary>
    public class DESEncrypt
    {
        public DESEncrypt()
        {            
        }

        #region ========加密======== 

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text) 
        {
            return Encrypt(Text, "MATICSOFT");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text,string sKey) 
        { 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            byte[] inputByteArray; 
            inputByteArray=Encoding.Default.GetBytes(Text); 
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
            CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); 
            cs.Write(inputByteArray,0,inputByteArray.Length); 
            cs.FlushFinalBlock(); 
            StringBuilder ret=new StringBuilder(); 
            foreach( byte b in ms.ToArray()) 
            { 
                ret.AppendFormat("{0:X2}",b); 
            } 
            return ret.ToString(); 
        } 

        #endregion

        #region ========解密======== 


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text) 
        {
            return Decrypt(Text, "MATICSOFT");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text,string sKey) 
        { 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            int len; 
            len=Text.Length/2; 
            byte[] inputByteArray = new byte[len]; 
            int x,i; 
            for(x=0;x<len;x  ) 
            { 
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 
                inputByteArray[x]=(byte)i; 
            } 
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
            System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
            CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); 
            cs.Write(inputByteArray,0,inputByteArray.Length); 
            cs.FlushFinalBlock(); 
            return Encoding.Default.GetString(ms.ToArray()); 
        } 

        #endregion 

    }

View Code

 

刚烈建议使用ESC加密

全副代码如下:

图片 9图片 10

 public class DESCrypto
    {
        private static string key = "KABCMS2017";

        /// <summary>
        /// 加密(UTF-8)
        /// </summary>
        /// <param name="str">待加密字符串</param>
        /// <param name="secKey">密钥(长度不能少于8位字符)</param>
        /// <returns></returns>
        public static string Encode(string str, string secKey = "")
        {
            if (string.IsNullOrEmpty(secKey))
                secKey = key;
            else if (secKey.Length < 8)
                return "";
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            provider.Key = Encoding.ASCII.GetBytes(secKey.Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(secKey.Substring(0, 8));
            byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(str);
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();
            foreach (byte num in stream.ToArray())
            {
                builder.AppendFormat("{0:X2}", num);
            }
            stream.Close();
            return builder.ToString();
        }

        /// <summary>
        /// 解密(UTF-8)
        /// </summary>
        /// <param name="str">待解密字符串</param>
        /// <param name="secKey">密钥(长度不能少于8位字符)</param>
        /// <returns></returns>
        public static string Decode(string str, string secKey = "")
        {
            if (string.IsNullOrEmpty(secKey))
                secKey = key;
            else if (secKey.Length < 8)
                return "";
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            provider.Key = Encoding.ASCII.GetBytes(secKey.Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(secKey.Substring(0, 8));
            byte[] buffer = new byte[str.Length / 2];
            for (int i = 0; i < (str.Length / 2); i  )
            {
                int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
                buffer[i] = (byte)num2;
            }
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
            stream2.Write(buffer, 0, buffer.Length);
            stream2.FlushFinalBlock();
            stream.Close();
            return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());
        }
    }

View Code

 

下一场再配置文件中新建多少个字符串链接,分别连接分歧的库,代码如下:

    <add key="ConnectionString1" value="Server=.;Database=数据库名;Uid=账号;Pwd=密码;allow zero datetime = true" /> -- MySql
    <add key="ConnectionString" value="Server=.;Database=数据库名;Uid=账号;Pwd=密码;" />   -- SqlServer
    <add key="ConnectionString11" value="Provider=SQLOLEDB;Server=.;Initial Catalog=数据库名;Uid=账号;Pwd=密码;" /> -- SqlLole

使用

         /// <summary>
        /// 根据账号获取信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ServiceProvider GetNameByQR(string name)
        {
            try
            {
                string sql = "select 字段1, 字段2, 字段3 from viw_promotion where name='"   name   "'";
                DataSet ds = DbHelperMySQL.Query(sql);//此处调用MysqlDBHelper帮助类
                DataTable dt = ds.Tables[0];
                ServiceProvider ProviderQR = new ServiceProvider();
                foreach (DataRow item in dt.Rows)
                {
                    if (!string.IsNullOrEmpty(item["字段1"].ToString()))
                    {
                        ProviderQR.PropertName = item["字段1"].ToString();
                    }
                    if (!string.IsNullOrEmpty(item["字段2"].ToString()))
                    {
                        ProviderQR.PropertyURL = item["字段2"].ToString();
                    }
                    if (!string.IsNullOrEmpty(item["字段3"].ToString()))
                    {
                        ProviderQR.PropertyQRCode = item["字段3"].ToString();
                    }
                }
                return ProviderQR; //返回实体对象
            }
            catch (Exception)
            {
                return null;
            }
        }

② DbHelperMySQL支持类,全部代码如下:

 

图片 11图片 12

/// <summary>
    /// 数据访问抽象基础类
    /// Copyright (C) Maticsoft
    /// </summary>
    public abstract class DbHelperMySQL
    {
        //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.        
        // public static string connectionString = PubConstant.ConnectionString;Mysql_ConnectionString,ConnectionString1
        public static string connectionString = ConfigurationManager.AppSettings["ConnectionString1"];
        public DbHelperMySQL()
        {            
        }

        #region 公用方法
        /// <summary>
        /// 得到最大值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max("   FieldName   ") 1 from "   TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }    
        /// <summary>
        /// 是否存在(基于MySqlParameter)
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static 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 e;
                    }
                }
            }
        }

        public static int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行MySql和Oracle滴混合事务
        /// </summary>
        /// <param name="list">SQL命令行列表</param>
        /// <param name="oracleCmdSqlList">Oracle命令行列表</param>
        /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns>
        public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                MySqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    foreach (CommandInfo myDE in list)
                    {
                        string cmdText = myDE.CommandText;
                        MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                        PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
                        if (myDE.EffentNextType == EffentNextType.SolicitationEvent)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("违背要求" myDE.CommandText "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;
                            if (isHave)
                            {
                                //引发事件
                                myDE.OnSolicitationEvent();
                            }
                        }
                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求"   myDE.CommandText   "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求"   myDE.CommandText   "返回值必须大于0");
                                //return 0;
                            }
                            if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求"   myDE.CommandText   "返回值必须等于0");
                                //return 0;
                            }
                            continue;
                        }
                        int val = cmd.ExecuteNonQuery();
                        if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                        {
                            tx.Rollback();
                            throw new Exception("SQL:违背要求"   myDE.CommandText   "必须有影响行");
                            //return 0;
                        }
                        cmd.Parameters.Clear();
                    }
                    string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC");
                    bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList);
                    if (!res)
                    {
                        tx.Rollback();
                        throw new Exception("执行失败");
                        // return -1;
                    }
                    tx.Commit();
                    return 1;
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    tx.Rollback();
                    throw e;
                }
                catch (Exception e)
                {
                    tx.Rollback();
                    throw e;
                }
            }
        }        
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                MySqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n  )
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count  = cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(SQLString, connection);
                MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static object ExecuteSqlGet(string SQLString, string content)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(SQLString, connection);
                MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(strSQL, connection);
                MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        public static object GetSingle(string SQLString, int Times)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>MySqlDataReader</returns>
        public static MySqlDataReader ExecuteReader(string strSQL)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand cmd = new MySqlCommand(strSQL, connection);
            try
            {
                connection.Open();
                MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (MySql.Data.MySqlClient.MySqlException e)
            {
                throw e;
            }   

        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        public static DataSet Query(string SQLString, int Times)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    command.SelectCommand.CommandTimeout = Times;
                    command.Fill(ds, "ds");
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }



        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        throw e;
                    }
                }
            }
        }


        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    MySqlCommand cmd = new MySqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
        public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    MySqlCommand cmd = new MySqlCommand();
                    try
                    { int count = 0;
                        //循环
                        foreach (CommandInfo myDE in cmdList)
                        {
                            string cmdText = myDE.CommandText;
                            MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                            {
                                if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                                {
                                    trans.Rollback();
                                    return 0;
                                }

                                object obj = cmd.ExecuteScalar();
                                bool isHave = false;
                                if (obj == null && obj == DBNull.Value)
                                {
                                    isHave = false;
                                }
                                isHave = Convert.ToInt32(obj) > 0;

                                if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                continue;
                            }
                            int val = cmd.ExecuteNonQuery();
                            count  = val;
                            if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                            {
                                trans.Rollback();
                                return 0;
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return count;
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
        public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    MySqlCommand cmd = new MySqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (CommandInfo myDE in SQLStringList)
                        {
                            string cmdText = myDE.CommandText;
                            MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                            foreach (MySqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (MySqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
        public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    MySqlCommand cmd = new MySqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                            foreach (MySqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (MySqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>MySqlDataReader</returns>
        public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand cmd = new MySqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (MySql.Data.MySqlClient.MySqlException e)
            {
                throw e;
            }
            //            finally
            //            {
            //                cmd.Dispose();
            //                connection.Close();
            //            }    

        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }


        private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {


                foreach (MySqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion



    }

View Code

瞩目,Mysql要求引进mysql.dll 点本身下载

③ SQLite帮助类,全体代码如下:

图片 13图片 14

 /// <summary>
    /// Copyright (C) 2011 Maticsoft 
    /// 数据访问基础类(基于SQLite)
    /// 可以用户可以修改满足自己项目的需要。
    /// </summary>
    public abstract class DbHelperSQLite
    {
        //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.        
        public static string connectionString = PubConstant.ConnectionString;
        public DbHelperSQLite()
        {
        }


        #region 公用方法

        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max("   FieldName   ") 1 from "   TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static bool Exists(string strSql, params SQLiteParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public static void ExecuteSqlTran(ArrayList SQLStringList)
        {
            using (SQLiteConnection conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = conn;
                SQLiteTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n  )
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException e)
                    {
                        connection.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回SQLiteDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public static SQLiteDataReader ExecuteReader(string strSQL)
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
            try
            {
                connection.Open();
                SQLiteDataReader myReader = cmd.ExecuteReader();
                return myReader;
            }
            catch (System.Data.SQLite.SQLiteException e)
            {
                throw new Exception(e.Message);
            }

        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }


        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }


        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SQLiteConnection conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                using (SQLiteTransaction trans = conn.BeginTransaction())
                {
                    SQLiteCommand cmd = new SQLiteCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();

                            trans.Commit();
                        }
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }


        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SQLiteDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms)
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            SQLiteCommand cmd = new SQLiteCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SQLiteDataReader myReader = cmd.ExecuteReader();
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SQLite.SQLiteException e)
            {
                throw new Exception(e.Message);
            }

        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }


        private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SQLiteParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        #endregion



    }

View Code

④Oracle扶助类,全体代码如下:

图片 15图片 16

/// <summary>
    /// Copyright (C) Maticsoft
    /// 数据访问基础类(基于Oracle)
    /// 可以用户可以修改满足自己项目的需要。
    /// </summary>
    public abstract class DbHelperOra
    {
        //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.        
        public static string connectionString = PubConstant.ConnectionString;     
        public DbHelperOra()
        {            
        }

        #region 公用方法

        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max("   FieldName   ") 1 from "   TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static bool Exists(string strSql, params OracleParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        #endregion


        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {                
                using (OracleCommand cmd = new OracleCommand(SQLString,connection))
                {
                    try
                    {        
                        connection.Open();
                        int rows=cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch(System.Data.OracleClient.OracleException E)
                    {                    
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }                
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public static void ExecuteSqlTran(ArrayList SQLStringList)
        {
            using (OracleConnection conn = new OracleConnection(connectionString))
            {
                conn.Open();
                OracleCommand cmd = new OracleCommand();
                cmd.Connection=conn;                
                OracleTransaction tx=conn.BeginTransaction();            
                cmd.Transaction=tx;                
                try
                {           
                    for(int n=0;n<SQLStringList.Count;n  )
                    {
                        string strsql=SQLStringList[n].ToString();
                        if (strsql.Trim().Length>1)
                        {
                            cmd.CommandText=strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }                                        
                    tx.Commit();                    
                }
                catch(System.Data.OracleClient.OracleException E)
                {        
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString,string content)
        {                
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand(SQLString,connection);
                System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter("@content", OracleType.NVarChar);
                myParameter.Value = content ;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows=cmd.ExecuteNonQuery();
                    return rows;
                }
                catch(System.Data.OracleClient.OracleException E)
                {                
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }    
            }
        }        
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL,byte[] fs)
        {        
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand(strSQL,connection);
                System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter("@fs", OracleType.LongRaw);
                myParameter.Value = fs ;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows=cmd.ExecuteNonQuery();
                    return rows;
                }
                catch(System.Data.OracleClient.OracleException E)
                {                
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }                
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using(OracleCommand cmd = new OracleCommand(SQLString,connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value)))
                        {                    
                            return null;
                        }
                        else
                        {
                            return obj;
                        }                
                    }
                    catch(System.Data.OracleClient.OracleException e)
                    {                        
                        connection.Close();
                        throw new Exception(e.Message);
                    }    
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>OracleDataReader</returns>
        public static OracleDataReader ExecuteReader(string strSQL)
        {
            OracleConnection connection = new OracleConnection(connectionString);            
            OracleCommand cmd = new OracleCommand(strSQL,connection);                
            try
            {
                connection.Open();
                OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch(System.Data.OracleClient.OracleException e)
            {                                
                throw new Exception(e.Message);
            }            

        }        
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OracleDataAdapter command = new OracleDataAdapter(SQLString,connection);                
                    command.Fill(ds,"ds");
                }
                catch(System.Data.OracleClient.OracleException ex)
                {                
                    throw new Exception(ex.Message);
                }            
                return ds;
            }            
        }


        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString,params OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {                
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {        
                        PrepareCommand(cmd, connection, null,SQLString, cmdParms);
                        int rows=cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch(System.Data.OracleClient.OracleException E)
                    {                
                        throw new Exception(E.Message);
                    }
                }                
            }
        }


        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {            
            using (OracleConnection conn = new OracleConnection(connectionString))
            {
                conn.Open();
                using (OracleTransaction trans = conn.BeginTransaction()) 
                {
                    OracleCommand cmd = new OracleCommand();
                    try 
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {    
                            string     cmdText=myDE.Key.ToString();
                            OracleParameter[] cmdParms=(OracleParameter[])myDE.Value;
                            PrepareCommand(cmd,conn,trans,cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();

                            trans.Commit();
                        }                    
                    }
                    catch 
                    {
                        trans.Rollback();
                        throw;
                    }
                }                
            }
        }


        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString,params OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null,SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value)))
                        {                    
                            return null;
                        }
                        else
                        {
                            return obj;
                        }                
                    }
                    catch(System.Data.OracleClient.OracleException e)
                    {                
                        throw new Exception(e.Message);
                    }                    
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>OracleDataReader</returns>
        public static OracleDataReader ExecuteReader(string SQLString,params OracleParameter[] cmdParms)
        {        
            OracleConnection connection = new OracleConnection(connectionString);
            OracleCommand cmd = new OracleCommand();                
            try
            {
                PrepareCommand(cmd, connection, null,SQLString, cmdParms);
                OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch(System.Data.OracleClient.OracleException e)
            {                                
                throw new Exception(e.Message);
            }                    

        }        

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString,params OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand();
                PrepareCommand(cmd, connection, null,SQLString, cmdParms);
                using( OracleDataAdapter da = new OracleDataAdapter(cmd) )
                {
                    DataSet ds = new DataSet();    
                    try
                    {                                                
                        da.Fill(ds,"ds");
                        cmd.Parameters.Clear();
                    }
                    catch(System.Data.OracleClient.OracleException ex)
                    {                
                        throw new Exception(ex.Message);
                    }            
                    return ds;
                }                
            }            
        }


        private static void PrepareCommand(OracleCommand cmd,OracleConnection conn,OracleTransaction trans, string cmdText, OracleParameter[] cmdParms) 
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null) 
            {
                foreach (OracleParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        #endregion

        #region 存储过程操作

        /// <summary>
        /// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleDataReader</returns>
        public static OracleDataReader RunProcedure(string storedProcName, IDataParameter[] parameters )
        {
            OracleConnection connection = new OracleConnection(connectionString);
            OracleDataReader returnReader;
            connection.Open();
            OracleCommand command = BuildQueryCommand( connection,storedProcName, parameters );
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);                
            return returnReader;            
        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName )
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                OracleDataAdapter sqlDA = new OracleDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters );
                sqlDA.Fill( dataSet, tableName );
                connection.Close();
                return dataSet;
            }
        }


        /// <summary>
        /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleCommand</returns>
        private static OracleCommand BuildQueryCommand(OracleConnection connection,string storedProcName, IDataParameter[] parameters)
        {            
            OracleCommand command = new OracleCommand( storedProcName, connection );
            command.CommandType = CommandType.StoredProcedure;
            foreach (OracleParameter parameter in parameters)
            {
                command.Parameters.Add( parameter );
            }
            return command;            
        }

        /// <summary>
        /// 执行存储过程,返回影响的行数        
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected )
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                int result;
                connection.Open();
                OracleCommand command = BuildIntCommand(connection,storedProcName, parameters );
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                //Connection.Close();
                return result;
            }
        }

        /// <summary>
        /// 创建 OracleCommand 对象实例(用来返回一个整数值)    
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleCommand 对象实例</returns>
        private static OracleCommand BuildIntCommand(OracleConnection connection,string storedProcName, IDataParameter[] parameters)
        {
            OracleCommand command = BuildQueryCommand(connection,storedProcName, parameters );
            command.Parameters.Add( new OracleParameter ( "ReturnValue",
                OracleType.Int32, 4, ParameterDirection.ReturnValue,
                false,0,0,string.Empty,DataRowVersion.Default,null ));
            return command;
        }
        #endregion    

    }

View Code

 ⑤缓存扶植类,全体代码如下:

图片 17图片 18

    using System.Web.Caching;
    public class WebDataCache
    {
        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }
        /// <summary>
        /// 删除当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <returns></returns>
        public static object RemoveCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache.Remove(CacheKey);
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);

        }
        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        /// <param name="absoluteExpiration">设置绝对过期时间</param>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, Cache.NoSlidingExpiration);
        }
        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        /// <param name="slidingExpiration">设置滑动过期时间</param>
        public static void SetCache(string CacheKey, object objObject, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, Cache.NoAbsoluteExpiration, slidingExpiration);
        }
    }

View Code

应用方法:

举例说,登录的时候能够先获得是或不是有该缓存:

               if (WebDataCache.GetCache(userName   "固定标识符") == null)
                {
                    实体对象= _roles.UserRolesOperS(userName);//根据用户名查询出用户权限 赋值到实体中
                    WebDataCache.SetCache(userName   "固定标识符", UserRolesOper, DateTime.Now.AddSeconds(double.Parse(ConfigurationManager.AppSettings["Cache"].ToString())));//设置缓存过期时间,在配置文件中配置

 }

清空缓存操作:

 WebDataCache.RemoveCache(User_Name   "_MenuAction");//清空缓存

缓存为空或超时需另行摸清

选取缓存:

 object obj = WebDataCache.GetCache(userName   "固定标识符");
 var userRoleOper = (List<实体对象>)obj; // 

⑥字符串加密组件

图片 19图片 20

/// <summary>
    /// 字符串加密组件
    /// </summary>
    public class Encrypt
    {
        #region "定义加密字串变量"
        private SymmetricAlgorithm mCSP;  //声明对称算法变量
        private const string CIV = "Mi9l/ 7Zujhy12se6Yjy111A";  //初始化向量
        private const string CKEY = "jkHuIy9D/9i="; //密钥(常量)
        #endregion

        /// <summary>
        /// 实例化
        /// </summary>
        public Encrypt()
        {
            mCSP = new DESCryptoServiceProvider();  //定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象,此类是SymmetricAlgorithm的派生类
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="Value">需加密的字符串</param>
        /// <returns></returns>
        public string EncryptString(string Value)
        {
            ICryptoTransform ct; //定义基本的加密转换运算
            MemoryStream ms; //定义内存流
            CryptoStream cs; //定义将内存流链接到加密转换的流
            byte[] byt;

            //CreateEncryptor创建(对称数据)加密对象
            ct = mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); //用指定的密钥和初始化向量创建对称数据加密标准

            byt = Encoding.UTF8.GetBytes(Value); //将Value字符转换为UTF-8编码的字节序列

            ms = new MemoryStream(); //创建内存流
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); //将内存流链接到加密转换的流
            cs.Write(byt, 0, byt.Length); //写入内存流
            cs.FlushFinalBlock(); //将缓冲区中的数据写入内存流,并清除缓冲区
            cs.Close(); //释放内存流

            return Convert.ToBase64String(ms.ToArray()); //将内存流转写入字节数组并转换为string字符
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="Value">要解密的字符串</param>
        /// <returns>string</returns>
        public string DecryptString(string Value)
        {
            ICryptoTransform ct; //定义基本的加密转换运算
            MemoryStream ms; //定义内存流
            CryptoStream cs; //定义将数据流链接到加密转换的流
            byte[] byt;

            ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); //用指定的密钥和初始化向量创建对称数据解密标准
            byt = Convert.FromBase64String(Value); //将Value(Base 64)字符转换成字节数组

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();

            return Encoding.UTF8.GetString(ms.ToArray()); //将字节数组中的所有字符解码为一个字符串
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
       public string GetMixPwd(int num)//生成混合随机数
        {
            string a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < num; i  )
            {
                sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
            }

            return sb.ToString();
        }
    }

View Code

⑦ 输入汉字获取拼音或首字母大写 新建类 ConvertHzToPy,全体代码如下:

图片 21图片 22

/// <summary>
/// Summary description for ConvertHzToPz_Gb2312
/// </summary>
public class ConvertHzToPy
{
    public  ConvertHzToPy()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    private static int[] pyvalue = new int[]{-20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,-20032,-20026,     
          -20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,-19756,-19751,-19746,-19741,-19739,-19728,     
          -19725,-19715,-19540,-19531,-19525,-19515,-19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,     
          -19261,-19249,-19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,-19003,-18996,     
          -18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,-18731,-18722,-18710,-18697,-18696,-18526,     
          -18518,-18501,-18490,-18478,-18463,-18448,-18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183,     
          -18181,-18012,-17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,-17733,-17730,     
          -17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,-17468,-17454,-17433,-17427,-17417,-17202,     
          -17185,-16983,-16970,-16942,-16915,-16733,-16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,     
          -16452,-16448,-16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,-16212,-16205,     
          -16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,-15933,-15920,-15915,-15903,-15889,-15878,     
          -15707,-15701,-15681,-15667,-15661,-15659,-15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,     
          -15408,-15394,-15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,-15149,-15144,     
          -15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,-14941,-14937,-14933,-14930,-14929,-14928,     
          -14926,-14922,-14921,-14914,-14908,-14902,-14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,     
          -14663,-14654,-14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,-14170,-14159,     
          -14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,-14109,-14099,-14097,-14094,-14092,-14090,     
          -14087,-14083,-13917,-13914,-13910,-13907,-13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,     
          -13611,-13601,-13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,-13340,-13329,     
          -13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,-13068,-13063,-13060,-12888,-12875,-12871,     
          -12860,-12858,-12852,-12849,-12838,-12831,-12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,     
          -12320,-12300,-12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,-11781,-11604,     
          -11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,-11055,-11052,-11045,-11041,-11038,-11024,     
          -11020,-11019,-11018,-11014,-10838,-10832,-10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,     
          -10329,-10328,-10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254};
    private static string[] pystr = new string[]{"a","ai","an","ang","ao","ba","bai","ban","bang","bao","bei","ben","beng","bi","bian","biao",     
        "bie","bin","bing","bo","bu","ca","cai","can","cang","cao","ce","ceng","cha","chai","chan","chang","chao","che","chen",     
        "cheng","chi","chong","chou","chu","chuai","chuan","chuang","chui","chun","chuo","ci","cong","cou","cu","cuan","cui",     
        "cun","cuo","da","dai","dan","dang","dao","de","deng","di","dian","diao","die","ding","diu","dong","dou","du","duan",     
        "dui","dun","duo","e","en","er","fa","fan","fang","fei","fen","feng","fo","fou","fu","ga","gai","gan","gang","gao",     
        "ge","gei","gen","geng","gong","gou","gu","gua","guai","guan","guang","gui","gun","guo","ha","hai","han","hang",     
        "hao","he","hei","hen","heng","hong","hou","hu","hua","huai","huan","huang","hui","hun","huo","ji","jia","jian",     
        "jiang","jiao","jie","jin","jing","jiong","jiu","ju","juan","jue","jun","ka","kai","kan","kang","kao","ke","ken",     
        "keng","kong","kou","ku","kua","kuai","kuan","kuang","kui","kun","kuo","la","lai","lan","lang","lao","le","lei",     
        "leng","li","lia","lian","liang","liao","lie","lin","ling","liu","long","lou","lu","lv","luan","lue","lun","luo",     
        "ma","mai","man","mang","mao","me","mei","men","meng","mi","mian","miao","mie","min","ming","miu","mo","mou","mu",     
        "na","nai","nan","nang","nao","ne","nei","nen","neng","ni","nian","niang","niao","nie","nin","ning","niu","nong",     
        "nu","nv","nuan","nue","nuo","o","ou","pa","pai","pan","pang","pao","pei","pen","peng","pi","pian","piao","pie",     
        "pin","ping","po","pu","qi","qia","qian","qiang","qiao","qie","qin","qing","qiong","qiu","qu","quan","que","qun",     
        "ran","rang","rao","re","ren","reng","ri","rong","rou","ru","ruan","rui","run","ruo","sa","sai","san","sang",     
        "sao","se","sen","seng","sha","shai","shan","shang","shao","she","shen","sheng","shi","shou","shu","shua",     
        "shuai","shuan","shuang","shui","shun","shuo","si","song","sou","su","suan","sui","sun","suo","ta","tai",    
        "tan","tang","tao","te","teng","ti","tian","tiao","tie","ting","tong","tou","tu","tuan","tui","tun","tuo",     
        "wa","wai","wan","wang","wei","wen","weng","wo","wu","xi","xia","xian","xiang","xiao","xie","xin","xing",     
        "xiong","xiu","xu","xuan","xue","xun","ya","yan","yang","yao","ye","yi","yin","ying","yo","yong","you",     
        "yu","yuan","yue","yun","za","zai","zan","zang","zao","ze","zei","zen","zeng","zha","zhai","zhan","zhang",     
        "zhao","zhe","zhen","zheng","zhi","zhong","zhou","zhu","zhua","zhuai","zhuan","zhuang","zhui","zhun","zhuo",     
        "zi","zong","zou","zu","zuan","zui","zun","zuo"};
    /// <summary>
    /// 获取拼音
    /// </summary>
    /// <param name="str">汉字</param>
    /// <returns></returns>
    public static string Convert(string str)
    {
        byte[] array = new byte[2];
        string returnstr = "";
        int chrasc = 0;
        int i1 = 0;
        int i2 = 0;
        char[] nowchar = str.ToCharArray();
        for (int j = 0; j < nowchar.Length; j  )
        {
            byte[] btchk = System.Text.Encoding.Default.GetBytes(nowchar[j].ToString());
            if (btchk.Length == 1)
            {
                returnstr  = nowchar[j].ToString();
                continue;
            }
            array = btchk;
            //array = System.Text.Encoding.Default.GetBytes(nowchar[j].ToString());
            i1 = (short)(array[0]);
            i2 = (short)(array[1]);
            chrasc = i1 * 256   i2 - 65536;
            if (chrasc > 0 && chrasc < 160)
            {
                returnstr  = nowchar[j];
            }
            else
            {
                for (int i = (pyvalue.Length - 1); i >= 0; i--)
                {
                    if (pyvalue[i] <= chrasc)
                    {
                        returnstr  = pystr[i];
                        break;
                    }
                }
            }
        }
        return returnstr;
    }
    /// <summary>
    /// 获取拼音首字母
    /// </summary>
    /// <param name="str">汉字</param>
    /// <returns></returns>
    public static string GetShortPY(string str)
    {
        string tempStr = "";
        foreach (char c in str)
        {
            if ((int)c >= 33 && (int)c <= 126)
            {
                tempStr  = c.ToString(); //字母和符号原样保留 
            }
            else
            {
                if ((int)c != 32)//如果不是空格,那么转换
                {
                    tempStr  = GetPYChar(c.ToString()); //累加拼音声母 
                }
                else//如果是空格那么在字符串中间 上一个空字符
                {
                    tempStr  = " ";
                }

            }
        }
        return tempStr;
    }

    private static string GetPYChar(string c)
    {
        byte[] array = new byte[2];
        array = System.Text.Encoding.Default.GetBytes(c);
        int i = (short)(array[0] - '\0') * 256   ((short)(array[1] - '\0'));

        if (i < 0xB0A1) return "";
        if (i < 0xB0C5) return "a";
        if (i < 0xB2C1) return "b";
        if (i < 0xB4EE) return "c";
        if (i < 0xB6EA) return "d";
        if (i < 0xB7A2) return "e";
        if (i < 0xB8C1) return "f";
        if (i < 0xB9FE) return "g";
        if (i < 0xBBF7) return "h";
        if (i < 0xBFA6) return "j";
        if (i < 0xC0AC) return "k";
        if (i < 0xC2E8) return "l";
        if (i < 0xC4C3) return "m";
        if (i < 0xC5B6) return "n";
        if (i < 0xC5BE) return "o";
        if (i < 0xC6DA) return "p";
        if (i < 0xC8BB) return "q";
        if (i < 0xC8F6) return "r";
        if (i < 0xCBFA) return "s";
        if (i < 0xCDDA) return "t";
        if (i < 0xCEF4) return "w";
        if (i < 0xD1B9) return "x";
        if (i < 0xD4D1) return "y";
        if (i < 0xD7FA) return "z";
        return "";
    }

}

View Code

⑧INI文件读写类 ,新建类INIFile ,全体代码如下:

图片 23图片 24

  /// <summary>
    /// INI文件读写类。
    /// Copyright (C) Maticsoft
    /// </summary>
    public class INIFile
    {
        public string path;

        public INIFile(string INIPath)
        {
            path = INIPath;
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,string key,string def, StringBuilder retVal,int size,string filePath);


        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);


        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        public void IniWriteValue(string Section,string Key,string Value)
        {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string IniReadValue(string Section,string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp, 255, this.path);
            return temp.ToString();
        }
        public byte[] IniReadValues(string section, string key)
        {
            byte[] temp = new byte[255];
            int i = GetPrivateProfileString(section, key, "", temp, 255, this.path);
            return temp;

        }


        /// <summary>
        /// 删除ini文件下所有段落
        /// </summary>
        public void ClearAllSection()
        {
            IniWriteValue(null,null,null);
        }
        /// <summary>
        /// 删除ini文件下personal段落下的所有键
        /// </summary>
        /// <param name="Section"></param>
        public void ClearSection(string Section)
        {
            IniWriteValue(Section,null,null);
        }

    }

View Code

⑨页面数据效验类,能够新建类 PageValidate,全体代码如下:

图片 25图片 26

/// <summary>
    /// 页面数据校验类
    /// Copyright (C) Maticsoft 2004-2011
    /// </summary>
    public class PageValidate
    {
        private static Regex RegPhone = new Regex("^[0-9] [-]?[0-9] [-]?[0-9]$");
        private static Regex RegNumber = new Regex("^[0-9] $");
        private static Regex RegNumberSign = new Regex("^[ -]?[0-9] $");
        private static Regex RegDecimal = new Regex("^[0-9] [.]?[0-9] $");
        private static Regex RegDecimalSign = new Regex("^[ -]?[0-9] [.]?[0-9] $"); //等价于^[ -]?d [.]?d $
        private static Regex RegEmail = new Regex("^[\w-] @[\w-] \.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样 
        private static Regex RegCHZN = new Regex("[u4e00-u9fa5]");

        public PageValidate()
        {
        }


        #region 数字字符串检查        
        public static bool IsPhone(string inputData)
        {
            Match m = RegPhone.Match(inputData);
            return m.Success;
        }
        /// <summary>
        /// 检查Request查询字符串的键值,是否是数字,最大长度限制
        /// </summary>
        /// <param name="req">Request</param>
        /// <param name="inputKey">Request的键值</param>
        /// <param name="maxLen">最大长度</param>
        /// <returns>返回Request查询字符串</returns>
        public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
        {
            string retVal = string.Empty;
            if(inputKey != null && inputKey != string.Empty)
            {
                retVal = req.QueryString[inputKey];
                if(null == retVal)
                    retVal = req.Form[inputKey];
                if(null != retVal)
                {
                    retVal = SqlText(retVal, maxLen);
                    if(!IsNumber(retVal))
                        retVal = string.Empty;
                }
            }
            if(retVal == null)
                retVal = string.Empty;
            return retVal;
        }        
        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumber(string inputData)
        {
            Match m = RegNumber.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);
            return m.Success;
        }        
        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData);
            return m.Success;
        }        
        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData);
            return m.Success;
        }        

        #endregion

        #region 中文检测

        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }    

        #endregion

        #region 邮件地址
        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }        

        #endregion

        #region 日期格式判断
        /// <summary>
        /// 日期格式字符串判断
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsDateTime(string str)
        {
            try
            {
                if (!string.IsNullOrEmpty(str))
                {
                    DateTime.Parse(str);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        } 
        #endregion

        #region 其他

        /// <summary>
        /// 检查字符串最大长度,返回指定长度的串
        /// </summary>
        /// <param name="sqlInput">输入字符串</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>            
        public static string SqlText(string sqlInput, int maxLength)
        {            
            if(sqlInput != null && sqlInput != string.Empty)
            {
                sqlInput = sqlInput.Trim();                            
                if(sqlInput.Length > maxLength)//按最大长度截取字符串
                    sqlInput = sqlInput.Substring(0, maxLength);
            }
            return sqlInput;
        }        
        /// <summary>
        /// 字符串编码
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static string HtmlEncode(string inputData)
        {
            return HttpUtility.HtmlEncode(inputData);
        }
        /// <summary>
        /// 设置Label显示Encode的字符串
        /// </summary>
        /// <param name="lbl"></param>
        /// <param name="txtInput"></param>
        public static void SetLabel(Label lbl, string txtInput)
        {
            lbl.Text = HtmlEncode(txtInput);
        }
        public static void SetLabel(Label lbl, object inputObj)
        {
            SetLabel(lbl, inputObj.ToString());
        }        
        //字符串清理
        public static string InputText(string inputString, int maxLength) 
        {            
            StringBuilder retVal = new StringBuilder();

            // 检查是否为空
            if ((inputString != null) && (inputString != String.Empty)) 
            {
                inputString = inputString.Trim();

                //检查长度
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //替换危险字符
                for (int i = 0; i < inputString.Length; i  ) 
                {
                    switch (inputString[i]) 
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }                
                retVal.Replace("'", " ");// 替换单引号
            }
            return retVal.ToString();

        }
        /// <summary>
        /// 转换成 HTML code
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string Encode(string str)
        {            
            str = str.Replace("&","&amp;");
            str = str.Replace("'","''");
            str = str.Replace(""","&quot;");
            str = str.Replace(" ","&nbsp;");
            str = str.Replace("<","&lt;");
            str = str.Replace(">","&gt;");
            str = str.Replace("n","<br>");
            return str;
        }
        /// <summary>
        ///解析html成 普通文本
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string Decode(string str)
        {            
            str = str.Replace("<br>","n");
            str = str.Replace("&gt;",">");
            str = str.Replace("&lt;","<");
            str = str.Replace("&nbsp;"," ");
            str = str.Replace("&quot;",""");
            return str;
        }

        public static string SqlTextClear(string sqlText)
        {
            if (sqlText == null)
            {
                return null;
            }
            if (sqlText == "")
            {
                return "";
            }
            sqlText = sqlText.Replace(",", "");//去除,
            sqlText = sqlText.Replace("<", "");//去除<
            sqlText = sqlText.Replace(">", "");//去除>
            sqlText = sqlText.Replace("--", "");//去除--
            sqlText = sqlText.Replace("'", "");//去除'
            sqlText = sqlText.Replace(""", "");//去除"
            sqlText = sqlText.Replace("=", "");//去除=
            sqlText = sqlText.Replace("%", "");//去除%
            sqlText = sqlText.Replace(" ", "");//去除空格
            return sqlText;
        }
        #endregion

        #region 是否由特定字符组成
        public static bool isContainSameChar(string strInput)
        {
            string charInput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                charInput = strInput.Substring(0, 1);
            }
            return isContainSameChar(strInput, charInput, strInput.Length);
        }

        public static bool isContainSameChar(string strInput, string charInput, int lenInput)
        {
            if (string.IsNullOrEmpty(charInput))
            {
                return false;
            }
            else
            {
                Regex RegNumber = new Regex(string.Format("^([{0}]) $", charInput));
                //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}}) $", charInput,lenInput));
                Match m = RegNumber.Match(strInput);
                return m.Success;
            }
        }
        #endregion

        #region 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
        /// <summary>
        /// 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
        /// </summary>
        public static bool isContainSpecChar(string strInput)
        {
            string[] list = new string[] { "123456", "654321" };
            bool result = new bool();
            for (int i = 0; i < list.Length; i  )
            {
                if (strInput == list[i])
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
        #endregion
    }

View Code

⑩拍卖枚举类,新建类RenumDropList,全体代码如下:

图片 27图片 28

 /// <summary>
   /// 处理枚举类
   /// </summary>
   public class RenumDropList
    {

     /// <summary>
        /// 讲枚举绑定在DropDownList上
     /// </summary>
     /// <param name="list">类型</param>
     /// <param name="text">第一项文字</param>
     /// <param name="TypeEnum">枚举(默认第一项为0)</param>
       public static void BindDropDownList(DropDownList list,string text,Type TypeEnum)
       {
           List<ListItem> TypeList = new List<ListItem>();

          // TypeList.Add(new ListItem(text, value));
           TypeList.Add(new ListItem { Text = "" text "", Value = "0"});


           foreach (object type in Enum.GetValues(TypeEnum))
            {
                TypeList.Add(new ListItem(type.ToString(), ((int)type).ToString()));
            }
            list.DataSource = TypeList;
            list.DataTextField = "text";
            list.DataValueField = "value";
            list.DataBind();

       }
      /// <summary>
       /// 讲枚举绑定在DropDownList上
      /// </summary>
      /// <param name="list">控件</param>
      /// <param name="TypeEnum">枚举</param>
       public static void BindDropDownList(DropDownList list, Type TypeEnum)
       {
           List<ListItem> TypeList = new List<ListItem>();
           foreach (object type in Enum.GetValues(TypeEnum))
           {
               TypeList.Add(new ListItem(type.ToString(), ((int)type).ToString()));
           }
           list.DataSource = TypeList;
           list.DataTextField = "text";
           list.DataValueField = "value";
           list.DataBind();

       }
       /// <summary>
       /// 讲枚举绑定在RadioButtonList上面
       /// </summary>
       /// <param name="list"></param>
       public static void BindRadioButtonList(RadioButtonList list,Type TypeEnem)
       {
           List<ListItem> TypeList = new List<ListItem>();



           foreach (object type in Enum.GetValues(TypeEnem))
           {
               string str=type.ToString();
               if (str.Contains('X'))
               {

                   str = str.Replace("X", "/");
               }
               TypeList.Add(new ListItem(str, ((int)type).ToString()));
           }
           list.DataSource = TypeList;
           list.DataTextField = "text";
           list.DataValueField = "value";
           list.DataBind();
       }

       /// <summary>
       /// 讲枚举绑定在DropDownList上
       /// </summary>
       /// <param name="list">类型</param>
       /// <param name="text">第一项文字</param>
       /// <param name="TypeEnum">枚举(默认第一项为0)</param>
       public static void BindDropDownList_Replace(DropDownList list, Type TypeEnum)
       {
           List<ListItem> TypeList = new List<ListItem>();

           // TypeList.Add(new ListItem(text, value));
           //TypeList.Add(new ListItem { Text = ""   text   "", Value = "0" });


           foreach (object type in Enum.GetValues(TypeEnum))
           {
               string str=type.ToString();
               if (str.Contains('N') || str.Contains('D') || str.Contains('G')||str.Contains('M')||str.Contains('Q'))
               {
                   str=str.Replace("N", "$");
                   str=str.Replace("D", ",");
                   str=str.Replace("G", " - ");
                   str = str.Replace("M", ".");
                   str = str.Replace("Q", "");
               }
               TypeList.Add(new ListItem(str, ((int)type).ToString()));
           }
           list.DataSource = TypeList;
           list.DataTextField = "text";
           list.DataValueField = "value";
           list.DataBind();

       }

       /// <summary>
       /// 选中某一项
       /// </summary>
       /// <param name="radio">类型</param>
       /// <param name="value">值</param>
       public static void RadioButtonChecked(RadioButtonList radio,string value)
       {

           for (int i = 0; i < radio.Items.Count; i  )
           {
               if (radio.Items[i].Value != value)
               {
                   radio.Items[i].Selected = false;
                  // continue;
               }
               else
               {
                   radio.ClearSelection();
                   radio.Items[i].Selected = true;

               }
           }
       }


       /// <summary>
       /// 选中某一项
       /// </summary>
       /// <param name="radio">类型</param>
       /// <param name="value">值</param>
       public static void DropDownListChecked(DropDownList drop, string value)
       {

           for (int i = 0; i <drop.Items.Count; i  )
           {
               if (drop.Items[i].Value != value)
               {
                   drop.Items[i].Selected = false;
                   //continue;
               }
               else
               {
                   drop.ClearSelection();
                   drop.Items[i].Selected = true;

               }
           }
       }


       /// <summary>
       /// 选中某一项
       /// </summary>
       /// <param name="radio">类型</param>
       /// <param name="value">值</param>
       public static void DropListChecked(DropDownList drop, string text)
       {
          // drop.ClearSelection();
           for (int i = 0; i < drop.Items.Count; i  )
           {
               if (drop.Items[i].Text != text)
               {
                   drop.Items[i].Selected = false;
                   //continue;
               }
               else
               {
                   drop.ClearSelection();
                   drop.Items[i].Selected = true;

               }
           }
       }

       /// <summary>
       /// 绑定枚举在CheckBoxList上
       /// </summary>
       /// <param name="list"></param>
       /// <param name="TypeEnum"></param>
       public static void BindCheckBoxList(CheckBoxList list, Type TypeEnum)
       {
           List<ListItem> TypeList = new List<ListItem>();
           foreach (object type in Enum.GetValues(TypeEnum))
           {
               TypeList.Add(new ListItem(type.ToString(), ((int)type).ToString()));
           }
           list.DataSource = TypeList;
           list.DataTextField = "text";
           list.DataValueField = "value";
           list.DataBind();

       }



    }

View Code

11 调换RMB大小金额 ,新建类Evoquemb ,全体代码如下:

图片 29图片 30

 /// <summary> 
    /// Rmb 的摘要说明。 
    /// </summary> 
    public class Rmb
    {
        /// <summary> 
        /// 转换人民币大小金额 
        /// </summary> 
        /// <param name="num">金额</param> 
        /// <returns>返回大写形式</returns> 
        public static string CmycurD(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str3 = "";    //从原num值中取出的值 
            string str4 = "";    //数字的字符串形式 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            int j;    //num的值乘以100的字符串长度 
            string ch1 = "";    //数字的汉语读法 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 
            int temp;            //从原num值中取出的值 

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式 
            j = str4.Length;      //找出最高位 
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如:200.55,j为5所以str2=佰拾元角分 

            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i  )
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值 
                temp = Convert.ToInt32(str3);      //转换为数字 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero   1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零"   str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿,亿,万,元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零"   str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero   1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero   1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero   1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位,则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5   ch1   ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位(分)为0时,加上“整” 
                    str5 = str5   '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }

        /**/
        /// <summary> 
        /// 一个重载,将字符串先转换成数字在调用CmycurD(decimal num) 
        /// </summary> 
        /// <param name="num">用户输入的金额,字符串形式未转成decimal</param> 
        /// <returns></returns> 
        public static string CmycurD(string numstr)
        {
            try
            {
                decimal num = Convert.ToDecimal(numstr);
                return CmycurD(num);
            }
            catch
            {
                return "非数字形式!";
            }
        }
    } 

View Code

12 时间扶持类 TimeParser,全体代码如下:

图片 31图片 32

public class TimeParser
    {
        /// <summary>
        /// 把秒转换成分钟
        /// </summary>
        /// <returns></returns>
        public static int SecondToMinute(int Second)
        {
            decimal mm = (decimal)((decimal)Second / (decimal)60);
            return Convert.ToInt32(Math.Ceiling(mm));           
        }

        #region 返回某年某月最后一天
        /// <summary>
        /// 返回某年某月最后一天
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns>日</returns>
        public static int GetMonthLastDate(int year, int month)
        {
            DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
            int Day = lastDay.Day;
            return Day;
        }
        #endregion

        #region 返回时间差
        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;
            try
            {
                //TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                //TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                //TimeSpan ts = ts1.Subtract(ts2).Duration();
                TimeSpan ts = DateTime2 - DateTime1;
                if (ts.Days >=1)
                {
                    dateDiff = DateTime1.Month.ToString()   "月"   DateTime1.Day.ToString()   "日";
                }
                else
                {
                    if (ts.Hours > 1)
                    {
                        dateDiff = ts.Hours.ToString()   "小时前";
                    }
                    else
                    {
                        dateDiff = ts.Minutes.ToString()   "分钟前";
                    }
                }
            }
            catch
            { }
            return dateDiff;
        }
        #endregion
    }

View Code

13 UENVISIONL的操作类,全体代码如下:

图片 33图片 34

  /// <summary>
    /// URL的操作类
    /// </summary>
    public class UrlOper
    {
        static System.Text.Encoding encoding = System.Text.Encoding.UTF8;

        #region URL的64位编码
        public static string Base64Encrypt(string sourthUrl)
        {
            string eurl = HttpUtility.UrlEncode(sourthUrl);
            eurl = Convert.ToBase64String(encoding.GetBytes(eurl));
            return eurl;
        }
        #endregion

        #region URL的64位解码
        public static string Base64Decrypt(string eStr)
        {        
            if (!IsBase64(eStr))
            {
                return eStr;
            }
            byte[] buffer = Convert.FromBase64String(eStr);
            string sourthUrl = encoding.GetString(buffer);
            sourthUrl = HttpUtility.UrlDecode(sourthUrl);
            return sourthUrl;
        }
        /// <summary>
        /// 是否是Base64字符串
        /// </summary>
        /// <param name="eStr"></param>
        /// <returns></returns>
        public static bool IsBase64(string eStr)
        {
            if ((eStr.Length % 4) != 0)
            {
                return false;
            }
            if (!Regex.IsMatch(eStr, "^[A-Z0-9/ =]*$", RegexOptions.IgnoreCase))
            {
                return false;
            }
            return true;
        }
        #endregion

        /// <summary>
        /// 添加URL参数
        /// </summary>
        public static string AddParam(string url, string paramName, string value)
        {
            Uri uri = new Uri(url);
            if (string.IsNullOrEmpty(uri.Query))
            {
                string eval = HttpContext.Current.Server.UrlEncode(value);
                return String.Concat(url, "?"   paramName   "="   eval);
            }
            else
            {
                string eval = HttpContext.Current.Server.UrlEncode(value);
                return String.Concat(url, "&"   paramName   "="   eval);
            }
        }
        /// <summary>
        /// 更新URL参数
        /// </summary>
        public static string UpdateParam(string url, string paramName, string value)
        {
            string keyWord = paramName "=";
            int index = url.IndexOf(keyWord) keyWord.Length;
            int index1 = url.IndexOf("&", index);
            if (index1 == -1)
            {
                url = url.Remove(index, url.Length - index);
                url = string.Concat(url, value);
                return url;
            }
            url = url.Remove(index,index1 - index);
            url = url.Insert(index, value);
            return url;
        }

        #region 分析URL所属的域
        public static void GetDomain(string fromUrl, out string domain, out string subDomain)
        {
            domain = "";
            subDomain = "";
            try
            {
                if (fromUrl.IndexOf("的名片") > -1)
                {
                    subDomain = fromUrl;
                    domain = "名片";
                    return;
                }

                UriBuilder builder = new UriBuilder(fromUrl);
                fromUrl = builder.ToString();

                Uri u = new Uri(fromUrl);

                if (u.IsWellFormedOriginalString())
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";

                    }
                    else
                    {
                        string Authority = u.Authority;
                        string[] ss = u.Authority.Split('.');
                        if (ss.Length == 2)
                        {
                            Authority = "www."   Authority;
                        }
                        int index = Authority.IndexOf('.', 0);
                        domain = Authority.Substring(index   1, Authority.Length - index - 1).Replace("comhttp","com");
                        subDomain = Authority.Replace("comhttp", "com"); 
                        if (ss.Length < 2)
                        {
                            domain = "不明路径";
                            subDomain = "不明路径";
                        }
                    }
                }
                else
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";
                    }
                    else
                    {
                        subDomain = domain = "不明路径";
                    }
                }
            }
            catch
            {
                subDomain = domain = "不明路径";
            }
        }

        /// <summary>
        /// 分析 url 字符串中的参数信息
        /// </summary>
        /// <param name="url">输入的 URL</param>
        /// <param name="baseUrl">输出 URL 的基础部分</param>
        /// <param name="nvc">输出分析后得到的 (参数名,参数值) 的集合</param>
        public static void ParseUrl(string url, out string baseUrl, out NameValueCollection nvc)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            nvc = new NameValueCollection();
            baseUrl = "";

            if (url == "")
                return;

            int questionMarkIndex = url.IndexOf('?');

            if (questionMarkIndex == -1)
            {
                baseUrl = url;
                return;
            }
            baseUrl = url.Substring(0, questionMarkIndex);
            if (questionMarkIndex == url.Length - 1)
                return;
            string ps = url.Substring(questionMarkIndex   1);

            // 开始分析参数对    
            Regex re = new Regex(@"(^|&)?(w )=([^&] )(&|$)?", RegexOptions.Compiled);
            MatchCollection mc = re.Matches(ps);

            foreach (Match m in mc)
            {
                nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
            }
        }

        #endregion
    }

View Code

14 SessionHelper,全体代码如下:

图片 35图片 36

 public class SessionHelper
    {
        public const string LOGININFO_NAME = "LOGININFO_NAME";

        public static T Get<T>(string name)
        {
            var value = HttpContext.Current.Session[name];

            if (value == null)
            {
                return default(T);
            }
            else
            {
                return (T)value;
            }
        }


        public static void Set(string name, object value)
        {
            var s = HttpContext.Current.Session[name];

            if (s != null)
            {
                HttpContext.Current.Session[name] = value;
            }
            else
            {
                HttpContext.Current.Session.Add(name, value);
            }
        }

        public static void Delete(string name)
        {
            HttpContext.Current.Session.Remove(name);
        }

        public static void Clear()
        {
            HttpContext.Current.Session.Clear();
        }

        public static object GetLoginInfo()
        {
            var value = HttpContext.Current.Session[LOGININFO_NAME];
            return value;
        }

        public static void SetLoginInfo(object value)
        {

            var s = HttpContext.Current.Session[LOGININFO_NAME];

            if (s != null)
            {
                HttpContext.Current.Session[LOGININFO_NAME] = value;
            }
            else
            {
                HttpContext.Current.Session.Add(LOGININFO_NAME, value);
            }
        }

        public static void RemoveLoginInfo()
        {
            HttpContext.Current.Session.Remove(LOGININFO_NAME);
        }
    }

View Code

使用方法:

举个例子,登录模块,客户点击登入之后可设置:

 SessionHelper.SetLoginInfo(用户实体);

Session使用:

       if (SessionHelper.GetLoginInfo() != null)
            {
                实例化用户实体= (实体)SessionHelper.GetLoginInfo();
            }

客商退出最佳清空Session

SessionHelper.RemoveLoginInfo();

 

15 验证码扶持类

效果:图片 37

新建验证码协助类VerificationCodeHelper,全体代码如下:

图片 38图片 39

public class VerificationCodeHelper
    {
        private static Color BackColor = Color.White;
        private static int Width = 62;
        private static int Height = 21;
        private Random _random;
        // private string _code;



        private int _brushNameIndex;

        public byte[] GetVCode(string codeStr)
        {
            _random = new Random();
            using (Bitmap img = new Bitmap(Width, Height))
            {
                // _code = GetRandomCode();
                // System.Web.HttpContext.Current.Session["vcode"] = _code;
                using (Graphics g = Graphics.FromImage(img))
                {
                    g.Clear(Color.White);//绘画背景颜色

                    Paint_Text(g, codeStr);// 绘画文字
                    // g.DrawString(strCode, new Font("微软雅黑", 15), Brushes.Blue, new PointF(5, 2));// 绘画文字
                    Paint_TextStain(img);// 绘画噪音点
                    g.DrawRectangle(Pens.DarkGray, 0, 0, Width - 1, Height - 1);//绘画边框
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        //将图片 保存到内存流中
                        img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                        //将内存流 里的 数据  转成 byte 数组 返回
                        return ms.ToArray();
                    }
                }
            }

        }

        /// <summary>
        /// 绘画文字
        /// </summary>
        /// <param name="g"></param>
        private void Paint_Text(Graphics g, string code)
        {
            g.DrawString(code, GetFont(), GetBrush(), 3, 1);
        }

        /// <summary>
        /// 绘画文字噪音点
        /// </summary>
        /// <param name="g"></param>
        private void Paint_TextStain(Bitmap b)
        {
            string[] BrushName = new string[] {    "OliveDrab",
                                                  "ForestGreen",
                                                  "DarkCyan",
                                                  "LightSlateGray",
                                                  "RoyalBlue",
                                                  "SlateBlue",
                                                  "DarkViolet",
                                                  "MediumVioletRed",
                                                  "IndianRed",
                                                  "Firebrick",
                                                  "Chocolate",
                                                  "Peru",
                                                  "Goldenrod"
                                             };

            for (int n = 0; n < 30; n  )
            {
                int x = _random.Next(Width);
                int y = _random.Next(Height);
                b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));

            }

        }
        /// <summary>
        /// 随机取一个字体
        /// </summary>
        /// <returns></returns>
        private Font GetFont()
        {
            string[] FontItems = new string[]{   "Arial", 
                                                  "Helvetica", 
                                                  "Geneva", 
                                                  "sans-serif", 
                                                  "Verdana"
                                              };

            int fontIndex = _random.Next(0, FontItems.Length);
            FontStyle fontStyle = GetFontStyle(_random.Next(0, 2));
            return new Font(FontItems[fontIndex], 12, fontStyle);
        }
        /**/
        /**/
        /**/
        /// <summary>
        /// 随机取一个笔刷
        /// </summary>
        /// <returns></returns>
        private Brush GetBrush()
        {
            Brush[] BrushItems = new Brush[]{     Brushes.OliveDrab,
                                                  Brushes.ForestGreen,
                                                  Brushes.DarkCyan,
                                                  Brushes.LightSlateGray,
                                                  Brushes.RoyalBlue,
                                                  Brushes.SlateBlue,
                                                  Brushes.DarkViolet,
                                                  Brushes.MediumVioletRed,
                                                  Brushes.IndianRed,
                                                  Brushes.Firebrick,
                                                  Brushes.Chocolate,
                                                  Brushes.Peru,
                                                  Brushes.Goldenrod
                                            };

            int brushIndex = _random.Next(0, BrushItems.Length);
            _brushNameIndex = brushIndex;
            return BrushItems[brushIndex];
        }
        /// <summary>
        /// 绘画背景颜色
        /// </summary>
        /// <param name="g"></param>
        private void Paint_Background(Graphics g)
        {
            g.Clear(BackColor);
        }
        /**/
        /**/
        /**/
        /// <summary>
        /// 取一个字体的样式
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private FontStyle GetFontStyle(int index)
        {
            switch (index)
            {
                case 0:
                    return FontStyle.Bold;
                case 1:
                    return FontStyle.Italic;
                default:
                    return FontStyle.Regular;
            }
        }

        /// <summary>
        /// 取得一个 4 位的随机码
        /// </summary>
        /// <returns></returns>
        public string GetRandomCode()
        {
            return Guid.NewGuid().ToString().Substring(0, 5);
        }
    }

View Code

使用:

前台HTML

 <img id="checkloing" src="/Login/VCode" class="loginFormCheckCodeImg" onclick="reloadcode('/Login/VCode')" title="Can not see clearly, change one." />

JS:

//刷新验证码
        function reloadcode(srcStr) {
            document.getElementById("checkloing").src = srcStr   "?rand="   Math.random();
        }

Controller

 /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 10, VaryByParam = "rand")]//缓存10秒钟
        [AllowAnonymous]//跳过登陆验证
        public ActionResult VCode()
        {
            VerificationCodeHelper vcode = new VerificationCodeHelper();
            string codeStr = vcode.GetRandomCode();
            if (!string.IsNullOrEmpty(codeStr))
            {
                byte[] arrImg = vcode.GetVCode(codeStr);
                Session["code"] = codeStr;
                return File(arrImg, "image/gif");
            }
            else
            {
                return RedirectToAction("/控制器/VCode?rand="   Guid.NewGuid().ToString().Substring(1, 10), "image/jpeg");
            }
        }

 

16 CookieHelper帮助类

图片 40图片 41

using System;
using System.Web;

namespace ConsoleApplication5
{
    /// <summary>
    /// Cookie 助手
    /// </summary>
    public sealed class CookieHelper
    {
        /// <summary>
        /// 添加一个 Cookie
        /// </summary>
        /// <param name="name">名</param>
        /// <param name="value">值</param>
        public static void Add(string name, string value)
        {
            var cookie = new HttpCookie(name, value);

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 添加一个 Cookie
        /// </summary>
        /// <param name="name">名</param>
        /// <param name="value">值</param>
        /// <param name="expires">过期日期和时间</param>
        public static void Add(string name, string value, DateTime expires)
        {
            var cookie = new HttpCookie(name, value)
            {
                Expires = expires
            };

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 获取 Cookie 值
        /// </summary>
        /// <param name="name">名</param>
        /// <returns></returns>
        public static string Get(string name)
        {
            var cookie = HttpContext.Current.Request.Cookies[name];

            return cookie == null ? string.Empty : cookie.Value;
        }
    }
}

View Code

17 JsonHepler

图片 42图片 43

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Web.Script.Serialization;

/// <summary>
///JsonHandleHelper 的摘要说明
/// </summary>
public class JsonHandleHelper
{

    /// <summary> 
    /// 对象转JSON 
    /// </summary> 
    /// <param name="obj">对象</param> 
    /// <returns>JSON格式的字符串</returns> 
    public static string ObjectToJSON(object obj)
    {
        JavaScriptSerializer jss =new JavaScriptSerializer();
        try
        {
            return jss.Serialize(obj);
        }
        catch(Exception ex)
        {

            throw new Exception("JSONHelper.ObjectToJSON(): "  ex.Message);
        }
    }
    /// <summary>
    /// 转换对象为JSON格式数据
    /// </summary>
    /// <typeparam name="T">类</typeparam>
    /// <param name="obj">对象</param>
    /// <returns>字符格式的JSON数据</returns>
    public static string GetJSON<T>(object obj)
    {
        string result = String.Empty;
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return result;
    }
    /// <summary>
    /// 转换List<T>的数据为JSON格式
    /// </summary>
    /// <typeparam name="T">类</typeparam>
    /// <param name="vals">列表值</param>
    /// <returns>JSON格式数据</returns>
    public static string JSON<T>(List<T> vals)
    {
        System.Text.StringBuilder st = new System.Text.StringBuilder();
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

            foreach (T city in vals)
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    s.WriteObject(ms, city);
                    st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return st.ToString();
    }
    /// <summary>
    /// JSON格式字符转换为T类型的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="jsonStr"></param>
    /// <returns></returns>
    public static T ParseFormByJson<T>(string jsonStr)
    {
        T obj = Activator.CreateInstance<T>();
        using (System.IO.MemoryStream ms =
        new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
    /// <summary> 
    /// 数据表转键值对集合 
    /// 把DataTable转成 List集合, 存每一行 
    /// 集合中放的是键值对字典,存每一列 
    /// </summary> 
    /// <param name="dt">数据表</param> 
    /// <returns>哈希表数组</returns> 
    public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
    {
        List<Dictionary<string, object>> list= new List<Dictionary<string, object>>();

        foreach (DataRow dr in dt.Rows)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            foreach (DataColumn dc in dt.Columns)
            {
                dic.Add(dc.ColumnName, dr[dc.ColumnName]);
            }
            list.Add(dic);
        }
        return list;
    }
    /// <summary> 
    /// 数据集转键值对数组字典 
    /// </summary> 
    /// <param name="dataSet">数据集</param> 
    /// <returns>键值对数组字典</returns> 
    public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
    {
        Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();

        foreach (DataTable dt in ds.Tables)
            result.Add(dt.TableName, DataTableToList(dt));

        return result;
    }
    /// <summary> 
    /// 数据表转JSON 
    /// </summary> 
    /// <param name="dataTable">数据表</param> 
    /// <returns>JSON字符串</returns> 
    public static string DataTableToJSON(DataTable dt)
    {
        return ObjectToJSON(DataTableToList(dt));
    }
    /// <summary> 
    /// JSON文本转对象,泛型方法 
    /// </summary> 
    /// <typeparam name="T">类型</typeparam> 
    /// <param name="jsonText">JSON文本</param> 
    /// <returns>指定类型的对象</returns> 
    public static T JSONToObject<T>(string jsonText)
    {
        JavaScriptSerializer jss =new JavaScriptSerializer();
        try
        {
            return jss.Deserialize<T>(jsonText);
        }
        catch(Exception ex)
        {
            throw new Exception("JSONHelper.JSONToObject(): "  ex.Message);
        }
    }
    /// <summary> 
    /// 将JSON文本转换为数据表数据 
    /// </summary> 
    /// <param name="jsonText">JSON文本</param> 
    /// <returns>数据表字典</returns> 
    public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
    {
        return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
    }
    /// <summary> 
    /// 将JSON文本转换成数据行 
    /// </summary> 
    /// <param name="jsonText">JSON文本</param> 
    /// <returns>数据行的字典</returns> 
    public static Dictionary<string, object> DataRowFromJSON(string jsonText)
    {
        return JSONToObject<Dictionary<string, object>>(jsonText);
    }

}

View Code

18 Log4net高产出、十二线程日志记录

图片 44图片 45

using log4net;
using log4net.Config;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Emrys.FlashLog
{
    public sealed class FlashLogger
    {
        /// <summary>
        /// 记录消息Queue
        /// </summary>
        private readonly ConcurrentQueue<FlashLogMessage> _que;

        /// <summary>
        /// 信号
        /// </summary>
        private readonly ManualResetEvent _mre;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILog _log;

        /// <summary>
        /// 日志
        /// </summary>
        private static FlashLogger _flashLog = new FlashLogger();


        private FlashLogger()
        {
            var configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"));
            if (!configFile.Exists)
            {
                throw new Exception("未配置log4net配置文件!");
            }

            // 设置日志配置文件路径
            XmlConfigurator.Configure(configFile);

            _que = new ConcurrentQueue<FlashLogMessage>();
            _mre = new ManualResetEvent(false);
            _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }

        /// <summary>
        /// 实现单例
        /// </summary>
        /// <returns></returns>
        public static FlashLogger Instance()
        {
            return _flashLog;
        }

        /// <summary>
        /// 另一个线程记录日志,只在程序初始化时调用一次
        /// </summary>
        public void Register()
        {
            Thread t = new Thread(new ThreadStart(WriteLog));
            t.IsBackground = false;
            t.Start();
        }

        /// <summary>
        /// 从队列中写日志至磁盘
        /// </summary>
        private void WriteLog()
        {
            while (true)
            {
                // 等待信号通知
                _mre.WaitOne();

                FlashLogMessage msg;
                // 判断是否有内容需要如磁盘 从列队中获取内容,并删除列队中的内容
                while (_que.Count > 0 && _que.TryDequeue(out msg))
                {
                    // 判断日志等级,然后写日志
                    switch (msg.Level)
                    {
                        case FlashLogLevel.Debug:
                            _log.Debug(msg.Message, msg.Exception);
                            break;
                        case FlashLogLevel.Info:
                            _log.Info(msg.Message, msg.Exception);
                            break;
                        case FlashLogLevel.Error:
                            _log.Error(msg.Message, msg.Exception);
                            break;
                        case FlashLogLevel.Warn:
                            _log.Warn(msg.Message, msg.Exception);
                            break;
                        case FlashLogLevel.Fatal:
                            _log.Fatal(msg.Message, msg.Exception);
                            break;
                    }
                }

                // 重新设置信号
                _mre.Reset();
                Thread.Sleep(1);
            }
        }


        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="message">日志文本</param>
        /// <param name="level">等级</param>
        /// <param name="ex">Exception</param>
        public void EnqueueMessage(string message, FlashLogLevel level, Exception ex = null)
        {
            if ((level == FlashLogLevel.Debug && _log.IsDebugEnabled)
             || (level == FlashLogLevel.Error && _log.IsErrorEnabled)
             || (level == FlashLogLevel.Fatal && _log.IsFatalEnabled)
             || (level == FlashLogLevel.Info && _log.IsInfoEnabled)
             || (level == FlashLogLevel.Warn && _log.IsWarnEnabled))
            {
                _que.Enqueue(new FlashLogMessage
                {
                    Message = "["   DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff")   "]rn"   message,
                    Level = level,
                    Exception = ex
                });

                // 通知线程往磁盘中写日志
                _mre.Set();
            }
        }

        public static void Debug(string msg, Exception ex = null)
        {
            Instance().EnqueueMessage(msg, FlashLogLevel.Debug, ex);
        }

        public static void Error(string msg, Exception ex = null)
        {
            Instance().EnqueueMessage(msg, FlashLogLevel.Error, ex);
        }

        public static void Fatal(string msg, Exception ex = null)
        {
            Instance().EnqueueMessage(msg, FlashLogLevel.Fatal, ex);
        }

        public static void Info(string msg, Exception ex = null)
        {
            Instance().EnqueueMessage(msg, FlashLogLevel.Info, ex);
        }

        public static void Warn(string msg, Exception ex = null)
        {
            Instance().EnqueueMessage(msg, FlashLogLevel.Warn, ex);
        }

    }

    /// <summary>
    /// 日志等级
    /// </summary>
    public enum FlashLogLevel
    {
        Debug,
        Info,
        Error,
        Warn,
        Fatal
    }


    /// <summary>
    /// 日志内容
    /// </summary>
    public class FlashLogMessage
    {
        public string Message { get; set; }
        public FlashLogLevel Level { get; set; }
        public Exception Exception { get; set; }

    }





}

View Code

使用:

1)轻巧询问

private static ImageCodecInfo GetImageCodecInfo(ImageFormat imageFormat)
{
    ImageCodecInfo[] imageCodecInfoArr = ImageCodecInfo.GetImageDecoders();
    foreach (ImageCodecInfo imageCodecInfo in imageCodecInfoArr)
    {
        if (imageCodecInfo.FormatID == imageFormat.Guid)
        {
            return imageCodecInfo;
        }
    }
    return null;
}

图片 46

亟需在先后运转时注册,如asp.net 程序中在Global.asax中的Application_Start注册

FlashLogger.Instance().Register();

 必要记录日志的地点调用就能够:

            FlashLogger.Debug("Debug");
            FlashLogger.Debug("Debug", new Exception("testexception"));
            FlashLogger.Info("Info");
            FlashLogger.Fatal("Fatal");
            FlashLogger.Error("Error");
            FlashLogger.Warn("Warn", new Exception("testexception"));

 

19 js中汉字转拼音

js类(新建一个pinyin.js文件,代码如下)

图片 47图片 48

String.prototype.toPinyin = function () {
    var str = ConvertPinyin(this);
    str = str.toUpperCase();
    return str;
}

// JavaScript Document
var PinYin = { "a": "u554au963fu9515", "ai": "u57c3u6328u54ceu5509u54c0u7691u764cu853cu77eeu827eu788du7231u9698u8bf6u6371u55f3u55ccu5ad2u7477u66a7u7839u953fu972d", "an": "u978du6c28u5b89u4ffau6309u6697u5cb8u80fau6848u8c19u57efu63deu72b4u5eb5u6849u94f5u9e4cu9878u9eef", "ang": "u80aeu6602u76ce", "ao": "u51f9u6556u71acu7ff1u8884u50b2u5965u61cau6fb3u5773u62d7u55f7u5662u5c99u5ed2u9068u5aaau9a9cu8071u87afu93cau9cccu93d6", "ba": "u82adu634cu6252u53edu5427u7b06u516bu75a4u5df4u62d4u8dcbu9776u628au8019u575du9738u7f62u7238u8307u83ddu8406u636du5c9cu705eu6777u94afu7c91u9c85u9b43", "bai": "u767du67cfu767eu6446u4f70u8d25u62dcu7a17u859cu63b0u97b4", "ban": "u6591u73edu642cu6273u822cu9881u677fu7248u626eu62ccu4f34u74e3u534au529eu7ecau962au5742u8c73u94a3u7622u764du8228", "bang": "u90a6u5e2eu6886u699cu8180u7ed1u68d2u78c5u868cu9551u508du8c24u84a1u8783", "bao": "u82deu80deu5305u8912u96f9u4fddu5821u9971u5b9du62b1u62a5u66b4u8c79u9c8du7206u52f9u8446u5b80u5b62u7172u9e28u8913u8db5u9f85", "bo": "u5265u8584u73bbu83e0u64adu62e8u94b5u6ce2u535au52c3u640fu94c2u7b94u4f2fu5e1bu8236u8116u818au6e24u6ccau9a73u4eb3u8543u5575u997du6a97u64d8u7934u94b9u9e41u7c38u8ddb", "bei": "u676fu7891u60b2u5351u5317u8f88u80ccu8d1du94a1u500du72c8u5907u60ebu7119u88abu5b5bu9642u90b6u57e4u84d3u5457u602bu6096u789au9e4eu8919u943e", "ben": "u5954u82efu672cu7b28u755au574cu951b", "beng": "u5d29u7ef7u752du6cf5u8e66u8ff8u552au5623u750f", "bi": "u903cu9f3bu6bd4u9119u7b14u5f7cu78a7u84d6u853du6bd5u6bd9u6bd6u5e01u5e87u75f9u95edu655du5f0au5fc5u8f9fu58c1u81c2u907fu965bu5315u4ef3u4ffeu8298u835cu8378u5421u54d4u72f4u5eb3u610eu6ed7u6fdeu5f3cu59a3u5a62u5b16u74a7u8d32u7540u94cbu79d5u88e8u7b5au7b85u7be6u822du895eu8df8u9ac0", "bian": "u97adu8fb9u7f16u8d2cu6241u4fbfu53d8u535eu8fa8u8fa9u8fabu904du533eu5f01u82c4u5fedu6c74u7f0fu7178u782du78a5u7a39u7a86u8759u7b3eu9cca", "biao": "u6807u5f6au8198u8868u5a4au9aa0u98d1u98d9u98dau706cu9556u9573u762du88f1u9cd4", "bie": "u9cd6u618bu522bu762au8e69u9cd8", "bin": "u5f6cu658cu6fd2u6ee8u5bbeu6448u50a7u6d5cu7f24u73a2u6ba1u8191u9554u9accu9b13", "bing": "u5175u51b0u67c4u4e19u79c9u997cu70b3u75c5u5e76u7980u90b4u6452u7ee0u678bu69dfu71f9", "bu": "u6355u535cu54fau8865u57e0u4e0du5e03u6b65u7c3fu90e8u6016u62cau535fu900bu74ffu6661u949au91ad", "ca": "u64e6u5693u7924", "cai": "u731cu88c1u6750u624du8d22u776cu8e29u91c7u5f69u83dcu8521", "can": "u9910u53c2u8695u6b8bu60edu60e8u707fu9a96u74a8u7cb2u9eea", "cang": "u82cdu8231u4ed3u6ca7u85cfu4f27", "cao": "u64cdu7cd9u69fdu66f9u8349u8279u5608u6f15u87acu825a", "ce": "u5395u7b56u4fa7u518cu6d4bu5202u5e3bu607b", "ceng": "u5c42u8e6du564c", "cha": "u63d2u53c9u832cu8336u67e5u78b4u643du5bdfu5c94u5deeu8be7u7339u9987u6c4au59f9u6748u6942u69ceu6aabu9497u9538u9572u8869", "chai": "u62c6u67f4u8c7au4faau8308u7625u867fu9f87", "chan": "u6400u63bau8749u998bu8c17u7f20u94f2u4ea7u9610u98a4u5181u8c04u8c36u8487u5edbu5fcfu6f7au6fb6u5b71u7fbcu5a75u5b17u9aa3u89c7u7985u9561u88e3u87feu8e94", "chang": "u660cu7316u573au5c1du5e38u957fu507fu80a0u5382u655eu7545u5531u5021u4f25u9b2fu82ccu83d6u5f9cu6005u60ddu960au5a3cu5ae6u6636u6c05u9cb3", "chao": "u8d85u6284u949eu671du5632u6f6eu5de2u5435u7092u600au7ec9u6641u8016", "che": "u8f66u626fu64a4u63a3u5f7bu6f88u577cu5c6eu7817", "chen": "u90f4u81e3u8fb0u5c18u6668u5ff1u6c89u9648u8d81u886cu79f0u8c0cu62bbu55d4u5bb8u741bu6987u809cu80c2u789cu9f80", "cheng": "u6491u57ceu6a59u6210u5448u4e58u7a0bu60e9u6f84u8bdau627fu901eu9a8bu79e4u57d5u5d4au5fb5u6d48u67a8u67fdu6a18u665fu584du77a0u94d6u88ceu86cfu9172", "chi": "u5403u75f4u6301u5319u6c60u8fdfu5f1bu9a70u803bu9f7fu4f88u5c3au8d64u7fc5u65a5u70bdu50bau5880u82aau830cu640bu53f1u54e7u557bu55e4u5f73u996cu6cb2u5ab8u6555u80ddu7719u7735u9e31u761bu892bu86a9u87adu7b1eu7beau8c49u8e05u8e1fu9b51", "chong": "u5145u51b2u866bu5d07u5ba0u833au5fe1u61a7u94f3u825f", "chou": "u62bdu916cu7574u8e0cu7a20u6101u7b79u4ec7u7ef8u7785u4e11u4fe6u5733u5e31u60c6u6eb4u59afu7633u96e0u9c8b", "chu": "u81edu521du51fau6a71u53a8u8e87u9504u96cfu6ec1u9664u695au7840u50a8u77d7u6410u89e6u5904u4e8du520du61b7u7eccu6775u696eu6a17u870du8e70u9edc", "chuan": "u63e3u5dddu7a7fu693du4f20u8239u5598u4e32u63beu821bu60f4u9044u5ddbu6c1au948fu9569u8221", "chuang": "u75aeu7a97u5e62u5e8au95efu521bu6006", "chui": "u5439u708au6376u9524u5782u9672u68f0u69cc", "chun": "u6625u693fu9187u5507u6df3u7eafu8822u4fc3u83bcu6c8cu80abu6710u9e51u877d", "chuo": "u6233u7ef0u851fu8fb6u8f8du955eu8e14u9f8a", "ci": "u75b5u8328u78c1u96ccu8f9eu6148u74f7u8bcdu6b64u523au8d50u6b21u8360u5472u5d6fu9e5au8785u7ccdu8d91", "cong": "u806au8471u56f1u5306u4eceu4e1bu506cu82c1u6dd9u9aa2u742eu7481u679e", "cu": "u51d1u7c97u918bu7c07u731du6b82u8e59", "cuan": "u8e7fu7be1u7a9cu6c46u64bau6615u7228", "cui": "u6467u5d14u50acu8106u7601u7cb9u6decu7fe0u8403u60b4u7480u69b1u96b9", "cun": "u6751u5b58u5bf8u78cbu5fd6u76b4", "cuo": "u64aeu6413u63aau632bu9519u539du811eu9509u77ecu75e4u9e7eu8e49u8e9c", "da": "u642du8fbeu7b54u7629u6253u5927u8037u54d2u55d2u601bu59b2u75b8u8921u7b2au977cu9791", "dai": "u5446u6b79u50a3u6234u5e26u6b86u4ee3u8d37u888bu5f85u902eu6020u57edu7519u5454u5cb1u8fe8u902fu9a80u7ed0u73b3u9edb", "dan": "u803du62c5u4e39u5355u90f8u63b8u80c6u65e6u6c2eu4f46u60eeu6de1u8bdeu5f39u86cbu4ebbu510bu5369u840fu5556u6fb9u6a90u6b9au8d55u7708u7605u8043u7baa", "dang": "u5f53u6321u515au8361u6863u8c20u51fcu83eau5b95u7800u94dbu88c6", "dao": "u5200u6363u8e48u5012u5c9bu7977u5bfcu5230u7a3bu60bcu9053u76d7u53e8u5541u5fc9u6d2eu6c18u7118u5fd1u7e9b", "de": "u5fb7u5f97u7684u951d", "deng": "u8e6cu706fu767bu7b49u77aau51f3u9093u5654u5d9du6225u78f4u956bu7c26", "di": "u5824u4f4eu6ef4u8feau654cu7b1bu72c4u6da4u7fdfu5ae1u62b5u5e95u5730u8482u7b2cu5e1du5f1fu9012u7f14u6c10u7c74u8bcbu8c1bu90b8u577bu839cu837bu5600u5a23u67e2u68e3u89ccu7825u78b2u7747u955du7f9du9ab6", "dian": "u98a0u6382u6ec7u7898u70b9u5178u975bu57abu7535u4f43u7538u5e97u60e6u5960u6dc0u6bbfu4e36u963du576bu57ddu5dc5u73b7u765cu766bu7c1fu8e2e", "diao": "u7889u53fcu96d5u51cbu5201u6389u540au9493u8c03u8f7au94deu8729u7c9cu8c82", "die": "u8dccu7239u789fu8776u8fedu8c0du53e0u4f5au57a4u581eu63f2u558bu6e2bu8f76u7252u74deu8936u800bu8e40u9cbdu9cce", "ding": "u4e01u76efu53eeu9489u9876u9f0eu952du5b9au8ba2u4e22u4ec3u5576u738eu815au7887u753au94e4u7594u8035u914a", "dong": "u4e1cu51acu8463u61c2u52a8u680bu4f97u606bu51bbu6d1eu578cu549au5cbdu5cd2u5902u6c21u80e8u80f4u7850u9e2b", "dou": "u515cu6296u6597u9661u8c46u9017u75d8u8538u94adu7aa6u7aacu86aau7bfcu9161", "du": "u90fdu7763u6bd2u728au72ecu8bfbu5835u7779u8d4cu675cu9540u809au5ea6u6e21u5992u828fu561fu6e0eu691fu6a50u724du8839u7b03u9ad1u9ee9", "duan": "u7aefu77edu953bu6bb5u65adu7f0eu5f56u6934u7145u7c16", "dui": "u5806u5151u961fu5bf9u603cu619du7893", "dun": "u58a9u5428u8e72u6566u987fu56e4u949du76feu9041u7096u7818u7905u76f9u9566u8db8", "duo": "u6387u54c6u591au593au579bu8eb2u6735u8dfau8235u5241u60f0u5815u5484u54dau7f0du67c1u94ceu88f0u8e31", "e": "u86feu5ce8u9e45u4fc4u989du8bb9u5a25u6076u5384u627cu904fu9102u997fu5669u8c14u57a9u57adu82cau83aau843cu5443u6115u5c59u5a40u8f6du66f7u816du786au9507u9537u9e57u989au9cc4", "en": "u6069u84bdu6441u5514u55ef", "er": "u800cu513fu8033u5c14u9975u6d31u4e8cu8d30u8fe9u73e5u94d2u9e38u9c95", "fa": "u53d1u7f5au7b4fu4f10u4e4fu9600u6cd5u73d0u57a1u781d", "fan": "u85e9u5e06u756au7ffbu6a0au77feu9492u7e41u51e1u70e6u53cdu8fd4u8303u8d29u72afu996du6cdbu8629u5e61u72adu68b5u6535u71d4u7548u8e6f", "fang": "u574au82b3u65b9u80aau623fu9632u59a8u4effu8bbfu7ebau653eu531au90a1u5f77u94abu822bu9c82", "fei": "u83f2u975eu5561u98deu80a5u532au8bfdu5420u80bau5e9fu6cb8u8d39u82beu72d2u60b1u6dddu5983u7ecbu7eefu69a7u8153u6590u6249u7953u7829u9544u75f1u871au7bdau7fe1u970fu9cb1", "fen": "u82acu915au5429u6c1bu5206u7eb7u575fu711au6c7eu7c89u594bu4efdu5fffu6124u7caau507eu7035u68fcu610du9cbcu9f22", "feng": "u4e30u5c01u67abu8702u5cf0u950bu98ceu75afu70fdu9022u51afu7f1du8bbdu5949u51e4u4ff8u9146u8451u6ca3u781c", "fu": "u4f5bu5426u592bu6577u80a4u5b75u6276u62c2u8f90u5e45u6c1fu7b26u4f0fu4fd8u670du6d6eu6daau798fu88b1u5f17u752bu629au8f85u4fefu91dcu65a7u812fu8151u5e9cu8150u8d74u526fu8986u8d4bu590du5085u4ed8u961cu7236u8179u8d1fu5bccu8ba3u9644u5987u7f1au5490u5310u51ebu90dbu8299u82fbu832fu83a9u83d4u544bu5e5eu6ecfu8274u5b5au9a78u7ec2u6874u8d59u9efbu9efcu7f58u7a03u99a5u864du86a8u8709u8760u876eu9eb8u8dbau8dd7u9cc6", "ga": "u5676u560eu86e4u5c2cu5477u5c15u5c1cu65eeu9486", "gai": "u8be5u6539u6982u9499u76d6u6e89u4e10u9654u5793u6224u8d45u80f2", "gan": "u5e72u7518u6746u67d1u7affu809du8d76u611fu79c6u6562u8d63u5769u82f7u5c34u64c0u6cd4u6de6u6f89u7ec0u6a44u65f0u77f8u75b3u9150", "gang": "u5188u521au94a2u7f38u809bu7eb2u5c97u6e2fu6206u7f61u9883u7b7b", "gong": "u6760u5de5u653bu529fu606du9f9au4f9bu8eacu516cu5babu5f13u5de9u6c5eu62f1u8d21u5171u857bu5efeu54a3u73d9u80b1u86a3u86e9u89e5", "gao": "u7bd9u768bu9ad8u818fu7f94u7cd5u641eu9550u7a3fu544au777eu8bf0u90dcu84bfu85c1u7f1fu69d4u69c1u6772u9506", "ge": "u54e5u6b4cu6401u6208u9e3du80f3u7599u5272u9769u845bu683cu9601u9694u94ecu4e2au5404u9b32u4ee1u54ffu5865u55ddu7ea5u643fu8188u784cu94eau9549u88bcu988cu867cu8238u9abcu9ac2", "gei": "u7ed9", "gen": "u6839u8ddfu4e98u831bu54cfu826e", "geng": "u8015u66f4u5e9au7fb9u57c2u803fu6897u54fdu8d53u9ca0", "gou": "u94a9u52feu6c9fu82dfu72d7u57a2u6784u8d2du591fu4f5du8bdfu5ca3u9058u5abeu7f11u89cfu5f40u9e32u7b31u7bddu97b2", "gu": "u8f9cu83c7u5495u7b8du4f30u6cbdu5b64u59d1u9f13u53e4u86cau9aa8u8c37u80a1u6545u987eu56fau96c7u560fu8bc2u83f0u54ccu5d2eu6c69u688fu8f71u726fu727fu80cdu81ccu6bc2u77bdu7f5fu94b4u9522u74e0u9e2au9e44u75fcu86c4u9164u89dau9cb4u9ab0u9e58", "gua": "u522eu74dcu5250u5be1u6302u8902u5366u8bd6u5471u681du9e39", "guai": "u4e56u62d0u602au54d9", "guan": "u68fau5173u5b98u51a0u89c2u7ba1u9986u7f50u60efu704cu8d2fu500cu839eu63bcu6dabu76e5u9e73u9ccf", "guang": "u5149u5e7fu901bu72b7u6844u80f1u7592", "gui": "u7470u89c4u572du7845u5f52u9f9fu95fau8f68u9b3cu8be1u7678u6842u67dcu8deau8d35u523du5326u523fu5e8bu5b84u59abu6867u7085u6677u7688u7c0bu9c91u9cdc", "gun": "u8f8au6edau68cdu4e28u886eu7ef2u78d9u9ca7", "guo": "u9505u90edu56fdu679cu88f9u8fc7u9998u8803u57dau63b4u5459u56d7u5e3cu5d1eu7313u6901u8662u951eu8052u872eu873eu8748", "ha": "u54c8", "hai": "u9ab8u5b69u6d77u6c26u4ea5u5bb3u9a87u54b4u55e8u988fu91a2", "han": "u9163u61a8u90afu97e9u542bu6db5u5bd2u51fdu558au7f55u7ff0u64bcu634du65f1u61beu608du710au6c57u6c49u9097u83e1u6496u961au701au6657u7113u9894u86b6u9f3e", "hen": "u592fu75d5u5f88u72e0u6068", "hang": "u676du822au6c86u7ed7u73e9u6841", "hao": "u58d5u568eu8c6au6bebu90ddu597du8017u53f7u6d69u8585u55e5u5686u6fe0u704fu660au7693u98a2u869d", "he": "u5475u559du8377u83cfu6838u79beu548cu4f55u5408u76d2u8c89u9602u6cb3u6db8u8d6bu8910u9e64u8d3au8bc3u52beu58d1u85ffu55d1u55ecu9616u76cdu86b5u7fee", "hei": "u563fu9ed1", "heng": "u54fcu4ea8u6a2au8861u6052u8a07u8605", "hong": "u8f70u54c4u70d8u8679u9e3fu6d2au5b8fu5f18u7ea2u9ec9u8ba7u836du85a8u95f3u6cd3", "hou": "u5589u4fafu7334u543cu539au5019u540eu5820u5f8cu9005u760au7bccu7cc7u9c8eu9aba", "hu": "u547cu4e4eu5ffdu745au58f6u846bu80e1u8774u72d0u7ccau6e56u5f27u864eu552cu62a4u4e92u6caau6237u51b1u553fu56ebu5cb5u7322u6019u60dau6d52u6ef9u7425u69f2u8f77u89f3u70c0u7173u623du6248u795cu9e55u9e71u7b0fu9190u659b", "hua": "u82b1u54d7u534eu733eu6ed1u753bu5212u5316u8bddu5290u6d4du9a85u6866u94e7u7a1e", "huai": "u69d0u5f8au6000u6deeu574fu8fd8u8e1d", "huan": "u6b22u73afu6853u7f13u6362u60a3u5524u75eau8c62u7115u6da3u5ba6u5e7bu90c7u5942u57b8u64d0u571cu6d39u6d63u6f36u5bf0u902du7f33u953eu9ca9u9b1f", "huang": "u8352u614cu9ec4u78fau8757u7c27u7687u51f0u60f6u714cu6643u5e4cu604du8c0eu968du5fa8u6e5fu6f62u9051u749cu8093u7640u87e5u7bc1u9cc7", "hui": "u7070u6325u8f89u5fbdu6062u86d4u56deu6bc1u6094u6167u5349u60e0u6666u8d3fu79fdu4f1au70e9u6c47u8bb3u8bf2u7ed8u8bd9u8334u835fu8559u54d5u5599u96b3u6d04u5f57u7f0bu73f2u6656u605au867au87eau9ebe", "hun": "u8364u660fu5a5au9b42u6d51u6df7u8be8u9984u960du6eb7u7f17", "huo": "u8c41u6d3bu4f19u706bu83b7u6216u60d1u970du8d27u7978u6509u56afu5925u94acu952au956cu8020u8816", "ji": "u51fbu573eu57fau673au7578u7a3du79efu7b95u808cu9965u8ff9u6fc0u8ba5u9e21u59ecu7ee9u7f09u5409u6781u68d8u8f91u7c4du96c6u53cau6025u75beu6c72u5373u5ac9u7ea7u6324u51e0u810au5df1u84dfu6280u5180u5b63u4f0eu796du5242u60b8u6d4eu5bc4u5bc2u8ba1u8bb0u65e2u5fccu9645u5993u7ee7u7eaau5c45u4e0cu4e69u525eu4f76u4f74u8114u58bcu82a8u82b0u8401u84bau857au638eu53fdu54adu54dcu5527u5c8cu5d74u6d0eu5f50u5c50u9aa5u757fu7391u696bu6b9bu621fu6222u8d4du89cau7284u9f51u77f6u7f81u5d47u7a37u7620u7635u866eu7b08u7b04u66a8u8dfbu8dfdu9701u9c9au9cabu9afbu9e82", "jia": "u5609u67b7u5939u4f73u5bb6u52a0u835au988au8d3eu7532u94beu5047u7a3cu4ef7u67b6u9a7eu5ac1u4f3du90cfu62eeu5cacu6d43u8fe6u73c8u621bu80dbu605du94d7u9553u75c2u86f1u7b33u8888u8dcf", "jian": "u6b7cu76d1u575au5c16u7b3au95f4u714eu517cu80a9u8270u5978u7f04u8327u68c0u67ecu78b1u7877u62e3u6361u7b80u4fedu526au51cfu8350u69dbu9274u8df5u8d31u89c1u952eu7badu4ef6u5065u8230u5251u996fu6e10u6e85u6da7u5efau50edu8c0fu8c2bu83c5u84b9u641bu56ddu6e54u8e47u8b07u7f23u67a7u67d9u6957u620bu622cu726eu728du6bfdu8171u7751u950fu9e63u88e5u7b15u7bb4u7fe6u8dbcu8e3au9ca3u97af", "jiang": "u50f5u59dcu5c06u6d46u6c5fu7586u848bu6868u5956u8bb2u5320u9171u964du8333u6d1au7edbu7f30u729fu7913u8029u7ce8u8c47", "jiao": "u8549u6912u7901u7126u80f6u4ea4u90cau6d47u9a84u5a07u56bcu6405u94f0u77ebu4fa5u811au72e1u89d2u997au7f34u7edeu527fu6559u9175u8f7fu8f83u53ebu4f7cu50ecu832du6322u564du5ce4u5fbcu59e3u7e9fu656bu768eu9e6au86dfu91aeu8de4u9c9b", "jie": "u7a96u63edu63a5u7686u79f8u8857u9636u622au52abu8282u6854u6770u6377u776bu7aedu6d01u7ed3u89e3u59d0u6212u85c9u82a5u754cu501fu4ecbu75a5u8bebu5c4au5048u8ba6u8bd8u5588u55dfu736cu5a55u5b51u6840u7352u78a3u9534u7596u88b7u9889u86a7u7fafu9c92u9ab1u9aeb", "jin": "u5dfeu7b4bu65a4u91d1u4ecau6d25u895fu7d27u9526u4ec5u8c28u8fdbu9773u664bu7981u8fd1u70ecu6d78u5c3du537au8369u5807u5664u9991u5ed1u5997u7f19u747eu69ffu8d46u89d0u9485u9513u887fu77dc", "jing": "u52b2u8346u5162u830eu775bu6676u9cb8u4eacu60cau7cbeu7cb3u7ecfu4e95u8b66u666fu9888u9759u5883u656cu955cu5f84u75c9u9756u7adfu7adeu51c0u522du5106u9631u83c1u734du61acu6cfeu8ff3u5f2au5a67u80bcu80ebu8148u65cc", "jiong": "u70afu7a98u5182u8fe5u6243", "jiu": "u63eau7a76u7ea0u7396u97edu4e45u7078u4e5du9152u53a9u6551u65e7u81fcu8205u548eu5c31u759au50e6u557eu9604u67e9u6855u9e6bu8d73u9b0f", "ju": "u97a0u62d8u72d9u75bdu9a79u83cau5c40u5480u77e9u4e3eu6caeu805au62d2u636eu5de8u5177u8dddu8e1eu952fu4ff1u53e5u60e7u70acu5267u5028u8bb5u82e3u82f4u8392u63acu907du5c66u741au67b8u6910u6998u6989u6a58u728bu98d3u949cu9514u7aadu88feu8d84u91b5u8e3du9f83u96ceu97ab", "juan": "u6350u9e43u5a1fu5026u7737u5377u7ee2u9104u72f7u6d93u684au8832u9529u954cu96bd", "jue": "u6485u652bu6289u6398u5014u7235u89c9u51b3u8bc0u7eddu53a5u5282u8c32u77cdu8568u5658u5d1bu7357u5b53u73cfu6877u6a5bu721du9562u8e76u89d6", "jun": "u5747u83ccu94a7u519bu541bu5cfbu4fcau7ae3u6d5au90e1u9a8fu6343u72fbu76b2u7b60u9e87", "ka": "u5580u5496u5361u4f67u5494u80e9", "ke": "u54afu5777u82dbu67efu68f5u78d5u9897u79d1u58f3u54b3u53efu6e34u514bu523bu5ba2u8bfeu5ca2u606au6e98u9a92u7f02u73c2u8f72u6c2au778cu94b6u75b4u7aa0u874cu9ac1", "kai": "u5f00u63e9u6977u51efu6168u5240u57b2u8488u5ffeu607au94e0u950e", "kan": "u520au582au52d8u574eu780du770bu4f83u51f5u83b0u83b6u6221u9f9bu77b0", "kang": "u5eb7u6177u7ce0u625bu6297u4ea2u7095u5751u4f09u95f6u94aa", "kao": "u8003u62f7u70e4u9760u5c3bu6832u7292u94d0", "ken": "u80afu5543u57a6u6073u57a0u88c9u9880", "keng": "u542du5fd0u94ff", "kong": "u7a7au6050u5b54u63a7u5025u5d06u7b9c", "kou": "u62a0u53e3u6263u5bc7u82a4u853bu53e9u770du7b58", "ku": "u67afu54edu7a9fu82e6u9177u5e93u88e4u5233u5800u55beu7ed4u9ab7", "kua": "u5938u57aeu630eu8de8u80efu4f89", "kuai": "u5757u7b77u4fa9u5febu84afu90d0u8489u72efu810d", "kuan": "u5bbdu6b3eu9acb", "kuang": "u5321u7b50u72c2u6846u77ffu7736u65f7u51b5u8bd3u8bf3u909du5739u593cu54d0u7ea9u8d36", "kui": "u4e8fu76d4u5cbfu7aa5u8475u594eu9b41u5080u9988u6127u6e83u9997u532eu5914u9697u63c6u55b9u559fu609du6126u9615u9035u668cu777du8069u8770u7bd1u81feu8dec", "kun": "u5764u6606u6346u56f0u6083u9603u7428u951fu918cu9cb2u9ae1", "kuo": "u62ecu6269u5ed3u9614u86de", "la": "u5783u62c9u5587u8721u814au8fa3u5566u524cu647au908bu65efu782cu760c", "lai": "u83b1u6765u8d56u5d03u5f95u6d9eu6fd1u8d49u7750u94fcu765eu7c41", "lan": "u84ddu5a6au680fu62e6u7beeu9611u5170u6f9cu8c30u63fdu89c8u61d2u7f06u70c2u6ee5u5549u5c9au61d4u6f24u6984u6593u7f71u9567u8934", "lang": "u7405u6994u72fcu5ecau90ceu6717u6d6au83a8u8497u5577u9606u9512u7a02u8782", "lao": "u635eu52b3u7262u8001u4f6cu59e5u916au70d9u6d9du5520u5d02u6833u94d1u94f9u75e8u91aa", "le": "u52d2u4e50u808bu4ec2u53fbu561eu6cd0u9cd3", "lei": "u96f7u956du857eu78cau7d2fu5121u5792u64c2u7c7bu6ceau7fb8u8bd4u837du54a7u6f2fu5ad8u7f27u6a91u8012u9179", "ling": "u68f1u51b7u62ceu73b2u83f1u96f6u9f84u94c3u4f36u7f9au51ccu7075u9675u5cadu9886u53e6u4ee4u9143u5844u82d3u5464u56f9u6ce0u7eebu67c3u68c2u74f4u8046u86c9u7fceu9cae", "leng": "u695eu6123", "li": "u5398u68a8u7281u9eceu7bf1u72f8u79bbu6f13u7406u674eu91ccu9ca4u793cu8389u8354u540fu6817u4e3du5389u52b1u783eu5386u5229u5088u4f8bu4fd0u75e2u7acbu7c92u6ca5u96b6u529bu7483u54e9u4feau4fdau90e6u575cu82c8u8385u84e0u85dcu6369u5456u5533u55b1u7301u6ea7u6fa7u9026u5a0cu5ae0u9a8au7f21u73deu67a5u680eu8f79u623eu783au8a48u7f79u9502u9e42u75a0u75acu86ceu870au8821u7b20u7be5u7c9du91b4u8ddeu96f3u9ca1u9ce2u9ee7", "lian": "u4fe9u8054u83b2u8fdeu9570u5ec9u601cu6d9fu5e18u655bu8138u94feu604bu70bcu7ec3u631bu8539u5941u6f4bu6fc2u5a08u740fu695du6b93u81c1u81a6u88e2u880au9ca2", "liang": "u7caeu51c9u6881u7cb1u826fu4e24u8f86u91cfu667eu4eaeu8c05u589au690bu8e09u9753u9b49", "liao": "u64a9u804au50dau7597u71ceu5be5u8fbdu6f66u4e86u6482u9563u5ed6u6599u84fcu5c25u5639u7360u5beeu7f2du948cu9e69u8022", "lie": "u5217u88c2u70c8u52a3u730eu51bdu57d2u6d0cu8d94u8e90u9b23", "lin": "u7433u6797u78f7u9716u4e34u90bbu9cdeu6dcbu51dbu8d41u541du853au5d99u5eeau9074u6aa9u8f9au77b5u7cbcu8e8fu9e9f", "liu": "u6e9cu7409u69b4u786bu998fu7559u5218u7624u6d41u67f3u516du62a1u507bu848cu6cd6u6d4fu905bu9a9du7efau65d2u7198u950du954fu9e68u938f", "long": "u9f99u804bu5499u7b3cu7abfu9686u5784u62e2u9647u5f04u5785u830fu6cf7u73d1u680au80e7u783bu7643", "lou": "u697cu5a04u6402u7bd3u6f0fu964bu55bdu5d5du9542u7618u8027u877cu9ac5", "lu": "u82a6u5362u9885u5e90u7089u63b3u5364u864fu9c81u9e93u788cu9732u8defu8d42u9e7fu6f5eu7984u5f55u9646u622eu5786u6445u64b8u565cu6cf8u6e0cu6f09u7490u680cu6a79u8f73u8f82u8f98u6c07u80eau9565u9e2cu9e6du7c0fu823bu9c88", "lv": "u9a74u5415u94ddu4fa3u65c5u5c65u5c61u7f15u8651u6c2fu5f8bu7387u6ee4u7effu634bu95feu6988u8182u7a06u891b", "luan": "u5ce6u5b6au6ee6u5375u4e71u683eu9e3eu92ae", "lue": "u63a0u7565u950a", "lun": "u8f6eu4f26u4ed1u6ca6u7eb6u8bbau56f5", "luo": "u841du87bau7f57u903bu9523u7ba9u9aa1u88f8u843du6d1bu9a86u7edcu502eu8366u645eu7321u6cfau6924u8136u9559u7630u96d2", "ma": "u5988u9ebbu739bu7801u8682u9a6cu9a82u561bu5417u551bu72b8u5b37u6769u9ebd", "mai": "u57cbu4e70u9ea6u5356u8fc8u8109u52a2u836cu54aau973e", "man": "u7792u9992u86eeu6ee1u8513u66fcu6162u6f2bu8c29u5881u5e54u7f26u71b3u9558u989fu87a8u9cd7u9794", "mang": "u8292u832bu76f2u5fd9u83bdu9099u6f2du6726u786du87d2", "meng": "u6c13u840cu8499u6aacu76dfu9530u731bu68a6u5b5fu52d0u750du77a2u61f5u791eu867bu8722u8813u824bu8268u9efe", "miao": "u732bu82d7u63cfu7784u85d0u79d2u6e3au5e99u5999u55b5u9088u7f08u7f2au676au6dfcu7707u9e4bu8731", "mao": "u8305u951au6bdbu77dbu94c6u536fu8302u5192u5e3du8c8cu8d38u4f94u88a4u52d6u8306u5cc1u7441u6634u7266u8004u65c4u61cbu7780u86d1u8765u87cau9ae6", "me": "u4e48", "mei": "u73abu679au6885u9176u9709u7164u6ca1u7709u5a92u9541u6bcfu7f8eu6627u5bd0u59b9u5a9au5776u8393u5d4bu7338u6d7cu6e44u6963u9545u9e5bu8882u9b45", "men": "u95e8u95f7u4eecu626au739fu7116u61d1u9494", "mi": "u772fu919au9761u7cdcu8ff7u8c1cu5f25u7c73u79d8u89c5u6cccu871cu5bc6u5e42u8288u5196u8c27u863cu5627u7315u736fu6c68u5b93u5f2du8112u6549u7cf8u7e3bu9e8b", "mian": "u68c9u7720u7ef5u5195u514du52c9u5a29u7f05u9762u6c94u6e4eu817cu7704", "mie": "u8511u706du54a9u881bu7bfe", "min": "u6c11u62bfu76bfu654fu60afu95fdu82e0u5cb7u95f5u6cefu73c9", "ming": "u660eu879fu9e23u94edu540du547du51a5u8317u6e9fu669du7791u9169", "miu": "u8c2c", "mo": "u6478u6479u8611u6a21u819cu78e8u6469u9b54u62b9u672bu83abu58a8u9ed8u6cabu6f20u5bdeu964cu8c1fu8309u84e6u998du5aebu9546u79e3u763cu8031u87c6u8c8au8c98", "mou": "u8c0bu725fu67d0u53b6u54deu5a7au7738u936a", "mu": "u62c7u7261u4ea9u59c6u6bcdu5893u66aeu5e55u52dfu6155u6728u76eeu7766u7267u7a46u4eebu82dcu5452u6c90u6beau94bc", "na": "u62ffu54eau5450u94a0u90a3u5a1cu7eb3u5185u637au80adu954eu8872u7bac", "nai": "u6c16u4e43u5976u8010u5948u9f10u827fu8418u67f0", "nan": "u5357u7537u96beu56cau5583u56e1u6960u8169u877bu8d67", "nao": "u6320u8111u607cu95f9u5b6cu57b4u7331u7459u7847u94d9u86f2", "ne": "u6dd6u5462u8bb7", "nei": "u9981", "nen": "u5ae9u80fdu6798u6041", "ni": "u59aeu9713u502au6ce5u5c3cu62dfu4f60u533fu817bu9006u6ebau4f32u576du730au6029u6ee0u6635u65ceu7962u615du7768u94ccu9cb5", "nian": "u852bu62c8u5e74u78beu64b5u637bu5ff5u5effu8f87u9ecfu9c87u9cb6", "niang": "u5a18u917f", "niao": "u9e1fu5c3fu8311u5b32u8132u8885", "nie": "u634fu8042u5b7du556eu954au954du6d85u4e5cu9667u8616u55ebu8080u989eu81ecu8e51", "nin": "u60a8u67e0", "ning": "u72deu51ddu5b81u62e7u6cdeu4f5eu84e5u549bu752fu804d", "niu": "u725bu626du94aeu7ebdu72c3u5ff8u599eu86b4", "nong": "u8113u6d53u519cu4fac", "nu": "u5974u52aau6012u5476u5e11u5f29u80ecu5b65u9a7d", "nv": "u5973u6067u9495u8844", "nuan": "u6696", "nuenue": "u8650", "nue": "u759fu8c11", "nuo": "u632au61e6u7cefu8bfau50a9u6426u558fu9518", "ou": "u54e6u6b27u9e25u6bb4u85d5u5455u5076u6ca4u6004u74efu8026", "pa": "u556au8db4u722cu5e15u6015u7436u8469u7b62", "pai": "u62cdu6392u724cu5f98u6e43u6d3eu4ff3u848e", "pan": "u6500u6f58u76d8u78d0u76fcu7554u5224u53dbu723fu6ceeu88a2u897bu87e0u8e52", "pang": "u4e53u5e9eu65c1u802au80d6u6ec2u9004", "pao": "u629bu5486u5228u70aeu888du8dd1u6ce1u530fu72cdu5e96u812cu75b1", "pei": "u5478u80dau57f9u88f4u8d54u966au914du4f69u6c9bu638au8f94u5e14u6de0u65c6u952bu9185u9708", "pen": "u55b7u76c6u6e53", "peng": "u7830u62a8u70f9u6f8eu5f6du84ecu68dau787cu7bf7u81a8u670bu9e4fu6367u78b0u576fu580bu562du6026u87db", "pi": "u7812u9739u6279u62abu5288u7435u6bd7u5564u813eu75b2u76aeu5339u75deu50fbu5c41u8b6cu4e15u9674u90b3u90ebu572eu9f19u64d7u567cu5e80u5ab2u7eb0u6787u7513u7765u7f74u94cdu75e6u7656u758bu868du8c94", "pian": "u7bc7u504fu7247u9a97u8c1du9a88u728fu80fcu890au7fe9u8e41", "piao": "u98d8u6f02u74e2u7968u527du560cu5ad6u7f25u6b8du779fu87b5", "pie": "u6487u77a5u4e3fu82e4u6c15", "pin": "u62fcu9891u8d2bu54c1u8058u62dau59d8u5ad4u6980u725du98a6", "ping": "u4e52u576au82f9u840du5e73u51edu74f6u8bc4u5c4fu4fdcu5a09u67b0u9c86", "po": "u5761u6cfcu9887u5a46u7834u9b44u8febu7c95u53f5u9131u6ea5u73c0u948bu94b7u76a4u7b38", "pou": "u5256u88d2u8e23", "pu": "u6251u94fau4ec6u8386u8461u83e9u84b2u57d4u6734u5703u666eu6d66u8c31u66ddu7011u530du5657u6feeu749eu6c06u9564u9568u8e7c", "qi": "u671fu6b3au6816u621au59bbu4e03u51c4u6f06u67d2u6c8fu5176u68cbu5947u6b67u7566u5d0eu8110u9f50u65d7u7948u7941u9a91u8d77u5c82u4e5eu4f01u542fu5951u780cu5668u6c14u8fc4u5f03u6c7du6ce3u8babu4e9fu4e93u573bu8291u840bu847au5601u5c7au5c90u6c54u6dc7u9a90u7eeeu742au7426u675eu6864u69edu6b39u797au61a9u789bu86f4u871eu7da6u7daeu8dbfu8e4au9ccdu9e92", "qia": "u6390u6070u6d3du845c", "qian": "u7275u6266u948eu94c5u5343u8fc1u7b7eu4edfu8c26u4e7eu9ed4u94b1u94b3u524du6f5cu9063u6d45u8c34u5811u5d4cu6b20u6b49u4f65u9621u828au82a1u8368u63aeu5c8du60adu614au9a9eu6434u8930u7f31u6920u80b7u6106u94a4u8654u7b9d", "qiang": "u67aau545bu8154u7f8cu5899u8537u5f3au62a2u5af1u6a2fu6217u709du9516u9535u956au8941u8723u7f9fu8debu8dc4", "qiao": "u6a47u9539u6572u6084u6865u77a7u4e54u4fa8u5de7u9798u64acu7fd8u5cedu4fcfu7a8du5281u8beeu8c2fu835eu6100u6194u7f32u6a35u6bf3u7857u8df7u9792", "qie": "u5207u8304u4e14u602fu7a83u90c4u553cu60ecu59beu6308u9532u7ba7", "qin": "u94a6u4fb5u4eb2u79e6u7434u52e4u82b9u64d2u79bdu5bddu6c81u82a9u84c1u8572u63ffu5423u55eau5659u6eb1u6a8eu8793u887e", "qing": "u9752u8f7bu6c22u503eu537fu6e05u64ceu6674u6c30u60c5u9877u8bf7u5e86u5029u82d8u570au6aa0u78ecu873bu7f44u7b90u8b26u9cadu9ee5", "qiong": "u743cu7a77u909bu8315u7a79u7b47u928e", "qiu": "u79cbu4e18u90b1u7403u6c42u56dau914bu6cc5u4fc5u6c3du5defu827du72b0u6e6bu9011u9052u6978u8d47u9e20u866cu86afu8764u88d8u7cd7u9cc5u9f3d", "qu": "u8d8bu533au86c6u66f2u8eafu5c48u9a71u6e20u53d6u5a36u9f8bu8da3u53bbu8bceu52acu8556u8627u5c96u8862u9612u74a9u89d1u6c0du795bu78f2u766fu86d0u883cu9eb4u77bfu9ee2", "quan": "u5708u98a7u6743u919bu6cc9u5168u75cau62f3u72acu5238u529du8be0u8343u737eu609bu7efbu8f81u754eu94e8u8737u7b4cu9b08", "que": "u7f3au7094u7638u5374u9e4au69b7u786eu96c0u9619u60ab", "qun": "u88d9u7fa4u9021", "ran": "u7136u71c3u5189u67d3u82d2u9aef", "rang": "u74e4u58e4u6518u56b7u8ba9u79b3u7a70", "rao": "u9976u6270u7ed5u835bu5a06u6861", "ruo": "u60f9u82e5u5f31", "re": "u70edu504c", "ren": "u58ecu4ec1u4ebau5fcdu97e7u4efbu8ba4u5203u598au7eabu4edeu834fu845au996au8f6bu7a14u887d", "reng": "u6254u4ecd", "ri": "u65e5", "rong": "u620eu8338u84c9u8363u878du7194u6eb6u5bb9u7ed2u5197u5d58u72e8u7f1bu6995u877e", "rou": "u63c9u67d4u8089u7cc5u8e42u97a3", "ru": "u8339u8815u5112u5b7au5982u8fb1u4e73u6c5du5165u8925u84d0u85b7u5685u6d33u6ebdu6fe1u94f7u8966u98a5", "ruan": "u8f6fu962eu670a", "rui": "u854au745eu9510u82aeu8564u777fu868b", "run": "u95f0u6da6", "sa": "u6492u6d12u8428u5345u4ee8u6332u98d2", "sai": "u816eu9cc3u585eu8d5bu567b", "san": "u4e09u53c1u4f1eu6563u5f61u9993u6c35u6bf5u7cc1u9730", "sang": "u6851u55d3u4e27u6421u78c9u98a1", "sao": "u6414u9a9au626bu5ac2u57fdu81cau7619u9ccb", "se": "u745fu8272u6da9u556cu94e9u94efu7a51", "sen": "u68ee", "seng": "u50e7", "sha": "u838eu7802u6740u5239u6c99u7eb1u50bbu5565u715eu810eu6b43u75e7u88dfu970eu9ca8", "shai": "u7b5bu6652u917e", "shan": "u73cau82ebu6749u5c71u5220u717du886bu95eau9655u64c5u8d61u81b3u5584u6c55u6247u7f2eu5261u8baau912fu57cfu829fu6f78u59d7u9a9fu81bbu9490u759du87eeu8222u8ddau9cdd", "shang": "u5892u4f24u5546u8d4fu664cu4e0au5c1au88f3u57a7u7ef1u6b87u71b5u89de", "shao": "u68a2u634eu7a0du70e7u828du52fau97f6u5c11u54e8u90b5u7ecdu52adu82d5u6f72u86f8u7b24u7b72u8244", "she": "u5962u8d4au86c7u820cu820du8d66u6444u5c04u6151u6d89u793eu8bbeu538du4f58u731eu7572u9e9d", "shen": "u7837u7533u547bu4f38u8eabu6df1u5a20u7ec5u795eu6c88u5ba1u5a76u751au80beu614eu6e17u8bdcu8c02u5432u54c2u6e16u6939u77e7u8703", "sheng": "u58f0u751fu7525u7272u5347u7ef3u7701u76dbu5269u80dcu5723u4e1eu6e11u5ab5u771au7b19", "shi": "u5e08u5931u72eeu65bdu6e7fu8bd7u5c38u8671u5341u77f3u62feu65f6u4ec0u98dfu8680u5b9eu8bc6u53f2u77e2u4f7fu5c4eu9a76u59cbu5f0fu793au58ebu4e16u67ffu4e8bu62edu8a93u901du52bfu662fu55dcu566cu9002u4ed5u4f8du91cau9970u6c0fu5e02u6043u5ba4u89c6u8bd5u8c25u57d8u83b3u84cdu5f11u5511u9963u8f7cu8006u8d33u70bbu793bu94c8u94cau87abu8210u7b6eu8c55u9ca5u9cba", "shou": "u6536u624bu9996u5b88u5bffu6388u552eu53d7u7626u517du624cu72e9u7ef6u824f", "shu": "u852cu67a2u68b3u6b8au6292u8f93u53d4u8212u6dd1u758fu4e66u8d4eu5b70u719fu85afu6691u66d9u7f72u8700u9ecdu9f20u5c5eu672fu8ff0u6811u675fu620du7ad6u5885u5eb6u6570u6f31u6055u500fu587eu83fdu5fc4u6cadu6d91u6f8du59ddu7ebeu6bf9u8167u6bb3u956fu79ebu9e6c", "shua": "u5237u800du5530u6dae", "shuai": "u6454u8870u7529u5e05u87c0", "shuan": "u6813u62f4u95e9", "shuang": "u971cu53ccu723du5b40", "shui": "u8c01u6c34u7761u7a0e", "shun": "u542eu77acu987au821cu6042", "shuo": "u8bf4u7855u6714u70c1u84b4u6420u55cdu6fefu5981u69cau94c4", "si": "u65afu6495u5636u601du79c1u53f8u4e1du6b7bu8086u5bfau55e3u56dbu4f3au4f3cu9972u5df3u53aeu4fdfu5155u83e5u549du6c5cu6cd7u6f8cu59d2u9a77u7f0cu7940u7960u9536u9e36u801cu86f3u7b25", "song": "u677eu8038u6002u9882u9001u5b8bu8bbcu8bf5u51c7u83d8u5d27u5d69u5feau609au6ddeu7ae6", "sou": "u641cu8258u64deu55fdu53dfu55d6u55feu998au6eb2u98d5u778du953cu878b", "su": "u82cfu9165u4fd7u7d20u901fu7c9fu50f3u5851u6eafu5bbfu8bc9u8083u5919u8c21u850cu55c9u612bu7c0cu89ebu7a23", "suan": "u9178u849cu7b97", "sui": "u867du968bu968fu7ee5u9ad3u788eu5c81u7a57u9042u96a7u795fu84d1u51abu8c07u6fc9u9083u71e7u772du7762", "sun": "u5b59u635fu7b0bu836au72f2u98e7u69abu8de3u96bc", "suo": "u68adu5506u7f29u7410u7d22u9501u6240u5522u55e6u5a11u686bu7743u7fa7", "ta": "u584cu4ed6u5b83u5979u5854u736du631eu8e4bu8e0fu95fcu6ebbu9062u69bbu6c93", "tai": "u80ceu82d4u62acu53f0u6cf0u915eu592au6001u6c70u90b0u85b9u80bdu70b1u949bu8dc6u9c90", "tan": "u574du644au8d2au762bu6ee9u575bu6a80u75f0u6f6du8c2du8c08u5766u6befu8892u78b3u63a2u53f9u70adu90efu8548u6619u94bdu952cu8983", "tang": "u6c64u5858u642au5802u68e0u819bu5510u7cd6u50a5u9967u6e8fu746du94f4u9557u8025u8797u87b3u7fb0u91a3", "thang": "u5018u8ebau6dcc", "theng": "u8d9fu70eb", "tao": "u638fu6d9bu6ed4u7ee6u8404u6843u9003u6dd8u9676u8ba8u5957u6311u9f17u5555u97ecu9955", "te": "u7279", "teng": "u85e4u817eu75bcu8a8au6ed5", "ti": "u68afu5254u8e22u9511u63d0u9898u8e44u557cu4f53u66ffu568fu60d5u6d95u5243u5c49u8351u608cu9016u7ee8u7f07u9e48u88fcu918d", "tian": "u5929u6dfbu586bu7530u751cu606cu8214u8146u63adu5fddu9617u6b84u754bu94bfu86ba", "tiao": "u6761u8fe2u773au8df3u4f7bu7967u94ebu7a95u9f86u9ca6", "tie": "u8d34u94c1u5e16u841cu992e", "ting": "u5385u542cu70c3u6c40u5ef7u505cu4eadu5eadu633au8247u839bu8476u5a77u6883u8713u9706", "tong": "u901au6850u916eu77b3u540cu94dcu5f64u7ae5u6876u6345u7b52u7edfu75dbu4f5fu50eeu4eddu833cu55f5u6078u6f7cu783c", "tou": "u5077u6295u5934u900fu4ea0", "tu": "u51f8u79c3u7a81u56feu5f92u9014u6d82u5c60u571fu5410u5154u580du837cu83dfu948du9174", "tuan": "u6e4du56e2u7583", "tui": "u63a8u9893u817fu8715u892au9000u5fd2u717a", "tun": "u541eu5c6fu81c0u9968u66beu8c5au7a80", "tuo": "u62d6u6258u8131u9e35u9640u9a6eu9a7cu692du59a5u62d3u553eu4e47u4f57u5768u5eb9u6cb1u67ddu7823u7ba8u8204u8dceu9f0d", "wa": "u6316u54c7u86d9u6d3cu5a03u74e6u889cu4f64u5a32u817d", "wai": "u6b6au5916", "wan": "u8c4cu5f2fu6e7eu73a9u987du4e38u70f7u5b8cu7897u633du665au7696u60cbu5b9bu5a49u4e07u8155u525cu8284u82cbu83c0u7ea8u7efeu742cu8118u7579u873fu7ba2", "wang": "u6c6au738bu4ea1u6789u7f51u5f80u65fau671bu5fd8u5984u7f54u5c22u60d8u8f8bu9b4d", "wei": "u5a01u5dcdu5faeu5371u97e6u8fddu6845u56f4u552fu60dfu4e3au6f4du7ef4u82c7u840eu59d4u4f1fu4f2au5c3eu7eacu672au851au5473u754fu80c3u5582u9b4fu4f4du6e2du8c13u5c09u6170u536bu502du504eu8bffu9688u8473u8587u5e0fu5e37u5d34u5d6cu7325u732cu95f1u6ca9u6d27u6da0u9036u5a13u73aeu97eau8eceu709cu7168u71a8u75ffu8249u9c94", "wen": "u761fu6e29u868au6587u95fbu7eb9u543bu7a33u7d0au95eeu520eu6120u960cu6c76u74bau97ebu6b81u96ef", "weng": "u55e1u7fc1u74eeu84cau8579", "wo": "u631du8717u6da1u7a9du6211u65a1u5367u63e1u6c83u83b4u5e44u6e25u674cu809fu9f8c", "wu": "u5debu545cu94a8u4e4cu6c61u8becu5c4bu65e0u829cu68a7u543eu5434u6bcbu6b66u4e94u6342u5348u821eu4f0du4faeu575eu620au96feu6664u7269u52ffu52a1u609fu8befu5140u4ef5u9622u90acu572cu82b4u5e91u6003u5fe4u6d6fu5be4u8fd5u59a9u9a9bu727eu7110u9e49u9e5cu8708u92c8u9f2f", "xi": "u6614u7199u6790u897fu7852u77fdu6670u563bu5438u9521u727au7a00u606fu5e0cu6089u819du5915u60dcu7184u70efu6eaau6c50u7280u6a84u88adu5e2du4e60u5ab3u559cu94e3u6d17u7cfbu9699u620fu7ec6u50d6u516eu96b0u90d7u831cu8478u84f0u595au550fu5f99u9969u960bu6d60u6dc5u5c63u5b09u73bau6a28u66e6u89cbu6b37u71b9u798au79a7u94b8u7699u7a78u8725u87cbu823eu7fb2u7c9eu7fd5u91afu9f37", "xia": "u778eu867eu5323u971eu8f96u6687u5ce1u4fa0u72edu4e0bu53a6u590fu5413u6380u846du55c4u72ceu9050u7455u7856u7615u7f45u9ee0", "xian": "u9528u5148u4ed9u9c9cu7ea4u54b8u8d24u8854u8237u95f2u6d8eu5f26u5accu663eu9669u73b0u732eu53bfu817au9985u7fa1u5baau9677u9650u7ebfu51bcu85d3u5c98u7303u66b9u5a34u6c19u7946u9e47u75ebu86acu7b45u7c7cu9170u8df9", "xiang": "u76f8u53a2u9576u9999u7bb1u8944u6e58u4e61u7fd4u7965u8be6u60f3u54cdu4eabu9879u5df7u6a61u50cfu5411u8c61u8297u8459u9977u5ea0u9aa7u7f03u87d3u9c9eu98e8", "xiao": "u8427u785du9704u524au54eeu56a3u9500u6d88u5bb5u6dc6u6653u5c0fu5b5du6821u8096u5578u7b11u6548u54d3u54bbu5d24u6f47u900du9a81u7ee1u67adu67b5u7b71u7babu9b48", "xie": "u6954u4e9bu6b47u874eu978bu534fu631fu643au90aau659cu80c1u8c10u5199u68b0u5378u87f9u61c8u6cc4u6cfbu8c22u5c51u5055u4eb5u52f0u71eeu85a4u64b7u5ee8u7023u9082u7ec1u7f2cu69adu698du6b59u8e9e", "xin": "u85aau82afu950cu6b23u8f9bu65b0u5ffbu5fc3u4fe1u8845u56dfu99a8u8398u6b46u94fdu946b", "xing": "u661fu8165u7329u60fau5174u5211u578bu5f62u90a2u884cu9192u5e78u674fu6027u59d3u9649u8347u8365u64e4u60bbu784e", "xiong": "u5144u51f6u80f8u5308u6c79u96c4u718au828e", "xiu": "u4f11u4feeu7f9eu673du55c5u9508u79c0u8896u7ee3u83a0u5cabu9990u5ea5u9e3au8c85u9af9", "xu": "u589fu620cu9700u865au5618u987bu5f90u8bb8u84c4u9157u53d9u65edu5e8fu755cu6064u7d6eu5a7fu7eeau7eedu8bb4u8be9u5729u84ffu6035u6d2bu6e86u987cu6829u7166u7809u76f1u80e5u7cc8u9191", "xuan": "u8f69u55a7u5ba3u60acu65cbu7384u9009u7663u7729u7edau5107u8c16u8431u63ceu9994u6cebu6d35u6e32u6f29u7487u6966u6684u70abu714au78b9u94c9u955fu75c3", "xue": "u9774u859bu5b66u7a74u96eau8840u5671u6cf6u9cd5", "xun": "u52cbu718fu5faau65ecu8be2u5bfbu9a6fu5de1u6b89u6c5bu8badu8bafu900au8fc5u5dfdu57d9u8340u85b0u5ccbu5f87u6d54u66dbu7aa8u91bau9c9f", "ya": "u538bu62bcu9e26u9e2du5440u4e2bu82bdu7259u869cu5d16u8859u6dafu96c5u54d1u4e9au8bb6u4f22u63e0u5416u5c88u8fd3u5a05u740au6860u6c29u7811u775au75d6", "yan": "u7109u54bdu9609u70dfu6df9u76d0u4e25u7814u8712u5ca9u5ef6u8a00u989cu960eu708eu6cbfu5944u63a9u773cu884du6f14u8273u5830u71d5u538cu781au96c1u5501u5f66u7130u5bb4u8c1au9a8cu53a3u9765u8d5du4fe8u5043u5156u8ba0u8c33u90feu9122u82abu83f8u5d26u6079u95ebu960fu6d07u6e6eu6edfu598du5ae3u7430u664fu80edu814cu7131u7f68u7b75u917du9b47u990du9f39", "yang": "u6b83u592eu9e2fu79e7u6768u626cu4f6fu75a1u7f8au6d0bu9633u6c27u4ef0u75d2u517bu6837u6f3eu5f89u600fu6cf1u7080u70cau6059u86d8u9785", "yao": "u9080u8170u5996u7476u6447u5c27u9065u7a91u8c23u59dau54acu8200u836fu8981u8000u592du723bu5406u5d3eu5fadu7039u5e7au73e7u6773u66dcu80b4u9e5eu7a88u7e47u9cd0", "ye": "u6930u564eu8036u7237u91ceu51b6u4e5fu9875u6396u4e1au53f6u66f3u814bu591cu6db2u8c12u90bau63f6u9980u6654u70e8u94d8", "yi": "u4e00u58f9u533bu63d6u94f1u4f9du4f0au8863u9890u5937u9057u79fbu4eeau80f0u7591u6c82u5b9cu59e8u5f5du6905u8681u501au5df2u4e59u77e3u4ee5u827au6291u6613u9091u5c79u4ebfu5f79u81c6u9038u8084u75abu4ea6u88d4u610fu6bc5u5fc6u4e49u76cau6ea2u8be3u8baeu8c0au8bd1u5f02u7ffcu7fccu7eceu5208u5293u4f7eu8bd2u572au572fu57f8u61ffu82e1u858fu5f08u5955u6339u5f0bu5453u54a6u54bfu566bu5cc4u5db7u7317u9974u603fu6021u6092u6f2au8fe4u9a7fu7f22u6baau8d3bu65d6u71a0u9487u9552u9571u75cdu7617u7654u7fcau8864u8734u8223u7fbfu7ff3u914fu9edf", "yin": "u8335u836bu56e0u6bb7u97f3u9634u59fbu541fu94f6u6debu5bc5u996eu5c39u5f15u9690u5370u80e4u911eu5819u831au5591u72fau5924u6c24u94dfu763eu8693u972au9f88", "ying": "u82f1u6a31u5a74u9e70u5e94u7f28u83b9u8424u8425u8367u8747u8fceu8d62u76c8u5f71u9896u786cu6620u5b34u90e2u8314u83bau8426u6484u5624u81bau6ee2u6f46u701bu745bu748eu6979u9e66u763fu988du7f42", "yo": "u54dfu5537", "yong": "u62e5u4f63u81c3u75c8u5eb8u96cdu8e0au86f9u548fu6cf3u6d8cu6c38u607fu52c7u7528u4fd1u58c5u5889u6175u9095u955bu752cu9cd9u9954", "you": "u5e7du4f18u60a0u5fe7u5c24u7531u90aeu94c0u72b9u6cb9u6e38u9149u6709u53cbu53f3u4f51u91c9u8bf1u53c8u5e7cu5363u6538u4f91u83b8u5466u56ffu5ba5u67dau7337u7256u94d5u75a3u8763u9c7fu9eddu9f2c", "yu": "u8fc2u6de4u4e8eu76c2u6986u865eu611au8206u4f59u4fdeu903eu9c7cu6109u6e1du6e14u9685u4e88u5a31u96e8u4e0eu5c7fu79b9u5b87u8bedu7fbdu7389u57dfu828bu90c1u5401u9047u55bbu5ceau5fa1u6108u6b32u72f1u80b2u8a89u6d74u5bd3u88d5u9884u8c6bu9a6du79bau6bd3u4f1bu4fe3u8c00u8c15u8438u84e3u63c4u5581u5704u5709u5d5bu72f3u996bu5ebeu9608u59aau59a4u7ea1u745cu6631u89ceu8174u6b24u65bcu715cu71e0u807fu94b0u9e46u7610u7600u7ab3u8753u7afdu8201u96e9u9f89", "yuan": "u9e33u6e0au51a4u5143u57a3u8881u539fu63f4u8f95u56edu5458u5706u733fu6e90u7f18u8fdcu82d1u613fu6028u9662u586cu6c85u5a9bu7457u6a7cu7230u7722u9e22u8788u9f0b", "yue": "u66f0u7ea6u8d8au8dc3u94a5u5cb3u7ca4u6708u60a6u9605u9fa0u6a3eu5216u94ba", "yun": "u8018u4e91u90e7u5300u9668u5141u8fd0u8574u915du6655u97f5u5b55u90d3u82b8u72c1u607du7eadu6b92u6600u6c32", "za": "u531du7838u6742u62f6u5482", "zai": "u683du54c9u707eu5bb0u8f7du518du5728u54b1u5d3du753e", "zan": "u6512u6682u8d5eu74d2u661du7c2au7cccu8db1u933e", "zang": "u8d43u810fu846cu5958u6215u81e7", "zao": "u906du7cdfu51ffu85fbu67a3u65e9u6fa1u86a4u8e81u566au9020u7682u7076u71e5u5523u7f2b", "ze": "u8d23u62e9u5219u6cfdu4ec4u8d5cu5567u8feeu6603u7b2eu7ba6u8234", "zei": "u8d3c", "zen": "u600eu8c2e", "zeng": "u589eu618eu66feu8d60u7f2fu7511u7f7eu9503", "zha": "u624eu55b3u6e23u672du8f67u94e1u95f8u7728u6805u69a8u548bu4e4du70b8u8bc8u63f8u5412u54a4u54f3u600du781fu75c4u86b1u9f44", "zhai": "u6458u658bu5b85u7a84u503au5be8u7826", "zhan": "u77bbu6be1u8a79u7c98u6cbeu76cfu65a9u8f97u5d2du5c55u8638u6808u5360u6218u7ad9u6e5bu7efdu8c35u640cu65c3", "zhang": "u6a1fu7ae0u5f70u6f33u5f20u638cu6da8u6756u4e08u5e10u8d26u4ed7u80c0u7634u969cu4ec9u9123u5e5bu5d82u7350u5adcu748bu87d1", "zhao": "u62dbu662du627eu6cbcu8d75u7167u7f69u5146u8087u53ecu722au8bcfu68f9u948au7b0a", "zhe": "u906eu6298u54f2u86f0u8f99u8005u9517u8517u8fd9u6d59u8c2au966cu67d8u8f84u78d4u9e67u891au8707u8d6d", "zhen": "u73cdu659fu771fu7504u7827u81fbu8d1eu9488u4fa6u6795u75b9u8bcau9707u632fu9547u9635u7f1cu6862u699bu8f78u8d48u80d7u6715u796fu755bu9e29", "zheng": "u84b8u6323u7741u5f81u72f0u4e89u6014u6574u62efu6b63u653fu5e27u75c7u90d1u8bc1u8be4u5ce5u94b2u94eeu7b5d", "zhi": "u829du679du652fu5431u8718u77e5u80a2u8102u6c41u4e4bu7ec7u804cu76f4u690du6b96u6267u503cu4f84u5740u6307u6b62u8dbeu53eau65e8u7eb8u5fd7u631au63b7u81f3u81f4u7f6eu5e1cu5cd9u5236u667au79e9u7a1au8d28u7099u75d4u6edeu6cbbu7a92u536eu965fu90c5u57f4u82b7u646du5e19u5feeu5f58u54abu9a98u6809u67b3u6800u684eu8f75u8f7eu6534u8d3du81a3u7949u7957u9ef9u96c9u9e37u75e3u86edu7d77u916fu8dd6u8e2cu8e2fu8c78u89ef", "zhong": "u4e2du76c5u5fe0u949fu8877u7ec8u79cdu80bfu91cdu4ef2u4f17u51a2u953au87bdu8202u822fu8e35", "zhou": "u821fu5468u5ddeu6d32u8bccu7ca5u8f74u8098u5e1au5492u76b1u5b99u663cu9aa4u5544u7740u501cu8bf9u836eu9b3bu7ea3u80c4u78a1u7c40u8233u914eu9cb7", "zhu": "u73e0u682au86dbu6731u732au8bf8u8bdbu9010u7af9u70dbu716eu62c4u77a9u5631u4e3bu8457u67f1u52a9u86c0u8d2eu94f8u7b51u4f4fu6ce8u795du9a7bu4f2bu4f8fu90beu82ceu8331u6d19u6e1au6f74u9a7au677cu69e0u6a65u70b7u94e2u75b0u7603u86b0u7afau7bb8u7fe5u8e85u9e88", "zhua": "u6293", "zhuai": "u62fd", "zhuan": "u4e13u7816u8f6cu64b0u8d5au7bc6u629fu556du989b", "zhuang": "u6869u5e84u88c5u5986u649eu58eeu72b6u4e2c", "zhui": "u690eu9525u8ffdu8d58u5760u7f00u8411u9a93u7f12", "zhun": "u8c06u51c6", "zhuo": "u6349u62d9u5353u684cu7422u8301u914cu707cu6d4au502cu8bfcu5ef4u855eu64e2u555cu6d5eu6dbfu6753u712fu799au65ab", "zi": "u5179u54a8u8d44u59ffu6ecbu6dc4u5b5cu7d2bu4ed4u7c7du6ed3u5b50u81eau6e0du5b57u8c18u5d6bu59cau5b73u7f01u6893u8f8eu8d40u6063u7726u9531u79edu8014u7b2bu7ca2u89dcu8a3eu9cbbu9aed", "zong": "u9b03u68d5u8e2au5b97u7efcu603bu7eb5u8159u7cbd", "zou": "u90b9u8d70u594fu63cdu9139u9cb0", "zu": "u79dfu8db3u5352u65cfu7956u8bc5u963bu7ec4u4fceu83f9u5550u5f82u9a75u8e74", "zuan": "u94bbu7e82u6525u7f35", "zui": "u5634u9189u6700u7f6a", "zun": "u5c0au9075u6499u6a3du9cdf", "zuo": "u6628u5de6u4f50u67deu505au4f5cu5750u5ea7u961du963cu80d9u795au9162", "cou": "u85aeu6971u8f8fu8160", "nang": "u652eu54ddu56d4u9995u66e9", "o": "u5594", "dia": "u55f2", "chuai": "u562cu81aau8e39", "cen": "u5c91u6d94", "diu": "u94e5", "nou": "u8028", "fou": "u7f36", "bia": "u9adf" };
// 汉字转拼音
function ConvertPinyin(l1) {
    var l2 = l1.length;
    var I1 = "";
    var reg = new RegExp('[a-zA-Z0-9- ]');
    for (var i = 0; i < l2; i  ) {
        var val = l1.substr(i, 1);
        var name = arraySearch(val, PinYin);
        if (reg.test(val)) {
            I1  = val " ";
        } else if (name !== false) {
            I1  = name " ";
        }

    }
    //I1 = I1.replace(/ /g, '-');
    //while (I1.indexOf('--') > 0) {
    //    I1 = I1.replace('--', '-');
    //}
    return I1;
}
// 在对象中搜索
function arraySearch(l1, l2) {
    for (var name in PinYin) {
        if (PinYin[name].indexOf(l1) != -1) {
            return ucfirst(name); break;
        }
    }
    return false;
}
// 首字母大写
function ucfirst(l1) {
    if (l1.length > 0) {
        var first = l1.substr(0, 1).toUpperCase();
        var spare = l1.substr(1, l1.length);
        return first   spare;
        // return first;
    }
}

function nameConvertPy(txtNameID, txtName_pyID, notNullShowID, lengthCheckID) {
    var txt_Name_other = $("#"   txtNameID).val();
    //txt_Name_other = txt_Name_other.replace(/s/g, '');
    $("#"   txtNameID).val(txt_Name_other);

    if (txt_Name_other.length > 0) {
        $("#"   txtName_pyID).val(ConvertPinyin(txt_Name_other)); //这里是中文转换为拼音
        var txt_Name_pinyin = $.trim($("#"   txtName_pyID).val());
        if (txt_Name_pinyin.length > 0) {
            if (txt_Name_other.length > 128) {
                $("#"   lengthCheckID).show()
                $("#"   notNullShowID).hide();
            } else {
                $("#"   notNullShowID).hide();
                $("#"   lengthCheckID).hide()
            }
        } else {
            $("#"   notNullShowID).show();
            $("#"   lengthCheckID).hide();
        }
    } else {
        $("#"   notNullShowID).show();
        $("#"   lengthCheckID).hide();
    }
}
/*$(document).ready(function() {       
$("#<%=DeptName.ClientID %>").blur(function () {

var str=ConvertPinyin($("#<%=DeptName.ClientID %>").val());
$("#<%=PingYinCode.ClientID %>").text(str);

});
}); */

View Code

 

选取方法:

  var pinyin = name.toPinyin(); //name表示收获到的国语名 

 

后台代码

View Code

客户管理 

图表压缩

新建三个ImageHelper扶植类,代码如下:

图片 49图片 50

 public class ImageHelper
    {
        private static ImageCodecInfo GetEncoderInfo(string mime_type)
        {
            ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i <= imageEncoders.Length; i  )
            {
                if (imageEncoders[i].MimeType == mime_type)
                {
                    return imageEncoders[i];
                }
            }
            return null;
        }

        public static void SaveJpg(Image image, string file_name, int level)
        {
            try
            {
                EncoderParameters encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level);
                ImageCodecInfo encoderInfo = ImageHelper.GetEncoderInfo("image/jpeg");


                File.Delete(file_name);
                image.Save(file_name, encoderInfo, encoderParameters);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static MemoryStream SaveJpgToStream(Image image, int level)
        {
            try
            {
                EncoderParameters encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level);
                ImageCodecInfo encoderInfo = ImageHelper.GetEncoderInfo("image/jpeg");
                MemoryStream strem = new MemoryStream();
                image.Save(strem, encoderInfo, encoderParameters);
                return strem;


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static int SaveJpgAtFileSize(Image image, string file_name, long max_size)
        {
            int result;
            try
            {
                for (int i = 100; i > 5; i -= 5)
                {
                    ImageHelper.SaveJpg(image, file_name, i);
                    if (ImageHelper.GetFileSize(file_name) <= max_size)
                    {
                        result = i;
                        return result;
                    }
                }
                result = 5;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public static long GetFileSize(string file_name)
        {
            long length;
            try
            {
                length = new FileInfo(file_name).Length;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return length;
        }

        public static Bitmap ShrinkageImg(Image iSource, int maxWidth = 800, int maxHeight = 0)
        {
            int sW = iSource.Width, sH = iSource.Height;
            if (maxWidth != 0 && maxWidth < sW)
            {
                sW = maxWidth;
                sH = iSource.Height * maxWidth / iSource.Width;
            }
            else if (maxHeight != 0 && maxHeight < sH)
            {
                sH = maxHeight;
                sW = iSource.Width * maxHeight / iSource.Height;
            }
            Bitmap ob = new Bitmap(sW, sH);
            Graphics g = Graphics.FromImage(ob);
            try
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(iSource, new Rectangle(0, 0, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
                return ob;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                g.Dispose();
                iSource.Dispose();
            }

        }

        public static Bitmap LoadBitmap(string file_name)
        {
            Bitmap result;
            try
            {
                Bitmap bitmap2;
                using (Bitmap bitmap = new Bitmap(file_name))
                {
                    bitmap2 = new Bitmap(bitmap.Width, bitmap.Height);
                    using (Graphics graphics = Graphics.FromImage(bitmap2))
                    {
                        Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                        graphics.DrawImage(bitmap, rectangle, rectangle, GraphicsUnit.Pixel);
                    }
                }
                result = bitmap2;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public static byte[] ImageToBytes(Image image)
        {
            byte[] result;
            try
            {
                ImageFormat rawFormat = image.RawFormat;
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    if (rawFormat.Equals(ImageFormat.Jpeg))
                    {
                        image.Save(memoryStream, ImageFormat.Jpeg);
                    }
                    else if (rawFormat.Equals(ImageFormat.Png))
                    {
                        image.Save(memoryStream, ImageFormat.Png);
                    }
                    else if (rawFormat.Equals(ImageFormat.Bmp))
                    {
                        image.Save(memoryStream, ImageFormat.Bmp);
                    }
                    else if (rawFormat.Equals(ImageFormat.Gif))
                    {
                        image.Save(memoryStream, ImageFormat.Gif);
                    }
                    else if (rawFormat.Equals(ImageFormat.Icon))
                    {
                        image.Save(memoryStream, ImageFormat.Icon);
                    }
                    byte[] array = new byte[memoryStream.Length];
                    memoryStream.Seek(0L, SeekOrigin.Begin);
                    memoryStream.Read(array, 0, array.Length);
                    result = array;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public static byte[] ImageToBytes(string FilePath)
        {
            byte[] result;
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (Image image = Image.FromFile(FilePath))
                    {
                        using (Bitmap bitmap = new Bitmap(image))
                        {
                            bitmap.Save(memoryStream, image.RawFormat);
                        }
                    }
                    result = memoryStream.ToArray();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public static Image BytesToImage(byte[] buffer, int maxWidth = 800, int maxHeight = 0)
        {
            Image result;
            try
            {
                MemoryStream stream = new MemoryStream(buffer);
                Image image = Image.FromStream(stream);
                result = ShrinkageImg(image, maxWidth, maxHeight);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        } 

    }

View Code

 

 使用办法:申圣元(Synutra)个变量

private const string _filePath = "File";

 

         #region 上传
                FTP.FTPUpFile ftpUpLoad = new FTP.FTPUpFile();
                HttpPostedFileBase FileUpload_File = Request.Files["FileUpload_File"];
                if (FileUpload_File == null || string.IsNullOrEmpty(FileUpload_File.FileName))
                {
                    msg = "没找到上传文件!";
                    return Json(new { Result = "2", MSG = msg });
                }
                string ReFileName = string.Empty;

                if (!GeneralHelper.CheckFileExtension(FileUpload_File.FileName, FileUpload_File))
                    return Json(new { Result = "2", MSG = "文件格式不正确,允许上传的文件格式有“.jpg|.gif|.bmp|.jpeg|.png”" });
                if (FileUpload_File.ContentLength > 1024 * 1024 * 10)
                    return Json(new { Result = "2", MSG = "上传的文件不允许超过10M" });
                var buffer = new byte[FileUpload_File.ContentLength];
                FileUpload_File.InputStream.Read(buffer, 0, FileUpload_File.ContentLength);
                string dire = DateTime.Now.ToString("yyyy-MM-dd");
                string directory = string.Format("/{0}", _filePath);
                string filePath = Request.MapPath(directory);
                if (!System.IO.Directory.Exists(filePath))
                    System.IO.Directory.CreateDirectory(filePath);
                var tempDire = filePath   "/"   dire;
                if (!Directory.Exists(tempDire))
                    Directory.CreateDirectory(tempDire);
                string fileName = string.Format("/{0}/{1}{2}{3}", dire, DateTime.Now.ToString("yyyyMMddHHmmssfff"), GeneralHelper.GetMixPwd(10), ".jpg");
                ImageHelper.SaveJpg(ImageHelper.BytesToImage(buffer), filePath   fileName, 75);
                ReFileName = ftpUpLoad.UpFile(filePath   fileName);//调用ftp上传到服务器
                if (string.IsNullOrEmpty(ReFileName))
                    return Json(new { Result = "2", MSG = "上传失败,可能文件过大,请重试!" });

                #endregion

 

上述FTP类如下

图片 51图片 52

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.HtmlControls;
using KAB.Utility.Base;

namespace KAB.Utility.FTP
{
    /// <summary>
    /// FTP上传文件
    /// </summary>
    public class FTPUpFile
    {

        string Filetype = ConfigurationManager.AppSettings["FileType"];
        string ipaddress = ConfigurationManager.AppSettings["IPaddress"];
        string Username = ConfigurationManager.AppSettings["UserName"];
        string Password = ConfigurationManager.AppSettings["Password"];


        /// <summary>
        /// FTP上传文件
        /// </summary>
        /// <param name="filename">上传文件路径</param>
        /// <param name="ftpServerIP">FTP服务器的IP和端口</param>
        /// <param name="ftpPath">FTP服务器下的哪个目录</param>
        /// <param name="ftpUserID">FTP用户名</param>
        /// <param name="ftpPassword">FTP密码</param>
        public bool Upload(string filename, string ftpServerIP, string ftpPath, string ftpUserID, string ftpPassword)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://"   ftpServerIP   "/"   ftpPath   "/"   fileInf.Name;

            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;

                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                // 指定数据传输类型
                reqFTP.UseBinary = true;

                // 上传文件时通知服务器文件的大小
                reqFTP.ContentLength = fileInf.Length;

                //this.Invoke(InitUProgress, fileInf.Length);

                // 缓冲大小设置为2kb
                int buffLength = 4096;

                byte[] buff = new byte[buffLength];
                int contentLen;

                //// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                //FileStream fs = fileInf.OpenRead();

                //// 把上传的文件写入流
                //Stream strm = reqFTP.GetRequestStream();
                //contentLen = fs.Read(buff, 0, buffLength);
                //while (contentLen != 0)
                //{
                //    strm.Write(buff, 0, contentLen);
                //    contentLen = fs.Read(buff, 0, buffLength);
                //}
                //// 关闭两个流
                //strm.Close();
                //strm.Dispose();
                //fs.Close();
                //fs.Dispose();


                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                using (FileStream fs = fileInf.OpenRead())
                {
                    using (Stream strm = reqFTP.GetRequestStream())
                    {
                        contentLen = fs.Read(buff, 0, buffLength);
                        while (contentLen != 0)
                        {
                            strm.Write(buff, 0, contentLen);
                            contentLen = fs.Read(buff, 0, buffLength);
                        }
                    }
                }


                return true;
            }
            catch (Exception ex)
            {

                return false;
            }

        }



        /// <summary>
        /// 新建目录
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="dirName"></param>
        public void MakeDir(string ftpPath, string dirName, string username, string password)
        {
            try
            {

                //实例化FTP连接
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath   dirName));

                // ftp用户名和密码
                request.Credentials = new NetworkCredential(username, password);

                // 默认为true,连接不会被关闭

                request.KeepAlive = false;

                //指定FTP操作类型为创建目录
                request.Method = WebRequestMethods.Ftp.MakeDirectory;
                //获取FTP服务器的响应
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                //Respons
            }
        }

        /// <summary>
        /// 删除指定文件
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="dirName"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void DeleteFile(string ftpPath, string username, string password)
        {
            try
            {
                // string uri = "ftp://"   ftpServerIP   "/"   ftpPath   "/"   fileInf.Name;
                //ftpPath = "ftp://192.168.1.111:2005/2012-12-05/20121206O5CATICE.docx";
                //password = "111";
                //username = "yuanluluoli";
                //实例化FTP连接
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                request.Method = WebRequestMethods.Ftp.DeleteFile;
                // ftp用户名和密码
                request.Credentials = new NetworkCredential(username, password);
                // 默认为true,连接不会被关闭
                request.KeepAlive = false;
                //获取FTP服务器的响应
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                //Respons
            }
        }



        /// <summary>
        /// 检查目录是否存在
        /// </summary>
        /// <param name="ftpPath">要检查的目录的路径</param>
        /// <param name="dirName">要检查的目录名</param>
        /// <returns>存在返回true,否则false</returns>
        public bool CheckDirectoryExist(string ftpPath, string dirName, string username, string password)
        {
            bool result = false;
            try
            {

                //实例化FTP连接
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                // ftp用户名和密码
                request.Credentials = new NetworkCredential(username, password);
                request.KeepAlive = false;
                //指定FTP操作类型为创建目录
                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                //获取FTP服务器的响应
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                StringBuilder str = new StringBuilder();
                string line = sr.ReadLine();
                while (line != null)
                {
                    str.Append(line);
                    str.Append("|");
                    line = sr.ReadLine();
                }
                string[] datas = str.ToString().Split('|');

                for (int i = 0; i < datas.Length; i  )
                {
                    if (datas[i].Contains("<DIR>"))
                    {
                        int index = datas[i].IndexOf("<DIR>");
                        string name = datas[i].Substring(index   5).Trim();
                        if (name == dirName)
                        {
                            result = true;
                            break;
                        }
                    }
                }

                sr.Close();
                sr.Dispose();
                response.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return result;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="buffer">文件的Byte数组</param>
        /// <param name="originalName">文件原始名字(带后缀名)</param>
        /// <param name="perStr">新文件名的前缀</param>
        /// <returns></returns>
        public string UpFile(byte[] buffer, string originalName, string perStr = "")
        {
            if (buffer == null || buffer.Length <= 0 || string.IsNullOrEmpty(originalName))
                throw new ArgumentException("参数错误!");
            string filePathstr = string.Empty;
            string filepathsql = null;
            try
            {
                string pathstr = perStr   DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
                string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                filePathstr = "~/File/"   pathstr   rodumlist   Path.GetExtension(originalName);
                //Stream sr = upfile.PostedFile.InputStream;
                //byte[] file = new byte[sr.Length];
                //sr.Read(file, 0, file.Length);

                StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filePathstr));
                sw.BaseStream.Write(buffer, 0, buffer.Length);
                sw.Flush(); sw.Close();
                // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上

                bool check;
                string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                string uri = @"ftp://"   ipaddress   "/";
                //检查是否存在此目录文件夹
                if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                {

                    //存在此文件夹就直接上传
                    check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                }
                else
                {
                    MakeDir(uri, ftpPath, Username, Password);//创建
                    check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                }

                //成功就更新
                if (check)
                {

                    filepathsql = ftpPath   "/"   pathstr   rodumlist   Path.GetExtension(originalName);
                }

                //检查是否存在此文件
                if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
                {
                    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                }
                return filepathsql;
            }
            catch (Exception ex)
            {
                File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                throw ex;
            }
        }
        /// <summary>
        /// 上传文件
        /// 不修改名字及后缀名
        /// </summary>
        /// <param name="originalFilePath">上传文件的绝对路径</param>
        /// <returns></returns>
        public string UpFile(string originalFilePath)
        {
            if (string.IsNullOrEmpty(originalFilePath))
                throw new ArgumentException("参数错误!");
            string filepathsql = null;
            try
            {
                //检查是否存在此文件
                if (!File.Exists(originalFilePath))
                    throw new Exception("文件不存在!");

                //Stream sr = upfile.PostedFile.InputStream;
                //byte[] file = new byte[sr.Length];
                //sr.Read(file, 0, file.Length);


                // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上

                bool check;
                string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                string uri = @"ftp://"   ipaddress   "/";
                //检查是否存在此目录文件夹
                if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                {
                    //存在此文件夹就直接上传
                    check = Upload(originalFilePath, ipaddress, ftpPath, Username, Password);
                }
                else
                {
                    MakeDir(uri, ftpPath, Username, Password);//创建
                    check = Upload(originalFilePath, ipaddress, ftpPath, Username, Password);
                }
                //成功就更新
                if (check)
                {

                    filepathsql = ftpPath   "/"   Path.GetFileName(originalFilePath);
                }
                //检查是否存在此文件
                if (File.Exists(originalFilePath))
                {
                    File.Delete(originalFilePath);
                }
                return filepathsql;
            }
            catch (Exception ex)
            {
                //File.Delete(originalFilePath);
                throw ex;
            }
        }

        public string Ftp_Up(HtmlInputFile upfile)
        {
            //Encrypt En = new Encrypt();

            string filePathstr = string.Empty;
            string filepathsql = null;
            try
            {
                string pathstr = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
                string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                filePathstr = "~/File/"   pathstr   rodumlist   Path.GetExtension(upfile.PostedFile.FileName);
                Stream sr = upfile.PostedFile.InputStream;
                byte[] file = new byte[sr.Length];
                sr.Read(file, 0, file.Length);
                StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filePathstr));
                sw.BaseStream.Write(file, 0, file.Length);
                sw.Flush(); sw.Close(); sr.Flush(); sr.Close();
                // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上

                bool check;
                string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                string uri = @"ftp://"   ipaddress   "/";
                //检查是否存在此目录文件夹
                if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                {

                    //存在此文件夹就直接上传
                    check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                }
                else
                {
                    MakeDir(uri, ftpPath, Username, Password);//创建
                    check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                }

                //成功就更新
                if (check)
                {

                    filepathsql = ftpPath   "/"   pathstr   rodumlist   Path.GetExtension(upfile.PostedFile.FileName);
                }

                //检查是否存在此文件
                if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
                {
                    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                }
                return filepathsql;
            }
            catch (Exception)
            {
                File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                return filepathsql;
                //  Response.Write("<script>alert("   ex.Message   ");</script>");
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public string Ftp_Up(HttpPostedFileBase postedFile)
        {


            string filePathstr = string.Empty;
            string filepathsql = null;
            try
            {


                string pathstr = DateTime.Now.ToString("yyyyMMddHHmmss");
                string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                string filename = System.IO.Path.GetFileName(postedFile.FileName);
                string eExtension = Path.GetExtension(filename);
                string strLocation = HttpContext.Current.Server.MapPath("~/File/");
                filePathstr = strLocation   pathstr   rodumlist   eExtension;

                postedFile.SaveAs(filePathstr);



                bool check;
                string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                string uri = @"ftp://"   ipaddress   "/";
                //检查是否存在此目录文件夹
                if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                {
                    //存在此文件夹就直接上传
                    check = Upload(filePathstr, ipaddress, ftpPath, Username, Password);
                }
                else
                {
                    MakeDir(uri, ftpPath, Username, Password);//创建
                    check = Upload(filePathstr, ipaddress, ftpPath, Username, Password);
                }

                //成功就更新
                if (check)
                {

                    filepathsql = ftpPath   "/"   pathstr   rodumlist   eExtension;
                }

                //检查是否存在此文件
                if (File.Exists(filePathstr))
                {
                    File.Delete(filePathstr);
                }
                return filepathsql;
            }
            catch (Exception ex)
            {
                //检查是否存在此文件
                if (File.Exists(filePathstr))
                {
                    File.Delete(filePathstr);
                }
                return "";
                //  Response.Write("<script>alert("   ex.Message   ");</script>");
            }
        }

        /// <summary>
        /// FTP下载文件在服务器目录
        /// </summary>
        /// <param name="pathname">本地保存目录路径和文件名称</param>
        /// <param name="filename">FTP目录路径和文件名称</param>
        /// <returns></returns>
        public bool FileDown(string pathname, string filename)
        {
            string uri = "ftp://"   ipaddress   "/"   filename;
            string FileName = pathname;//本地保存目录

            //创建一个文件流
            FileStream fs = null;
            Stream responseStream = null;
            try
            {
                //创建一个与FTP服务器联系的FtpWebRequest对象
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(uri));

                //连接登录FTP服务器
                request.Credentials = new NetworkCredential(Username, Password);

                request.KeepAlive = false;

                //设置请求的方法是FTP文件下载
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                //获取一个请求响应对象
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //获取请求的响应流
                responseStream = response.GetResponseStream();

                //判断本地文件是否存在,如果存在,则打开和重写本地文件

                if (File.Exists(FileName))
                    fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);

                //判断本地文件是否存在,如果不存在,则创建本地文件
                else
                {
                    fs = File.Create(FileName);
                }

                if (fs != null)
                {

                    int buffer_count = 65536;
                    byte[] buffer = new byte[buffer_count];
                    int size = 0;
                    while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
                    {
                        fs.Write(buffer, 0, size);

                    }
                    fs.Flush();
                    fs.Close();
                    responseStream.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (responseStream != null)
                    responseStream.Close();
            }
        }


        /// <summary>
        /// 保存和上传图片
        /// </summary>
        /// <param name="imgtwo">需要上传图片</param>
        /// <param name="date"></param>
        /// <returns>文件路径</returns>
        public string SaveUploadImg(Bitmap imgtwo)
        {
            string filePathstr = string.Empty;
            string filepathsql = null;
            try
            {
                string pathstr = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
                string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                filePathstr = "~/File/"   pathstr   rodumlist   ".jpg";
                imgtwo.Save(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上

                bool check;
                string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                string uri = @"ftp://"   ipaddress   "/";
                //检查是否存在此目录文件夹
                if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                {
                    //存在此文件夹就直接上传
                    check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                }
                else
                {
                    MakeDir(uri, ftpPath, Username, Password);//创建
                    check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                }

                //成功就更新
                if (check)
                {
                    filepathsql = ftpPath   "/"   pathstr   rodumlist   ".jpg";
                }

                //检查是否存在此文件
                if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
                {
                    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                }
                imgtwo.Dispose();

                return filepathsql;
            }
            catch (Exception ex)
            {
                File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                return filepathsql;
            }
        }


        #region
        /// <summary>
        /// 文件大小
        /// </summary>
        public bool _File_Length(int ContentLength)
        {
            bool length = false;
            int FileLen = ContentLength;
            if (FileLen > 2048 * 1024 == false)//不能超过2M
            {
                length = true;
            }
            return length;
        }
        #endregion


        //用来获取文件类型
        public bool File_PastFileName(string fileName)
        {
            //bmp, doc, docx, gif, jpg, jpeg, pdf, png, tif, tiff
            bool isnot = true;
            string ext = Path.GetExtension(fileName);
            string[] type = Filetype.Split(';');
            for (int i = 0; i < type.Length; i  )
            {
                if (type[i].ToLower() == ext.ToLower())
                {
                    isnot = false;
                    break;
                }
            }
            return isnot;

        }

    }
}

View Code

FTP类中利用到的GeneralHelper类如下

图片 53图片 54

  public class GeneralHelper
    {
        //private static string[] _extensionList = { ".jpg", ".gif", ".bmp", ".doc", ".docx", ".jpeg", ".png", ".tif", ".tiff" };
        private static string[] optionABC = { "A", "B", "C" };
        private static string numStr = "123456789";
        private static string lowEnStr = "abcdefghijkmnpqrstuvwxyz";
        private static string uperEnStr = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
        public GeneralHelper() { }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string GetMixPwd(int num)//生成混合随机数
        {
            string a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < num; i  )
            {
                sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 生成随机数不包含0跟O
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string GetMT4pwd(int num)
        {
            string a = "23456789ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";


            StringBuilder sb = new StringBuilder();
            Random randObj = new Random();
            if (num > 4)
            {
                int ri = randObj.Next(1, num);
                int rli = (num - ri) / 2;
                int rui = num - ri - rli;
                for (int i = 0; i < rli; i  )
                {
                    sb.Append(lowEnStr[new Random(Guid.NewGuid().GetHashCode()).Next(0, lowEnStr.Length - 1)]);
                }
                for (int i = 0; i < ri; i  )
                {
                    sb.Append(numStr[new Random(Guid.NewGuid().GetHashCode()).Next(0, numStr.Length - 1)]);
                }
                for (int i = 0; i < rui; i  )
                {
                    sb.Append(uperEnStr[new Random(Guid.NewGuid().GetHashCode()).Next(0, uperEnStr.Length - 1)]);
                }
            }
            else
                for (int i = 0; i < num; i  )
                {
                    sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
                }

            string str = sb.ToString();
            Regex re = new Regex("(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]");//必须包含大小写字母和数字。
            while (!re.IsMatch(str))
            {
                str = GetMT4pwd(num);
            }
            return str;
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string GetMixPWD(int num)//生成混合随机数
        {
            string a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < num; i  )
            {
                sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
            }

            return sb.ToString();
        }
        //随机字符串生成器的主要功能如下: 
        //1、支持自定义字符串长度
        //2、支持自定义是否包含数字
        //3、支持自定义是否包含小写字母
        //4、支持自定义是否包含大写字母
        //5、支持自定义是否包含特殊符号
        //6、支持自定义字符集
        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length">目标字符串的长度</param>
        /// <param name="useNum">是否包含数字,1=包含,默认为包含</param>
        /// <param name="useLow">是否包含小写字母,1=包含,默认为包含</param>
        /// <param name="useUpp">是否包含大写字母,1=包含,默认为包含</param>
        /// <param name="useSpe">是否包含特殊字符,1=包含,默认为不包含</param>
        /// <param name="custom">要包含的自定义字符,直接输入要包含的字符列表</param>
        /// <returns>指定长度的随机字符串</returns>
        public static string GetRndstr(int length, string custom = "", bool useNum = true, bool useLow = true, bool useUpp = false, bool useSpe = false)
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;

            if (useNum == true) { str  = "23456789"; }
            if (useLow == true) { str  = "abcdefghijkmnpqrstuvwxyz"; }
            if (useUpp == true) { str  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str  = "!"#$%&'()* ,-./:;<=>?@[\]^_`{|}~"; }

            for (int i = 0; i < length; i  )
            {
                s  = str.Substring(r.Next(0, str.Length - 1), 1);
            }

            return s;
        }

        /// <summary>
        /// 检查上传文件的后缀名
        /// 允许上传的有:".jpg", ".gif", ".bmp", ".doc", ".docx", ".jpeg", ".png", ".tif", ".tiff"
        /// </summary>
        /// <param name="fileName">待检查的文件完整名称</param>
        /// <returns></returns>
        public static bool CheckFileExtension(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                    return false;
                fileName = fileName.ToLower();
                string extension = Path.GetExtension(fileName);
                if (string.IsNullOrEmpty(extension))
                    return false;
                string[] _extensionList = { ".jpg", ".gif", ".bmp", ".doc", ".docx", ".jpeg", ".png", ".tif", ".tiff" };
                if (!_extensionList.Contains(extension))
                    return false;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 检查上传文件的后缀名
        /// 允许上传的有:“.jpg|.gif|.bmp|.jpeg|.png”
        /// </summary>
        /// <param name="fileName">待检查的文件完整名称</param>
        /// <returns></returns>
        public static bool CheckIsImgExtension(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                    return false;
                fileName = fileName.ToLower();
                string extension = Path.GetExtension(fileName);
                if (string.IsNullOrEmpty(extension))
                    return false;
                string[] _extensionList = { ".jpg", ".gif", ".bmp", ".jpeg", ".png" };
                if (!_extensionList.Contains(extension))
                    return false;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string GeneraOpionAnswer(int mmss)
        {
            int CurrentMMss = DateTime.Now.Millisecond;
            if (mmss == CurrentMMss)
                CurrentMMss = Convert.ToInt32(Convert.ToInt32(CurrentMMss / 1245) * 131337933);
            else
                CurrentMMss = mmss;
            Random ran = new Random(CurrentMMss);
            int j = ran.Next(0, optionABC.Length);//因为数组长度是7,所以这里范围就用0到6
            return optionABC[j];
        }
        public static string CorrectAnswerList()
        {
            string[] CorrectAnswer = new string[2];
            Random rdr = new Random(DateTime.Now.Millisecond * 12734);
            CorrectAnswer[0] = "A,C,B,B";
            CorrectAnswer[1] = "B,C,B,B";
            int rj = rdr.Next(0, CorrectAnswer.Length);
            return CorrectAnswer[rj];
        }
        public static string ErrorAnswerList()
        {
            string[] ErrorAnswer = new string[7];
            Random rdd = new Random(DateTime.Now.Millisecond);
            // RandomHelper r = new RandomHelper();
            ErrorAnswer[0] = "C,"   GeneraOpionAnswer(DateTime.Now.Millisecond * 123)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 760)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 123);
            ErrorAnswer[1] = GeneraOpionAnswer(DateTime.Now.Millisecond * 123)   ",A,"   GeneraOpionAnswer(DateTime.Now.Millisecond * 321)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 231);
            ErrorAnswer[2] = GeneraOpionAnswer(DateTime.Now.Millisecond * 456)   ",B,"   GeneraOpionAnswer(DateTime.Now.Millisecond * 654)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 564);
            ErrorAnswer[3] = GeneraOpionAnswer(DateTime.Now.Millisecond * 674)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 789)   ",A,"   GeneraOpionAnswer(DateTime.Now.Millisecond * 761);
            ErrorAnswer[4] = GeneraOpionAnswer(DateTime.Now.Millisecond * 954)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 785)   ",C,"   GeneraOpionAnswer(DateTime.Now.Millisecond * 234);
            ErrorAnswer[5] = GeneraOpionAnswer(DateTime.Now.Millisecond * 243)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 879)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 563)   ",A";
            ErrorAnswer[6] = GeneraOpionAnswer(DateTime.Now.Millisecond * 908)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 547)   ","   GeneraOpionAnswer(DateTime.Now.Millisecond * 748)   ",C";
            return ErrorAnswer[rdd.Next(0, ErrorAnswer.Length)];
        }




        /// <summary>
        /// 检查上传文件的后缀名
        /// 允许上传的有:".jpg", ".gif", ".bmp", ".doc", ".docx", ".jpeg", ".png", ".tif", ".tiff"
        /// </summary>
        /// <param name="fileName">待检查的文件完整名称</param>
        /// <returns></returns>
        public static bool CheckFileExtension(string fileName, HttpPostedFileBase postedFile = null)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                    return false;
                string extension = Path.GetExtension(fileName);
                if (string.IsNullOrEmpty(extension))
                {
                    if (postedFile == null)
                        return false;
                    else
                    {
                        int iEx = GetIExtension(postedFile);
                        if (iEx == (int)FileExtension.BMP ||
                            iEx == (int)FileExtension.JPG ||
                            iEx == (int)FileExtension.GIF ||
                            iEx == (int)FileExtension.PNG)
                        {
                            return true;
                        }
                        return false;
                    }
                }
                else
                    extension = extension.ToLower();
                string[] _extensionList = { ".jpg", ".gif", ".bmp", ".doc", ".docx", ".jpeg", ".png", ".tif", ".tiff" };
                if (!_extensionList.Contains(extension))
                    return false;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        public enum FileExtension
        {
            GIF = 7173,
            JPG = 255216,
            BMP = 6677,
            PNG = 13780,
            DOC = 208207,
            DOCX = 8075,
            XLSX = 8075,
            JS = 239187,
            XLS = 208207,
            SWF = 6787,
            MID = 7784,
            RAR = 8297,
            ZIP = 8075,
            XML = 6063,
            TXT = 7067,
            MP3 = 7368,
            WMA = 4838

            // 239187 aspx
            // 117115 cs
            // 119105 js
            // 210187 txt
            //255254 sql         
            // 7790 exe dll,
            // 8297 rar
            // 6063 xml
            // 6033 html
        }
        /// <summary>
        /// 根据数据流,获取文件格式
        /// </summary>
        /// <param name="fu"></param>
        /// <returns></returns>
        private static int GetIExtension(HttpPostedFileBase fu)
        {
            try
            {
                int fileLen = fu.ContentLength;
                byte[] imgArray = new byte[fileLen];
                fu.InputStream.Read(imgArray, 0, fileLen);
                MemoryStream ms = new MemoryStream(imgArray);
                System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
                string fileclass = "";
                byte buffer;
                try
                {
                    buffer = br.ReadByte();
                    fileclass = buffer.ToString();
                    buffer = br.ReadByte();
                    fileclass  = buffer.ToString();
                }
                catch
                {
                }
                br.Close();
                ms.Close();
                //注意将文件流指针还原
                fu.InputStream.Position = 0;
                int iExt = Int32.Parse(fileclass);
                return iExt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }

View Code

 

 FTP再weboConfig中新建多少个key

图片 55

 

前台:

  <!--上传的地方-->
    <table id="tablefileup" width="100%" border="0" cellspacing="0" cellpadding="0" style="text-align: center; display: none;">
        <tr>
            <td align="center">
                <label id="lblerror" style="color: Red" />
            </td>
        </tr>
        <tr>
            <td align="center">
                @using (Html.BeginForm("IDCardExpireUpload", "AccountCommon", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmUP" }))
                {

                    <input type="hidden" id="fileType" name="fileType" />
                    <input style="WIDTH: 300px" id="upfileCer" name="FileUpload_File" type="file" />
                    <input type="button" id="btnUpload" class="cup1" />
                }


            </td>
        </tr>
        <tr>
            <td align="center">
                <br />
                <label id="info"></label>
                <br />
                <font style="color: Red">仅接受格式为:bmp,jpg,jpeg,png;文件大小需小于6M</font>
            </td>
        </tr>
    </table>

JS

$("#btnUpload").click(function () {
                var index = layer.load(0, { shade: [0.1, '#fff'] });
                $("#frmUP").ajaxSubmit({
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);
                        if (data.Result == "1") {
                            //alert(data.MSG);
                            if (data.fileType == 1) {
                                document.getElementById("idcardFront").innerHTML = data.URL;
                                $("#upfileCer").val('');
                                layer.close(index);
                                $("#tablefileup").hide();
                                layer.msg('上传成功');
                            }
                            else {
                                document.getElementById("idcardBack").innerHTML = data.URL;
                                $("#upfileCer").val('');
                                layer.close(index);
                                $("#tablefileup").hide();
                                layer.msg('上传成功');
                            }
                            // window.location.reload();
                            return;
                        } else {
                            layer.msg(''   data.MSG, function () { });
                            layer.close(index);
                            //alert(data.MSG);
                            return;
                        }
                    },
                    error: function (msg) {
                        console.log(msg);
                        layer.close(index);
                        return;
                    }
                })
            })

 

功效体现:

图片 56

未完待续,持续立异。。。。

 

图片 57图片 58

代码:

图片 59

 1 using MvcApplication18.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.SqlClient;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.Mvc;
 8 
 9 namespace MvcApplication18.Controllers
10 {
11     public class HomeController : Controller
12     {
13         //
14         // GET: /Home/
15         appDBEntities db = new appDBEntities();
16         public ActionResult Index()
17         {
18             SqlParameter[] parameter = { };
19             List<SecondHand_info> list = db.Database.SqlQuery<SecondHand_info>("select * from SecondHand_info where SecondHand_keyID >88", parameter).ToList();
20           ViewData["list"] = list;
21             return View();
22         }
23 
24     }
25 }

图片 60图片 61

Controller代码

View Code

MemoryStream ms = HttpUtil.HttpDownloadFile(url);
Bitmap bmp = new Bitmap(ms);

EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
encoderParameters.Param[0] = encoderParameter;

MemoryStream msCompress = new MemoryStream();
bmp.Save(msCompress, GetImageCodecInfo(ImageFormat.Jpeg), encoderParameters);
Bitmap bmpCompress = new Bitmap(msCompress);
bmpCompress.Save(path);
bmp.Save(path2);

msCompress.Close();
ms.Close();

图片 62图片 63

前台代码

View Code

  1 public class SystemUserController : Controller
  2     {
  3         //public void Log()
  4         //{
  5         //    string meg = "";
  6         //    int user = int.Parse(CookieHelper.GetValue("SysUserID"));
  7         //    string ip = IPHelper.GetUserIp;
  8         //    foreach (var item in RouteData.Values)
  9         //    {
 10         //        meg  = item.Key.ToUpper()   ":"   item.Value   "|";
 11         //    }
 12         //    AuditLogConfig.InsertAuditLog(meg, user, ip);
 13         //}
 14         SystemUserRepository sysuserrepository = new SystemUserRepository();
 15         RoleRepository roleryrepository = new RoleRepository();
 16         DepartmentRepository departmentryrepository = new DepartmentRepository();
 17         JobRepository jobryrepository = new JobRepository();
 18         #region 列表页
 19         /// <summary>
 20         /// 列表页
 21         /// </summary>
 22         /// <param name="page">当前页</param>
 23         /// <returns></returns>
 24         [Authorize]
 25         public ActionResult Index(int? page)
 26         {
 27             ViewBag.ControllerName=RouteData.Values["controller"].ToString().ToLower();
 28             CookieHelper.Del("LogName");
 29             var source = sysuserrepository.GetPageModelList(10, page ?? 1, -1);
 30             return View(source);
 31         }
 32         #endregion
 33 
 34         #region 添加管理员
 35         /// <summary>
 36         /// 添加页
 37         /// </summary>
 38         /// <param name="model">管理员实体类</param>
 39         /// <returns></returns>
 40         [Authorize]
 41         public ActionResult Add(SystemUser model)
 42         {
 43             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 44 
 45             var rolelist = roleryrepository.GetModelListByState(1);
 46             ViewBag.RoleID = SelectListExtension.ToSelectList(rolelist, d => d.RoleName, d => d.RoleID.ToString());
 47 
 48             var departmentlist = departmentryrepository.GetModelListByState(1);
 49             ViewBag.DepartmentID = SelectListExtension.ToSelectList(departmentlist, d => d.DepartmentName, d => d.DepartmentID.ToString());
 50 
 51             var joblist = jobryrepository.GetModelListByState(1);
 52             ViewBag.JobID = SelectListExtension.ToSelectList(joblist, d => d.JobName, d => d.JobID.ToString());
 53 
 54             // ViewData["State"] = SelectListHelper.GetIsOrNoSelectList(0);
 55             return View();
 56         }
 57 
 58         /// <summary>
 59         /// 添加事件
 60         /// </summary>
 61         /// <param name="model">实体类</param>
 62         /// <param name="fc"></param>
 63         /// <returns></returns>
 64         [Authorize, HttpPost, ValidateInput(false)]
 65         public ActionResult Add(SystemUser model, FormCollection fc)
 66         {
 67             model.State = 1;
 68             model.CreateTime = DateTime.Now;
 69             sysuserrepository.SaveOrEditModel(model);
 70             return RedirectToAction("Index");
 71         }
 72         #endregion
 73 
 74         #region 删除
 75         /// <summary>
 76         /// 删除
 77         /// </summary>
 78         /// <param name="id">删除编号</param>
 79         /// <returns></returns>
 80         [Authorize]
 81         public ActionResult Delete(int id)
 82         {
 83             try
 84             {
 85                 var model = sysuserrepository.GetModel(id);
 86                 if (model != null)
 87                 {
 88                     sysuserrepository.DeleteModel(id);
 89                     return RedirectToAction("Index");
 90                 }
 91                 else
 92                     return View("404");
 93                 //throw new Exception("方法出错!");
 94 
 95             }
 96             catch (Exception ex)
 97             {
 98                 Log4netHelper.InvokeErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "删除方法出错-Author:ryanding IP地址["   IPHelper.GetUserIp   "]"   "操作人ID:"   CookieHelper.GetValue("SystemUserID"), ex);
 99                 return View("404");
100             }
101            
102            
103         }
104         #endregion
105 
106         #region 查询
107         [Authorize]
108         public ActionResult Search(int? page)
109         {
110             string logname = "";
111             if (page == null)
112             {
113                 logname = Request.Form["KeyWord"];
114                 CookieHelper.SetObj("KeyWord", 0, logname);
115             }
116             else
117                 logname = CookieHelper.GetValue("KeyWord");
118 
119             var query = QueryBuilder.Create<SystemUser>().Like(d => d.LogName, logname);
120             var source = sysuserrepository.GetModelList().Where(query.Expression);
121             return View(new Pager<SystemUser>(source, page ?? 1));
122         }
123 
124         #endregion
125 
126         #region 编辑
127         [Authorize]
128         public ActionResult Edit(int id)
129         {
130             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
131             var model = sysuserrepository.GetModel(id);
132             if (model != null)
133             {
134                 var rolelist = roleryrepository.GetModelListByState(1);
135                 ViewBag.RoleID = SelectListExtension.ToSelectList(rolelist, d => d.RoleName, d => d.RoleID.ToString(),model.RoleID);
136 
137                 var departmentlist = departmentryrepository.GetModelListByState(1);
138                 ViewBag.DepartmentID = SelectListExtension.ToSelectList(departmentlist, d => d.DepartmentName, d => d.DepartmentID.ToString(), model.DepartmentID);
139 
140                 var joblist = jobryrepository.GetModelListByState(1);
141                 ViewBag.JobID = SelectListExtension.ToSelectList(joblist, d => d.JobName, d => d.JobID.ToString(), model.JobID);
142                 ViewData["State"] = SelectListHelper.GetStateSelectList(model.State);
143                 return View(model);
144             }
145             else
146                 return View("404");
147         }
148 
149         [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
150         public ActionResult Edit(int id, FormCollection fc)
151         {
152             var model = sysuserrepository.GetModel(id);
153 
154             if (model != null)
155             {
156                 string password = model.Password;
157                 if (Request.Form["PassWord"] != "")
158                 {
159                     UpdateModel(model);
160                     sysuserrepository.SaveOrEditModel(model);
161                 }
162                 else
163                 {
164                     UpdateModel(model);
165                     model.Password = password;
166                     sysuserrepository.SaveOrEditModel(model);
167                 }
168                 return RedirectToAction("index");
169             }
170             else
171                 return View("404");
172         }
173         #endregion
174 
175         #region 用户名是否可用
176         //检测用户名是否可用
177         [HttpPost]
178         public ActionResult GetUsers(string param, string name)
179         {
180             if (sysuserrepository.IsExist(param))
181                 return Content("y");
182             else
183                 return Content("用户名已存在");
184         }
185         #endregion
186 
187 
188         public bool Login()
189         {
190             try
191             {
192                 //TODO:
193                 throw new Exception("方法出错!");
194 
195             }
196             catch (Exception ex)
197             {
198                 Log4netHelper.InvokeErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "登录方法Login出错-Author:ryanding IP地址["   IPHelper.GetUserIp   "]"   "操作人ID:"   CookieHelper.GetValue("SystemUserID"), ex);
199                 return false;
200             }
201             return true;
202         }
203     }

图片 64图片 65

 

View Code

 1 @model MvcApplication18.Models.SecondHand_info
 2 @using MvcApplication18.Models
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 @foreach (SecondHand_info item in ViewData["list"] as List<SecondHand_info>)
 8 {
 9   <p>@item.SecondHand_keyID </p> 
10      <p>@item.SecondHand_mobile </p> 
11      <p>@item.SecondHand_title </p> 
12      <p>@item.SecondHand_context </p> 
13   
14 }

 

View Code

View代码

 2)带参数查询

Index.cshtml

后台代码

图片 66图片 67

图片 68图片 69

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.SystemUser>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10             <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                     <a href="/systemuser/add">添加用户</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">用户编号</td>
31                         <td class="rgtd3">登录名</td>
32                         <td class="rgtd3">手机</td>
33                         <td class="rgtd3">Email</td>
34                         <td class="rgtd3">昵称</td>
35                         <td class="rgtd3">状态</td>
36                         <td class="rgtd4">操作</td>
37                     </tr>
38                 </table>
39 
40             </div>
41             <div class="rg4">
42                 @{int classnum = 1;}
43                 @foreach (var item in Model)
44                 {
45                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
46                                                                                    {<text>class="rgbg2"</text>}>
47                         <tr>
48                             <td class="rgtd2">@item.SystemUserID</td>
49                             <td class="rgtd3">@(item.LogName)</td>
50                             <td class="rgtd3">@item.Mobile</td>
51                             <td class="rgtd3">@item.Email</td>
52                             <td class="rgtd3">@item.TrueName</td>
53                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
54                             <td class="rgtd4"><a href="/systemuser/delete/@item.SystemUserID">删除</a>&nbsp;|&nbsp;<a href="/systemuser/edit/@item.SystemUserID">编辑</a>&nbsp; </td>
55                         </tr>
56                     </table>
57                                                                                    classnum = classnum   1;
58                 }
59             </div>
60 
61         </div>
62         <div class="rg5">
63             @UIHelper.PagesHelper(ViewBag.ControllerName, Model.TotalPages, Model.PageIndex, Model.PageSize, Model.TotalCount, Model.HasPreviousPage, Model.HasNextPage, Model.PageList)
64         </div>
65     </div>
66 </div>
67 <script>
68     //菜单显示
69     $("#@(ViewBag.ControllerName)sys").addClass("hbg");
70     $("#@(ViewBag.ControllerName)").removeClass("navli");
71     $("#@(ViewBag.ControllerName)").addClass("navlihg");
72     $(".@(ViewBag.ControllerName)sys").each(function (index, item) {
73         $(this).show();
74     });
75 </script>
 1 using MvcApplication18.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.SqlClient;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.Mvc;
 8 
 9 namespace MvcApplication18.Controllers
10 {
11     public class HomeController : Controller
12     {
13         //
14         // GET: /Home/
15         appDBEntities db = new appDBEntities();
16         public ActionResult Index()
17         {
18             var id = "88";
19             var mobile = "18017848011";
20             var sql = "select * from SecondHand_info where SecondHand_keyID =@id and SecondHand_mobile=@mobile";
21          List<SecondHand_info> list=   db.Database.SqlQuery<SecondHand_info>(
22                 sql,
23                 new SqlParameter("@id",id),
24                 new SqlParameter("@mobile",mobile)
25 
26                 ).ToList();
27          db.SaveChanges();
28           ViewData["list"] = list;
29             return View();
30         }
31 
32     }
33 }

View Code

View Code

Add.cshtml

前台代码

图片 70图片 71

图片 72图片 73

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 <div class="contrgcon">
 6     <div class="rgtit3">
 7         <div class="tit1">
 8             <h3>添加用户</h3>
 9         </div>
10         <div class="rgtit3con">
11             @using (Html.BeginForm())
12             {
13                 <dl>
14                     <dd class="dc1">用户名:</dd>
15                     <dd>
16                         <input name="LogName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" />
17                     </dd>
18                 </dl>
19               
20                 <dl>
21                     <dd class="dc1">昵称:</dd>
22                     <dd>
23                         <input name="TrueName" type="text" class="rgtxt2" datatype="n" nullmsg="请输入产品名称" />
24                     </dd>
25                 </dl>
26                 
27                 <dl>
28                     <dd class="dc1">Email:</dd>
29                     <dd>
30                         <input type="text" name="Email" id="Email" class="rgtxt2" />
31                     </dd>
32                 </dl>
33                 <dl>
34                     <dd class="dc1">手机号:</dd>
35                     <dd>
36                         <input type="text" name="Mobile" id="Mobile" class="rgtxt2" />
37                     </dd>
38                 </dl>
39                 <dl>
40                     <dd class="dc1">密码:</dd>
41                     <dd>
42                         <input type="text" name="Password" id="Password" class="rgtxt2" />
43                     </dd>
44                 </dl>
45                 <dl>
46                     <dd class="dc1">确认密码:</dd>
47                     <dd>
48                         <input type="text" name="PassWordto" id="PassWordto" class="rgtxt2" />
49                     </dd>
50                 </dl>
51                 <dl>
52                     <dd class="dc1">岗位:</dd>
53                     <dd>
54                         @Html.DropDownList("JobID", ViewBag.JobID as SelectList)
55                     </dd>
56                 </dl>
57                 <dl>
58                     <dd class="dc1">部门:</dd>
59                     <dd>
60                          @Html.DropDownList("DepartmentID", ViewBag.DepartmentID as SelectList)
61                     </dd>
62                 </dl>
63                 <dl>
64                     <dd class="dc1">角色:</dd>
65                     <dd>
66                          @Html.DropDownList("RoleID", ViewBag.RoleID as SelectList)
67                     </dd>
68                 </dl>
69                 
70                 <dl>
71                     <dd>
72                         <input type="submit" value="提 交" class="rgbut4" />
73                     </dd>
74                 </dl>
75             }
76         </div>
77     </div>
78 </div>
79 <script>
80     //菜单显示
81     $("#@(ViewBag.ControllerName)sys").addClass("hbg");
82     $("#@(ViewBag.ControllerName)").removeClass("navli");
83     $("#@(ViewBag.ControllerName)").addClass("navlihg");
84     $(".@(ViewBag.ControllerName)sys").each(function (index, item) {
85         $(this).show();
86     });
87 </script>
 1 @model MvcApplication18.Models.SecondHand_info
 2 @using MvcApplication18.Models
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 @foreach (SecondHand_info item in ViewData["list"] as List<SecondHand_info>)
 8 {
 9   <p>@item.SecondHand_keyID </p> 
10      <p>@item.SecondHand_mobile </p> 
11      <p>@item.SecondHand_title </p> 
12      <p>@item.SecondHand_context </p> 
13   
14 }
15 <h2>Index</h2>

View Code

View Code

Edit.cshtml

 

图片 74图片 75

3)修改

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 @model SJCRM.Models.SystemUser
 6 <div class="contrgcon">
 7     <div class="rgtit3">
 8         <div class="tit1">
 9             <h3>编辑用户</h3>
10         </div>
11         <div class="rgtit3con">
12             @using (Html.BeginForm())
13             {
14                 <dl>
15                     <dd class="dc1">用户名:</dd>
16                     <dd>
17                         <input name="LogName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" value="@Model.LogName"/>
18                     </dd>
19                 </dl>
20               
21                 <dl>
22                     <dd class="dc1">昵称:</dd>
23                     <dd>
24                         <input name="TrueName" type="text" class="rgtxt2" datatype="n" nullmsg="请输入产品名称" value="@Model.TrueName" />
25                     </dd>
26                 </dl>
27                 
28                 <dl>
29                     <dd class="dc1">Email:</dd>
30                     <dd>
31                         <input type="text" name="Email" id="Email" class="rgtxt2" value="@Model.Email" />
32                     </dd>
33                 </dl>
34                 <dl>
35                     <dd class="dc1">手机号:</dd>
36                     <dd>
37                         <input type="text" name="Mobile" id="Mobile" class="rgtxt2" value="@Model.Mobile" />
38                     </dd>
39                 </dl>
40                 <dl>
41                     <dd class="dc1">修改密码:</dd>
42                     <dd>
43                         <input type="text" name="Password" id="Password" class="rgtxt2" value="@Model.Password" />
44                     </dd>
45                 </dl>
46                 
47                 <dl>
48                     <dd class="dc1">岗位:</dd>
49                     <dd>
50                         @Html.DropDownList("JobID", ViewBag.JobID as SelectList)
51                     </dd>
52                 </dl>
53                 <dl>
54                     <dd class="dc1">部门:</dd>
55                     <dd>
56                          @Html.DropDownList("DepartmentID", ViewBag.DepartmentID as SelectList)
57                     </dd>
58                 </dl>
59                 <dl>
60                     <dd class="dc1">角色:</dd>
61                     <dd>
62                          @Html.DropDownList("RoleID", ViewBag.RoleID as SelectList)
63                     </dd>
64                 </dl>
65                 
66                 <dl>
67                     <dd>
68                         <input type="submit" value="提 交" class="rgbut4" />
69                     </dd>
70                 </dl>
71             }
72         </div>
73     </div>
74 </div>
75 <script>
76     //菜单显示
77     $("#@(ViewBag.ControllerName)sys").addClass("hbg");
78     $("#@(ViewBag.ControllerName)").removeClass("navli");
79     $("#@(ViewBag.ControllerName)").addClass("navlihg");
80     $(".@(ViewBag.ControllerName)sys").each(function (index, item) {
81         $(this).show();
82     });
83 </script>

后台代码

View Code

图片 76图片 77

Search.cshtml

using MvcApplication18.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication18.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        appDBEntities db = new appDBEntities();
        public ActionResult Index()
        {

            //修改
            List<SecondHand_info> list = db.Set<SecondHand_info>().SqlQuery("select * from SecondHand_info where SecondHand_keyID =88").ToList();
            list.Last().SecondHand_mobile = "18017848011";//把SecondHand_keyID =88 的手机号改为18017848011
            db.SaveChanges();
          ViewData["list"] = list;
            return View();
        }

    }
}

图片 78图片 79

View Code

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@model SJCRM.Helpers.Pager<SJCRM.Models.SystemUser>
<div class="contrgcon">
    <div class="contrg_list">
        <div class="rgtit">
            <form method="post" action="/@ViewBag.ControllerName/search">
                <dl>
                    <dd>关键词:</dd>
                    <dd>
                        <input name="KeyWord" type="text" class="rgtxt2" /></dd>
                    <dd>
                        <input type="submit" value="查 询" class="rgbut1" /></dd>
                </dl>
            </form>
        </div>
        <div class="rgc">
            <dl class="rgt11">
                <dt>
                    <a href="/systemuser/add">添加用户</a>
                </dt>
            </dl>

            <div class="rg3">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td class="rgtd2">用户编号</td>
                        <td class="rgtd3">登录名</td>
                        <td class="rgtd3">手机</td>
                        <td class="rgtd3">Email</td>
                        <td class="rgtd3">昵称</td>
                        <td class="rgtd3">状态</td>
                        <td class="rgtd4">操作</td>
                    </tr>
                </table>

            </div>
            <div class="rg4">
                @{int classnum = 1;}
                @foreach (var item in Model)
                {
                    <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
                                                                                   {<text>class="rgbg2"</text>}>
                        <tr>
                            <td class="rgtd2">@item.SystemUserID</td>
                            <td class="rgtd3">@(item.LogName)</td>
                            <td class="rgtd3">@item.Mobile</td>
                            <td class="rgtd3">@item.Email</td>
                            <td class="rgtd3">@item.TrueName</td>
                            <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
                            <td class="rgtd4"><a href="/systemuser/delete/@item.SystemUserID">删除</a>&nbsp;|&nbsp;<a href="/systemuser/edit/@item.SystemUserID">编辑</a>&nbsp; </td>
                        </tr>
                    </table>
                                                                                   classnum = classnum   1;
                }
            </div>

        </div>

    </div>
</div>
<script>
    //菜单显示
    $("#@(ViewBag.ControllerName)sys").addClass("hbg");
    $("#@(ViewBag.ControllerName)").removeClass("navli");
    $("#@(ViewBag.ControllerName)").addClass("navlihg");
    $(".@(ViewBag.ControllerName)sys").each(function (index, item) {
        $(this).show();
    });
</script>

前台代码

View Code

图片 80图片 81

 剧中人物管理

 1 @model MvcApplication18.Models.SecondHand_info
 2 @using MvcApplication18.Models
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 @foreach (SecondHand_info item in ViewData["list"] as List<SecondHand_info>)
 8 {
 9   <p>@item.SecondHand_keyID </p> 
10      <p>@item.SecondHand_mobile </p> 
11      <p>@item.SecondHand_title </p> 
12      <p>@item.SecondHand_context </p> 
13   
14 }

图片 82

View Code

Controller代码

 4)带参数的仓库储存进度(所以字段都要列出不然会产出难题)

图片 83图片 84

图片 85图片 86

  1  public class RoleController : Controller
  2     {
  3         RoleRepository roleryrepository = new RoleRepository();
  4         MenuRepository menurepository = new MenuRepository();
  5         RoleMenuMappingRepository rmmrepositoy = new RoleMenuMappingRepository();
  6 
  7         #region 列表
  8         /// <summary>
  9         /// 默认页面
 10         /// </summary>
 11         /// <returns></returns>
 12         /// 
 13         [Authorize]
 14         public ActionResult Index(int? page)
 15         {
 16             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 17             var source = roleryrepository.GetModelList();
 18             return View(roleryrepository.GetPageModelList(source, 10, page ?? 1));
 19         }
 20         #endregion
 21 
 22         #region 添加
 23         /// <summary>
 24         /// 添加页
 25         /// </summary>
 26         /// <param name="model">实体类</param>
 27         /// <returns></returns>
 28         [Authorize]
 29         public ActionResult Add(Role model)
 30         {
 31             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 32             var menu = menurepository.GetModelListByState(1);
 33 
 34             ViewBag.Menu = new SelectList(menu, "MenuID", "MenuName");
 35             // ViewData["State"] = SelectListHelper.GetIsOrNoSelectList(0);
 36             return View();
 37         }
 38         public string Log()
 39         {
 40             string meg = "";
 41             //int user = int.Parse(CookieHelper.GetValue("SysUserID"));
 42             //string ip = IPHelper.GetUserIp;
 43             foreach (var item in RouteData.Values)
 44             {
 45                 meg  = item.Key.ToUpper()   ":"   item.Value   "|";
 46             }
 47             return meg;
 48         }
 49         /// <summary>
 50         /// 添加事件
 51         /// </summary>
 52         /// <param name="model">实体类</param>
 53         /// <param name="fc"></param>
 54         /// <returns></returns>
 55         [Authorize, HttpPost, ValidateInput(false)]
 56         public ActionResult Add(Role model, FormCollection fc, int[] Menu)
 57         {
 58             try
 59             {
 60 
 61 
 62                 ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 63                 model.State = 1;
 64 
 65                 model.CreateTime = DateTime.Now;
 66                 roleryrepository.SaveOrEditModel(model);
 67                 if (Menu.Length > 0)
 68                 {
 69 
 70                     foreach (int gsi in Menu)
 71                     {
 72                         RoleMenuMapping rmm = new RoleMenuMapping();
 73                         rmm.MenuID = gsi;
 74                         rmm.RoleID = model.RoleID;
 75                         rmmrepositoy.SaveOrEditModel(rmm);
 76                     }
 77                 }
 78                 else
 79                 {
 80                     return RedirectToAction("Index");
 81                 }
 82                
 83             }
 84             catch (Exception ex)
 85             {
 86 
 87                 Log4netHelper.InvokeErrorLog(MethodBase.GetCurrentMethod().DeclaringType, ViewBag.ControllerName   "添加方法出错-Author:ryanding IP地址["   IPHelper.GetUserIp   "]"   "操作人ID:"   CookieHelper.GetValue("SystemUserID")   "当前来源信息:"   Log(), ex);
 88             }
 89             return View("404");
 90             
 91         }
 92         #endregion
 93 
 94         #region 删除
 95         /// <summary>
 96         /// 删除
 97         /// </summary>
 98         /// <param name="id">删除编号</param>
 99         /// <returns></returns>
100         [Authorize]
101         public ActionResult Delete(int id)
102         {
103             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
104             var model = roleryrepository.GetModel(id);
105             model.State = 0;
106             if (model != null)
107             {
108                 roleryrepository.SaveOrEditModel(model);
109                 return RedirectToAction("index");
110             }
111             else
112                 return View("404");
113           
114 
115         }
116         #endregion
117 
118         #region 查询
119         [Authorize]
120         public ActionResult Search(int? page)
121         {
122             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
123             string name = "";
124             if (page == null)
125             {
126                 name = Request.Form["KeyWord"];
127                 CookieHelper.SetObj("KeyWord", 0, name);
128             }
129             else
130                 name = CookieHelper.GetValue("KeyWord");
131 
132             var query = QueryBuilder.Create<Role>().Like(d => d.RoleName, name);
133             var source = roleryrepository.GetModelList().Where(query.Expression);
134             return View(new Pager<Role>(source, page ?? 1, 10));
135         }
136         #endregion
137 
138         #region 编辑
139         [Authorize]
140         public ActionResult Edit(int id)
141         {
142             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
143             var rmmList = rmmrepositoy.GetModelList().Where(d => d.RoleID == id);
144 
145 
146             var menu = menurepository.GetModelListByState(1);
147             ViewBag.Menu = new SelectList(menu, "MenuID", "MenuName", string.Join(",", rmmList.Select(p => p.MenuID)));
148             var model = roleryrepository.GetModel(id);
149             if (model != null)
150             {
151                 ViewData["State"] = SelectListHelper.GetStateSelectList(model.State);
152                 return View(model);
153             }
154             else
155                 return View("404");
156         }
157 
158         [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
159         public ActionResult Edit(int id, FormCollection fc, int[] Menu)
160         {
161             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
162             var model = roleryrepository.GetModel(id);
163 
164             if (model != null)
165             {
166                 if (Menu.Length > 0)
167                 {
168                     rmmrepositoy.DeleteModel(rmmrepositoy.GetModelList().Where(d => d.RoleID == model.RoleID));
169                     foreach (int gsi in Menu)
170                     {
171                         RoleMenuMapping rmm = new RoleMenuMapping();
172                         rmm.MenuID = gsi;
173                         rmm.RoleID = model.RoleID;
174                         rmmrepositoy.SaveOrEditModel(rmm);
175                     }
176                 }
177 
178 
179                 UpdateModel(model);
180                 roleryrepository.SaveOrEditModel(model);
181                 return RedirectToAction("index");
182             }
183             else
184                 return View("404");
185         }
186         #endregion
187     }
1 create proc P_QuerybyId_secondhand
2 @SecondHand_keyID int
3 as
4 begin
5 select SecondHand_keyID, SecondHand_mobile, SecondHand_title, SecondHand_new, SecondHand_type, SecondHand_money, SecondHand_context, SecondHand_pic1, SecondHand_pic2, SecondHand_pic3, SecondHand_pic4, SecondHand_pic5, SecondHand_pic, SecondHand_time, Memo FROM SecondHand_info where SecondHand_keyID=@SecondHand_keyID
6 end

View Code

View Code

View代码

图片 87图片 88

Index.cshtml

 1 using MvcApplication18.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.SqlClient;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.Mvc;
 8 
 9 namespace MvcApplication18.Controllers
10 {
11     public class HomeController : Controller
12     {
13         //
14         // GET: /Home/
15         appDBEntities db = new appDBEntities();
16         public ActionResult Index()
17         {
18          
19             var param = new SqlParameter("SecondHand_keyID", 89);
20             List<SecondHand_info> list = db.Database.SqlQuery<SecondHand_info>("P_QuerybyId_secondhand @SecondHand_keyID", param).ToList();
21          db.SaveChanges();
22           ViewData["list"] = list;
23             return View();
24         }
25 
26     }
27 }

图片 89图片 90

View Code

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Role>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10             <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                    <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd2">角色名称</td>
32                         <td class="rgtd3">角色内容</td>
33                         <td class="rgtd3">创建时间</td>
34                         <td class="rgtd3">状态</td>
35                         <td class="rgtd4">操作</td>
36                     </tr>
37                 </table>
38 
39             </div>
40             <div class="rg4">
41                 @{int classnum = 1;}
42                 @foreach (var item in Model)
43                 {
44                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
45                                                                                    {<text>class="rgbg2"</text>}>
46                         <tr>
47                             <td class="rgtd2">@item.RoleID</td>
48                             <td class="rgtd2">@item.RoleName</td>
49                             <td class="rgtd3">@item.RoleContent</td>
50                             <td class="rgtd3">@String.Format("{0:yyyy-MM-dd}", item.CreateTime)</td>
51                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
52                             <td class="rgtd4"><a href="/@ViewBag.ControllerName/delete/@item.RoleID">删除</a>&nbsp;|&nbsp;<a href="/@ViewBag.ControllerName/edit/@item.RoleID">编辑</a>&nbsp; </td>
53                         </tr>
54                     </table>
55                                                                                    classnum = classnum   1;
56                 }
57             </div>
58 
59         </div>
60         <div class="rg5">
61            @UIHelper.PagesHelper(ViewBag.ControllerName, Model.TotalPages, Model.PageIndex, Model.PageSize, Model.TotalCount, Model.HasPreviousPage, Model.HasNextPage, Model.PageList);
62  
63         </div>
64     </div>
65 </div>
66 <script>
67     //菜单显示
68     $("#systemusersys").addClass("hbg");
69     $("#@(ViewBag.ControllerName)").removeClass("navli");
70     $("#@(ViewBag.ControllerName)").addClass("navlihg");
71     $(".systemusersys").each(function (index, item) {
72         $(this).show();
73     });
74 </script>

图片 91图片 92

View Code

 1 @model MvcApplication18.Models.SecondHand_info
 2 @using MvcApplication18.Models
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 @foreach (SecondHand_info item in ViewData["list"] as List<SecondHand_info>)
 8 {
 9   <p>@item.SecondHand_keyID </p> 
10      <p>@item.SecondHand_mobile </p> 
11      <p>@item.SecondHand_title </p> 
12      <p>@item.SecondHand_context </p> 
13   
14 }
15 <h2>Index</h2>

Add.cshtml

View Code

图片 93图片 94

 5)带输出参数的累积进程

 1 @using SJCRM.Helpers
 2 @{
 3     ViewBag.Title = "Add";
 4     Layout = "~/Views/Shared/_Layout.cshtml";
 5 }
 6 <div class="contrgcon">
 7     <div class="rgtit3">
 8         <div class="tit1">
 9             <h3>添加</h3>
10         </div>
11         <div class="rgtit3con">
12             @using (Html.BeginForm())
13             {
14                 <dl>
15                     <dd class="dc1">角色名称:</dd>
16                     <dd>
17                         <input name="RoleName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入名称" />
18                     </dd>
19                 </dl>
20               
21       <dl>
22                     <dd class="dc1">角色权限:</dd>
23                     <dd>
24                         @Html.CheckBoxList("Menu")
25                     </dd>
26                 </dl>
27                
28                 <dl>
29                     <dd class="dc1">角色内容:</dd>
30                     <dd>
31                          <textarea rows="10" cols="82" name="RoleContent" id="RoleContent"></textarea>
32                     </dd>
33                 </dl>
34                 <dl>
35                     <dd>
36                         <input type="submit" value="提 交" class="rgbut4" />
37                     </dd>
38                 </dl>
39             }
40         </div>
41     </div>
42 </div>
43 <script>
44     //菜单显示
45     $("#systemusersys").addClass("hbg");
46     $("#@(ViewBag.ControllerName)").removeClass("navli");
47     $("#@(ViewBag.ControllerName)").addClass("navlihg");
48     $(".systemusersys").each(function (index, item) {
49         $(this).show();
50     });
51 </script>

图片 95图片 96

View Code

 1 CREATE PROCEDURE [dbo].[Myproc]
 2     @Name NVARCHAR(max),
 3     @PageIndex int,
 4     @PageSize INT,
 5     @TotalCount int OUTPUT
 6 as 
 7 
 8     declare @startRow int
 9     declare @endRow    int
10     
11     set @startRow = (@PageIndex - 1) * @PageSize   1
12     set @endRow = @startRow   @PageSize - 1
13     
14     select *
15     FROM
16     (
17         select top (@endRow)
18            ID,
19             Age,
20             Name,
21             row_number() over(order by [ID] desc) as [RowIndex]
22         from dbo.Student
23     ) as T    
24     where [RowIndex] >= @startRow AND T.Name = @Name
25     
26     SET @TotalCount=(select count(1) as N 
27     FROM dbo.Student WHERE Name = @Name) 

Edit.cshtml

View Code

图片 97图片 98

图片 99图片 100

 1 @using SJCRM.Helpers
 2 @{
 3     ViewBag.Title = "Add";
 4     Layout = "~/Views/Shared/_Layout.cshtml";
 5 }
 6 @model SJCRM.Models.Role
 7 <div class="contrgcon">
 8     <div class="rgtit3">
 9         <div class="tit1">
10             <h3>编辑</h3>
11         </div>
12         <div class="rgtit3con">
13             @using (Html.BeginForm())
14             {
15                 <dl>
16                     <dd class="dc1">角色名称:</dd>
17                     <dd>
18                         <input name="RoleName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入名称" value="@Model.RoleName"/>
19                     </dd>
20                 </dl>
21               
22       <dl>
23                     <dd class="dc1">角色权限:</dd>
24                     <dd>
25                         
26                         @Html.CheckBoxList("Menu")
27                     </dd>
28                 </dl>
29                
30                 <dl>
31                     <dd class="dc1">角色内容:</dd>
32                     <dd>
33                          <textarea rows="10" cols="82" name="RoleContent" id="RoleContent">@Model.RoleName</textarea>
34                     </dd>
35                 </dl>
36                 <dl>
37                     <dd>
38                         <input type="submit" value="提 交" class="rgbut4" />
39                     </dd>
40                 </dl>
41             }
42         </div>
43     </div>
44 </div>
45 <script>
46     //菜单显示
47     $("#systemusersys").addClass("hbg");
48     $("#@(ViewBag.ControllerName)").removeClass("navli");
49     $("#@(ViewBag.ControllerName)").addClass("navlihg");
50     $(".systemusersys").each(function (index, item) {
51         $(this).show();
52     });
53 </script>
1 var name = new SqlParameter { ParameterName = "Name", Value = Name };
2             var currentpage = new SqlParameter { ParameterName = "PageIndex", Value = currentPage };
3             var pagesize = new SqlParameter { ParameterName = "PageSize", Value = pageSize };
4             var totalcount = new SqlParameter { ParameterName = "TotalCount", Value = 0, Direction = ParameterDirection.Output };
5 
6             var list = ctx.Database.SqlQuery<Student>("Myproc @Name, @PageIndex, @PageSize, @TotalCount output",
7         name, currentpage, pagesize, totalcount);
8 
9             totalCount = (int)totalcount.Value;  /*获得要输出参数totalcount的值*/

View Code

View Code

Search.cshtml

 

图片 101图片 102

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Role>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10             <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                    <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd2">角色名称</td>
32                         <td class="rgtd3">角色内容</td>
33                         <td class="rgtd3">创建时间</td>
34                         <td class="rgtd3">状态</td>
35                         <td class="rgtd4">操作</td>
36                     </tr>
37                 </table>
38 
39             </div>
40             <div class="rg4">
41                 @{int classnum = 1;}
42                 @foreach (var item in Model)
43                 {
44                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
45                                                                                    {<text>class="rgbg2"</text>}>
46                         <tr>
47                             <td class="rgtd2">@item.RoleID</td>
48                             <td class="rgtd2">@item.RoleName</td>
49                             <td class="rgtd3">@item.RoleContent</td>
50                             <td class="rgtd3">@String.Format("{0:yyyy-MM-dd}", item.CreateTime)</td>
51                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
52                             <td class="rgtd4"><a href="/@ViewBag.ControllerName/delete/@item.RoleID">删除</a>&nbsp;|&nbsp;<a href="/@ViewBag.ControllerName/edit/@item.RoleID">编辑</a>&nbsp; </td>
53                         </tr>
54                     </table>
55                                                                                    classnum = classnum   1;
56                 }
57             </div>
58 
59         </div>
60  
61     </div>
62 </div>
63 <script>
64     //菜单显示
65     $("#systemusersys").addClass("hbg");
66     $("#@(ViewBag.ControllerName)").removeClass("navli");
67     $("#@(ViewBag.ControllerName)").addClass("navlihg");
68     $(".systemusersys").each(function (index, item) {
69         $(this).show();
70     });
71 </script>

View Code

 

 菜单管理

图片 103

Controller代码

图片 104图片 105

  1 public class MenuController : Controller
  2     {
  3         MenuRepository repository = new MenuRepository();
  4 
  5         #region 列表
  6         /// <summary>
  7         /// 默认页面
  8         /// </summary>
  9         /// <returns></returns>
 10         /// 
 11         [Authorize]
 12         public ActionResult Index(int? page)
 13         {
 14             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 15             var source = repository.GetModelListByState(1);
 16             return View(repository.GetPageModelList(source, 10, page ?? 1));
 17         }
 18         #endregion
 19 
 20         #region 添加
 21         /// <summary>
 22         /// 添加页
 23         /// </summary>
 24         /// <param name="model">实体类</param>
 25         /// <returns></returns>
 26         [Authorize]
 27         public ActionResult Add(Menu model)
 28         {
 29             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 30             // ViewData["State"] = SelectListHelper.GetIsOrNoSelectList(0);
 31             return View();
 32         }
 33 
 34         /// <summary>
 35         /// 添加事件
 36         /// </summary>
 37         /// <param name="model">实体类</param>
 38         /// <param name="fc"></param>
 39         /// <returns></returns>
 40         [Authorize, HttpPost, ValidateInput(false)]
 41         public ActionResult Add(Menu model, FormCollection fc)
 42         {
 43             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 44             model.State = 1;
 45             model.CreateTime = DateTime.Now;
 46             repository.SaveOrEditModel(model);
 47             return RedirectToAction("Index");
 48         }
 49         #endregion
 50 
 51         #region 删除
 52         /// <summary>
 53         /// 删除
 54         /// </summary>
 55         /// <param name="id">删除编号</param>
 56         /// <returns></returns>
 57         [Authorize]
 58         public ActionResult Delete(int id)
 59         {
 60             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 61             var model = repository.GetModel(id);
 62             model.State = 0;
 63             if (model != null)
 64             {
 65                 repository.SaveOrEditModel(model);
 66                 return RedirectToAction("index");
 67             }
 68             else
 69                 return View("404");
 70             //var model = categoryrepository.GetModel(id);
 71             //if (model != null)
 72             //{
 73             //    categoryrepository.DeleteModel(id);
 74             //    return RedirectToAction("Index");
 75             //}
 76             //else
 77             //    return View("404");
 78 
 79         }
 80         #endregion
 81 
 82         #region 查询
 83         [Authorize]
 84         public ActionResult Search(int? page)
 85         {
 86             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 87             string name = "";
 88             if (page == null)
 89             {
 90                 name = Request.Form["KeyWord"];
 91                 CookieHelper.SetObj("KeyWord", 0, name);
 92             }
 93             else
 94                 name = CookieHelper.GetValue("KeyWord");
 95 
 96             var query = QueryBuilder.Create<Menu>().Like(d => d.MenuName, name);
 97             var source = repository.GetModelList().Where(query.Expression);
 98             return View(new Pager<Menu>(source, page ?? 1, 10));
 99         }
100         #endregion
101 
102         #region 编辑
103         [Authorize]
104         public ActionResult Edit(int id)
105         {
106             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
107             var model = repository.GetModel(id);
108             if (model != null)
109             {
110                 ViewData["State"] = SelectListHelper.GetStateSelectList(model.State);
111                 return View(model);
112             }
113             else
114                 return View("404");
115         }
116 
117         [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
118         public ActionResult Edit(int id, FormCollection fc)
119         {
120             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
121             var model = repository.GetModel(id);
122 
123             if (model != null)
124             {
125                 UpdateModel(model);
126                 repository.SaveOrEditModel(model);
127                 return RedirectToAction("index");
128             }
129             else
130                 return View("404");
131         }
132         #endregion
133      }

View Code

View代码

Index.cshtml

图片 106图片 107

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Menu>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10             <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                    <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd3">菜单名称</td>
32                         <td class="rgtd3">别名样式</td>
33                         <td class="rgtd3">连接地址</td>
34                         <td class="rgtd3">创建时间</td>
35                         <td class="rgtd3">状态</td>
36                         <td class="rgtd4">操作</td>
37                     </tr>
38                 </table>
39 
40             </div>
41             <div class="rg4">
42                 @{int classnum = 1;}
43                 @foreach (var item in Model)
44                 {
45                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
46                                                                                    {<text>class="rgbg2"</text>}>
47                         <tr>
48                             <td class="rgtd2">@item.MenuID</td>
49                             <td class="rgtd3">@item.MenuName</td>
50                             <td class="rgtd3">@item.Alias</td>
51                             <td class="rgtd3">@item.Url</td>
52                             <td class="rgtd3">@String.Format("{0:yyyy-MM-dd}", item.CreateTime)</td>
53                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
54                             <td class="rgtd4"><a href="/@ViewBag.ControllerName/delete/@item.MenuID">删除</a>&nbsp;|&nbsp;<a href="/@ViewBag.ControllerName/edit/@item.MenuID">编辑</a>&nbsp; </td>
55                         </tr>
56                     </table>
57                                                                                    classnum = classnum   1;
58                 }
59             </div>
60 
61         </div>
62         <div class="rg5">
63            @UIHelper.PagesHelper(ViewBag.ControllerName, Model.TotalPages, Model.PageIndex, Model.PageSize, Model.TotalCount, Model.HasPreviousPage, Model.HasNextPage, Model.PageList);
64  
65         </div>
66     </div>
67 </div>
68 <script>
69     //菜单显示
70     $("#systemusersys").addClass("hbg");
71     $("#@(ViewBag.ControllerName)").removeClass("navli");
72     $("#@(ViewBag.ControllerName)").addClass("navlihg");
73     $(".systemusersys").each(function (index, item) {
74         $(this).show();
75     });
76 </script>

View Code

Add.cshtml

图片 108图片 109

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 <div class="contrgcon">
 6     <div class="rgtit3">
 7         <div class="tit1">
 8             <h3>添加菜单</h3>
 9         </div>
10         <div class="rgtit3con">
11             @using (Html.BeginForm())
12             {
13                 <dl>
14                     <dd class="dc1">菜单名称:</dd>
15                     <dd>
16                         <input name="MenuName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" />
17                     </dd>
18                 </dl>
19               
20                 <dl>
21                     <dd class="dc1">连接地址:</dd>
22                     <dd>
23                         <input name="Url" type="text" class="rgtxt2" datatype="n" nullmsg="请输入产品名称" />
24                     </dd>
25                 </dl>
26                 <dl>
27                     <dd class="dc1">别名样式:</dd>
28                     <dd>
29                         <input name="Alias" type="text" class="rgtxt2" datatype="n" nullmsg="请输入产品名称" />
30                     </dd>
31                 </dl>
32                 
33                 
34                 <dl>
35                     <dd>
36                         <input type="submit" value="提 交" class="rgbut4" />
37                     </dd>
38                 </dl>
39             }
40         </div>
41     </div>
42 </div>
43 <script>
44     //菜单显示
45     $("#systemusersys").addClass("hbg");
46     $("#@(ViewBag.ControllerName)").removeClass("navli");
47     $("#@(ViewBag.ControllerName)").addClass("navlihg");
48     $(".systemusersys").each(function (index, item) {
49         $(this).show();
50     });
51 </script>

View Code

Edit.cshtml

图片 110图片 111

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 @model SJCRM.Models.Menu
 6 <div class="contrgcon">
 7     <div class="rgtit3">
 8         <div class="tit1">
 9             <h3>编辑</h3>
10         </div>
11         <div class="rgtit3con">
12             @using (Html.BeginForm())
13             {
14                 <dl>
15                     <dd class="dc1">菜单名称:</dd>
16                     <dd>
17                         <input name="MenuName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" value="@Model.MenuName" />
18                     </dd>
19                 </dl>
20               
21                 <dl>
22                     <dd class="dc1">连接地址:</dd>
23                     <dd>
24                         <input name="Url" type="text" class="rgtxt2" datatype="n" nullmsg="请输入产品名称" value="@Model.Url" />
25                     </dd>
26                 </dl>
27                 <dl>
28                     <dd class="dc1">别名样式:</dd>
29                     <dd>
30                         <input name="Alias" type="text" class="rgtxt2" datatype="n" nullmsg="请输入产品名称" value="@Model.Alias" />
31                     </dd>
32                 </dl>
33                 
34                 
35                 <dl>
36                     <dd>
37                         <input type="submit" value="提 交" class="rgbut4" />
38                     </dd>
39                 </dl>
40             }
41         </div>
42     </div>
43 </div>
44 <script>
45     //菜单显示
46     $("#systemusersys").addClass("hbg");
47     $("#@(ViewBag.ControllerName)").removeClass("navli");
48     $("#@(ViewBag.ControllerName)").addClass("navlihg");
49     $(".systemusersys").each(function (index, item) {
50         $(this).show();
51     });
52 </script>

View Code

Search.cshtml

图片 112图片 113

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Menu>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10             <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                    <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd3">菜单名称</td>
32                         <td class="rgtd3">别名样式</td>
33                         <td class="rgtd3">连接地址</td>
34                         <td class="rgtd3">创建时间</td>
35                         <td class="rgtd3">状态</td>
36                         <td class="rgtd4">操作</td>
37                     </tr>
38                 </table>
39 
40             </div>
41             <div class="rg4">
42                 @{int classnum = 1;}
43                 @foreach (var item in Model)
44                 {
45                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
46                                                                                    {<text>class="rgbg2"</text>}>
47                         <tr>
48                             <td class="rgtd2">@item.MenuID</td>
49                             <td class="rgtd3">@item.MenuName</td>
50                             <td class="rgtd3">@item.Alias</td>
51                             <td class="rgtd3">@item.Url</td>
52                             <td class="rgtd3">@String.Format("{0:yyyy-MM-dd}", item.CreateTime)</td>
53                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
54                             <td class="rgtd4"><a href="/@ViewBag.ControllerName/delete/@item.MenuID">删除</a>&nbsp;|&nbsp;<a href="/@ViewBag.ControllerName/edit/@item.MenuID">编辑</a>&nbsp; </td>
55                         </tr>
56                     </table>
57                                                                                    classnum = classnum   1;
58                 }
59             </div>
60 
61         </div>
62        
63     </div>
64 </div>
65 <script>
66     //菜单显示
67     $("#systemusersys").addClass("hbg");
68     $("#@(ViewBag.ControllerName)").removeClass("navli");
69     $("#@(ViewBag.ControllerName)").addClass("navlihg");
70     $(".systemusersys").each(function (index, item) {
71         $(this).show();
72     });
73 </script>

View Code

 部门管理

图片 114

Controller代码

图片 115图片 116

  1  public class DepartmentController : Controller
  2     {
  3         DepartmentRepository departmentryrepository = new DepartmentRepository();
  4 
  5         #region 列表
  6         /// <summary>
  7         /// 默认页面
  8         /// </summary>
  9         /// <returns></returns>
 10         /// 
 11         [Authorize]
 12         public ActionResult Index(int? page)
 13         {
 14             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 15             var source = departmentryrepository.GetModelList();
 16             return View(departmentryrepository.GetPageModelList(source, 10, page ?? 1));
 17         }
 18         #endregion
 19 
 20         #region 添加
 21         /// <summary>
 22         /// 添加页
 23         /// </summary>
 24         /// <param name="model">实体类</param>
 25         /// <returns></returns>
 26         [Authorize]
 27         public ActionResult Add(Department model)
 28         {
 29             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 30             // ViewData["State"] = SelectListHelper.GetIsOrNoSelectList(0);
 31             return View();
 32         }
 33 
 34         /// <summary>
 35         /// 添加事件
 36         /// </summary>
 37         /// <param name="model">实体类</param>
 38         /// <param name="fc"></param>
 39         /// <returns></returns>
 40         [Authorize, HttpPost, ValidateInput(false)]
 41         public ActionResult Add(Department model, FormCollection fc)
 42         {
 43             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 44             model.State = 1;
 45             model.CreateTime = DateTime.Now;
 46             departmentryrepository.SaveOrEditModel(model);
 47             return RedirectToAction("Index");
 48         }
 49         #endregion
 50 
 51         #region 删除
 52         /// <summary>
 53         /// 删除
 54         /// </summary>
 55         /// <param name="id">删除编号</param>
 56         /// <returns></returns>
 57         [Authorize]
 58         public ActionResult Delete(int id)
 59         {
 60             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 61             var model = departmentryrepository.GetModel(id);
 62             model.State = 0;
 63             if (model != null)
 64             {
 65                 departmentryrepository.SaveOrEditModel(model);
 66                 return RedirectToAction("index");
 67             }
 68             else
 69                 return View("404");
 70             //var model = categoryrepository.GetModel(id);
 71             //if (model != null)
 72             //{
 73             //    categoryrepository.DeleteModel(id);
 74             //    return RedirectToAction("Index");
 75             //}
 76             //else
 77             //    return View("404");
 78 
 79         }
 80         #endregion
 81 
 82         #region 查询
 83         [Authorize]
 84         public ActionResult Search(int? page)
 85         {
 86             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 87             string jobname = "";
 88             if (page == null)
 89             {
 90                 jobname = Request.Form["KeyWord"];
 91                 CookieHelper.SetObj("KeyWord", 0, jobname);
 92             }
 93             else
 94                 jobname = CookieHelper.GetValue("KeyWord");
 95 
 96             var query = QueryBuilder.Create<Department>().Like(d => d.DepartmentName, jobname);
 97             var source = departmentryrepository.GetModelList().Where(query.Expression);
 98             return View(new Pager<Department>(source, page ?? 1, 10));
 99         }
100         #endregion
101 
102         #region 编辑
103         [Authorize]
104         public ActionResult Edit(int id)
105         {
106             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
107             var model = departmentryrepository.GetModel(id);
108             if (model != null)
109             {
110                 ViewData["State"] = SelectListHelper.GetStateSelectList(model.State);
111                 return View(model);
112             }
113             else
114                 return View("404");
115         }
116 
117         [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
118         public ActionResult Edit(int id, FormCollection fc)
119         {
120             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
121             var model = departmentryrepository.GetModel(id);
122 
123             if (model != null)
124             {
125                 UpdateModel(model);
126                 departmentryrepository.SaveOrEditModel(model);
127                 return RedirectToAction("index");
128             }
129             else
130                 return View("404");
131         }
132         #endregion
133       }

View Code

View代码

Index.cshtml

图片 117图片 118

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Department>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10              <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                    <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd2">部门名称</td>
32                         <td class="rgtd3">是否销售</td>
33                         <td class="rgtd3">创建时间</td>
34                         <td class="rgtd3">状态</td>
35                         <td class="rgtd4">操作</td>
36                     </tr>
37                 </table>
38 
39             </div>
40             <div class="rg4">
41                 @{int classnum = 1;}
42                 @foreach (var item in Model)
43                 {
44                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
45                                                                                    {<text>class="rgbg2"</text>}>
46                         <tr>
47                             <td class="rgtd2">@item.DepartmentID</td>
48                             <td class="rgtd2">@item.DepartmentName</td>
49                             <td class="rgtd3">@(item.IsSale == 1 ? "是" : "否")</td>
50                             <td class="rgtd3">@String.Format("{0:yyyy-MM-dd}", item.CreateTime)</td>
51                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
52                             <td class="rgtd4"><a href="/@ViewBag.ControllerName/delete/@item.DepartmentID">删除</a>&nbsp;|&nbsp;<a href="/@ViewBag.ControllerName/edit/@item.DepartmentID">编辑</a>&nbsp; </td>
53                         </tr>
54                     </table>
55                                                                                    classnum = classnum   1;
56                 }
57             </div>
58 
59         </div>
60         <div class="rg5">
61            @UIHelper.PagesHelper(ViewBag.ControllerName, Model.TotalPages, Model.PageIndex, Model.PageSize, Model.TotalCount, Model.HasPreviousPage, Model.HasNextPage, Model.PageList);
62  
63         </div>
64     </div>
65 </div>
66 <script>
67     //菜单显示
68     $("#systemusersys").addClass("hbg");
69     $("#@(ViewBag.ControllerName)").removeClass("navli");
70     $("#@(ViewBag.ControllerName)").addClass("navlihg");
71     $(".systemusersys").each(function (index, item) {
72         $(this).show();
73     });
74 </script>

View Code

Add.cshtml

图片 119图片 120

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 <div class="contrgcon">
 6     <div class="rgtit3">
 7         <div class="tit1">
 8             <h3>添加</h3>
 9         </div>
10         <div class="rgtit3con">
11             @using (Html.BeginForm())
12             {
13                 <dl>
14                     <dd class="dc1">部门名称:</dd>
15                     <dd>
16                         <input name="DepartmentName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" />
17                     </dd>
18                 </dl>
19               
20      
21                 <dl>
22                     <dd class="dc1">是否销售:</dd>
23                     <dd>
24                         <select name="IsSale">
25                             <option value="1">是</option>
26                             <option value="0">否</option>
27                         </select>
28                     </dd>
29                 </dl>
30                
31                 <dl>
32                     <dd>
33                         <input type="submit" value="提 交" class="rgbut4" />
34                     </dd>
35                 </dl>
36             }
37         </div>
38     </div>
39 </div>
40 <script>
41     //菜单显示
42     $("#systemusersys").addClass("hbg");
43     $("#@(ViewBag.ControllerName)").removeClass("navli");
44     $("#@(ViewBag.ControllerName)").addClass("navlihg");
45     $(".systemusersys").each(function (index, item) {
46         $(this).show();
47     });
48 </script>

View Code

Edit.cshtml

图片 121图片 122

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 @model SJCRM.Models.Department
 6 <div class="contrgcon">
 7     <div class="rgtit3">
 8         <div class="tit1">
 9             <h3>编辑</h3>
10         </div>
11         <div class="rgtit3con">
12             @using (Html.BeginForm())
13             {
14                 <dl>
15                     <dd class="dc1">部门名称:</dd>
16                     <dd>
17                         <input name="DepartmentName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" value="@Model.DepartmentName" />
18                     </dd>
19                 </dl>
20               
21      
22                 <dl>
23                     <dd class="dc1">是否销售:</dd>
24                     <dd>
25                         @UIHelper.IsSelect("IsSale", @Model.IsSale.ToString());
26                         
27                     </dd>
28                 </dl>
29                
30                 <dl>
31                     <dd>
32                         <input type="submit" value="提 交" class="rgbut4" />
33                     </dd>
34                 </dl>
35             }
36         </div>
37     </div>
38 </div>
39 <script>
40     //菜单显示
41     $("#systemusersys").addClass("hbg");
42     $("#@(ViewBag.ControllerName)").removeClass("navli");
43     $("#@(ViewBag.ControllerName)").addClass("navlihg");
44     $(".systemusersys").each(function (index, item) {
45         $(this).show();
46     });
47 </script>

View Code

Search.cshtml

图片 123图片 124

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Department>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10              <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                    <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd2">部门名称</td>
32                         <td class="rgtd3">是否销售</td>
33                         <td class="rgtd3">创建时间</td>
34                         <td class="rgtd3">状态</td>
35                         <td class="rgtd4">操作</td>
36                     </tr>
37                 </table>
38 
39             </div>
40             <div class="rg4">
41                 @{int classnum = 1;}
42                 @foreach (var item in Model)
43                 {
44                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
45                                                                                    {<text>class="rgbg2"</text>}>
46                         <tr>
47                             <td class="rgtd2">@item.DepartmentID</td>
48                             <td class="rgtd2">@item.DepartmentName</td>
49                             <td class="rgtd3">@(item.IsSale == 1 ? "是" : "否")</td>
50                             <td class="rgtd3">@String.Format("{0:yyyy-MM-dd}", item.CreateTime)</td>
51                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
52                             <td class="rgtd4"><a href="/@ViewBag.ControllerName/delete/@item.DepartmentID">删除</a>&nbsp;|&nbsp;<a href="/@ViewBag.ControllerName/edit/@item.DepartmentID">编辑</a>&nbsp; </td>
53                         </tr>
54                     </table>
55                                                                                    classnum = classnum   1;
56                 }
57             </div>
58 
59         </div>
60 
61     </div>
62 </div>
63 <script>
64     //菜单显示
65     $("#systemusersys").addClass("hbg");
66     $("#@(ViewBag.ControllerName)").removeClass("navli");
67     $("#@(ViewBag.ControllerName)").addClass("navlihg");
68     $(".systemusersys").each(function (index, item) {
69         $(this).show();
70     });
71 </script>

View Code

 岗位管理

图片 125

Controller代码

图片 126图片 127

  1  public class JobController : Controller
  2     {
  3 
  4         JobRepository jobryrepository = new JobRepository();
  5 
  6         #region 岗位列表
  7         /// <summary>
  8         /// 默认页面
  9         /// </summary>
 10         /// <returns></returns>
 11         /// 
 12         [Authorize]
 13         public ActionResult Index(int? page)
 14         {
 15             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 16             var source = jobryrepository.GetModelListByState(1);
 17             return View(jobryrepository.GetPageModelList(source, 10, page ?? 1));
 18         }
 19         #endregion
 20 
 21         #region 添加
 22         /// <summary>
 23         /// 添加页
 24         /// </summary>
 25         /// <param name="model">实体类</param>
 26         /// <returns></returns>
 27         [Authorize]
 28         public ActionResult Add(Job model)
 29         {
 30             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 31             // ViewData["State"] = SelectListHelper.GetIsOrNoSelectList(0);
 32             return View();
 33         }
 34 
 35         /// <summary>
 36         /// 添加事件
 37         /// </summary>
 38         /// <param name="model">实体类</param>
 39         /// <param name="fc"></param>
 40         /// <returns></returns>
 41         [Authorize, HttpPost, ValidateInput(false)]
 42         public ActionResult Add(Job model, FormCollection fc)
 43         {
 44             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 45             model.State = 1;
 46             model.CreateTime = DateTime.Now;
 47             jobryrepository.SaveOrEditModel(model);
 48             return RedirectToAction("Index");
 49         }
 50         #endregion
 51 
 52         #region 删除
 53         /// <summary>
 54         /// 删除
 55         /// </summary>
 56         /// <param name="id">删除编号</param>
 57         /// <returns></returns>
 58         [Authorize]
 59         public ActionResult Delete(int id)
 60         {
 61             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 62             var model = jobryrepository.GetModel(id);
 63             model.State = 0;
 64             if (model != null)
 65             {
 66                 jobryrepository.SaveOrEditModel(model);
 67                 return RedirectToAction("index");
 68             }
 69             else
 70                 return View("404");
 71             //var model = categoryrepository.GetModel(id);
 72             //if (model != null)
 73             //{
 74             //    categoryrepository.DeleteModel(id);
 75             //    return RedirectToAction("Index");
 76             //}
 77             //else
 78             //    return View("404");
 79 
 80         }
 81         #endregion
 82 
 83         #region 查询
 84         [Authorize]
 85         public ActionResult Search(int? page)
 86         {
 87             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
 88             string jobname = "";
 89             if (page == null)
 90             {
 91                 jobname = Request.Form["KeyWord"];
 92                 CookieHelper.SetObj("KeyWord", 0, jobname);
 93             }
 94             else
 95                 jobname = CookieHelper.GetValue("KeyWord");
 96 
 97             var query = QueryBuilder.Create<Job>().Like(d => d.JobName, jobname);
 98             var source = jobryrepository.GetModelList().Where(query.Expression);
 99             return View(new Pager<Job>(source, page ?? 1, 10));
100         }
101         #endregion
102 
103         #region 编辑
104         [Authorize]
105         public ActionResult Edit(int id)
106         {
107             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
108             var model = jobryrepository.GetModel(id);
109             if (model != null)
110             {
111                 ViewData["State"] = SelectListHelper.GetStateSelectList(model.State);
112                 return View(model);
113             }
114             else
115                 return View("404");
116         }
117 
118         [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
119         public ActionResult Edit(int id, FormCollection fc)
120         {
121             ViewBag.ControllerName = RouteData.Values["controller"].ToString().ToLower();
122             var model = jobryrepository.GetModel(id);
123 
124             if (model != null)
125             {
126                 UpdateModel(model);
127                 jobryrepository.SaveOrEditModel(model);
128                 return RedirectToAction("index");
129             }
130             else
131                 return View("404");
132         }
133         #endregion
134     }

View Code

View代码

Index.cshtml

图片 128图片 129

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Job>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10              <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                     <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd2">岗位名称</td>
32                         <td class="rgtd3">岗位说明</td>
33                         <td class="rgtd3">是否主管</td>
34                         <td class="rgtd3">状态</td>
35                         <td class="rgtd4">操作</td>
36                     </tr>
37                 </table>
38 
39             </div>
40             <div class="rg4">
41                 @{int classnum = 1;}
42                 @foreach (var item in Model)
43                 {
44                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
45                                                                                    {<text>class="rgbg2"</text>}>
46                         <tr>
47                             <td class="rgtd2">@item.JobID</td>
48                             <td class="rgtd2">@item.JobName</td>
49                             <td class="rgtd3">@item.JobContent</td>
50                             <td class="rgtd3">@(item.IsManager == 1 ? "是" : "否")</td>
51                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
52                             <td class="rgtd4"><a href="/job/delete/@item.JobID">删除</a>&nbsp;|&nbsp;<a href="/job/edit/@item.JobID">编辑</a>&nbsp; </td>
53                         </tr>
54                     </table>
55                                                                                    classnum = classnum   1;
56                 }
57             </div>
58 
59         </div>
60         <div class="rg5">
61             @UIHelper.PagesHelper(ViewBag.ControllerName, Model.TotalPages, Model.PageIndex, Model.PageSize, Model.TotalCount, Model.HasPreviousPage, Model.HasNextPage, Model.PageList);
62  
63         </div>
64     </div>
65 </div>
66 <script>
67     //菜单显示
68     $("#systemusersys").addClass("hbg");
69     $("#@(ViewBag.ControllerName)").removeClass("navli");
70     $("#@(ViewBag.ControllerName)").addClass("navlihg");
71     $(".systemusersys").each(function (index, item) {
72         $(this).show();
73     });
74 </script>

View Code

Add.cshtml

图片 130图片 131

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 <div class="contrgcon">
 6     <div class="rgtit3">
 7         <div class="tit1">
 8             <h3>添加</h3>
 9         </div>
10         <div class="rgtit3con">
11             @using (Html.BeginForm())
12             {
13                 <dl>
14                     <dd class="dc1">岗位名称:</dd>
15                     <dd>
16                         <input name="JobName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" />
17                     </dd>
18                 </dl>
19               
20      
21                 <dl>
22                     <dd class="dc1">是否主管:</dd>
23                     <dd>
24                         <select name="IsManager">
25                             <option value="1">是</option>
26                             <option value="0">否</option>
27                         </select>
28                     </dd>
29                 </dl>
30                 <dl>
31                     <dd class="dc1">岗位说明:</dd>
32                     <dd>
33                          <textarea rows="10" cols="82" name="JobContent" id="JobContent"></textarea>
34                     </dd>
35                 </dl>
36                 <dl>
37                     <dd>
38                         <input type="submit" value="提 交" class="rgbut4" />
39                     </dd>
40                 </dl>
41             }
42         </div>
43     </div>
44 </div>
45 <script>
46     //菜单显示
47     $("#systemusersys").addClass("hbg");
48     $("#@(ViewBag.ControllerName)").removeClass("navli");
49     $("#@(ViewBag.ControllerName)").addClass("navlihg");
50     $(".systemusersys").each(function (index, item) {
51         $(this).show();
52     });
53 </script>

View Code

Edit.cshtml

图片 132图片 133

 1 @{
 2     ViewBag.Title = "Add";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 @model SJCRM.Models.Job
 6 <div class="contrgcon">
 7     <div class="rgtit3">
 8         <div class="tit1">
 9             <h3>编辑</h3>
10         </div>
11         <div class="rgtit3con">
12             @using (Html.BeginForm())
13             {
14                 <dl>
15                     <dd class="dc1">岗位名称:</dd>
16                     <dd>
17                         <input name="JobName" type="text" class="rgtxt2" datatype="*" nullmsg="请输入产品名称" value="@Model.JobName" />
18                     </dd>
19                 </dl>
20               
21      
22                 <dl>
23                     <dd class="dc1">是否主管:</dd>
24                     <dd>
25                         @UIHelper.IsSelect("IsManager",Model.IsManager.ToString());
26                        
27                     </dd>
28                 </dl>
29                 <dl>
30                     <dd class="dc1">岗位说明:</dd>
31                     <dd>
32                         <textarea rows="10" cols="82" name="JobContent" id="JobContent">@Model.JobContent</textarea>
33                     </dd>
34                 </dl>
35                 <dl>
36                     <dd>
37                         <input type="submit" value="提 交" class="rgbut4" />
38                     </dd>
39                 </dl>
40             }
41         </div>
42     </div>
43 </div>
44 <script>
45     //菜单显示
46     $("#systemusersys").addClass("hbg");
47     $("#@(ViewBag.ControllerName)").removeClass("navli");
48     $("#@(ViewBag.ControllerName)").addClass("navlihg");
49     $(".systemusersys").each(function (index, item) {
50         $(this).show();
51     });
52 </script>
53 @*<script src="/Content/Scripts/Validform_v5.3.2.js"></script>
54 <script>
55     $(document).ready(function () {
56         $("#addform").Validform({
57             tiptype: 3
58         });
59     });
60 </script>*@
61 <script src="@Url.Content("~/Content/kindeditor/kindeditor-min.js")" type="text/javascript"></script>
62 @*<script type="text/javascript">
63     KindEditor.ready(function (K) {
64         K.create('#JobContent', {
65             allowFileManager: true
66         });
67     });
68 </script>*@

View Code

Search.cshtml

图片 134图片 135

 1 @{
 2     ViewBag.Title = "Index";
 3     Layout = "~/Views/Shared/_Layout.cshtml";
 4 }
 5 
 6 @model SJCRM.Helpers.Pager<SJCRM.Models.Job>
 7 <div class="contrgcon">
 8     <div class="contrg_list">
 9         <div class="rgtit">
10              <form method="post" action="/@ViewBag.ControllerName/search">
11                 <dl>
12                     <dd>关键词:</dd>
13                     <dd>
14                         <input name="KeyWord" type="text" class="rgtxt2" /></dd>
15                     <dd>
16                         <input type="submit" value="查 询" class="rgbut1" /></dd>
17                 </dl>
18             </form>
19         </div>
20         <div class="rgc">
21             <dl class="rgt11">
22                 <dt>
23                     <a href="/@ViewBag.ControllerName/add">添加</a>
24                 </dt>
25             </dl>
26 
27             <div class="rg3">
28                 <table width="100%" border="0" cellspacing="0" cellpadding="0">
29                     <tr>
30                         <td class="rgtd2">编号</td>
31                         <td class="rgtd2">岗位名称</td>
32                         <td class="rgtd3">岗位说明</td>
33                         <td class="rgtd3">是否主管</td>
34                         <td class="rgtd3">状态</td>
35                         <td class="rgtd4">操作</td>
36                     </tr>
37                 </table>
38 
39             </div>
40             <div class="rg4">
41                 @{int classnum = 1;}
42                 @foreach (var item in Model)
43                 {
44                     <table width="100%" border="0" cellspacing="0" cellpadding="0" @if (classnum % 2 == 0)
45                                                                                    {<text>class="rgbg2"</text>}>
46                         <tr>
47                             <td class="rgtd2">@item.JobID</td>
48                             <td class="rgtd2">@item.JobName</td>
49                             <td class="rgtd3">@item.JobContent</td>
50                             <td class="rgtd3">@(item.IsManager == 1 ? "是" : "否")</td>
51                             <td class="rgtd3">@(item.State == 1 ? "有效" : "无效")</td>
52                             <td class="rgtd4"><a href="/job/delete/@item.JobID">删除</a>&nbsp;|&nbsp;<a href="/job/edit/@item.JobID">编辑</a>&nbsp; </td>
53                         </tr>
54                     </table>
55                                                                                    classnum = classnum   1;
56                 }
57             </div>
58 
59         </div>
60 
61     </div>
62 </div>
63 <script>
64     //菜单显示
65     $("#systemusersys").addClass("hbg");
66     $("#@(ViewBag.ControllerName)").removeClass("navli");
67     $("#@(ViewBag.ControllerName)").addClass("navlihg");
68     $(".systemusersys").each(function (index, item) {
69         $(this).show();
70     });
71 </script>

View Code

 

 

本文由星彩网app下载发布于计算机编程,转载请注明出处:各个帮扶类大全,完毕图片压缩

TAG标签: 星彩网app下载
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。