C# 常用公共方法,具体内容如下 1.后台调用weburl string hostUrl = "http://www.a.comid=123" ;HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(hostUrl);myReq.Method = "GET";HttpWebResponse HttpWResp = (HttpWebResponse)m
C# 常用公共方法,具体内容如下
1.后台调用weburl
string hostUrl = "http://www.a.com?id=123" ; HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(hostUrl); myReq.Method = "GET"; HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse(); Stream myStream = HttpWResp.GetResponseStream(); StreamReader sr = new StreamReader(myStream, Encoding.UTF8); StringBuilder strBuilder = new StringBuilder(); while (-1 != sr.Peek()) { strBuilder.Append(sr.ReadLine()); } sr.Close(); myStream.Close(); HttpWResp.Close(); Newtonsoft.Json.Linq.JObject jo = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strBuilder.ToString()); string resCode = jo["ReturnCode"].ToString();
2.检测输入URL是否合法
/// <summary> /// 判断网址是否可以访问 /// </summary> /// <param name="Url"></param> /// <returns></returns> protected bool ChkPageUrl(string url) { bool result = false; try { HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; myHttpWebRequest.Method = "GET"; HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); if (myHttpWebResponse.StatusCode == HttpStatusCode.OK) { result = true; } myHttpWebResponse.Close(); } catch { result = false; } return result; }
3.批量导出
/// <summary> /// 批量导出 /// </summary> /// <returns></returns> public FileResult ExportStu() { //创建Excel文件的对象 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一个sheet NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); int pager_totalcount = (int)Session["pager_totalcount"]; int totalCount = 0; //获取list数据 List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", pager_totalcount, 1, out totalCount); //给sheet1添加第一行的头部标题 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); //创建时间 名称 商户订单号 | 交易号 对方 金额(元) 状态 row1.CreateCell(0).SetCellValue("编号"); row1.CreateCell(1).SetCellValue("标题"); row1.CreateCell(2).SetCellValue("内容"); int Width = 256; sheet1.SetColumnWidth(0, 10 * Width); sheet1.SetColumnWidth(1, 25 * Width); sheet1.SetColumnWidth(2, 60 * Width); if (infoList != null) { var list = infoList.OrderByDescending(p => p.ID); if (list != null) { int i = 0; //将数据逐步写入sheet1各个行 foreach (var item in list) { i = i + 1; NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i); rowtemp.CreateCell(0).SetCellValue(item.ID.ToString()); rowtemp.CreateCell(1).SetCellValue(item.Title == null ? "" : item.Title.ToString()); rowtemp.CreateCell(2).SetCellValue(item.Content == null ? "" : item.Content.ToString()); } } } // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, System.IO.SeekOrigin.Begin); return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出", Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); }
4.批量导入
<input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="上传" />
/// <summary> /// 批量导入 /// </summary> /// <returns></returns> [HttpPost] public ActionResult ImportStu() { HttpPostedFileBase file = Request.Files["file"]; string FileName; string savePath; if (file == null || file.ContentLength <= 0) { return Content("<script>alert('上传失败,请选择上传文件!');location.href='/MyTest/MVCPager';</script>"); } else { string filename = Path.GetFileName(file.FileName); int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名 string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名 string FileType = ".xls,.xlsx";//定义上传文件的类型字符串 if (FileType.Contains(".exe"))//EXCEL { return Content("<script>alert('上传文件类型格式错误,不允许导入exe格式的文件!');location.href='/MyTest/MVCPager';</script>"); } FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx; string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/"; savePath = Path.Combine(path, FileName); file.SaveAs(savePath); if (FileType.Contains(fileEx))//EXCEL { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 8.0"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn); DataSet myDataSet = new DataSet(); try { myCommand.Fill(myDataSet, "ExcelInfo"); } catch (Exception ex) { return Content("<script>alert('上传失败," + ex.Message + "!');location.href='/MyTest/MVCPager';</script>"); } //列顺序 标题 内容 DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable(); //事物 异常回滚 using (TransactionScope transaction = new TransactionScope()) { for (int i = 0; i < table.Rows.Count; i++) { ArticleEntity model = new ArticleEntity(); model.Title = table.Rows[i][0].ToString(); model.Content = table.Rows[i][1].ToString(); new AchieveDAL.MyTestDAL().AddArticle(model); } transaction.Complete(); } } return RedirectToAction("MVCPager", "MyTest"); } }
5.获取客户端的IP地址
/// <summary> /// 获取客户端的IP地址 /// </summary> /// <returns>客户端IP地址</returns> public static string Get_ClientIP() { string result = string.Empty; result = HttpContext.Current.Request.Headers["X-Real-IP"]; //Nginx 为前端时获取IP地址的方法 if (result != null) return result; if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)//发出请求的远程主机的IP地址 { result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); } else if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)//判断是否设置代理,若使用了代理 { if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//获取代理服务器的IP { result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } else { result = HttpContext.Current.Request.UserHostAddress; } } else { result = HttpContext.Current.Request.UserHostAddress; } if (result == "::1") result = string.Empty; return result; }
6.AES对称加密
/// <summary> /// 对称加密类 /// </summary> public class AES { /// <summary> /// 解密 /// </summary> /// <param name="strDecrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Decrypt(string strDecrypt, string strKey) { try { byte[] bytes = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "md5")); byte[] inputBuffer = Convert.FromBase64String(strDecrypt); byte[] buffer3 = null; using (RijndaelManaged managed = new RijndaelManaged()) { managed.Key = bytes; managed.Mode = CipherMode.ECB; managed.Padding = PaddingMode.PKCS7; buffer3 = managed.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length); } return Encoding.UTF8.GetString(buffer3); } catch { return null; } } /// <summary> /// 解密 /// </summary> /// <param name="strDecrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Decrypt(string toDecrypt, string key, string iv) { byte[] bytes = Encoding.UTF8.GetBytes(key); byte[] buffer2 = Encoding.UTF8.GetBytes(iv); byte[] inputBuffer = Convert.FromBase64String(toDecrypt); RijndaelManaged managed = new RijndaelManaged { Key = bytes, IV = buffer2, Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; byte[] buffer4 = managed.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length); return Encoding.UTF8.GetString(buffer4); } public static string DecryptStr(string EncryptString) { string str = ""; if (!string.IsNullOrEmpty(EncryptString)) { string sSource = Decrypt(EncryptString, "cn.solefu"); if (Utility.Left(sSource, 3) == "gk_") { str = sSource.Substring(3); } } return str; } public static string DecryptStrByCBC(string EncryptString) { string str = ""; if (!string.IsNullOrEmpty(EncryptString)) { string sSource = Decrypt(EncryptString, "cn.solefu", "cn.solefu"); if (Utility.Left(sSource, 3) == "gk_") { str = sSource.Substring(3); } } return str; } /// <summary> /// 加密 /// </summary> /// <param name="strEncrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Encrypt(string strEncrypt, string strKey) { try { byte[] bytes = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "md5")); byte[] inputBuffer = Encoding.UTF8.GetBytes(strEncrypt); byte[] inArray = null; using (RijndaelManaged managed = new RijndaelManaged()) { managed.Key = bytes; managed.Mode = CipherMode.ECB; managed.Padding = PaddingMode.PKCS7; inArray = managed.CreateEncryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length); } return Convert.ToBase64String(inArray, 0, inArray.Length); } catch { return null; } } /// <summary> /// 加密 /// </summary> /// <param name="strEncrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Encrypt(string toEncrypt, string key, string iv) { byte[] bytes = Encoding.UTF8.GetBytes(key); byte[] buffer2 = Encoding.UTF8.GetBytes(iv); byte[] inputBuffer = Encoding.UTF8.GetBytes(toEncrypt); RijndaelManaged managed = new RijndaelManaged { Key = bytes, IV = buffer2, Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; byte[] inArray = managed.CreateEncryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length); return Convert.ToBase64String(inArray, 0, inArray.Length); } public static string EncryptStr(string SourceString) { return Encrypt("gk_" + SourceString, "cn.solefu"); } public static string EncryptStr(string SourceString, bool UseInUrl) { return HttpUtility.UrlEncode(EncryptStr(SourceString)); } public static string EncryptStrByCBC(string SourceString) { return Encrypt("gk_" + SourceString, "cn.solefu", "cn.solefu"); } public static string EncryptStrByCBC(string SourceString, bool UseInUrl) { return HttpUtility.UrlEncode(EncryptStrByCBC(SourceString)); } }
7.Cookies帮助类
public class CookiesHelper { public static void AddCookie(string cookieName, DateTime expires) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; AddCookie(cookie, null); } public static void AddCookie(string key, string value) { AddCookie(new HttpCookie(key, value), null); } public static void AddCookie(HttpCookie cookie, string Domain) { HttpResponse response = HttpContext.Current.Response; if (response != null) { cookie.HttpOnly = true; cookie.Path = "/"; if (!string.IsNullOrEmpty(Domain)) { cookie.Domain = Domain; } response.AppendCookie(cookie); } } public static void AddCookie(string cookieName, DateTime expires, string Domain) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; AddCookie(cookie, Domain); } public static void AddCookie(string key, string value, DateTime expires) { HttpCookie cookie = new HttpCookie(key, value) { Expires = expires }; AddCookie(cookie, null); } public static void AddCookie(string cookieName, string key, string value) { HttpCookie cookie = new HttpCookie(cookieName); cookie.Values.Add(key, value); AddCookie(cookie, null); } public static void AddCookie(string key, string value, bool withDomain, string Domain) { if (withDomain) { AddCookie(new HttpCookie(key, value), Domain); } else { AddCookie(new HttpCookie(key, value), null); } } public static void AddCookie(string key, string value, DateTime expires, string Domain) { HttpCookie cookie = new HttpCookie(key, value) { Expires = expires }; AddCookie(cookie, Domain); } public static void AddCookie(string cookieName, string key, string value, DateTime expires) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; cookie.Values.Add(key, value); AddCookie(cookie, null); } public static void AddCookie(string cookieName, string key, string value, string Domain) { HttpCookie cookie = new HttpCookie(cookieName); cookie.Values.Add(key, value); AddCookie(cookie, Domain); } public static void AddCookie(string cookieName, string key, string value, DateTime expires, string Domain) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; cookie.Values.Add(key, value); AddCookie(cookie, Domain); } public static void AddDomainCookie(string key, string value, string Domain) { AddCookie(new HttpCookie(key, value), Domain); } public static HttpCookie GetCookie(string cookieName) { HttpRequest request = HttpContext.Current.Request; if (request != null) { if (request.Cookies[cookieName] != null) { return request.Cookies[cookieName]; } if (request.Cookies[", " + cookieName] != null) { return request.Cookies[", " + cookieName]; } } return null; } public static string GetCookieValue(string cookieName) { return GetCookieValue(cookieName, null); } public static string GetCookieValue(string cookieName, string key) { HttpRequest request = HttpContext.Current.Request; if (request == null) { return ""; } if (request.Cookies[cookieName] != null) { if (!string.IsNullOrEmpty(key) && request.Cookies[cookieName].HasKeys) { return request.Cookies[cookieName].Values[key]; } return request.Cookies[cookieName].Value; } string str = ", " + cookieName; if (request.Cookies[str] == null) { return ""; } if (!string.IsNullOrEmpty(key) && request.Cookies[str].HasKeys) { return request.Cookies[str].Values[key]; } return request.Cookies[str].Value; } public static string GetCookieValue(HttpCookie cookie, string key) { if (cookie == null) { return ""; } if (!string.IsNullOrEmpty(key) && cookie.HasKeys) { return cookie.Values[key]; } return cookie.Value; } public static void RemoveCookie(string cookieName) { RemoveCookie(cookieName, null); } public static void RemoveCookie(string cookieName, string key) { HttpResponse response = HttpContext.Current.Response; if (response != null) { HttpCookie cookie = response.Cookies[cookieName]; if (cookie != null) { if (!string.IsNullOrEmpty(key) && cookie.HasKeys) { cookie.Values.Remove(key); } else { response.Cookies.Remove(cookieName); } } } } public static void SetCookie(string cookieName, DateTime expires) { SetCookie(cookieName, null, null, new DateTime?(expires), null); } public static void SetCookie(string key, string value) { SetCookie(key, null, value, null, null); } public static void SetCookie(string cookieName, DateTime expires, string Domain) { SetCookie(cookieName, null, null, new DateTime?(expires), Domain); } public static void SetCookie(string key, string value, DateTime expires) { SetCookie(key, null, value, new DateTime?(expires), null); } public static void SetCookie(string cookieName, string key, string value) { SetCookie(cookieName, key, value, null, null); } public static void SetCookie(string key, string value, bool withDomain, string Domain) { if (withDomain) { SetCookie(key, null, value, null, Domain); } else { SetCookie(key, null, value, null, null); } } public static void SetCookie(string key, string value, DateTime expires, string Domain) { SetCookie(key, null, value, new DateTime?(expires), Domain); } public static void SetCookie(string cookieName, string key, string value, string Domain) { SetCookie(cookieName, key, value, null, Domain); } public static void SetCookie(string cookieName, string key, string value, DateTime? expires, string Domain) { HttpResponse response = HttpContext.Current.Response; if (response != null) { HttpCookie cookie = response.Cookies[cookieName]; if (cookie != null) { cookie.Path = "/"; if (!string.IsNullOrEmpty(Domain)) { cookie.Domain = Domain; } if (!string.IsNullOrEmpty(key) && cookie.HasKeys) { cookie.Values.Set(key, value); } else if (!string.IsNullOrEmpty(value)) { cookie.Value = value; } if (expires.HasValue) { cookie.Expires = expires.Value; } response.SetCookie(cookie); } } } /// <summary> /// 设置域的cookie /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="Domain"></param> public static void SetDomainCookie(string key, string value, string Domain) { SetCookie(key, null, value, null, Domain); } }
8.DataTable转换成实体类
/// <summary> /// #region DataTable转换成实体类 /// </summary> /// <typeparam name="T"></typeparam> public class ModelUtil<T> where T : new() { /// <summary> /// 填充对象列表:用DataSet的第一个表填充实体类 /// </summary> /// <param name="ds">DataSet</param> /// <returns></returns> public static List<T> FillModel(DataSet ds) { if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0) { return null; } else { return FillModel(ds.Tables[0]); } } /// <summary> /// 填充对象列表:用DataSet的第index个表填充实体类 /// </summary> public static List<T> FillModel(DataSet ds, int index) { if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0) { return null; } else { return FillModel(ds.Tables[index]); } } /// <summary> /// 填充对象列表:用DataTable填充实体类 /// </summary> public static List<T> FillModel(DataTable dt) { if (dt == null || dt.Rows.Count == 0) { return null; } List<T> modelList = new List<T>(); foreach (DataRow dr in dt.Rows) { //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); for (int i = 0; i < dr.Table.Columns.Count; i++) { List<PropertyInfo> propertyInfos = model.GetType().GetProperties().ToList(); PropertyInfo item = propertyInfos.FirstOrDefault(p => string.Compare(p.Name, dr.Table.Columns[i].ColumnName, true) == 0); if (item != null && dr[i] != DBNull.Value) try { item.SetValue(model, dr[i], null); } catch { } } modelList.Add(model); } return modelList; } /// <summary> /// 填充对象:用DataRow填充实体类 /// </summary> public static T FillModel(DataRow dr) { if (dr == null) { return default(T); } //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); for (int i = 0; i < dr.Table.Columns.Count; i++) { List<PropertyInfo> propertyInfos = model.GetType().GetProperties().ToList(); PropertyInfo item = propertyInfos.FirstOrDefault(p => string.Compare(p.Name, dr.Table.Columns[i].ColumnName, true) == 0); if (item != null && dr[i] != DBNull.Value) try { item.SetValue(model, dr[i], null); } catch { } } return model; } /// <summary> /// 实体类转换成DataSet /// </summary> /// <param name="modelList">实体类列表</param> /// <returns></returns> public static DataSet FillDataSet(List<T> modelList) { if (modelList == null || modelList.Count == 0) { return null; } else { DataSet ds = new DataSet(); ds.Tables.Add(FillDataTable(modelList)); return ds; } } /// <summary> /// 实体类转换成DataTable /// </summary> /// <param name="modelList">实体类列表</param> /// <returns></returns> public static DataTable FillDataTable(List<T> modelList) { if (modelList == null || modelList.Count == 0) { return null; } DataTable dt = CreateData(modelList[0]); foreach (T model in modelList) { DataRow dataRow = dt.NewRow(); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null); } dt.Rows.Add(dataRow); } return dt; } /// <summary> /// 根据实体类得到表结构 /// </summary> /// <param name="model">实体类</param> /// <returns></returns> private static DataTable CreateData(T model) { DataTable dataTable = new DataTable(typeof(T).Name); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType)); } return dataTable; } /// <summary> /// 将DataTable以转为List与Dictionary嵌套集合保存 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<Dictionary<string, string>> ToListDictionary(DataTable dt) { List<Dictionary<string, string>> list = null; if (dt != null && dt.Rows.Count > 0) { list = new List<Dictionary<string, string>>(); Dictionary<string, string> dic = null; foreach (DataRow dr in dt.Rows) { dic = new Dictionary<string, string>(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName].ToString()); } list.Add(dic); } } return list; } /// <summary> /// 请求的request的内容转换为model /// cza /// 2016-5-30 19:06:21 /// </summary> /// <param name="context"></param> /// <returns></returns> public static T ConvertToModel(HttpContext context) { T t = new T(); PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { if (!pi.CanWrite) continue; object value = context.Request[pi.Name]; if (value != null && value != DBNull.Value) { try { if (value.ToString() != "") pi.SetValue(t, Convert.ChangeType(value, pi.PropertyType), null);//这一步很重要,用于类型转换 else pi.SetValue(t, value, null); } catch { } } } return t; } }
9.SQL Server数据库访问类
/// <summary> /// SQL Server数据库访问类 /// </summary> public abstract class SqlHelper { //读取配置文件里的数据库连接字符串 public static readonly string connStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; //空构造 public SqlHelper() { } //Hashtable to store cached parameters private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// 执行增删改【常用】 /// </summary> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, commandType, commandText, paras); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); //清空参数 return val; } } /// <summary> /// 执行增删改(对现有的数据库连接)【不常用】 /// </summary> public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, commandType, commandText, paras); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// 执行多条sql语句(List泛型集合)【事务】(无参数) /// </summary> /// <param name="connectionString">数据库连接字符串</param> /// <param name="listSql">包含多条sql语句的泛型集合</param> /// <returns>受影响行数</returns> public static int ExecuteNonQuery(string connectionString, List<string> listSql) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlTransaction trans = conn.BeginTransaction(); PrepareCommand(cmd, conn, trans, CommandType.Text, null, null); try { int count = 0; for (int n = 0; n < listSql.Count; n++) { string strSql = listSql[n]; if (strSql.Trim().Length > 1) { cmd.CommandText = strSql; count += cmd.ExecuteNonQuery(); } } trans.Commit(); cmd.Parameters.Clear(); return count; } catch { trans.Rollback(); cmd.Parameters.Clear(); return 0; } finally { conn.Close(); } } /// <summary> /// 执行多条sql语句(Hashtable)【事务】(带一组参数,一个参数也得封装成组) /// </summary> /// <param name="connectionString">数据库连接字符串</param> /// <param name="sqlStringList">Hashtable表,键值对形式</param> public static void ExecuteNonQuery(string connectionString, Hashtable sqlStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { foreach (DictionaryEntry item in sqlStringList) { string cmdText = item.Key.ToString(); //要执行的sql语句 SqlParameter[] cmdParas = (SqlParameter[])item.Value; //sql语句对应的参数 PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, cmdParas); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } if (sqlStringList.Count > 0) trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 返回DataReader对象 /// </summary> public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string cmdText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); try { PrepareCommand(cmd, conn, null, commandType, cmdText, paras); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return reader; } catch { conn.Close(); throw; } } /// <summary> /// 返回第一行第一列信息(可能是字符串 所以返回类型是object)【常用】 /// </summary> public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection connection = new SqlConnection(connectionString)) { PrepareCommand(cmd, connection, null, commandType, commandText, paras); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /// <summary> /// 返回第一行第一列信息(针对现有的数据库连接)【不常用】 /// </summary> public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, commandType, commandText, paras); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } /// <summary> /// 返回DataTable /// </summary> public static DataTable GetDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, commandType, commandText, paras); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); da.Fill(dt); return dt; } } } /// <summary> /// 返回DataSet /// </summary> public static DataSet GetDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, commandType, commandText, paras); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); da.Fill(ds); return ds; } } } /// <summary> /// add parameter array to the cache /// </summary> /// <param name="cacheKey">Key to the parameter cache</param> /// <param name="cmdParms">an array of SqlParamters to be cached</param> public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Retrieve cached parameters /// </summary> /// <param name="cacheKey">key used to lookup parameters</param> /// <returns>Cached SqlParamters array</returns> public static SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// 准备一个待执行的SqlCommand /// </summary> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, params SqlParameter[] paras) { try { if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); } cmd.Connection = conn; if (commandText != null) cmd.CommandText = commandText; cmd.CommandType = commandType; //这里设置执行的是T-Sql语句还是存储过程 if (trans != null) cmd.Transaction = trans; if (paras != null && paras.Length > 0) { //cmd.Parameters.AddRange(paras); for (int i = 0; i < paras.Length; i++) { if (paras[i].Value == null || paras[i].Value.ToString() == "") paras[i].Value = DBNull.Value; //插入或修改时,如果有参数是空字符串,那么以NULL的形式插入数据库 cmd.Parameters.Add(paras[i]); } } } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 通用分页存储过程,有条件查询,有排序字段,按照排序字段的降序排列 /// </summary> /// <param name="PageSize">每页记录数</param> /// <param name="CurrentCount">当前记录数量(页码*每页记录数)</param> /// <param name="TableName">表名称</param> /// <param name="Where">查询条件,例:"ID>1000 AND Name like '%LiLinFeng%'" 排序条件,直接在后面加,例:" ORDER BY ID DESC,NAME ASC"</param> /// <param name="TotalCount">记录总数</param> /// <returns></returns> public static DataSet GetList(string connectionString, string Order, int PageSize, int CurrentCount, string TableName, string Where, out int TotalCount) { SqlParameter[] parmList = { new SqlParameter("@PageSize",PageSize), new SqlParameter("@CurrentCount",CurrentCount), new SqlParameter("@TableName",TableName), new SqlParameter("@Where",Where), new SqlParameter("@Order",Order), new SqlParameter("@TotalCount",SqlDbType.Int,4) }; parmList[5].Direction = ParameterDirection.Output; DataSet ds = GetDataset(connectionString, CommandType.StoredProcedure, "sp_MvcPager", parmList); TotalCount = Convert.ToInt32(parmList[5].Value); return ds; } }
10.日志文件记录
public class WriteLog { /// <summary> /// /// </summary> /// <param name="fileName">文件名</param> /// <param name="ex"></param> public static void WriteErorrLog(string fileName, Exception ex) { if (ex == null) return; //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日志存放路径 string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine(ex.Message); write.WriteLine("异常信息:" + ex); write.WriteLine("异常堆栈:" + ex.StackTrace); write.WriteLine("异常简述:" + ex.Message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } } catch { } } /// <summary> /// /// </summary> /// <param name="fileName">文件名</param> /// <param name="message"></param> public static void WriteMessage(string fileName, string message) { //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日志存放路径 string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine("信息:" + message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } } catch { } } public static void WriteErorrLog(Exception ex, string message) { if (ex == null) return; //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径 string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine(ex.Message); write.WriteLine("异常信息:" + ex); write.WriteLine("异常堆栈:" + ex.StackTrace); write.WriteLine("异常简述:" + message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } } catch { } } public static void WriteMessage(string message) { //ex = null 返回 DateTime dt = DateTime.Now; // 设置日志时间 string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 string logName = dt.ToString("yyyy-MM-dd"); //日志名称 string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径 string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称 try { FileInfo info = new FileInfo(log); if (info.Directory != null && !info.Directory.Exists) { info.Directory.Create(); } using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8"))) { write.WriteLine(time); write.WriteLine("信息:" + message); write.WriteLine("\r\n----------------------------------\r\n"); write.Flush(); write.Close(); write.Dispose(); } } catch { } } }
11.JSON帮助类
/// <summary> /// JSON帮助类 /// </summary> public class JsonHelper { #region 通用方法 /// <summary> /// 格式化字符型、日期型、布尔型 /// </summary> public static string StringFormat(string str, Type type) { if (type == typeof(string)) { str = StringFilter(str); str = "\"" + str + "\""; } else if (type == typeof(DateTime) || type == typeof(DateTime?)) { str = "\"" + str + "\""; } else if (type == typeof(bool)) { str = str.ToLower(); } else if (type == typeof(Guid)) { str = "\"" + str + "\""; } else if (type != typeof(string) && string.IsNullOrEmpty(str)) { str = "\"" + str + "\""; } return str; } /// <summary> /// 过滤字符串 /// </summary> public static string StringFilter(string str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { char c = str.ToCharArray()[i]; switch (c) { case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: sb.Append(c); break; } } return sb.ToString(); } #endregion #region 列转json /// <summary> /// 列转json /// </summary> /// <param name="dt">表</param> /// <param name="r">列</param> public static string ColumnToJson(DataTable dt, int r) { StringBuilder strSql = new StringBuilder(); for (int i = 0; i < dt.Rows.Count; i++) { strSql.Append(dt.Rows[i][r]); strSql.Append(","); } return strSql.ToString().Trim(','); } #endregion #region 对象转json /// <summary> /// 对象转json /// </summary> public static string ToJson(object jsonObject) { StringBuilder sb = new StringBuilder(); sb.Append("{"); PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties(); for (int i = 0; i < propertyInfo.Length; i++) { object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null); Type type = propertyInfo[i].PropertyType; string strValue = objectValue.ToString(); strValue = StringFormat(strValue, type); sb.Append("\"" + propertyInfo[i].Name + "\":"); sb.Append(strValue + ","); } sb.Remove(sb.Length - 1, 1); sb.Append("}"); return sb.ToString(); } #endregion #region list转json /// <summary> /// list转json /// </summary> public static string ListToJson<T>(IList<T> list) { object obj = list[0]; return ListToJson<T>(list, obj.GetType().Name); } private static string ListToJson<T>(IList<T> list, string JsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(JsonName)) JsonName = list[0].GetType().Name; Json.Append("{\"" + JsonName + "\":["); if (list.Count > 0) { for (int i = 0; i < list.Count; i++) { T obj = Activator.CreateInstance<T>(); PropertyInfo[] pi = obj.GetType().GetProperties(); Json.Append("{"); for (int j = 0; j < pi.Length; j++) { Type type = pi[j].GetValue(list[i], null).GetType(); Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type)); if (j < pi.Length - 1) { Json.Append(","); } } Json.Append("}"); if (i < list.Count - 1) { Json.Append(","); } } } Json.Append("]}"); return Json.ToString(); } #endregion #region 对象集合转换为json /// <summary> /// 对象集合转换为json /// </summary> /// <param name="array">对象集合</param> /// <returns>json字符串</returns> public static string ToJson(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString += ToJson(item) + ","; } jsonString = jsonString.Substring(0, jsonString.Length - 1); return jsonString + "]"; } #endregion #region 普通集合转换Json /// <summary> /// 普通集合转换Json /// </summary> /// <param name="array">集合对象</param> /// <returns>Json字符串</returns> public static string ToArrayString(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString = ToJson(item.ToString()) + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "]"; } #endregion #region DataSet转换为Json /// <summary> /// DataSet转换为Json /// </summary> /// <param name="dataSet">DataSet对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataSet dataSet) { string jsonString = "{"; foreach (DataTable table in dataSet.Tables) { jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ","; } jsonString = jsonString.TrimEnd(','); return jsonString + "}"; } #endregion #region Datatable转换为Json /// <summary> /// Datatable转换为Json /// </summary> public static string ToJson(DataTable dt) { if (dt.Rows.Count > 0) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { jsonString.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType; jsonString.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (j < dt.Columns.Count - 1) jsonString.Append(strValue + ","); else jsonString.Append(strValue); } jsonString.Append("},"); } jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } else return "[]"; } /// <summary> /// DataTable转换为Json /// </summary> public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName; Json.Append("{\"" + jsonName + "\":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { Type type = dt.Rows[i][j].GetType(); Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type)); if (j < dt.Columns.Count - 1) Json.Append(","); } Json.Append("}"); if (i < dt.Rows.Count - 1) Json.Append(","); } } Json.Append("]}"); return Json.ToString(); } #endregion #region DataReader转换为Json /// <summary> /// DataReader转换为Json /// </summary> /// <param name="dataReader">DataReader对象</param> /// <returns>Json字符串</returns> public static string ToJson(DbDataReader dataReader) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); while (dataReader.Read()) { jsonString.Append("{"); for (int i = 0; i < dataReader.FieldCount; i++) { Type type = dataReader.GetFieldType(i); string strKey = dataReader.GetName(i); string strValue = dataReader[i].ToString(); jsonString.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (i < dataReader.FieldCount - 1) jsonString.Append(strValue + ","); else jsonString.Append(strValue); } jsonString.Append("},"); } dataReader.Close(); jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } #endregion #region 返回错误 public static string error() { DataTable dt = new DataTable(); dt.Columns.Add("error", typeof(int)); DataRow dr = dt.NewRow(); dr["error"] = 1; dt.Rows.Add(dr); return ToJson(dt); } #endregion } 11.转换帮助类 public class ConvertHelper { public static int DateTimeToUnixInt(DateTime time) { DateTime time2 = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1)); TimeSpan span = (TimeSpan)(time - time2); return (int)span.TotalSeconds; } public static decimal MoneyRound(decimal value, int decimals) { if (value < 0M) { return Math.Round((decimal)(value + (5M / ((decimal)Math.Pow(10.0, (double)(decimals + 1))))), decimals, MidpointRounding.AwayFromZero); } return Math.Round(value, decimals, MidpointRounding.AwayFromZero); } public static double MoneyRound(double value, int decimals) { if (value < 0.0) { return Math.Round((double)(value + (5.0 / Math.Pow(10.0, (double)(decimals + 1)))), decimals, MidpointRounding.AwayFromZero); } return Math.Round(value, decimals, MidpointRounding.AwayFromZero); } public static decimal MoneyToDecimal(string str) { try { str = str.Replace(",", ""); return decimal.Parse(str); } catch { return 0M; } } public static decimal Round(decimal d, int i) { if (d >= 0M) { d += 5M * ((decimal)Math.Pow(10.0, (double)-(i + 1))); } else { d += -5M * ((decimal)Math.Pow(10.0, (double)-(i + 1))); } string str = d.ToString(); string[] strArray = str.Split(new char[] { '.' }); int index = str.IndexOf('.'); string str2 = strArray[0]; string str3 = strArray[1]; if (str3.Length > i) { str3 = str.Substring(index + 1, i); } d = decimal.Parse(str2 + "." + str3); return d; } public static double Round(double d, int i) { if (d >= 0.0) { d += 5.0 * Math.Pow(10.0, (double)-(i + 1)); } else { d += -5.0 * Math.Pow(10.0, (double)-(i + 1)); } string str = d.ToString(); string[] strArray = str.Split(new char[] { '.' }); int index = str.IndexOf('.'); string str2 = strArray[0]; string str3 = strArray[1]; if (str3.Length > i) { str3 = str.Substring(index + 1, i); } d = double.Parse(str2 + "." + str3); return d; } public static bool ToBool(object o) { return ToBool(o, false); } public static bool ToBool(object o, bool DefaultValue) { bool flag; if (bool.TryParse(ToString(o, true), out flag)) { return flag; } return DefaultValue; } public static DateTime ToDateTime(object o) { return ToDateTime(o, DateTime.Now); } public static DateTime ToDateTime(object o, DateTime DefaultValue) { DateTime time; if (DateTime.TryParse(ToString(o, true), out time)) { return time; } return DefaultValue; } public static decimal ToDecimal(object o) { return ToDecimal(o, 0M); } public static decimal ToDecimal(object o, decimal DefaultValue) { decimal num; if (decimal.TryParse(ToString(o, true), out num)) { return num; } return DefaultValue; } public static double ToDouble(object o) { return ToDouble(o, 0.0); } public static double ToDouble(object o, double DefaultValue) { double num; if (double.TryParse(ToString(o, true), out num)) { return num; } return DefaultValue; } public static float ToFloat(object o) { return ToFloat(o, 0f); } public static float ToFloat(object o, float DefaultValue) { float num; if (float.TryParse(ToString(o, true), out num)) { return num; } return DefaultValue; } public static int ToInt(object o) { return ToInt(o, 0); } public static int ToInt(object o, int DefaultValue) { int num; if (int.TryParse(ToString(o, true), out num)) { return num; } return DefaultValue; } public static long ToLong(object o) { return ToLong(o, 0L); } public static long ToLong(object o, long DefaultValue) { long num; if (long.TryParse(ToString(o, true), out num)) { return num; } return DefaultValue; } public static string ToMoney(object o) { return ToDecimal(o).ToString("###,###,###,###,###,##0.##"); } public static string ToMoney(string str) { try { return decimal.Parse(str).ToString("###,###,###,###,###,##0.##"); } catch { return "0"; } } public static string ToString(object o) { return ToString(o, "", false); } public static string ToString(object o, bool bTrim) { return ToString(o, "", bTrim); } public static string ToString(object o, string DefaultValue) { return ToString(o, DefaultValue, false); } public static string ToString(object o, string DefaultValue, bool bTrim) { if (object.Equals(o, null) || Convert.IsDBNull(o)) { return DefaultValue; } if (bTrim) { return o.ToString().Trim(); } return o.ToString(); } public static DateTime UnixIntToDateTime(string timeStamp) { DateTime time = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1)); long ticks = long.Parse(timeStamp + "0000000"); TimeSpan span = new TimeSpan(ticks); return time.Add(span); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。