.Net Core3.1 MVC + EF Core+ AutoFac+LayUI+Sqlserver的框架搭建--------基础架构--2

  上一篇说了针对EFcore单个实体的增删改查操作,是满足不了真正开发需求的,如果牵扯到复杂逻辑的多表操做的,这个就显得捉襟见肘了。那么我们要如何做呢,个人推荐就是写存储过程了。所以我们还有在加一种对数据的操作的通用类,用来处理复杂的联合查询,通过调用存储过程实现复杂逻辑。

   数据库操作通用类:SqlHelper

using Core.Net.Common.Core.Net.Core;
using Microsoft.Data.SqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;

namespace Core.Net.Common.Core.Net.Data
{
    /// <summary>
    /// 数据访问基础类(基于SQLServer)
    /// </summary>
    public abstract class SqlHelper
    {
        //数据库连接字符串(web.config来配置)
        public static readonly string LocalSqlServer = CoreNetDBContext.DbConnStr;
        public static readonly int DefPageSize = 20;

        /// <summary>
        /// 通用分页存储过程
        /// </summary>
        /// <param name="connectionString">连接</param>
        /// <param name="tblName">要显示的表或多个表的连接</param>
        /// <param name="fldName">要显示的字段列表,可为Null,表示*</param>
        /// <param name="pageSize">每页显示的记录个数</param>
        /// <param name="pageIndex">要显示那一页的记录</param>
        /// <param name="fldSort">排序字段列表或条件</param>
        /// <param name="Sort">排序方法,False为升序,True为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如:' SortA Asc,SortB Desc,SortC ')</param>
        /// <param name="strCondition">查询条件,不需where,以And开始,可为Null,表示""</param>
        /// <param name="ID">主表的主键</param>
        /// <param name="Disk">是否添加查询字段的 DISTINCT 默认False不添加/True添加</param>
        /// <param name="pageCount">查询结果分页后的总页数</param>
        /// <param name="Counts">查询到的记录数</param>
        /// <param name="strSql">最后返回的SQL语句</param>
        /// <returns>查询当前页的数据集</returns>
        public static DataSet PageList(string connectionString, string tblName, string fldName, int pageSize, int pageIndex,
            string fldSort, bool Sort, string strCondition, string ID, bool Dist,
            out int pageCount, out int Counts, out string strSql)
        {
            SqlParameter[] parameters ={ new SqlParameter("@tblName",SqlDbType.NVarChar,200),
                new SqlParameter("@fldName",SqlDbType.NVarChar,500),
                new SqlParameter("@pageSize",SqlDbType.Int),
                new SqlParameter("@page",SqlDbType.Int),
                new SqlParameter("@fldSort",SqlDbType.NVarChar,200),
                new SqlParameter("@Sort",SqlDbType.Bit),
                new SqlParameter("@strCondition",SqlDbType.NVarChar,1000),
                new SqlParameter("@ID",SqlDbType.NVarChar,150),
                new SqlParameter("@Dist",SqlDbType.Bit),
                new SqlParameter("@pageCount",SqlDbType.Int),
                new SqlParameter("@Counts",SqlDbType.Int),
                new SqlParameter("@strSql",SqlDbType.NVarChar,1000)};

            parameters[0].Value = tblName;
            parameters[1].Value = (fldName == null) ? "*" : fldName;
            parameters[2].Value = (pageSize == 0) ? DefPageSize : pageSize;
            parameters[3].Value = pageIndex;
            parameters[4].Value = fldSort;
            parameters[5].Value = Sort;
            parameters[6].Value = strCondition == null ? "" : strCondition;
            parameters[7].Value = ID;
            parameters[8].Value = Dist;
            parameters[9].Direction = ParameterDirection.Output;
            parameters[10].Direction = ParameterDirection.Output;
            parameters[11].Direction = ParameterDirection.Output;

            DataSet ds = RunProcedure(connectionString, "PageList", parameters, "ds");

            pageCount = (int)parameters[9].Value;
            Counts = (int)parameters[10].Value;
            strSql = parameters[11].Value.ToString();
            return ds;
        }
        /// <summary>
        /// 将DataTable数据集导入SQL数据库.5中
        /// 注意:DataTable中的列头和数据库总表的列名要一致
        /// </summary>
        /// <param name="dt">需要存入数据库的datatable</param>
        /// <param name="string">数据库表名</param>
        public static bool BulkToDB(DataTable dt, string tablemark)
        {

            using (SqlConnection sqlConn = new SqlConnection(LocalSqlServer))
            {
                SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);
                bulkCopy.DestinationTableName = tablemark;
                bulkCopy.BatchSize = dt.Rows.Count;
                try
                {
                    sqlConn.Open();
                    if (dt != null && dt.Rows.Count != 0)
                        bulkCopy.WriteToServer(dt);
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    sqlConn.Close();
                    if (bulkCopy != null)
                        bulkCopy.Close();
                }
                return true;
            };

        }
        #region 执行简单SQL语句
        /// <summary>
        /// 获取表某个字段的最大值

        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static int GetMaxID(string connectionString, string FieldName, string TableName)
        {
            string strSql = "select max(" + FieldName + ") from " + TableName;
            DataSet ds = Query(connectionString, strSql);
            if (ds.Tables[0].Rows[0][0] != DBNull.Value)
                return int.Parse(ds.Tables[0].Rows[0][0].ToString());
            else
                return 0;
        }

        /// <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 + ") from " + TableName;
            DataSet ds = Query(LocalSqlServer, strSql);
            if (ds.Tables[0].Rows[0][0] != DBNull.Value)
                return int.Parse(ds.Tables[0].Rows[0][0].ToString());
            else
                return 0;
        }

        /// <summary>
        ///  检测一个记录是否存在(SqlParameter语句方式)
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static bool Exists(string connectionString, string strSql, params SqlParameter[] cmdParms)
        {
            DataTable ds = Query(connectionString, strSql, cmdParms);
            return int.Parse(ds.Rows[0][0].ToString()) > 0;
        }

        /// <summary>
        /// 执行SQL语句,返回影响的记录数

        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string connectionString, 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 (SqlException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句,返回影响的记录数

        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static bool ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        if (rows > 0) { return true; }
                        else { return false; }
                    }
                    catch (SqlException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 执行SQL语句,返回记录的个数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteCountSql(string connectionString, string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        SqlDataReader dr = cmd.ExecuteReader();
                        int count = 0;
                        if (dr.Read())
                        {
                            count = int.Parse(dr[0].ToString());
                        }
                        return count;
                    }
                    catch (SqlException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。

        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>
        public static void ExecuteSqlTran(string connectionString, List<string> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlTransaction tx = null;
                try
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    tx = conn.BeginTransaction();
                    cmd.Transaction = tx;

                    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 (SqlException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。

        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string connectionString, string SQLString, string content)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(SQLString, connection);
                SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (SqlException 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 connectionString, string strSQL, byte[] fs)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(strSQL, connection);
              SqlParameter myParameter = new SqlParameter("@fs", SqlDbType.Image);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (SqlException 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 connectionString, string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    object obj = null;
                    try
                    {
                        connection.Open();
                        obj = cmd.ExecuteScalar();
                    }
                    catch (SqlException ex)
                    {
                        connection.Close();
                        string sErr = ex.ToString();
                    }
                    finally
                    {
                        cmd.Dispose();
                        if (null != connection)
                        {
                            connection.Close();
                        }
                    }
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SqlDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string connectionString, string strSQL)
        {
            SqlDataReader myReader = null;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    SqlCommand cmd = new SqlCommand(strSQL, connection);
                    myReader = cmd.ExecuteReader();
                }
                catch (SqlException e)
                {
                    throw new Exception(e.Message);
                }
                bool re = myReader.IsClosed;
                return myReader;
            }
        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable Query(string SQLString)
        {
            DataTable ds = new DataTable();
            if (SQLString != null && SQLString.Trim() != "")
            {
                using (SqlConnection connection = new SqlConnection(LocalSqlServer))
                {
                    try
                    {
                        connection.Open();
                        SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                        command.Fill(ds);
                        command.Dispose();
                    }
                    catch (Exception ex)
                    {
                        string sErr = ex.ToString();
                    }
                    finally
                    {
                        if (null != connection)
                        {
                            connection.Close();
                        }
                    }
                    return ds;
                }
            }
            else
            {
                return ds;
            }
        }


        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string connectionString, string SQLString)
        {
            if (SQLString != null && SQLString.Trim() != "")
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        connection.Open();
                        SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                        command.Fill(ds, "ds");
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        if (null != connection)
                        {
                            connection.Close();
                        }
                    }
                    return ds;
                }
            }
            else
            {
                return null;
            }
        }
        #endregion 执行简单SQL语句

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数

        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string connectionString, 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 (SqlException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (SqlException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 执行SQL语句,返回要取的ID
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteCountSql(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        SqlDataReader dr = cmd.ExecuteReader();
                        dr.Read();
                        int count = int.Parse(dr[0].ToString());
                        cmd.Parameters.Clear();
                        return count;
                    }
                    catch (SqlException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 执行SQL语句,返回要取的ID
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteCountSql(string connectionString, string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        SqlDataReader dr = cmd.ExecuteReader();
                        dr.Read();
                        int count = int.Parse(dr[0].ToString());
                        cmd.Parameters.Clear();
                        return count;
                    }
                    catch (SqlException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。

        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
        public static void ExecuteSqlTran(string connectionString, 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>
        /// 执行一条计算查询结果语句,返回查询结果(object)。

        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string connectionString, 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 (SqlException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SqlDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string connectionString, 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();
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (SqlException e)
            {
                throw new Exception(e.Message);
            }

        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable Query(string connectionString, 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))
                {
                    DataTable ds = new DataTable();
                    try
                    {
                        da.Fill(ds);
                        cmd.Parameters.Clear();
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回rowsAffected
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>rowsAffected</returns>
        /// rowsAffected = command.ExecuteNonQuery();
        public static int Query(string connectionString, string SQLString, SqlParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                int outValue;
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    PrepareCommand(cmd, connection, null, SQLString, parameters);
                    rowsAffected = cmd.ExecuteNonQuery();
                    outValue = (int)cmd.Parameters[0].Value;
                }
                catch (SqlException ex)
                {
                    connection.Close();
                    throw new Exception(ex.Message);
                }
                return outValue;
                //using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                //{
                //    DataTable ds = new DataTable();
                //    try
                //    {
                //        da.Fill(ds);
                //        cmd.Parameters.Clear();
                //    }
                //    catch (System.Data.SqlClient.SqlException ex)
                //    {
                //        throw new Exception(ex.Message);
                //    }
                //    return ds;
                //}
            }
        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, LocalSqlServer, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable Query(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataTable ds = new DataTable();
                    try
                    {
                        da.Fill(ds);
                        cmd.Parameters.Clear();
                    }
                    catch (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 parm in cmdParms)
                {
                    if (parm.SqlDbType == SqlDbType.DateTime)
                    {
                        if (parm.Value.ToString().Length > 0)
                        {
                            if ((DateTime)parm.Value == DateTime.MinValue)
                                parm.Value = System.DBNull.Value;
                        }
                    }
                    cmd.Parameters.Add(parm);
                }
            }
        }

        #endregion 执行带参数的SQL语句

        #region 存储过程操作
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <returns>int</returns>
        public static int ExecuteScalar(string storedProcName)
        {
            SqlConnection connection = new SqlConnection(LocalSqlServer);
            SqlCommand cmd = new SqlCommand(storedProcName, connection);
            cmd.CommandType = CommandType.StoredProcedure;
            int val = 0;
            try
            {
                connection.Open();
                val = int.Parse(cmd.ExecuteScalar().ToString());
            }
            catch (SqlException ex)
            {
                string sErr = ex.ToString();
            }
            finally
            {
                if (null != connection)
                {
                    connection.Close();
                }
            }
            return val;
        }
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>int</returns>
        public static int ExecuteScalar(string storedProcName, IDataParameter[] parameters)
        {
            return ExecuteScalar(LocalSqlServer, storedProcName, parameters);
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="connectionString">连接名</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static int ExecuteScalar(string connectionString, string storedProcName, IDataParameter[] parameters)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            int val = 0;
            try
            {
                connection.Open();
                SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
                command.CommandType = CommandType.StoredProcedure;
                val = int.Parse(command.ExecuteScalar().ToString());
            }
            catch (System.Exception ex)
            {
                string sErr = ex.ToString();
            }
            finally
            {
                if (null != connection)
                {
                    connection.Close();
                }
            }
            return val;
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlDataReader returnReader = null;
            try
            {
                connection.Open();
                SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
                command.CommandType = CommandType.StoredProcedure;
                returnReader = command.ExecuteReader();
            }
            catch (System.Exception ex)
            {
                connection.Close();
                string sErr = ex.ToString();
            }
            return returnReader;
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            SqlConnection connection = new SqlConnection(LocalSqlServer);
            SqlDataReader returnReader = null;
            try
            {
                connection.Open();
                SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
                command.CommandType = CommandType.StoredProcedure;
                returnReader = command.ExecuteReader();
            }
            catch (System.Exception ex)
            {
                connection.Close();
                string sErr = ex.ToString();
            }
            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 connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataSet, tableName);
                }
                catch (System.Exception ex)
                {
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
                return dataSet;
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataTable GetTable(string storedProcName, IDataParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                DataTable dataTable = new DataTable();
                try
                {
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataTable);
                }
                catch (System.Exception ex)
                {
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
                return dataTable;
            }
        }
        /// <summary>
        /// 返回数据列表 DataTable Created By Suzongwei
        /// </summary>
        /// <param name="storeProcName">存储过程名</param> 
        /// <returns></returns>
        public static DataTable GetTable(string storeProcName)
        {
            using (SqlConnection con = new SqlConnection(LocalSqlServer))
            {
                DataTable dt = new DataTable();
                try
                {
                    con.Open();
                    SqlDataAdapter sda = new SqlDataAdapter();
                    sda.SelectCommand = BuildQueryCommand(con, storeProcName, null);
                    sda.Fill(dt);
                }
                catch (Exception ex)
                {
                    string sErr = ex.ToString();
                }
                finally
                {
                    con.Close();
                }
                return dt;
            }
        }
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataTable GetTable(string strConn, string storedProcName, IDataParameter[] parameters)
        {
            DateTime startTime = DateTime.Now;
            DataTable dataTable = new DataTable();

            using (SqlConnection connection = new SqlConnection(strConn))
            {
                try
                {
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataTable);
                    return dataTable;
                }
                catch (System.Exception ex)
                {
                    AddLog(0, "err", storedProcName + " 查询错误:" + ex.ToString(), "", 0);
                }
                finally
                {
                    connection.Close();
                }
            }
            TimeSpan ts = DateTime.Now - startTime;
            AddLog(0, "err", storedProcName + " 查询时间:" + ts.TotalSeconds.ToString(), "", 0);

            return dataTable;
        }
        public static DataTable GetTable(string strConn, string storedProcName, IDataParameter[] parameters, out int outValue)
        {
            DateTime startTime = DateTime.Now;
            DataTable dataTable = new DataTable();

            using (SqlConnection connection = new SqlConnection(strConn))
            {
                try
                {
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataTable);
                    if (null != sqlDA.SelectCommand.Parameters[0].Value)
                    {
                        outValue = ConvertHelper.SafeParse(sqlDA.SelectCommand.Parameters[0].Value.ToString(), 0);
                    }
                    else
                        outValue = 0;
                }
                catch (System.Exception ex)
                {
                    outValue = 0;
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
            }

            TimeSpan ts = DateTime.Now - startTime;
            AddLog(0, "time", storedProcName + " 查询时间:" + ts.TotalSeconds.ToString(), "", 0);

            return dataTable;
        }
        /// <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)
        {
            DateTime startTime = DateTime.Now;

            DataSet dataSet = new DataSet();
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {

                try
                {
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataSet, tableName);
                }
                catch (System.Exception ex)
                {
                    AddLog(0, "err", storedProcName + " 加载错误:" + ex.ToString(), "", 0);
                }
                finally
                {
                    connection.Close();
                }

            }
            TimeSpan ts = DateTime.Now - startTime;
            AddLog(0, "time", storedProcName + " 加载时间:" + ts.TotalSeconds.ToString(), "", 0);
            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;
            if (parameters != null)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    if (parameter.SqlDbType == SqlDbType.DateTime)
                    {
                        if ((DateTime)parameter.Value == DateTime.MinValue)
                            parameter.Value = System.DBNull.Value;
                    }
                    if (parameter.Value == null) { parameter.Value = System.DBNull.Value; }
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        /// <summary>
        /// 执行存储过程,返回Return值
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                int result = 0;
                try
                {
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();
                    result = ConvertHelper.SafeParse(command.Parameters["ReturnValue"].Value.ToString(), 0);
                }
                catch (System.Exception ex)
                {
                    rowsAffected = 0;
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
                if (rowsAffected > 0 && result == 0)
                {
                    return rowsAffected;
                }
                return result;
            }
        }

        /// <summary>
        /// 得到存储过程执行删除语句影响的行数

        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>删除语句影响的行数</returns>
        public static int GetProcedureNonQuery(string connectionString, string storedProcName, IDataParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                int rowsAffected = 0;
                try
                {
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();
                }
                catch (System.Exception ex)
                {
                    rowsAffected = 0;
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
                return rowsAffected;
            }
        }

        /// <summary>
        /// 执行存储过程,返回Return值
        /// </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(LocalSqlServer))
            {
                int result = 0;
                rowsAffected = 0;
                try
                {
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();
                    result = (int)command.Parameters["ReturnValue"].Value;
                }
                catch (System.Exception ex)
                {
                    result = 0;
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
                return result;
            }
        }
        /// <summary>
        /// 执行存储过程,返回Return值
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedureRows(string storedProcName, IDataParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                int result;
                try
                {
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    result = command.ExecuteNonQuery();
                }
                catch (System.Exception ex)
                {
                    result = 0;
                    string sErr = ex.ToString();
                }
                finally
                {
                    connection.Close();
                }
                return result;
            }
        }
        /// <summary>
        /// 执行存储过程,返回Return值
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int ReturnProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(LocalSqlServer))
            {
                int result = 0;
                try
                {
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();

                    result = int.Parse(parameters[1].Value.ToString());
                }
                catch (System.Exception ex)
                {
                    rowsAffected = 0;
                    string sErr = ex.ToString();
                }
                finally
                {
                    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 存储过程操作

        #region 构造语句常用类
        /// <summary>
        /// Make input param.
        /// </summary>
        /// <param name="ParamName">Name of param.</param>
        /// <param name="DbType">Param type.</param>
        /// <param name="Size">Param size.</param>
        /// <param name="Value">Param value.</param>
        /// <returns>New parameter.</returns>
        public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }
        public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, object Value)
        {
            return MakeParam(ParamName, DbType, 0, ParameterDirection.Input, Value);
        }

        /// <summary>
        /// Make input param.
        /// </summary>
        /// <param name="ParamName">Name of param.</param>
        /// <param name="DbType">Param type.</param>
        /// <param name="Size">Param size.</param>
        /// <returns>New parameter.</returns>
        public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
        }

        /// <summary>
        /// Make stored procedure param.
        /// </summary>
        /// <param name="ParamName">Name of param.</param>
        /// <param name="DbType">Param type.</param>
        /// <param name="Size">Param size.</param>
        /// <param name="Direction">Parm direction.</param>
        /// <param name="Value">Param value.</param>
        /// <returns>New parameter.</returns>
        public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param;

            if (Size > 0)
                param = new SqlParameter(ParamName, DbType, Size);
            else
                param = new SqlParameter(ParamName, DbType);

            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
                param.Value = Value;

            return param;
        }
        #endregion 构造语句常用类

        #region 由Object取
        /// <summary>
        /// 取得Int值

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int GetInt(object obj)
        {
            if (obj.ToString() != "")
                return int.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 取得byte值

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte Getbyte(object obj)
        {
            if (obj.ToString() != "")
                return byte.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 获得Long值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static long GetLong(object obj)
        {
            if (obj.ToString() != "")
                return long.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 取得Decimal值

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal GetDecimal(object obj)
        {
            if (obj.ToString() != "")
                return decimal.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 取得Guid值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Guid GetGuid(object obj)
        {
            if (obj.ToString() != "")
                return new Guid(obj.ToString());
            else
                return Guid.Empty;
        }

        /// <summary>
        /// 取得DateTime值

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DateTime GetDateTime(object obj)
        {
            if (obj.ToString() != "")
                return DateTime.Parse(obj.ToString());
            else
                return DateTime.MinValue;
        }

        /// <summary>
        /// 取得bool值

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool GetBool(object obj)
        {
            if (obj.ToString() == "1" || obj.ToString().ToLower() == "true")
                return true;
            else
                return false;
        }

        /// <summary>
        /// 取得byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Byte[] GetByte(object obj)
        {
            if (obj.ToString() != "")
            {
                return (Byte[])obj;
            }
            else
                return null;
        }

        /// <summary>
        /// 取得string值

        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetString(object obj)
        {
            return obj.ToString();
        }
        #endregion

        #region 序列化与反序列化
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>返回二进制</returns>
        public static byte[] SerializeModel(Object obj)
        {
            if (obj != null)
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                byte[] b;
                binaryFormatter.Serialize(ms, obj);
                ms.Position = 0;
                b = new Byte[ms.Length];
                ms.Read(b, 0, b.Length);
                ms.Close();
                return b;
            }
            else
                return new byte[0];
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <param name="b">要反序列化的二进制</param>
        /// <returns>返回对象</returns>
        public static object DeserializeModel(byte[] b, object SampleModel)
        {
            if (b == null || b.Length == 0)
                return SampleModel;
            else
            {
                object result = new object();
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                try
                {
                    ms.Write(b, 0, b.Length);
                    ms.Position = 0;
                    result = binaryFormatter.Deserialize(ms);
                    ms.Close();
                }
                catch { }
                return result;
            }
        }
        #endregion

        #region Model与XML互相转换
        /// <summary>
        /// Model转化为XML的方法


        /// </summary>
        /// <param name="model">要转化的Model</param>
        /// <returns></returns>
        public static string ModelToXML(object model)
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlElement ModelNode = xmldoc.CreateElement("Model");
            xmldoc.AppendChild(ModelNode);

            if (model != null)
            {
                foreach (PropertyInfo property in model.GetType().GetProperties())
                {
                    XmlElement attribute = xmldoc.CreateElement(property.Name);
                    if (property.GetValue(model, null) != null)
                        attribute.InnerText = property.GetValue(model, null).ToString();
                    else
                        attribute.InnerText = "[Null]";
                    ModelNode.AppendChild(attribute);
                }
            }

            return xmldoc.OuterXml;
        }

        /// <summary>
        /// XML转化为Model的方法

        /// </summary>
        /// <param name="xml">要转化的XML</param>
        /// <param name="SampleModel">Model的实体示例,New一个出来即可</param>
        /// <returns></returns>
        public static object XMLToModel(string xml, object SampleModel)
        {
            if (string.IsNullOrEmpty(xml))
                return SampleModel;
            else
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xml);

                XmlNodeList attributes = xmldoc.SelectSingleNode("Model").ChildNodes;
                foreach (XmlNode node in attributes)
                {
                    foreach (PropertyInfo property in SampleModel.GetType().GetProperties())
                    {
                        if (node.Name == property.Name)
                        {
                            if (node.InnerText != "[Null]")
                            {
                                if (property.PropertyType == typeof(System.Guid))
                                    property.SetValue(SampleModel, new Guid(node.InnerText), null);
                                else
                                    property.SetValue(SampleModel, Convert.ChangeType(node.InnerText, property.PropertyType), null);
                            }
                            else
                                property.SetValue(SampleModel, null, null);
                        }
                    }
                }
                return SampleModel;
            }
        }
        #endregion

        #region 错误日志
        public static int AddLog(int AID, string LogType, string Body, string IP, int TenantId)
        {
            int rowsAffected;
            SqlParameter[] parameters = {
                    new SqlParameter("@ID", SqlDbType.Int,4) ,
                        new SqlParameter("@AID", SqlDbType.Int,4) ,
                        new SqlParameter("@LogType", SqlDbType.VarChar,30) ,
                        new SqlParameter("@Body", SqlDbType.VarChar,3000) ,
                        new SqlParameter("@IP", SqlDbType.VarChar,30) ,
                        new SqlParameter("@Module", SqlDbType.VarChar,50)  ,
                        new SqlParameter("@RealName", SqlDbType.VarChar,50)  ,
                        new SqlParameter("@TenantId", SqlDbType.Int,4)

            };
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = AID;
            parameters[2].Value = LogType;
            parameters[3].Value = Body;
            parameters[4].Value = IP;
            parameters[5].Value = "";
            parameters[6].Value = "";
            parameters[7].Value = TenantId;
            SqlHelper.RunProcedure("UP_Sys_Log_ADD", parameters, out rowsAffected);
            return (int)parameters[0].Value;
        }
        #endregion
    }
}

 

这里因为这个数据库操作类可能用到了其他通用类,所以单个可能会报错,想了想,干脆把常用的操作通用类,都放在下面:

通用文件操作类:FileHelper

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace Core.Net.Common.Core.Net.Core
{
    /// <summary>
    /// 系统中常用的一些IO操作:磁盘空间检测、文件创建等
    /// </summary>
    public class FileHelper
    {

        /// ******************************************************************
        #region 模板生成网页专用
        /// ******************************************************************
        /// <summary>
        /// 模板读取文件内容
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string strFileName)
        {
            string strUrlText = "";
            if (File.Exists(strFileName))
            {
                StreamReader sr = new StreamReader(strFileName, System.Text.Encoding.GetEncoding("gb2312"));
                strUrlText = sr.ReadToEnd();
                sr.Close();
            }
            return strUrlText;
        }
        /// <summary>
        /// 模板自动生成网页文件
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="sContent">文件内容</param>
        public static void CreatNewFile(string sFilePath, string sContent)
        {
            string dir = sFilePath.Substring(0, sFilePath.LastIndexOf("\\"));
            CreatFolder(dir);
            if (!File.Exists(sFilePath))
            {
                System.IO.FileStream myFileStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Create);
                myFileStream.Close();
            }
            System.IO.StreamWriter sw = new StreamWriter(sFilePath, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);
            sw.Close();
        }
        /// <summary>
        /// 模板自动生成网页文件
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="sContent">文件内容</param>
        /// <param name="sContent">文件编码</param>
        public static void CreatNewFile(string sFilePath, string sContent, string sEncode)
        {
            string dir = sFilePath.Substring(0, sFilePath.LastIndexOf("\\"));
            CreatFolder(dir);
            if (!File.Exists(sFilePath))
            {
                System.IO.FileStream myFileStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Create);
                myFileStream.Close();
            }
            System.IO.StreamWriter sw = new StreamWriter(sFilePath, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);
            sw.Close();
        }
        public static void CreatFolder(string directoryName)
        {
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
        }
        #endregion
        /// ******************************************************************
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string strFileName, string encoding)
        {
            string strUrlText = string.Empty;
            if (File.Exists(strFileName))
            {
                StreamReader sr = new StreamReader(strFileName, string.IsNullOrEmpty(encoding) ? System.Text.Encoding.Default : System.Text.Encoding.GetEncoding(encoding));
                strUrlText = sr.ReadToEnd();
                sr.Close();
            }
            return strUrlText;
        }
        public static void AddLog(string LogContent, string FloderName)
        {
            LogContent = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToString() + ":  " + LogContent;
            string strtime = DateTime.Now.ToString("yyyy-MM-dd").ToString();
            string path = "UpFile/PushLog/" + FloderName + "/" + DateTime.Now.ToString("yyyy-MM-dd").ToString() + ".txt";
            CreatePath("UpFile/PushLog/" + FloderName);
            if (!FileExist(path))
            {
                CreatFile(path);
            }
            AddSaveFile(path, LogContent, "utf-8");
        }
        ///******************************************************************
        /// ******************************************************************
        /// <summary>
        /// 向文件添加文本
        /// </summary>
        /// <param name="strFileName">文件路径</param>
        /// <param name="strText">文件内容</param>
        /// <param name="strEncode">存储编码 utf-8  gb2312</param>
        /// <returns></returns>
        public static bool AddSaveFile(string strFileName, string strText, string strEncode)
        {
            if (strText.Length < 1) { return false; }

            StreamWriter urlWrite = new StreamWriter(strFileName, true, Encoding.GetEncoding(strEncode));
            urlWrite.WriteLine(strText);
            urlWrite.Close();

            return true;
        }
      
        /// ******************************************************************
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static int DeleteFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
                return 1;
            }
            else
            {
                return 0;
            }

        }
        /// ******************************************************************
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static void DelFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
            }
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void CreatFile(string strFileName)
        {
            System.IO.FileStream myFileStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Create);
            myFileStream.Close();
        }
        /// <summary>
        /// 创建目录,如果目录不存在就创建,存在则直接返回。
        /// </summary>
        /// <param name="path"></param>
        public static string CreatePath(string strPath)
        {
            if (!System.IO.Directory.Exists(strPath))
                System.IO.Directory.CreateDirectory(strPath);
            return strPath;
        }
        /// ******************************************************************
        /// <summary>
        /// 向文件添加文本
        /// </summary>
        /// <param name="strFileName">文件路径</param>
        /// <param name="strText">文件内容</param>
        /// <param name="strEncode">存储编码</param>
        /// <returns></returns>
        public static bool SaveFile(string strFileName, string strText, string strEncode)
        {
            if (strText.Length < 1) { return false; }

            StreamWriter urlWrite = new StreamWriter(strFileName, false, Encoding.GetEncoding(strEncode));
            urlWrite.Write(strText);
            urlWrite.Close();

            return true;
        }

        ///******************************************************************

        public static bool FileExist(string strPath)
        {
            return File.Exists(strPath);
        }
        ///******************************************************************
        /// <summary>
        ///   //检查并创建文件
        /// </summary>
        /// <param name="strFileName">文件全路径</param>
        /// <param name="boolDelExist">如果文件存在是否删除</param>
        /// <returns></returns>
        ///******************************************************************     
        public static string CheckAndCreateFile(string strFileName, bool boolDelExist)
        {
            strFileName = strFileName.Replace("/", "\\");
            //存在文件
            if (File.Exists(strFileName))
            {
                if (boolDelExist)
                {
                    File.Delete(strFileName);
                    CreatFile(strFileName);
                }
            }
            else //不存在文件
            {
                int end = strFileName.LastIndexOf("\\");
                if (end > 0)
                {
                    string strFolder = strFileName.Substring(0, end);
                    if (!Directory.Exists(strFolder))
                    {
                        Directory.CreateDirectory(strFolder);
                    }
                }
                CreatFile(strFileName);
            }
            return strFileName;
        }

        public static void CreatDefaultXml(string strFileName)
        {
            string strMyXml = "<?xml version=\"1.0\" encoding=\"gb2312\"?><configuration></configuration>";
            System.IO.FileStream myFileStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Create);
            myFileStream.Close();
            StreamWriter urlWrite = new StreamWriter(strFileName, false, Encoding.GetEncoding("gb2312"));
            urlWrite.Write(strMyXml);
            urlWrite.Close();
        }
        //用户WINDOW应用程序与WEN项目CONFIG切换
        public static string GetConfigPath(string path)
        {
            string strPath = path;
            if (!System.IO.File.Exists(path) || strPath.IndexOf(":") == -1)
            {
                //string strPath1 = System.IO.Directory.GetCurrentDirectory();
                //string strPath2 = System.Environment.CurrentDirectory;
                //以上两种取个人文档地址,下面两种取WEB文件夹路径
                //strPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

                strPath = System.AppDomain.CurrentDomain.BaseDirectory + path;
            }
            return strPath;
        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strMath">文件名</param>
        /// <returns>绝对路径</returns>
        public static string GetImgPath(string strMath)
        {
            string strPath = "\\Photo\\";
            string strMonth = DateTime.Now.Month.ToString();
            if (strMonth.Length == 1) { strMonth = "0" + strMonth; }
            strPath += DateTime.Now.Year.ToString() + strMonth + "\\";
            string strTime = DateTime.Now.ToString() + DateTime.Now.Millisecond.ToString();
            strPath += strTime.Replace(" ", "").Replace("-", "").Replace(":", "");
            if (strMath == null || strMath.Length < 1)
            {
                strPath += ".jpg";
            }
            else
            {
                strPath += "-" + strMath + ".jpg";
            }
            return strPath;
        }
        /// <summary>
        /// 判断文件名是否为浏览器可以直接显示的图片文件名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否可以直接显示</returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }

        public static string SearchConfigPath()
        {
            string BaseDic = System.AppDomain.CurrentDomain.BaseDirectory;
            int i = 0;
            DirectoryInfo info = new DirectoryInfo(BaseDic);
            while (i < 8)
            {
                //要查的目录必须是小写
                DirectoryInfo[] tempInfo = info.GetDirectories("snipconfig");
                if (tempInfo.Length > 0)
                {
                    BaseDic = tempInfo[0].FullName;
                    break;
                }
                else
                {
                    info = info.Parent;
                    tempInfo = info.GetDirectories("web");
                    if (tempInfo.Length > 0)
                    {
                        info = tempInfo[0];
                    }
                }
                i++;
            }
            return BaseDic.TrimEnd('\\');
        }

        /// <summary>
        /// 索引一个文件夹 name  size time path
        /// </summary>
        /// <param name="strDirectory">文件夹路径</param>
        public static DataTable IndexDic(string strDirectory)
        {
            DirectoryInfo directory = new DirectoryInfo(strDirectory);
            DataTable dtFile = new DataTable();
            dtFile.Columns.Add("name", typeof(string));
            dtFile.Columns.Add("size", typeof(string));
            dtFile.Columns.Add("time", typeof(string));
            dtFile.Columns.Add("path", typeof(string));
            dtFile.Columns.Add("type", typeof(string));
            DataRow newRow;
            foreach (FileInfo fi in directory.GetFiles())
            {
                //跳过临时文件
                if (fi.Name.StartsWith("~"))
                    continue;
                newRow = dtFile.NewRow();
                newRow["name"] = fi.Name;
                newRow["size"] = fi.Length / 100;
                newRow["time"] = fi.LastWriteTime.ToString();
                newRow["path"] = fi.FullName;
                newRow["type"] = fi.Extension.Replace(".", "");
                dtFile.Rows.Add(newRow);
            }
            return dtFile;
        }
        /// <summary>
        /// 获取应用程序所在根目录,并拼接传入的目录名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCurrPath(string name)
        {
            return System.AppDomain.CurrentDomain.BaseDirectory + name;
        }

       
    }
}

通用类型转换类:ConvertHelper

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Core.Net.Common.Core.Net.Core
{
    public class ConvertHelper
    {
        /// <summary>
        /// 取Url中参数的字符
        /// </summary>
        /// <param name="ParaName"></param>
        /// <param name="DefValue"></param>
        /// <returns></returns>
        public static string SafeRequest(string ParaName, string DefValue, HttpRequest request)
        {
            if (string.IsNullOrEmpty(request.Query[ParaName]))
            {
                return DefValue;
            }
            else
            {
                return request.Query[ParaName];
            }
        }

        /// <summary>
        /// 取Url中参数的字符并转为Int
        /// </summary>
        /// <param name="ParaName">参数名</param>
        /// <param name="DefValue">对应参数无值则返回默认值</param>
        /// <param name="request">当前请求</param>
        /// <returns></returns>
        public static int SafeRequest(string ParaName, int DefValue, HttpRequest request)
        {
            if (string.IsNullOrEmpty(request.Query[ParaName]))
            {
                return DefValue;
            }
            else
            {
                return SafeParse(request.Query[ParaName], DefValue);
            }
        }
        /// <summary>
        /// 转换为数值型,不是数值型则返回默认值
        /// </summary>
        public static int SafeParse(string paraValue, int DefValue)
        {
            if (IsNumeric(paraValue))
            {
                return Convert.ToInt32(paraValue);
            }
            else
            {
                return DefValue;
            }
        }

        /// <summary>
        /// 判断字符串为NULL则返回默认值
        /// </summary>
        public static string SafeParse(string paraValue, string defValue)
        {
            if (null == paraValue)
            {
                return defValue;
            }
            else
            {
                return paraValue;
            }
        }

        /// <summary>
        /// 转换时间型
        /// </summary>
        public static DateTime SafeParseDate(string paraValue, DateTime DefValue)
        {
            if (IsTime(paraValue))
            {
                return Convert.ToDateTime(paraValue);
            }
            else
            {
                return DefValue;
            }
        }

        /// <summary>
        /// 转换价格数字型
        /// </summary>
        public static Decimal SafeParseDouble(string paraValue, Decimal DefValue)
        {
            if (IsDouble(paraValue))
            {
                return Convert.ToDecimal(paraValue);
            }
            else
            {
                return DefValue;
            }
        }
        /// <summary>
        /// 是否为Double类型
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static bool IsDouble(string expression)
        {
            if (string.IsNullOrEmpty(expression))
            {
                return false;
            }
            return Regex.IsMatch(expression, @"^[+-]?([0-9])[0-9]*(\.\w*)?$");
        }

        /// <summary>
        /// 是否是数值型
        /// </summary>
        /// <param name="value">检测值</param>
        /// <returns></returns>
        public static bool IsNumeric(string strValue)
        {
            if (string.IsNullOrEmpty(strValue))
            {
                return false;
            }
            else
            {
                return Regex.IsMatch(strValue, @"^[+-]?\d*[.]?\d*$");
            }
        }

        /// <summary>
        /// 检查字符串是否是时间格式
        /// </summary>.以下正确的输入格式: [2007-9-29], [2007-09-29 10:29:39 pm], [2007/12/31],[2008-10-27 01:21:20.000]
        /// <param name="timeString">时间字符串</param>
        /// <returns></returns>
        public static bool IsTime(string timeString)
        {
            if (string.IsNullOrEmpty(timeString))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
    }
}

通用Json转换类:JsonHelper:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

namespace Core.Net.Common.Core.Net.Core
{
    public static class JsonHelper
    {
        #region DataTable、JSON 互转
        public static DataTable jsonToTable(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
        }
        /// <summary>
        /// 数据表格转JSON
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string dtToJson(DataTable dt)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            return Newtonsoft.Json.JsonConvert.SerializeObject(dt, timeFormat);
        }
        #endregion

        #region 其他转换方式
        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static object ToJson(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        /// <summary>
        /// 将对象转换成JSON格式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static T ToObject<T>(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
        }

        public static List<T> ToList<T>(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
        }

        public class ModelConvertHelper<T> where T : new()  // 此处一定要加上new()
        {
            //datatable to list
            public static List<T> ConvertToModel(DataTable dt)
            {

                List<T> ts = new List<T>();// 定义集合
                Type type = typeof(T); // 获得此模型的类型
                string tempName = "";
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                    foreach (PropertyInfo pi in propertys)
                    {
                        tempName = pi.Name;
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!pi.CanWrite) continue;
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
        }
        #endregion

        public static string MsgBuild(int MsgID, string MsgBody, bool NeedAuthkey)
        {
            if (NeedAuthkey)
            {
                return "\"message\":" + MsgID + ",\"messagestr\":\"" + MsgBody + "\",\"authkey\":\"jiaozheng\"";
            }
            else
            {
                return "\"message\":" + MsgID + ",\"messagestr\":\"" + MsgBody + "\"";
            }
        }
        public static string EnityTojson(object model)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            return Newtonsoft.Json.JsonConvert.SerializeObject(model, timeFormat);
        }
    }
}

通用图片处理类:ImageHelper

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

namespace Core.Net.Common.Core.Net.Core
{
    public class ImageHelper
    {
        #region 保存BASE64图片

        /// <summary>
        /// 上传任务步骤图片
        /// </summary>
        /// <param name="Base64Str">64位字符串</param>
        /// <param name="fileName">图片名称</param>
        /// <param name="uid">用户Id</param>
        /// <param name="imgSize">图片大小</param>
        /// <returns></returns>
        public static bool SaveBase64Img(string Base64Str, string fileName, out int imgSize)
        {
            //过滤特殊字符即可  
            if (Base64Str.Contains(","))
                Base64Str = Base64Str.Split(',')[1];

            byte[] buffer = Convert.FromBase64String(Base64Str);
            imgSize = buffer.Length;

            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();
            return true;
        }
        #endregion

        #region 生成缩略图
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="oldImagePath">原图路径(物理路径),服务器端路径</param>
        /// <param name="smallPath">缩略图路径(物理路径),服务器端路径</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式 HW:高宽缩放-变形;W:指定宽,高按比例,宽度小于指定宽度,则按最小宽度;H:指定高,宽按比例;all:根据原图的高宽来缩放图片,图片背景为白色;Cut:指定高宽裁减(不变形)</param>    
        public static void MakeThumbnail(string oldImagePath, string smallPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(oldImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放(可能变形)                
                    break;
                case "W"://指定宽,高按比例      
                    if (originalImage.Width < width)
                    {
                        width = originalImage.Width;
                        towidth = originalImage.Width;
                    }
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "all"://根据原图的高宽来缩放图片,图片背景为白色
                    {
                        if (originalImage.Height > originalImage.Width)
                        {
                            towidth = (int)(((double)height / (double)originalImage.Height) * (double)originalImage.Width);
                        }
                        else
                        {
                            toheight = (int)(((double)width / (double)originalImage.Width) * (double)originalImage.Height);
                        }

                        break;
                    }
                case "Cut"://指定高宽裁减(不变形)                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;

                default:
                    break;
            }
            Image bitmap;
            Graphics g;


            if (mode == "all")
            {
                //新建一个bmp图片
                bitmap = new System.Drawing.Bitmap(width, height);
                //新建一个画板
                g = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以白色背景色填充
                g.Clear(Color.White);

                //在指定位置并且按指定大小绘制原图片的指定部分
                if (originalImage.Height > originalImage.Width)//原图的高大于宽,宽取中间
                {
                    int Qwidth;
                    Qwidth = (width - towidth) / 2;
                    g.DrawImage(originalImage, new Rectangle(Qwidth, 0, towidth, toheight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);

                }
                else  //原图的宽大于高,高取中间
                {
                    int Qheight;
                    Qheight = (height - toheight) / 2;
                    g.DrawImage(originalImage, new Rectangle(0, Qheight, towidth, toheight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);
                }

            }
            else
            {
                //新建一个bmp图片
                bitmap = new System.Drawing.Bitmap(towidth, toheight);
                //新建一个画板
                g = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);
            }

            //处理JPG质量的函数
            ImageCodecInfo[] ICI;
            ImageCodecInfo code = null;

            EncoderParameters myEncoderParameters = new EncoderParameters();
            ICI = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo codes in ICI)
            {
                if (codes.MimeType == "image/jpeg")  //只保存JPEG格式
                { code = codes; }
            }
            myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)96);

            try
            {
                //以jpg格式保存缩略图
                //bitmap.Save(smallPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmap.Save(smallPath, code, myEncoderParameters);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }
        public enum PhotoMode
        {
            /**/
            /// <summary>
            /// 指定高宽缩放(可能变形)
            /// </summary>
            HW,

            /**/
            /// <summary>
            /// 指定宽,高按比例 
            /// </summary>
            W,

            /**/
            /// <summary>
            /// 指定高,宽按比例
            /// </summary>
            H,

            /**/
            /// <summary>
            /// 指定高宽裁减(不变形)
            /// </summary>
            Cut
        }

        #endregion

        #region 生成水印
        /// <summary>
        /// 添加水印
        /// </summary>
        /// <param name="Path">源图路径(物理路径)</param>
        /// <param name="Path_sy">水印图路径(物理路径)</param>
        /// <param name="txtFamily">水印字体</param>
        /// <param name="txtSize">水印字大小</param>
        /// <param name="mode">生成缩略图的方式</param> 
        protected static void AddShuiYinWord(string Path, string Path_sy, string addTxt, string txtFamily, int txtSize)
        {
            Image image = Image.FromFile(Path);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            Font f = new Font(txtFamily, txtSize);
            Brush b = new SolidBrush(System.Drawing.Color.LightGray);
            g.DrawString(addTxt, f, b, 15, 15);
            g.Dispose();
            //if (imgtype.ToLower() == ".jpg")
            //{
            image.Save(Path_sy, System.Drawing.Imaging.ImageFormat.Jpeg);
            //}
            //if (imgtype.ToLower() == ".gif")
            //{
            //    image.Save(Path_sy, System.Drawing.Imaging.ImageFormat.Gif);
            //}
            //if (imgtype.ToLower() == ".bmp")
            //{
            //    image.Save(Path_sy, System.Drawing.Imaging.ImageFormat.Bmp);
            //}
            image.Dispose();

        }
        /// <summary>
        /// 生成文字水印图片
        /// </summary>
        /// <param name="oldpath">原始图片路径</param>
        /// <param name="Path_W">存放水印图片路径</param>
        /// <param name="WaterText">要加上的水印文字</param>
        /// <param name="WaterMarkPosition">水印添加的位置</param>
        public static void AddMarkWarter(string oldpath, string Path_W, string WaterText, string WaterMarkPosition)
        {
            try
            {
                Image image = Image.FromFile(oldpath);
                Bitmap p = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = System.Drawing.Graphics.FromImage(p);
                g.DrawImage(image, 0, 0, image.Width, image.Height);
                int[] sizes = new int[] { 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4 };//选择字体大小
                Font crFont = null;
                SizeF crSize = new SizeF();
                for (int i = 0; i < sizes.Length; i++)
                {
                    crFont = new Font("Arial Black", sizes[i], FontStyle.Bold);
                    crSize = g.MeasureString(WaterText, crFont);

                    if ((ushort)crSize.Width < (ushort)image.Width)
                    {
                        break;
                    }
                }
                int x = 0;
                int y = 0;
                int WatermarkWidth = 0;//水印字体的宽
                int WatermarkHeight = 0;//水印字体的高
                double bl = 1;
                WatermarkWidth = Convert.ToInt32((ushort)crSize.Width * bl);
                WatermarkHeight = Convert.ToInt32((ushort)crSize.Height * bl);
                switch (WaterMarkPosition)                     //判断水印所加的位置
                {
                    case "TOP_LEFT":
                        {
                            x = 10;
                            y = 10;
                            break;
                        }
                    case "TOP_RIGHT":
                        {
                            x = image.Width - WatermarkWidth - 10;
                            y = 10;
                            break;
                        }
                    case "BOTTOM_RIGHT":
                        {
                            x = image.Width - WatermarkWidth - 10;
                            y = image.Height - WatermarkHeight - 10;
                            break;
                        }
                    case "BOTTOM_LEFT":
                        {
                            x = 10;
                            y = image.Height - WatermarkHeight - 10;
                            break;
                        }
                    case "TOP_Center":
                        {
                            x = (image.Width - WatermarkWidth) / 2;
                            y = 10;
                            break;
                        }
                    case "BOTTOM_Center":
                        {
                            x = (image.Width - WatermarkWidth) / 2;
                            y = image.Height - WatermarkHeight - 10;
                            break;
                        }
                    case "Center_Left":
                        {
                            x = 10;
                            y = (image.Height - WatermarkHeight) / 2;
                            break;
                        }
                    case "Center_Center":
                        {
                            x = (image.Width - WatermarkWidth) / 2;
                            y = (image.Height - WatermarkHeight) / 2;
                            break;
                        }
                    case "Center_Right":
                        {
                            x = image.Width - WatermarkWidth - 10;
                            y = (image.Height - WatermarkHeight) / 2;
                            break;
                        }

                }
                //new SolidBrush(Color.FromArgb(153, 255, 255, 255))
                Brush b = new SolidBrush(System.Drawing.Color.LightGray);
                g.DrawString(WaterText, crFont, new SolidBrush(Color.FromArgb(128, 0, 0, 255)), x, y);//绘制图片其中solidbrush控制图片的颜色和透明度
                g.Dispose();
                p.Save(Path_W, System.Drawing.Imaging.ImageFormat.Jpeg);//保存加好水印的图片
                p.Dispose();
                image.Dispose();

            }
            catch
            {
                //if (File.Exists(Path_sy))
                //{
                //    File.Delete(oldpath);
                //}
            }
            //finally
            //{
            //    if (File.Exists(oldpath))
            //    {
            //        File.Delete(oldpath);
            //    }
            //}  

        }

        #endregion

        #region 添加文字图片
        /// <summary>
        /// 添加文字水印
        /// </summary>
        /// <param name="oldpath">原图路径</param>
        /// <param name="Path_W">添加完水印后图片保存路径</param>
        /// <param name="WaterPath">水印图片路径</param>
        /// <param name="WaterText">要添加的文字</param>
        /// <param name="WaterMarkPosition">添加的位置</param>
        /// <param name="Alpha">透明度</param>
        /// <param name="Red"></param>
        /// <param name="Green">绿</param>
        /// <param name="Blue"></param>
        /// <param name="FontSize">字体大小</param>
        public static void AddMarkWarter(string oldpath, string Path_W, string WaterPath, string WaterText, int WaterMarkPosition, int Alpha, int Red, int Green, int Blue, int FontSize, int Wwidth, int Wheight)
        {
            try
            {
                #region old
                /*
                int nAlpha = Alpha / 100 * 255;
                //取得原图
                Image sImage = Image.FromFile(oldpath);

                //水印图
                Image wImage = Image.FromFile(WaterPath);


                Graphics g = System.Drawing.Graphics.FromImage(sImage);
                //g.DrawImage(sImage, 0, 0, sImage.Width, sImage.Height);

                Font crFont = null;
                SizeF crSize = new SizeF();
                crFont = new Font("Arial Black", FontSize, FontStyle.Bold);
                crSize = g.MeasureString(WaterText, crFont);

                int x = 0;
                int y = 0;
                int WatermarkWidth = 0;//水印字体的宽
                int WatermarkHeight = 0;//水印字体的高
                double bl = 1;
                WatermarkWidth = Convert.ToInt32((ushort)crSize.Width * bl);
                WatermarkHeight = Convert.ToInt32((ushort)crSize.Height * bl);
                switch (WaterMarkPosition)                     //判断水印所加的位置
                {
                    case 0://"TOP_LEFT":
                        {
                            x = 10;
                            y = 10;
                            break;
                        }
                    case 2://"TOP_RIGHT":
                        {
                            x = sImage.Width - WatermarkWidth - 10;
                            y = 10;
                            break;
                        }
                    case 8://"TOP_RIGHT":
                        {
                            x = sImage.Width - WatermarkWidth - 10;
                            y = sImage.Height - WatermarkHeight - 10;
                            break;
                        }
                    case 6://"BOTTOM_LEFT":
                        {
                            x = 10;
                            y = sImage.Height - WatermarkHeight - 10;
                            break;
                        }
                    case 1://"TOP_Center":
                        {
                            x = (sImage.Width - WatermarkWidth) / 2;
                            y = 10;
                            break;
                        }
                    case 7://"BOTTOM_Center":
                        {
                            x = (sImage.Width - WatermarkWidth) / 2;
                            y = sImage.Height - WatermarkHeight - 10;
                            break;
                        }
                    case 3://"Center_Left":
                        {
                            x = 10;
                            y = (sImage.Height - WatermarkHeight) / 2;
                            break;
                        }
                    case 4://"Center_Center":
                        {
                            x = (sImage.Width - WatermarkWidth) / 2;
                            y = (sImage.Height - WatermarkHeight) / 2;
                            break;
                        }
                    case 5://"Center_Right":
                        {
                            x = sImage.Width - WatermarkWidth - 10;
                            y = (sImage.Height - WatermarkHeight) / 2;
                            break;
                        }

                }
                Brush b = new SolidBrush(System.Drawing.Color.LightGray);
                //添加水印图片                
                g.DrawImage(wImage, new Rectangle(sImage.Width - wImage.Width, sImage.Height - wImage.Height, wImage.Width, wImage.Height), 0, 0, wImage.Width, wImage.Height, GraphicsUnit.Pixel);
                //g.DrawImage(wImage, new Point(x, y));
                g.Dispose();
                sImage.Save(Path_W);//保存加好水印的图片
                sImage.Dispose();
                 */
                #endregion

                Image image = Image.FromFile(oldpath);
                Image copyImage = Image.FromFile(WaterPath);
                Graphics g = Graphics.FromImage(image);
                int x = 0, y = 0;//初始位置
                int width = copyImage.Width, height = copyImage.Height;
                if (Wwidth < width && Wwidth != 0)
                {
                    width = Wwidth;
                }
                if (Wheight < height && Wheight != 0)
                {
                    height = Wheight;
                }
                switch (WaterMarkPosition)
                {
                    case 0:
                        x = image.Width - width;
                        y = image.Height - height;
                        break;
                    case 1:
                        x = 0;
                        y = 0;
                        break;
                    case 2:
                        x = (image.Width - width) / 2;
                        y = 0;
                        break;
                    case 3:
                        x = image.Width - width;
                        y = 0;
                        break;
                    case 4:
                        x = 0;
                        y = (image.Height - height) / 2;
                        break;
                    case 5:
                        x = (image.Width - width) / 2;
                        y = (image.Height - height) / 2;
                        break;
                    case 6:
                        x = image.Width - width; ;
                        y = (image.Height - height) / 2;
                        break;
                    case 7:
                        x = 0;
                        y = image.Height - height;
                        break;
                    case 8:
                        x = (image.Width - width) / 2;
                        y = image.Height - height;
                        break;
                    case 9:
                        x = image.Width - width;
                        y = image.Height - height;
                        break;
                    default:
                        x = image.Width - width;
                        y = image.Height - height;
                        break;
                }
                //g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                g.DrawImage(copyImage, new Rectangle(x, y, width, height), 0, 0, width, height, GraphicsUnit.Pixel);
                g.Dispose();
                string path = Path_W.Substring(0, Path_W.LastIndexOf("\\"));
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                image.Save(Path_W);
                image.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 添加水印图片
        /// <summary>
        /// 添加水印图片
        /// </summary>
        /// <param name="Water_Path">水印图片路径</param>
        /// <param name="Img_Path">要添加水印的图片路径</param>
        /// <param name="Save_Path">添加完水印保存的路径</param>
        /// <param name="WaterMarkPosition">水印添加位置</param>
        /// <param name="Alpha">水印透明度</param>
        public static void AddImgWaterMark(string Water_Path, string Img_Path, string Save_Path, int WaterMarkPosition, int Alpha)
        {
            try
            {
                float fAlpha = (float)((float)(Alpha) / 100.00);
                Image Water_Img = new Bitmap(Water_Path);  //Image.FromFile(Water_Path);//水印图
                Image Img = Image.FromFile(Img_Path);//要加上水印的图片
                Bitmap b = new Bitmap(Img.Width, Img.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.High;
                g.DrawImage(Img, 0, 0, Img.Width, Img.Height);

                ImageAttributes IAB = new ImageAttributes();
                ColorMap CM = new ColorMap();
                //这个水印的背景定义成100%绿色,并用来替代透明
                CM.OldColor = Color.FromArgb(255, 0, 255, 0);
                CM.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { CM };
                IAB.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                //第二个颜色是用来控制水印图片的不透明度的 
                //是使用一个5*5的RGBA矩阵来实现的 
                // 设置第4行、第4列的值为0.3来不透明度的级别
                float[][] colorMatrixElements = {
                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                new float[] {0.0f,  0.0f,  0.0f,  fAlpha, 0.0f},
                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
            };
                ColorMatrix CMX = new ColorMatrix(colorMatrixElements);

                IAB.SetColorMatrix(CMX, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                int x = 0;
                int y = 0;
                switch (WaterMarkPosition)                     //判断水印所加的位置
                {
                    case 0://"TOP_LEFT":
                        {
                            x = 10;
                            y = 10;
                            break;
                        }
                    case 2://"TOP_RIGHT":
                        {
                            x = Img.Width - Water_Img.Width - 10;
                            y = 10;
                            break;
                        }
                    case 8://"BOTTOM_RIGHT":
                        {
                            x = Img.Width - Water_Img.Width - 10;
                            y = Img.Height - Water_Img.Height - 10;
                            break;
                        }
                    case 6://"BOTTOM_LEFT":
                        {
                            x = 10;
                            y = Img.Height - Water_Img.Height - 10;
                            break;
                        }
                    case 1://"TOP_Center":
                        {
                            x = (Img.Width - Water_Img.Width) / 2;
                            y = 10;
                            break;
                        }
                    case 7://"BOTTOM_Center":
                        {
                            x = (Img.Width - Water_Img.Width) / 2;
                            y = Img.Height - Water_Img.Height - 10;
                            break;
                        }
                    case 3://"Center_Left":
                        {
                            x = 10;
                            y = (Img.Height - Water_Img.Height) / 2;
                            break;
                        }
                    case 4://"Center_Center":
                        {
                            x = (Img.Width - Water_Img.Width) / 2;
                            y = (Img.Height - Water_Img.Height) / 2;
                            break;
                        }
                    case 5://"Center_Right":
                        {
                            x = Img.Width - Water_Img.Width - 10;
                            y = (Img.Height - Water_Img.Height) / 2;
                            break;
                        }

                }
                //处理JPG质量的函数
                ImageCodecInfo[] ICI;
                ImageCodecInfo code = null;
                EncoderParameters myEncoderParameters = new EncoderParameters();
                ICI = ImageCodecInfo.GetImageEncoders();
                foreach (ImageCodecInfo codes in ICI)
                {
                    if (codes.MimeType == "image/jpeg")  //只保存JPEG格式
                    { code = codes; }
                }
                myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)96);

                g.DrawImage(Water_Img, new Rectangle(x, y, Water_Img.Width, Water_Img.Height), 0, 0, Water_Img.Width, Water_Img.Height, GraphicsUnit.Pixel, IAB);
                b.Save(Save_Path, code, myEncoderParameters);
                //b.Save(Save_Path, ImageFormat.Jpeg);
                g.Dispose();
                Img.Dispose();
            }
            catch (Exception ex)
            {

                throw ex;

            }

        }
        #endregion

        #region 添加图片水印的方法 位置固定为右下脚透明度为50%
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="Water_Path">水印图</param>
        /// <param name="Img_Path">要加上水印的图片</param>
        /// <param name="Save_Path">保存路径</param>
        public static void AddImgWaterMark(string Water_Path, string Img_Path, string Save_Path)
        {
            Image Water_Img = new Bitmap(Water_Path);  //Image.FromFile(Water_Path);//水印图
            Image Img = Image.FromFile(Img_Path);//要加上水印的图片
            Bitmap b = new Bitmap(Img.Width, Img.Height, PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage(b);
            g.Clear(Color.White);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.High;
            g.DrawImage(Img, 0, 0, Img.Width, Img.Height);

            ImageAttributes IAB = new ImageAttributes();
            ColorMap CM = new ColorMap();
            //这个水印的背景定义成100%绿色,并用来替代透明
            CM.OldColor = Color.FromArgb(255, 0, 255, 0);
            CM.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { CM };
            IAB.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //第二个颜色是用来控制水印图片的不透明度的 
            //是使用一个5*5的RGBA矩阵来实现的 
            // 设置第4行、第4列的值为0.3来不透明度的级别
            float[][] colorMatrixElements = {
                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},
                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
            };
            ColorMatrix CMX = new ColorMatrix(colorMatrixElements);

            IAB.SetColorMatrix(CMX, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            //水印图片居中放置
            int x = 0;
            int y = 0;
            int NewsWidth = 0;
            int NewsHeight = 0;
            NewsWidth = Water_Img.Width;
            NewsHeight = Water_Img.Height;

            x = Img.Width - Water_Img.Width - 10;
            y = Img.Height - Water_Img.Height - 10;
            if (Img.Width < Water_Img.Width + 10)//防止出现水印过宽的现象
            {
                x = 0;
                NewsWidth = Img.Width;
                NewsHeight = (int)((double)Img.Width / (double)Water_Img.Width * (double)Water_Img.Height);
            }
            if (Img.Height < Water_Img.Height + 10)
            {
                y = 0;
                NewsHeight = Img.Height;
                NewsWidth = (int)((double)Img.Height / (double)Water_Img.Height * (double)Water_Img.Width);
            }


            //处理JPG质量的函数
            ImageCodecInfo[] ICI;
            ImageCodecInfo code = null;

            EncoderParameters myEncoderParameters = new EncoderParameters();
            ICI = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo codes in ICI)
            {
                if (codes.MimeType == "image/jpeg")  //只保存JPEG格式
                { code = codes; }
            }
            myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)96);

            g.DrawImage(Water_Img, new Rectangle(x, y, NewsWidth, NewsHeight), 0, 0, Water_Img.Width, Water_Img.Height, GraphicsUnit.Pixel, IAB);
            // bitmap.Save(smallPath, code, myEncoderParameters);
            b.Save(Save_Path, code, myEncoderParameters);
            g.Dispose();
            Img.Dispose();


        }
        #endregion

        #region
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pPath">原图路径</param>
        /// <param name="pSavedPath">截取后保存路径</param>
        /// <param name="pPartStartPointX">0</param>
        /// <param name="pPartStartPointY">0</param>
        /// <param name="pPartWidth">截取宽</param>
        /// <param name="pPartHeight">截取高</param>
        /// <param name="pOrigStartPointX">距顶边距</param>
        /// <param name="pOrigStartPointY">左边距</param>
        /// <param name="imageWidth">图宽</param>
        /// <param name="imageHeight">图高</param>
        /// <returns>图片名称</returns>
        public static string SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight)
        {
            using (Image originalImg = Image.FromFile(pPath))
            {
                if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)//不需要缩放,直接裁剪
                {
                    return SaveCutPic(pPath, pSavedPath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight,
                            pOrigStartPointX, pOrigStartPointY);

                }
                string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                string filePath = pSavedPath + "\\" + filename;

                Bitmap thumimg = MakeThumbnail(originalImg, imageWidth, imageHeight);

                Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);

                Graphics graphics = Graphics.FromImage(partImg);
                Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
                Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置(默认从原图中截取的图片大小等于目标图片的大小)

                ///文字水印  
                Graphics G = Graphics.FromImage(partImg);
                //Font f = new Font("Lucida Grande", 6);
                //Brush b = new SolidBrush(Color.Gray);
                G.Clear(Color.White);
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
                G.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // 指定高质量、低速度呈现。 
                G.SmoothingMode = SmoothingMode.HighQuality;

                graphics.DrawImage(thumimg, destRect, origRect, GraphicsUnit.Pixel);
                //G.DrawString("Xuanye", f, b, 0, 0);
                G.Dispose();

                originalImg.Dispose();
                if (File.Exists(filePath))
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    File.Delete(filePath);
                }
                partImg.Save(filePath, ImageFormat.Jpeg);

                partImg.Dispose();
                thumimg.Dispose();
                return filename;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pPath">原图路径</param>
        /// <param name="pSavedPath">保存路径</param>
        /// <param name="pPartStartPointX">0</param>
        /// <param name="pPartStartPointY">0</param>
        /// <param name="pPartWidth">截取宽</param>
        /// <param name="pPartHeight">截取高</param>
        /// <param name="pOrigStartPointX">距顶边距</param>
        /// <param name="pOrigStartPointY">左边距</param>
        /// <returns>图片名称</returns>
        public static string SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY)
        {
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
            string filePath = pSavedPath + "\\" + filename;

            using (Image originalImg = Image.FromFile(pPath))
            {
                Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);
                Graphics graphics = Graphics.FromImage(partImg);
                Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
                Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置(默认从原图中截取的图片大小等于目标图片的大小)

                ///注释 文字水印  
                Graphics G = Graphics.FromImage(partImg);
                //Font f = new Font("Lucida Grande", 6);
                //Brush b = new SolidBrush(Color.Gray);
                G.Clear(Color.White);
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
                G.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // 指定高质量、低速度呈现。 
                G.SmoothingMode = SmoothingMode.HighQuality;

                graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
                //G.DrawString("Xuanye", f, b, 0, 0);
                G.Dispose();

                originalImg.Dispose();
                if (File.Exists(filePath))
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    File.Delete(filePath);
                }
                partImg.Save(filePath, ImageFormat.Jpeg);
                partImg.Dispose();
            }
            return filename;
        }

        public static Bitmap MakeThumbnail(Image fromImg, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            int ow = fromImg.Width;
            int oh = fromImg.Height;

            //新建一个画板
            Graphics g = Graphics.FromImage(bmp);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            g.DrawImage(fromImg, new Rectangle(0, 0, width, height),
                new Rectangle(0, 0, ow, oh),
                GraphicsUnit.Pixel);
            return bmp;
        }
        #endregion

    }
}

队列通用类:ConcurrentQueueHelper

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Net.Common.Core.Net.Core
{
    /// <summary>
    /// 队列通用类
    /// </summary>
    /// <typeparam name="T"></typeparam>
   public class ConcurrentQueueHelper<T>
    {
        private static ConcurrentQueue<T> concurrentQueue = new ConcurrentQueue<T>();//定义一个消息队列
        private static int QueueMaxLenght = 1000;//队列最大值
        public static T OutT;
        public ConcurrentQueueHelper(int maxCapacity)
        {
            QueueMaxLenght = maxCapacity;
        }
        /// <summary>
        /// 清空缓存
        /// </summary>
        public static bool Clear()
        {
            int count = Query().Count;
            for (int i = 0; i < count; i++)
            {
                if (!concurrentQueue.TryDequeue(out OutT))
                {
                    return false;
                }

            }
            return true;
        }
        /// <summary>
        /// 根据队列设置的最大值判断
        /// 超过最大值,移除队列第一条,队列末尾添加一条
        /// 没超过最大值,一直在队列尾部添加
        /// </summary>
        /// <param name="info"></param>
        public static void Append(T t)
        {
            concurrentQueue.Enqueue(t);
            if (concurrentQueue.Count > QueueMaxLenght)
            {
                concurrentQueue.TryDequeue(out t);
            }
        }
        /// <summary>
        /// 获取队列中元素的个数
        /// </summary>
        /// <returns></returns>
        public static int GetCount()
        {
            return concurrentQueue.Count;
        }
        /// <summary>
        /// 判断队列是否为空
        /// </summary>
        /// <returns></returns>
        public static bool GetEmpty()
        {
            return concurrentQueue.IsEmpty;
        }
        /// <summary>
        /// 尝试移除并返回并发队列开头处的对象
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool RemoveQueue()
        {
            //Dequeue
            return concurrentQueue.TryDequeue(out OutT);
        }
        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        public static List<T> Query()
        {
            return concurrentQueue.ToList();
        }

        /// <summary>
        /// 获取最后一条数据
        /// </summary>
        /// <returns></returns>
        public static T GetLastOrDefault()
        {
            return concurrentQueue.LastOrDefault<T>();
        }

        /// <summary>
        /// 获取第一条数据,但是不会移除第一条记录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static T GetFirstOrDefault()
        {
            concurrentQueue.TryPeek(out OutT);
            return OutT;
        }
    }
}

通用cache缓存类:CacheHelper

using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;

namespace Core.Net.Common.Core.Net.Core
{
    /// <summary>
    /// 通用缓存设置 Core2.0 后HttpRuntime.Cache改为MemoryCache
    /// </summary>
    public class CacheHelper
    {
        private static readonly MemoryCache cache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 增加缓存,过期时间自己设置
        /// </summary>
        /// <typeparam name="T"></typeparam>    
        /// <param name="key">缓存关键字</param>
        /// <param name="value">缓存值</param>
        /// <param name="expiration">从插入开始有效分钟数</param
        public static void AddCache<T>(string key, T value, TimeSpan expiration)
        {
            cache.Set<T>(key, value, expiration);
        }

        public static T TryGetValue<T>(string key)
        {
            var value = default(T);
            object result = null;
            if (cache.TryGetValue(key, out result) && result is T)
            {
                value = (T)result;
            }
            return value;
        }
        /// <summary>
        /// 判断Cache是否为Null
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool CheckCache(string key)
        {
            object result = null;
            return cache.TryGetValue(key, out result);
        }
        public static void Remove(string key)
        {
            cache.Remove(key);
        }

    }
}

 

 

至于如何通过SqlHelper调用存储过程,后续会详细介绍。

 

posted @ 2021-11-02 18:59  代码如风~~~  阅读(422)  评论(0编辑  收藏  举报