using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; using XS_DAL; namespace XS_BLL { public static class UtilityBLL { /// /// Md5 加密 /// /// /// public static string GenerateMD5(string txt) { using (MD5 mi = MD5.Create()) { byte[] buffer = Encoding.UTF8.GetBytes(txt); //开始加密 byte[] newBuffer = mi.ComputeHash(buffer); StringBuilder sb = new StringBuilder(); for (int i = 0; i < newBuffer.Length; i++) { sb.Append(newBuffer[i].ToString("X2")); } return sb.ToString(); } } /// /// 生成获取UUID /// /// /// public static string GetUuid(bool bl = false) { string uuid = string.Empty; if (bl) { //带'-' uuid = System.Guid.NewGuid().ToString(); } else { //不带'-' uuid = System.Guid.NewGuid().ToString("N"); } return uuid; } /// /// 获取json中指定Key的value值 不能取集合中数据 /// /// json串 /// json节点 /// public static string GetReceiveValues(string recieveBuffer, string key) { try { key = key.Replace(" ", ""); string[] keys = key.Split(','); string resMag = recieveBuffer; if (!string.IsNullOrEmpty(recieveBuffer)) { for (int i = 0; i < keys.Count(); i++) { JObject obj = Newtonsoft.Json.Linq.JObject.Parse(resMag); resMag = obj[keys[i]].ToString(); } } return resMag; } catch (Exception ex) { LogHelper.ErrorLog(ex); return ""; } } /// /// 接收就送数据返回泛型集合{"header":{},"body":{"reqCode":"qw","data":[{}]}} /// /// 泛型实体类 /// json数据 /// public static List GetReceiveValuesList(string recieveBuffer, string key) { try { JavaScriptSerializer Jss = new JavaScriptSerializer(); Dictionary DicText = (Dictionary)Jss.DeserializeObject(recieveBuffer); string resMag = GetReceiveValues(recieveBuffer, key); List busList = Jss.Deserialize>(resMag); return busList; } catch (Exception ex) { LogHelper.ErrorLog(ex); return null; } } ///// ///// 转JSON ///// ///// 返回实体类 ///// 当前页 ///// 每页行数 ///// 总页数 ///// //public static string retHttpJson(t_result rModel, int i = 0) //{ // try // { // string paramString = string.Empty; // JObject joB = new JObject(); // string sign = Global.appSecret; // string message = string.IsNullOrEmpty(rModel.message) ? "" : rModel.message; // var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; // if (rModel.i_type == 0) // { // string js = string.Empty; // if (rModel.dtCount > 0) // { // paramString = JsonConvert.SerializeObject(new // { // reqCode = rModel.reqCode, // code = rModel.code, // message = message, // data = new { list = rModel.data, totalPage = rModel.pageNum, pageSize = rModel.totalPage, count = rModel.dtCount } // }, Formatting.Indented, jsonSetting); // } // else // { // if (i == 1) // { // paramString = JsonConvert.SerializeObject(new // { // reqCode = rModel.reqCode, // code = rModel.code, // message = message, // data = rModel.materielList // }, Formatting.Indented, jsonSetting); // } // else // { // paramString = JsonConvert.SerializeObject(new // { // reqCode = rModel.reqCode, // code = rModel.code, // message = message, // data = rModel.data // }, Formatting.Indented, jsonSetting); // } // } // } // else // { // string uuid = getUuid(); // paramString = JsonConvert.SerializeObject(new // { // reqCode = string.IsNullOrEmpty(rModel.reqCode) ? uuid : rModel.reqCode, // data = rModel.data // }, Formatting.Indented, jsonSetting); // } // //var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include }; // //var json = JsonConvert.SerializeObject(paramString, Formatting.Indented, jsonSetting); // return paramString; // //return json; // } // catch (Exception ex) // { // return ex.Message; // } //} //public static string retHttpJson(t_result rModel) //{ // JObject joH = new JObject(); // JObject joB = new JObject(); // JObject jo = new JObject(); // string sign = Global.appSecret; // string message = string.IsNullOrEmpty(rModel.message) ? "" : rModel.message; // joH.Add("appKey", Global.appKey); // joH.Add("requestPlan", Global.requestPlan); // joH.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); // joH.Add("version", Global.version); // joH.Add("httpVersion", Global.httpVersion); // if (rModel.i_type == 0) // { // joH.Add("sign", GenerateMD5(sign + rModel.reqCode)); // joB.Add("reqCode", rModel.reqCode); // joB.Add("code", rModel.code); // if (message.Length > 255) // { // message = message.Substring(0, 250) + "..."; // } // joB.Add("message", message); // if (rModel.data != null) // { // joB.Add("data", rModel.data); // } // } // else // { // string uuid = getUuid(); // joH.Add("sign", GenerateMD5(sign + uuid)); // joB.Add("reqCode", uuid); // if (rModel.data != null) // { // joB.Add("data", rModel.data); // } // if (rModel.file != null) // { // string myStr = System.Text.Encoding.UTF8.GetString(rModel.file); // byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(myStr); // string myStr001 = System.Text.Encoding.UTF8.GetString(rModel.file); // joB.Add("file", rModel.file); // } // } // jo.Add("header", joH); // jo.Add("body", joB); // string paramString = jo.ToString(Newtonsoft.Json.Formatting.None, null); // string strFile = utilityBLL.getReceiveValues(paramString, "body,file"); // return paramString; //} /// /// List集合转换为DataTable /// 调用示例 : DataTable tb = ToDataTable(List集合); /// /// 类型 /// 集合 /// DataTable public static DataTable ListToDataTable(List list) { //创建一个名为"tableName"的空表 DataTable dt = new DataTable("tableName"); if (list.Count > 0) { //创建传入对象名称的列 foreach (var item in list.FirstOrDefault().GetType().GetProperties()) { dt.Columns.Add(item.Name); } //循环存储 foreach (var item in list) { //新加行 DataRow value = dt.NewRow(); //根据DataTable中的值,进行对应的赋值 foreach (DataColumn dtColumn in dt.Columns) { int i = dt.Columns.IndexOf(dtColumn); //基元元素,直接复制,对象类型等,进行序列化 if (value.GetType().IsPrimitive) { value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item); } else { string aa = ""; if (item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item) != null) { aa = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item).ToString(); value[i] = aa; } else { aa = ""; } //value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item)); } } dt.Rows.Add(value); } } return dt; /* var props = typeof(T).GetProperties(); var dt = new DataTable(); dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()); if (collection.Count() > 0) { for (int i = 0; i < collection.Count(); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in props) { object obj = pi.GetValue(collection.ElementAt(i), null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array, true); } } return dt; */ } /// /// JSON格式化 /// /// /// public static string JsonToString(string str) { try { //格式化json字符串 JsonSerializer serializer = new JsonSerializer(); TextReader tr = new StringReader(str); JsonTextReader jtr = new JsonTextReader(tr); object obj = serializer.Deserialize(jtr); if (obj != null) { StringWriter textWriter = new StringWriter(); JsonTextWriter jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.Indented, Indentation = 4, IndentChar = ' ' }; serializer.Serialize(jsonWriter, obj); return textWriter.ToString(); } else { return str; } } catch (Exception ex) { return str; } } public static bool PrevInstance() { string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; if (System.Diagnostics.Process.GetProcessesByName(procName).GetUpperBound(0) >= 1) { return true; } else { return false; } } /// /// SqlServer 数据库链接验证 /// /// 链接字符 /// public static bool IsDbConnected(string connString = "") { SqlConnection mySqlConnection; //获取数据库连接字符串 //创建连接对象 if (string.IsNullOrEmpty(connString)) { mySqlConnection = new SqlConnection(Global.connstring); } else { mySqlConnection = new SqlConnection(connString); } //ConnectionTimeout 在.net 1.x 可以设置 在.net 2.0后是只读属性,则需要在连接字符串设置 //如:server=.;uid=sa;pwd=;database=PMIS;Integrated Security=SSPI; Connection Timeout=30 //mySqlConnection.ConnectionTimeout = 10;//设置连接超时的时间 bool IsCanConnectioned = false; try { //Open DataBase //打开数据库 mySqlConnection.Open(); IsCanConnectioned = true; } catch { //Can not Open DataBase //打开不成功 则连接不成功 IsCanConnectioned = false; } finally { //Close DataBase //关闭数据库连接 mySqlConnection.Close(); } //mySqlConnection is a SqlConnection object if (mySqlConnection.State == ConnectionState.Closed || mySqlConnection.State == ConnectionState.Broken) { //Connection is not available return IsCanConnectioned; } else { //Connection is available return IsCanConnectioned; } } /// /// DataTable转成List /// /// /// /// public static List ToDataList(DataTable dt) { var list = new List(); var plist = new List(typeof(T).GetProperties()); foreach (DataRow item in dt.Rows) { T s = Activator.CreateInstance(); for (int i = 0; i < dt.Columns.Count; i++) { PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName); if (info != null) { try { if (!Convert.IsDBNull(item[i])) { object v = null; if (info.PropertyType.ToString().Contains("System.Nullable")) { v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType)); } else { v = Convert.ChangeType(item[i], info.PropertyType); } info.SetValue(s, v, null); } } catch (Exception ex) { throw new Exception("字段[" + info.Name + "]转换出错,value:" + item[i] + ex.ToString()); } } } list.Add(s); } return list; } /// /// 删除表数据 /// /// /// public static void DelInterface(string delName, string where) { try { string sql = " delete " + delName; if (!string.IsNullOrEmpty(where.Trim())) { sql += where; } DBOperator.delSql(sql); } catch (Exception ex) { throw; } } } }