常用操作方法类
2015-08-10止总结的常用方法类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Security.Cryptography; using System.Collections; using System.Reflection; using System.Web; using System.Web.UI.WebControls; using System.IO; using System.Drawing.Imaging; using System.Drawing; using System.Drawing.Drawing2D; namespace CommonHelpr { /// <summary> /// 业务逻辑层基类 /// </summary> public class CommonMethod { /// <summary> /// 根据列名字符串数组,创建自定义DataTable /// </summary> /// <param name="sList">列名字符串数组</param> /// <returns>DataTable</returns> public static DataTable CreateSelfDataTable(String[] sList) { DataTable _dtSelf = new DataTable(); foreach (String s in sList) { _dtSelf.Columns.Add(s); } _dtSelf.AcceptChanges(); return _dtSelf; } /// <summary> /// 加密一个字符串 /// </summary> /// <param name="vStringToEncrypt">待要去加密的字符串</param> /// <returns>返回一个加密后的字符串</returns> public static String Encrypt(String vStrToEncrypt) { byte[] key = { }; byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 }; byte[] inputByteArray; String vEncryptKey = "!@#$1234"; try { key = System.Text.Encoding.UTF8.GetBytes(vEncryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = System.Text.Encoding.UTF8.GetBytes(vStrToEncrypt); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (System.Exception ex) { throw ex; } } /// <summary> /// 对一进行加密的字符串进行解密 /// </summary> /// <param name="vStringToDecrypt">待要去解密的字符串</param> /// <returns>返回一个明文</returns> public static String Decrypt(String vStrToDecrypt) { vStrToDecrypt = vStrToDecrypt.Trim().Replace(" ", "+"); //process blank char for the encrypt method. byte[] key = { }; byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 }; byte[] inputByteArray = new byte[vStrToDecrypt.Length]; String vDecryptKey = "!@#$1234"; try { key = System.Text.Encoding.UTF8.GetBytes(vDecryptKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(vStrToDecrypt); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (System.Exception ex) { throw ex; } } /// <summary> /// WebForm弹出信息框 /// </summary> /// <param name="strMsg"></param> public static void JsAlert(string strMsg) { HttpResponse response = HttpContext.Current.Response; string s = string.Format("<script type=\"text/javascript\">alert('{0}');</script>", strMsg); response.Write(s); } /// <summary> /// 弹出并关闭信息对话框 /// </summary> /// <param name="strMsg"></param> public static void JsAlertAndCloseWindow(string strMsg) { JsAlert(strMsg); JsCloseWindow(); } public static void JsCloseWindow() { HttpResponse response = HttpContext.Current.Response; response.Write("<script type=\"text/javascript\">window.close();</script>"); response.End(); } /// <summary> /// 弹出信息并回到上一个页面 /// </summary> /// <param name="strMsg"></param> public static void JsAlertAndGoback(string strMsg) { JsAlert(strMsg); JsGoBack(); } public static void JsGoBack() { HttpResponse response = HttpContext.Current.Response; string s = string.Format("<script type=\"text/javascript\">history.go(-1);</script>", new object[0]); response.Write(s); response.End(); } /// <summary> /// 弹出信息并转移到指定页面 /// </summary> /// <param name="strMsg"></param> /// <param name="url"></param> public static void JsAlertAndGoUrl(string strMsg, string url) { JsAlert(strMsg); JsGoUrl(url); } public static void JsGoUrl(string url) { HttpResponse response = HttpContext.Current.Response; response.Write(string.Format("<script type=\"text/javascript\">window.location.href='{0}';</script>", url)); response.End(); } /// <summary> /// 加载所有的单位并新增一条记录"全部单位"到ComboBox控件 /// </summary> /// <param name="cbbCompany"></param> public static void LoadComboxPassword(System.Web.UI.WebControls.DropDownList ddlPassword) { ddlPassword.DataSource = null; ddlPassword.DataTextField = "PRODUCT_ID"; ddlPassword.DataValueField = "PASSWORD"; BLL.Password objPassword = new BLL.Password(); DataTable _dt = objPassword.GetPasswordInfo().Tables[0]; DataRow _drNew = _dt.NewRow(); _drNew["PASSWORD"] = 0; _drNew["PRODUCT_ID"] = "请选择"; _dt.Rows.Add(_drNew); _dt.AcceptChanges(); ddlPassword.DataSource = _dt; ddlPassword.DataBind(); } /// <summary> /// 绑定数据源ComboBox控件重载方法 /// </summary> /// <param name="cbbCompany"></param> public void LoadValueCombox(System.Web.UI.WebControls.DropDownList ddlControl,DataTable dt,string messageName,int messageValue) { //if (dt != null) //{ // DataRow dr = dt.NewRow(); // dr[0] =messageValue; // dr[1] =messageName; // dt.Rows.Add(dr); // dt.AcceptChanges(); // ddlControl.DataTextField = dr[0]; //} //PropertyCenter.BLL.Organize org = new PropertyCenter.BLL.Organize(); //org.GetModelList(""); //ddlPassword.DataSource = null; //ddlPassword.DataTextField = "PRODUCT_ID"; //ddlPassword.DataValueField = "PASSWORD"; //BLL.Password objPassword = new BLL.Password(); //DataTable _dt = objPassword.GetPasswordInfo().Tables[0]; //DataRow _drNew = _dt.NewRow(); //_drNew["PASSWORD"] = 0; //_drNew["PRODUCT_ID"] = "请选择"; //_dt.Rows.Add(_drNew); //_dt.AcceptChanges(); //ddlPassword.DataSource = _dt; //ddlPassword.DataBind(); } /// <summary> /// 验证字符串是否为正整数 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumeric(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]*[1-9][0-9]*$"); return reg1.IsMatch(str); } /// <summary> /// 验证字符串是否为0或正浮点类型 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isDouble(String str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))|(00)|(0)|((0)+\.[0])|((0)+\.[00])$"); return reg1.IsMatch(str); } /// <summary> /// 验证正则表达式 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isHEX(String str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^([0-9|a-z|A-Z]*)$"); return reg1.IsMatch(str); } /// <summary> /// 验证手机号码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isMobile(String str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[1][3-8]\d{9}$"); return reg1.IsMatch(str); } /// <summary> /// 验证数字 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isNumber(String str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^\d+$"); return reg1.IsMatch(str); } /// <summary> /// 验证邮政编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isPost(String str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^\d{6}$"); return reg1.IsMatch(str); } /// <summary> /// 验证邮件地址 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isEmail(String str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"); return reg1.IsMatch(str); } //验证身份证 /* function isIdCardNo(num) { var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"); var varArray = new Array(); var intValue; var lngProduct = 0; var intCheckDigit; var intStrLen = num.length; var idNumber = num; // initialize if ((intStrLen != 15) && (intStrLen != 18)) { return false; } // check and set value for (i = 0; i < intStrLen; i++) { varArray[i] = idNumber.charAt(i); if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) { return false; } else if (i < 17) { varArray[i] = varArray[i] * factorArr[i]; } } return true; } */ //验证是否是中文 public static bool isChinese(string str) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[\u4e00-\u9fa5]"); return reg.IsMatch(str); } //验证固定电话号码 public static bool isFixPhone(string str) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$"); return reg.IsMatch(str); } //判断是否字符串是否为日期类型 public static bool isDataTime(string strDate) { DateTime dtDate; if (DateTime.TryParse(strDate, out dtDate)) { return true; } else { return false; } } //16进制数组转16进制字符串 public static string GetByteToStr(byte[] receiveData) { return ByteToHex(receiveData); } /// <summary> /// 转换字节数组到十六进制字符串 /// </summary> /// <param name="comByte">待转换字节数组</param> /// <returns>十六进制字符串</returns> public static string ByteToHex(byte[] comByte) { if (comByte != null) { StringBuilder builder = new StringBuilder(comByte.Length * 3); foreach (byte data in comByte) { builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' ')); } return builder.ToString().ToUpper(); } else { return ""; } } /// <summary> /// 字符串到字节数组 /// </summary> /// <param name="msg">待转换字符串</param> /// <returns>字节数组</returns> public static byte[] HexToByte(string msg) { msg = msg.Replace(" ", "");//移除空格 //create a byte array the length of the //divided by 2 (Hex is 2 characters in length) byte[] comBuffer = new byte[msg.Length / 2]; for (int i = 0; i < msg.Length; i += 2) { //convert each set of 2 characters to a byte and add to the array comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16); } return comBuffer; } /// <summary> /// 下面通过一个方法来实现返回DataTable类型 /// LINQ返回DataTable类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="varlist"></param> /// <returns></returns> public static DataTable ToDataTable<T>(IEnumerable<T> varlist) { DataTable dtReturn = new DataTable(); // column names PropertyInfo[] oProps = null; if (varlist == null) return dtReturn; foreach (T rec in varlist) { if (oProps == null) { oProps = ((Type)rec.GetType()).GetProperties(); foreach (PropertyInfo pi in oProps) { Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); } } DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps) { dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue (rec, null); } dtReturn.Rows.Add(dr); } return dtReturn; } //用Linq语法过滤重复标签EPC public static DataTable ConvertToTable(DataTable dt) { var query2 = (from contact2 in dt.AsEnumerable() // orderby contact2.Field<string>("ID") descending group contact2 by contact2.Field<string>("EPC") into g select new { // ID = g.FirstOrDefault().Field<string>("ID"), // PC = g.FirstOrDefault().Field<string>("PC"), EPC = g.FirstOrDefault().Field<string>("EPC"), TIME = g.FirstOrDefault().Field<string>("TIME"), // CRC = g.FirstOrDefault().Field<string>("CRC"), //RSSI = g.FirstOrDefault().Field<string>("RSSI"), FREQANT = g.FirstOrDefault().Field<string>("FREQANT"), INVCOUNT = g.FirstOrDefault().Field<string>("INVCOUNT") } ).ToList(); return ToDataTable(query2); } /// <summary> /// 判断文件夹是否存在,不存在创建 /// 同时返回文件夹路径 /// </summary> /// <param name="sFolderPath">文件夹绝对路径</param> /// <returns></returns> public static String IsFolderExist(String sFolderPath) { if (System.IO.Directory.Exists(sFolderPath) == false) { System.IO.Directory.CreateDirectory(sFolderPath); } return sFolderPath; } #region GetPicThumbnail /// <summary> /// 无损压缩图片 /// </summary> /// <param name="sFile">原图片</param> /// <param name="dFile">压缩后保存位置</param> /// <param name="dHeight">高度</param> /// <param name="dWidth"></param> /// <param name="flag">压缩质量 1-100</param> /// <returns></returns> public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag) { if (File.Exists(sFile)) { System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; int sW = 0, sH = 0; //按比例缩放 Size tem_size = new Size(iSource.Width, iSource.Height); if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号 { if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth)) { sW = dWidth; sH = (dWidth * tem_size.Height) / tem_size.Width; } else { sH = dHeight; sW = (tem_size.Width * dHeight) / tem_size.Height; } } else { sW = tem_size.Width; sH = tem_size.Height; } Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { ob.Save(dFile, tFormat); } return true; } catch { return false; } finally { iSource.Dispose(); ob.Dispose(); } } else { return false; } } #endregion /// <summary> /// 一个生成GUID的函数: /// </summary> /// <returns></returns> public static string getGUID() { System.Guid guid = new Guid(); guid = Guid.NewGuid(); string str = guid.ToString(); return str; } /// <summary> /// 判断文件夹是否存在,不存在就创建 /// </summary> /// <param name="sFileFolder">文件夹路径</param> /// <returns>文件夹路径</returns> public static string GetFileFolder(String sFileFolder) { if (!System.IO.Directory.Exists(sFileFolder)) { System.IO.Directory.CreateDirectory(sFileFolder); } return sFileFolder; } /// <summary> /// 生成一个错误日志 /// </summary> /// <param name="sErrMsg">错误信息</param> public static void LogErrorLog(string sErrMsg) { string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + "log"; if (!System.IO.Directory.Exists(logFilePath)) { System.IO.Directory.CreateDirectory(logFilePath); } string fileName = logFilePath + "\\" + DateTime.Now.ToString("yyyyMM") + "_log.txt"; FileStream fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); StreamWriter streamWrite = new StreamWriter(fileStream); try { streamWrite.WriteLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss : ") + sErrMsg); } catch(Exception exception) { throw new Exception(exception.ToString()); } finally { streamWrite.Flush(); streamWrite.Close(); } } } /// <summary> /// Gridview绑定的数据记录为空时显示Gridview的表头,并显示没有记录的提示 /// </summary> public class GridviewControl { //当Gridview数据为空时显示的信息 private static string EmptyText = "没有记录"; public GridviewControl() { } /// <summary> /// 防止PostBack后Gridview不能显示 /// </summary> /// <param name="gridview"></param> public static void ResetGridView(GridView gridview) { //如果数据为空则重新构造Gridview if (gridview.Rows.Count == 1 && gridview.Rows[0].Cells[0].Text == EmptyText) { int columnCount = gridview.Columns.Count; gridview.Rows[0].Cells.Clear(); gridview.Rows[0].Cells.Add(new TableCell()); gridview.Rows[0].Cells[0].ColumnSpan = columnCount; gridview.Rows[0].Cells[0].Text = EmptyText; gridview.Rows[0].Cells[0].Style.Add("text-align", "center"); } } /// <summary> /// 绑定数据到GridView,当表格数据为空时显示表头 /// </summary> /// <param name="gridview"></param> /// <param name="table"></param> public static void GridViewDataBind(GridView gridview, DataTable table) { //记录为空重新构造Gridview if (table.Rows.Count == 0) { table = table.Clone(); table.Rows.Add(table.NewRow()); gridview.DataSource = table; gridview.DataBind(); int columnCount = table.Columns.Count; gridview.Rows[0].Cells.Clear(); gridview.Rows[0].Cells.Add(new TableCell()); gridview.Rows[0].Cells[0].ColumnSpan = columnCount; gridview.Rows[0].Cells[0].Text = EmptyText; gridview.Rows[0].Cells[0].Style.Add("text-align", "center"); } else { //数据不为空直接绑定 gridview.DataSource = table; gridview.DataBind(); } //重新绑定取消选择 gridview.SelectedIndex = -1; } ///随机生成不重复的10位数字,且在数据库里判断 protected string GetAreaId() { string result = string.Empty; int areaId = GetTenNumber(); return IsExists(areaId).ToString(); } protected int IsExists(int areaId) { PropertyCenter.BLL.Area areaBLL = new PropertyCenter.BLL.Area(); DataSet ds = areaBLL.GetList(string.Format(" AreaID={0} AND IsDelete=0 ", areaId)); if (ds != null && ds.Tables[0].Rows.Count > 0) { areaId=GetTenNumber(); return IsExists(areaId); } else { return areaId; } } //随机获取十位数字 public int GetTenNumber() { Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); int[] arrNum = new int[100]; int tmp = 0; int minValue = 1000000000; int maxValue = 2147483646; BLL.Password _objPassword = new BLL.Password(); tmp = rand.Next(minValue, maxValue); //随机取数 return GetNumber(arrNum, tmp, minValue, maxValue, rand); //取出值赋到数组中 } //活动随机数 public int GetNumber(int[] arrNum, int tmp, int minValue, int maxValue, Random rand) { int n = 0; while (n <= arrNum.Length - 1) { if (arrNum[n] == tmp) //利用循环判断是否有重复 { tmp = rand.Next(minValue, maxValue); //重新随机获取 GetNumber(arrNum, tmp, minValue, maxValue, rand); //递归:如果取出的数字和已取得的数字有重复就重新读取 } n++; } return tmp; } /// <summary> /// 补齐6为字符串的数字 /// </summary> /// <param name="number"></param> /// <returns></returns> public string GetSixNumber(int number) { string _strNumber = ""; if(number <10) { _strNumber = "00000" + number.ToString(); } else if (number >= 10 && number < 100) { _strNumber = "0000" + number.ToString(); }else if(number >=100 && number <1000) { _strNumber = "000" + number.ToString(); }else if(number >= 1000 && number <10000) { _strNumber = "00" + number.ToString(); } else if (number >= 10000 && number < 100000) { _strNumber = "0" + number.ToString(); } else if(number >= 100000) { _strNumber = number.ToString(); } return _strNumber; } } }
所有问题都会有一定程度的抽象和假设