using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using JiShe.CollectBus.Common.Attributes; using System.Collections.Specialized; using JiShe.CollectBus.Common.Enums; using Newtonsoft.Json.Linq; namespace JiShe.CollectBus.Common.Helpers { public static class CommonHelper { /// /// 获得无符号GUID /// /// public static string GetGUID() { return Guid.NewGuid().ToString("N"); } /// /// 获取时间戳 /// /// 是否返回秒,false返回毫秒 /// public static long GetTimeStampTen(bool isSeconds) { if (isSeconds) { return DateTimeOffset.UtcNow.ToUnixTimeSeconds(); } else { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } } /// /// 获取指定长度的随机数 /// /// /// public static string GetRandomNumber(int length = 8) { if (length <= 8) { length = 8; } if (length > 31) { length = 32; } var randomArray = RandomNumberGenerator.GetBytes(length); StringBuilder stringBuilder = new StringBuilder(); foreach (var item in randomArray) { stringBuilder.Append(item); } return stringBuilder.ToString().Substring(0, length); } /// /// C#反射遍历对象属性获取键值对 /// /// 对象类型 /// 对象 public static Dictionary GetClassProperties(T model) { Type t = model.GetType(); List propertyList = new List(); PropertyInfo[] tempPropertyList = t.GetProperties(); if (tempPropertyList != null && tempPropertyList.Length > 0) { propertyList.AddRange(tempPropertyList); } var parentPropertyInfo = t.BaseType?.GetProperties(); if (parentPropertyInfo != null && parentPropertyInfo.Length > 0) { foreach (var item in parentPropertyInfo) { if (!propertyList.Any(d => d.Name == item.Name)) //如果子类已经包含父类的属性或者字段,跳过不处理 { propertyList.Add(item); } } } Dictionary resultData = new Dictionary(); foreach (PropertyInfo item in propertyList) { resultData.Add(item.Name, item.GetValue(model, null)); } return resultData; } /// /// C#反射遍历对象属性,将键值对赋值给属性 /// public static object SetClassProperties(string typeModel, Dictionary keyValues) { if (keyValues.Count <= 0) { return null; } Type tType = Type.GetType(typeModel); PropertyInfo[] PropertyList = tType.GetProperties(); object objModel = tType.Assembly.CreateInstance(tType.FullName); foreach (PropertyInfo item in PropertyList) { if (keyValues.ContainsKey(item.Name)) { object objectValue = keyValues[item.Name]; item.SetValue(objModel, objectValue); } } return objModel; } /// /// 获取指定枚举的所有 Attribute 说明以及value组成的键值对 /// /// 对象类 /// false获取字段、true获取属性 /// public static List GetEnumAttributeList(Type type, bool getPropertie = false) { if (type == null) { return null; } List selectResults = new List(); List memberInfos = new List(); if (getPropertie == false) { FieldInfo[] fieldArray = type.GetFields(); if (null == fieldArray || fieldArray.Length <= 0) { return null; } memberInfos.AddRange(fieldArray); //获取父类的字段 var parentFieldInfo = type.BaseType?.GetFields(); if (parentFieldInfo != null && parentFieldInfo.Length > 0) { foreach (var item in parentFieldInfo) { if (!memberInfos.Any(d => d.Name == item.Name)) //如果子类已经包含父类的属性或者字段,跳过不处理 { memberInfos.Add(item); } } } } else { PropertyInfo[] properties = type.GetProperties(); if (null == properties || properties.Length <= 0) { return null; } memberInfos.AddRange(properties); //获取父类的属性 var parentPropertyInfo = type.BaseType?.GetProperties(); if (parentPropertyInfo != null && parentPropertyInfo.Length > 0) { foreach (var item in parentPropertyInfo) { if (!memberInfos.Any(d => d.Name == item.Name)) //如果子类已经包含父类的属性或者字段,跳过不处理 { memberInfos.Add(item); } } } } foreach (var item in memberInfos) { DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false); dynamic infoObject = null; if (getPropertie == false) { infoObject = (FieldInfo)item; } else { infoObject = (PropertyInfo)item; } if (EnumAttributes.Length > 0) { SelectResult selectResult = new SelectResult() { Key = Convert.ToInt32(infoObject.GetValue(null)).ToString(), Value = EnumAttributes[0].Description, }; selectResults.Add(selectResult); } DisplayAttribute[] DisplayAttributes = (DisplayAttribute[])item.GetCustomAttributes(typeof(DisplayAttribute), false); if (DisplayAttributes.Length > 0) { SelectResult selectResult = selectResults.FirstOrDefault(e => e.Key == Convert.ToInt32(infoObject.GetValue(null)).ToString()); if (selectResult != null) { selectResult.SecondValue = DisplayAttributes[0].Name; } } } return selectResults; } /// /// 获取指定枚举的所有 Attribute 说明以及value组成的键值对 /// /// 对象类 /// 第三个标签类型 /// 第三个标签类型取值名称 /// false获取字段、true获取属性 /// public static List GetEnumAttributeListWithThirdValue(Type type, Type thirdAttributeType, string thirdAttributePropertieName, bool getPropertie = false) { if (type == null) { return null; } List selectResults = new List(); List memberInfos = new List(); if (getPropertie == false) { FieldInfo[] EnumInfo = type.GetFields(); if (null == EnumInfo || EnumInfo.Length <= 0) { return null; } memberInfos.AddRange(EnumInfo); var parentFieldInfo = type.BaseType?.GetFields(); if (parentFieldInfo != null && parentFieldInfo.Length > 0) { memberInfos.AddRange(parentFieldInfo); } } else { PropertyInfo[] EnumInfo = type.GetProperties(); if (null == EnumInfo || EnumInfo.Length <= 0) { return null; } memberInfos.AddRange(EnumInfo); var parentPropertyInfo = type.BaseType?.GetProperties(); if (parentPropertyInfo != null && parentPropertyInfo.Length > 0) { memberInfos.AddRange(parentPropertyInfo); } } foreach (var item in memberInfos) { var thirdAttributes = item. GetCustomAttributes(thirdAttributeType, false); if (thirdAttributes == null || thirdAttributes.Length <= 0) { continue; } DescriptionAttribute[] descriptionAttributes = (DescriptionAttribute[])item. GetCustomAttributes(typeof(DescriptionAttribute), false); dynamic infoObject = null; if (getPropertie == false) { infoObject = (FieldInfo)item; } else { infoObject = (PropertyInfo)item; } if (descriptionAttributes.Length > 0) { SelectResult selectResult = new SelectResult() { Key = infoObject.Name, Value = descriptionAttributes[0].Description, }; selectResults.Add(selectResult); } DisplayAttribute[] displayAttributes = (DisplayAttribute[])item. GetCustomAttributes(typeof(DisplayAttribute), false); if (displayAttributes.Length > 0) { SelectResult selectResult = selectResults.FirstOrDefault(e => e.Key == infoObject.Name); if (selectResult != null) { selectResult.SecondValue = displayAttributes[0].Name; } } if (thirdAttributes.Length > 0 && !string.IsNullOrWhiteSpace(thirdAttributePropertieName)) { foreach (var attr in thirdAttributes) { // 使用反射获取特性的属性值 var properties = thirdAttributeType.GetProperties(); foreach (var prop in properties) { // 假设你要获取特性的某个属性值,例如 TypeName if (prop.Name == thirdAttributePropertieName) { object value = prop.GetValue(attr); SelectResult selectResult = selectResults.FirstOrDefault(e => e.Key == infoObject.Name); if (selectResult != null) { selectResult.ThirdValue = value?.ToString(); // 将属性值赋给 ThirdValue } break; // 如果找到了需要的属性,可以跳出循环 } } } } } return selectResults; } /// /// 获取指定类、指定常量值的Description说明 /// 包含直接继承的父级字段 /// /// 对象类 /// /// public static List> GetTypeDescriptionListToTuple(Type t, bool getPropertie = false) { if (t == null) { return null; } List memberInfos = new List(); if (getPropertie == false) { FieldInfo[] fieldInfo = t.GetFields(); if (null == fieldInfo || fieldInfo.Length <= 0) { return null; } memberInfos.AddRange(fieldInfo); var parentFieldInfo = t.BaseType?.GetFields(); if (parentFieldInfo != null && parentFieldInfo.Length > 0) { foreach (var item in parentFieldInfo) { if (!memberInfos.Any(d => d.Name == item.Name)) //如果子类已经包含父类的属性或者字段,跳过不处理 { memberInfos.Add(item); } } } } else { PropertyInfo[] fieldInfo = t.GetProperties(); if (null == fieldInfo || fieldInfo.Length <= 0) { return null; } memberInfos.AddRange(fieldInfo); var parentPropertyInfo = t.BaseType?.GetProperties(); if (parentPropertyInfo != null && parentPropertyInfo.Length > 0) { foreach (var item in parentPropertyInfo) { if (!memberInfos.Any(d => d.Name == item.Name)) //如果子类已经包含父类的属性或者字段,跳过不处理 { memberInfos.Add(item); } } } } List> tuples = new List>(); foreach (var item in memberInfos) { DescriptionAttribute[] descriptionAttribute = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false); NumericalOrderAttribute[] indexAttributes = (NumericalOrderAttribute[])item.GetCustomAttributes(typeof(NumericalOrderAttribute), false); if (descriptionAttribute.Length > 0 && indexAttributes.Length > 0) { Tuple tuple = new Tuple(item.Name, descriptionAttribute[0].Description, indexAttributes[0].Index); tuples.Add(tuple); } } return tuples; } /// /// 获取指定类、指定常量值的常量说明 /// /// 常量字段名称 ///属性还是字段 /// public static string GetTypeDescriptionName(string fieldName, bool getPropertie = false) { if (string.IsNullOrEmpty(fieldName)) { return ""; } MemberInfo memberInfo = null; if (getPropertie == false) { memberInfo = typeof(T).GetField(fieldName); } else { memberInfo = typeof(T).GetProperty(fieldName); } if (null == memberInfo) { return ""; } DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (EnumAttributes.Length <= 0) { return ""; } return EnumAttributes[0].Description; } /// /// 获取指定命名空间下指定常量值的常量说明 /// /// 常量字段名称 /// 命名空间,主要用来找到对应程序集 ///属性还是字段 /// public static string GetTypeDescriptionName(string fieldName, string assemblyName, bool getPropertie = false) { if (string.IsNullOrWhiteSpace(fieldName) || string.IsNullOrWhiteSpace(assemblyName)) { return null; } string desc = ""; foreach (var item in GetEnumList(assemblyName)) { desc = GetTypeDescriptionName(item, fieldName, getPropertie); if (!string.IsNullOrEmpty(desc)) { break; } } return desc; } /// /// 获取指定类、指定常量值的常量说明 /// /// 对象类 /// 常量字段名称 ///属性还是字段 /// public static string GetTypeDescriptionName(this Type t, string fieldName, bool getPropertie = false) { if (string.IsNullOrWhiteSpace(fieldName)) { return ""; } MemberInfo memberInfo = null; if (getPropertie == false) { memberInfo = t.GetField(fieldName); } else { memberInfo = t.GetProperty(fieldName); } if (null != memberInfo) { DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (EnumAttributes.Length > 0) { return EnumAttributes[0].Description; } } return ""; } /// /// 扩展方法,获得枚举值集合 /// ///枚举的DisplayName public static List GetEnumList() where T : Enum { List enumList = new List(); foreach (T value in Enum.GetValues(typeof(T))) { enumList.Add(value); } return enumList; } private static List GetEnumList(string assemblyName) { if (!String.IsNullOrEmpty(assemblyName)) { Assembly assembly = Assembly.Load(assemblyName); List ts = assembly.GetTypes().Where(x => x.GetTypeInfo().IsClass).ToList(); return ts; } return new List(); } /// /// 扩展方法,获得枚举的Display值 /// ///枚举值 ///当枚举值没有定义DisplayNameAttribute,是否使用枚举名代替,默认是使用 ///属性还是字段 ///枚举的DisplayName public static string GetDisplayName(this Enum value, Boolean nameInstead = true, bool getPropertie = false) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name == null) { return null; } DisplayAttribute attribute = null; if (getPropertie == false) { attribute = Attribute.GetCustomAttribute(type.GetField(name), typeof(DisplayAttribute)) as DisplayAttribute; } else { attribute = Attribute.GetCustomAttribute(type.GetProperty(name), typeof(DisplayAttribute)) as DisplayAttribute; } if (attribute == null && nameInstead == true) { return name; } return attribute == null ? null : attribute.Name; } /// /// 获取枚举的描述信息 /// /// /// public static string GetEnumDescription(this Enum value) { var name = value.ToString(); var field = value.GetType().GetField(name); if (field == null) return name; var att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false); return att == null ? field.Name : ((DescriptionAttribute)att).Description; } /// /// 根据枚举类型值返回枚举定义Description属性 /// /// /// /// public static string GetEnumDescription(this int value, Type enumType) { NameValueCollection nameValueCollection = new NameValueCollection(); Type typeFromHandle = typeof(DescriptionAttribute); FieldInfo[] fields = enumType.GetFields(); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.FieldType.IsEnum) { string name = ((int)enumType.InvokeMember(fieldInfo.Name, BindingFlags.GetField, null, null, null)).ToString(); object[] customAttributes = fieldInfo.GetCustomAttributes(typeFromHandle, inherit: true); string value2 = ((customAttributes.Length == 0) ? "" : ((DescriptionAttribute)customAttributes[0]).Description); nameValueCollection.Add(name, value2); } } return nameValueCollection[value.ToString()]; } /// /// 将传入的字符串中间部分字符替换成特殊字符 /// /// 需要替换的字符串 /// 前保留长度 /// 尾保留长度 /// 特殊字符 /// 被特殊字符替换的字符串 public static string ReplaceWithSpecialChar(this string value, int startLen = 1, int endLen = 1, char specialChar = '*') { if (string.IsNullOrEmpty(value)) { return value; } try { if (value.Length <= startLen + endLen) { var temStartVal = value.Substring(0, startLen); return $"{temStartVal}{"".PadLeft(endLen, specialChar)}"; } if (value.Length == 10 && endLen == 1) { endLen = 3; } var startVal = value.Substring(0, startLen); var endVal = value.Substring(value.Length - endLen); if (value.Length == 2) { endVal = ""; } value = $"{startVal}{endVal.PadLeft(value.Length - startLen, specialChar)}"; } catch (Exception) { throw; } return value; } /// /// Linux下字体名称转换 /// /// /// public static string GetLinuxFontFamily(this string fontValue) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { if (fontValue == "楷体") { fontValue = "KaiTi"; } else if (fontValue == "隶书") { fontValue = "LiSu"; } else if (fontValue == "宋体") { fontValue = "SimSun"; } else if (fontValue == "微软雅黑") { fontValue = "Microsoft YaHei"; } else if (fontValue == "新宋体") { fontValue = "NSimSun"; } else if (fontValue == "仿宋") { fontValue = "FangSong"; } else if (fontValue == "黑体") { fontValue = "SimHei"; } } return fontValue; } /// /// 获取任务标识 /// /// /// /// /// /// /// public static string GetTaskMark(int afn, int fn, int pn, int msa, int seq) { var makstr = $"{afn.ToString().PadLeft(2, '0')}{fn.ToString().PadLeft(2, '0')}{pn.ToString().PadLeft(2, '0')}{msa.ToString().PadLeft(2, '0')}{seq.ToString().PadLeft(2, '0')}"; return makstr;// Convert.ToInt32(makstr) << 32 | msa; } /// /// 判断是生成月 /// /// /// /// public static bool JudgeIsGenerate_Month(string eachMonthWith, DateTime curTime) { var arr = eachMonthWith.Split(','); if (arr.Contains(curTime.Day.ToString())) return true; return false; } /// /// 判断是生成一次 /// /// /// /// public static bool JudgeIsGenerate_Once(DateTime onceWithDate, DateTime curTime) => curTime.Date.Equals(onceWithDate);//为当天时发送 /// /// 判断是生成日 /// /// /// /// public static bool JudgeIsGenerate_Day(string eachDayWithout, DateTime curTime) { if (string.IsNullOrWhiteSpace(eachDayWithout)) { return false; } var weekName = strWeeks[(int)curTime.DayOfWeek]; var arr = eachDayWithout.Split(','); return !arr.Contains(weekName); } public static readonly List strWeeks = new List() { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; /// /// 判断是生成周 /// /// /// /// public static bool JudgeIsGenerate_Week(string eachWeekWith, DateTime curTime) { if (string.IsNullOrWhiteSpace(eachWeekWith)) { return false; } var weekName = strWeeks[(int)curTime.DayOfWeek]; var arr = eachWeekWith.Split(','); return arr.Contains(weekName); } /// /// 系统采集频率转换为集中器采集密度 /// /// /// public static int GetFocusDensity(this int timeDensity) => timeDensity switch { 0 => 0,//无 1 => 255,//1分钟 5 => 245,//5分钟 15 => 1,//15分钟 30 => 2,//30分钟 60 => 3,//60分钟 _ => -1//采集项本身无密度位 }; /// /// 集中器采集密度转换为系统采集频率 /// /// /// public static int GetSystemDensity(this int density) => density switch { 0 => 0,//无 255 => 1,//1分钟 245 => 5,//5分钟 1 => 15,//15分钟 2 => 30,//30分钟 3 => 60,//60分钟 _ => -1//采集项本身无密度位 }; /// /// 获取集中器ZSet Scores /// /// /// /// public static long GetFocusScores(string focusScores, int point) { bool hasInvalidChars = focusScores.Any(c => !(c >= '0' && c <= '9')); if (hasInvalidChars) { throw new Exception($"{nameof(GetFocusScores)} 集中器地址格式错误"); } var scoresStr = $"{focusScores}{point.ToString().PadLeft(2, '0')}"; return Convert.ToInt64(scoresStr); } /// /// 加载指定名称的程序集 /// /// /// public static List LoadAssemblies(string[] assemblyNames) { var assemblies = new List(); // 获取已加载的程序集 foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { if (assemblyNames.Contains(asm.GetName().Name)) assemblies.Add(asm); } // 尝试加载未加载的程序集 foreach (var name in assemblyNames) { if (!assemblies.Any(a => a.GetName().Name == name)) { try { var assembly = Assembly.Load(name); assemblies.Add(assembly); } catch (FileNotFoundException) { // 若Load失败,尝试从基目录加载 var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll"); if (File.Exists(path)) { try { assemblies.Add(Assembly.LoadFrom(path)); } catch { /* 记录错误 */ } } } } } return assemblies; } /// /// 创建类型实例 /// /// /// public static List CreateInstances(List types) { var instances = new List(); foreach (var type in types) { try { instances.Add(Activator.CreateInstance(type)); } catch (Exception) { throw; } } return instances; } } }