.Net Core3.1 MVC + EF Core+ AutoFac+LayUI+Sqlserver的框架搭建--------基礎架構--2
阿新 • • 發佈:2021-11-02
上一篇說了針對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呼叫儲存過程,後續會詳細介紹。
.Net Core