using Newtonsoft.Json; using QRCoder; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; using XGL.Models; using XGL.Models.Model; namespace CommonFunc.Tools { /// /// 通用方法 /// public static class Utils { public static SqlServerDBHelper cloudDBHelper = new SqlServerDBHelper(SqlDataObject.GetCloudSqlConnectionString); public static SqlServerDBHelper clientDBHelper = new SqlServerDBHelper(SqlDataObject.GetMESClientSqlConnectionString); public static SqlServerDBHelper netClientDBHelper = new SqlServerDBHelper(SqlDataObject.GetMESNetClientSqlConnectionString); public static List userList { get; set; } public static string GetServerIP() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlDataObject.GetMESNetClientSqlConnectionString); string serverIp = builder.DataSource.Split(',')[0]; return serverIp; } public static DateTime lastActivityTime = DateTime.Now; public static bool isAnyBodyPerating = false; /// /// 根据日期查询周天 /// /// /// public static string GetWeek(DateTime day) { switch ((int)day.DayOfWeek) { case 1: return "周一"; case 2: return "周二"; case 3: return "周三"; case 4: return "周四"; case 5: return "周五"; case 6: return "周六"; default: return "周日"; } } /// /// MD5加密 /// /// /// /// public static string MD5Encrypt(string val, bool upper = true) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(val); bs = md5.ComputeHash(bs); System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2")); } return upper ? s.ToString().ToUpper() : s.ToString(); } /// ///生成制定位数的随机码(数字) /// /// /// public static string GenerateRandomCode(int length) { var result = new StringBuilder(); for (var i = 0; i < length; i++) { var r = new Random(Guid.NewGuid().GetHashCode()); result.Append(r.Next(0, 10)); } return result.ToString(); } #region Json序列化与反序列化 /// /// 序列化为JSON格式 /// /// /// /// public static string EnJson(this T val) { if (val.IsEmpty()) return ""; if (val.GetType().ToString().Contains("DataTable")) { return JsonConvert.SerializeObject(DataTableToDictionary(val as DataTable)); } if (val.GetType().ToString().Contains("DataRow")) { return JsonConvert.SerializeObject(DataRowToDictionary(val as DataRow)); } var nv = val as NameValueCollection; if (nv != null) return JsonConvert.SerializeObject(NvcToDic(nv)); return JsonConvert.SerializeObject(val); } /// /// 反序列化 /// /// /// /// public static T DeJson(this string value) { if (!string.IsNullOrEmpty(value)) { return JsonConvert.DeserializeObject(value); } return default(T); } private static List> DataTableToDictionary(DataTable table) { List> items = new List>(); foreach (DataRow dr in table.Rows) { Dictionary item = new Dictionary(); foreach (DataColumn col in table.Columns) { item.Add(col.ColumnName, dr[col.ColumnName]); } items.Add(item); } return items; } private static Dictionary DataRowToDictionary(DataRow dr) { List> items = new List>(); Dictionary item = new Dictionary(); foreach (DataColumn col in dr.Table.Columns) { item.Add(col.ColumnName, dr[col.ColumnName]); } return item; } private static Dictionary NvcToDic(NameValueCollection nvc) { Dictionary dic = new Dictionary(); foreach (string key in nvc.Keys) { if (!key.IsEmpty()) dic.Add(key, nvc[key]); } return dic; } #endregion /// /// 值转decimal /// /// /// /// public static decimal ToDecimal(this T o) { try { return decimal.Parse(o.ToString()); } catch { return 0; } } /// /// 判断是否为空 /// /// /// public static bool HasValue(this T obj) { return obj != null && !string.IsNullOrEmpty(obj.ToString()); } public static bool IsEmpty(this T val) { return val == null || String.IsNullOrEmpty(val.ToString().Trim()); } /// /// string类型转 int /// /// /// public static int ToInt(this T o) { try { string a = o == null ? "0" : o.ToString(); return int.Parse(a); } catch { return 0; } } public static string GetAppSetting(string key) { string value = ""; try { if (!ConfigurationManager.AppSettings.AllKeys.Contains(key)) { return ""; } value = ConfigurationManager.AppSettings[key]; } catch { } return value; } public static void SetAppSetting(string key, string value) { if (!ConfigurationManager.AppSettings.AllKeys.Contains(key)) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings.Add(key, value); config.Save(); //return; } else { Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfa.AppSettings.Settings[key].Value = value; cfa.Save(); } } /// /// DataTable转成List /// /// /// /// public static List ToDataList(this 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) { LogHelper.instance.log.Error("字段[" + info.Name + "]转换出错," + ex.Message); } } } list.Add(s); } return list; } /// /// Convert a List{T} to a DataTable. /// public static DataTable ListToTable(List items) { var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { Type t = GetCoreType(prop.PropertyType); tb.Columns.Add(prop.Name, t); } foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } tb.Rows.Add(values); } return tb; } /// /// Determine of specified type is nullable /// public static bool IsNullable(Type t) { return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } /// /// Return underlying type if type is Nullable otherwise return the type /// public static Type GetCoreType(Type t) { if (t != null && IsNullable(t)) { if (!t.IsValueType) { return t; } else { return Nullable.GetUnderlyingType(t); } } else { return t; } } /// /// 创建二维码 /// /// 二维码信息 /// 大小 默认20 /// public static BitmapImage CreateQR(string info, int pixelsPerModule = 20) { System.Drawing.Color qrColor = System.Drawing.Color.Green; System.Drawing.Color qrBackgroundColor = System.Drawing.Color.White; QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(info, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(pixelsPerModule, qrColor, qrBackgroundColor, true); return ConvertBitmap(qrCodeImage); //IntPtr hBitmap = qrCodeImage.GetHbitmap(); //ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( // hBitmap, // IntPtr.Zero, // Int32Rect.Empty, // BitmapSizeOptions.FromEmptyOptions()); //return wpfBitmap; } public static BitmapImage ConvertBitmap(Bitmap bitmap) { MemoryStream ms = new MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); BitmapImage image = new BitmapImage(); image.BeginInit(); ms.Seek(0, SeekOrigin.Begin); image.StreamSource = ms; image.EndInit(); return image; } public static string EncodePassword(string plainPassword) { string salt = BCrypt.Net.BCrypt.GenerateSalt(10, 'a'); string hashedPassword = BCrypt.Net.BCrypt.HashPassword(plainPassword, salt); return hashedPassword; } public static bool VerifyPassword(string plainPassword, string hashedPassword) { bool passwordMatches = BCrypt.Net.BCrypt.Verify(plainPassword, hashedPassword); return passwordMatches; } } }