using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Complex.Application.Utility { public static class ExtendFunction { public static string ObjectToJson(this object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, }); //return System.Text.Json.JsonSerializer.Serialize(obj); } public static byte[] ToByteArray(this Stream input) { using (MemoryStream ms = new MemoryStream()) { input.CopyTo(ms); return ms.ToArray(); } } //public static void Log(this Exception ex) //{ // if (ex is ThreadAbortException) // { // return; // } // var a = new List() { "[" + ex.Message + "]
" }; // a.Add(ex.StackTrace); // while (ex.InnerException != null) // { // ex = ex.InnerException; // //a.Add("
-----------
[" + ex.Message + "]
---------
" + ex.StackTrace); // } // long personId = 0; // if (HttpContext.Current.Session != null && HttpContext.Current.Session["PersonID"] != null) // personId = HttpContext.Current.Session["PersonID"].ToString().ToLong().Value; // LogClass.SetLog(personId, -1, ex.Message, false, a, -1, 2); //} public static string CodeID(this short ID) { return Code_ID(ID); } public static string CodeID(this int ID) { return Code_ID(ID); } public static string CodeID(this long ID) { return Code_ID(ID); } static string Code_ID(long ID) { long id1 = ID ^ 0;//GetResourceLongValue("KeyCode1"); id1 = id1 * 7 + 5; long id2 = id1.ToString().Length + ID % 10 ^ 0;//GetResourceLongValue("KeyCode2"); return id1 + "_" + id2; } public static long DeCodeID(this string ID) { string[] ids = ID.Split('_'); long id1 = ids[0].ToLong().Value; id1 = (id1 - 5) / 7; id1 = id1 ^ 0;//GetResourceLongValue("KeyCode1"); long id2 = ids[0].Length + id1 % 10 ^ 0;//GetResourceLongValue("KeyCode2"); if (ids[1] == id2.ToString()) return id1; return -1; } public static long? ToLong(this object ID, long? defaultValue = null) { long LID; bool IsLong = long.TryParse(ID + "", out LID); if (IsLong) return LID; else return defaultValue; } public static int Value(this int? number, int defaultInt = 0) { if (number.HasValue) return number.Value; return defaultInt; } public static double Value(this double? number, int defaultInt = 0) { if (number.HasValue) return number.Value; return defaultInt; } public static string NumberToDate(this int? Date) { if (Date == null) return ""; return Date.Value.NumberToDate(); } public static string NumberToDate(this int Date) { try { var st = Date.ToString(); return st.Substring(0, 4) + "/" + st.Substring(4, 2) + "/" + st.Substring(6, 2); } catch { return ""; } } public static int? ToInt(this object ID, int? defaultInt = null) { int LID; bool IsLong = int.TryParse(ID + "", out LID); if (IsLong) return LID; else return defaultInt; } //public static string GetSql(this IQueryable query) //{ // return ((System.Data.Objects.ObjectQuery)query).ToTraceString(); //} public static double? ToDouble(this object ID, double? defaultValue = null) { double LID; bool IsDouble = double.TryParse(ID + "", out LID); if (IsDouble) return LID; else return defaultValue; } public static short? ToShort(this object ID) { short LID; bool IsLong = short.TryParse(ID + "", out LID); if (IsLong) return LID; else return null; } public static byte? ToByte(this object ID, byte defaultValue = 0) { byte LID; bool IsLong = byte.TryParse(ID + "", out LID); if (IsLong) return LID; else return defaultValue; } public static bool? ToBool(this object obj) { if (obj == null) return null; var ID = obj.ToString(); bool b; if (ID.ToLower() == "false" || ID == "0") return false; if (ID.ToLower() == "true" || ID == "1" || ID.ToLower() == "on") return true; bool isConvert = bool.TryParse(ID, out b); if (!isConvert) return null; return b; } public static string ConvertToBase64(this string str) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(str)); } public static string ConvertToBase64(this byte[] bytes) { return Convert.ToBase64String(bytes); } public static string ConvertBase64ToString(this string str) { return Encoding.UTF8.GetString(Convert.FromBase64String(str)); } public static byte[] Base64ToByte(this string str) { return Convert.FromBase64String(str); } public static string[] Split(this string str, string spliter, StringSplitOptions spo = StringSplitOptions.RemoveEmptyEntries) { string[] sp = new string[] { spliter }; return str.Split(sp, spo); } public static bool IsNullOrEmpty(this string? str) { return string.IsNullOrEmpty(str); } public static bool IsNotNullOrEmpty(this string? str) { return !string.IsNullOrEmpty(str); } public static string CalculateMD5Hash(this string input) { // step 1, calculate MD5 hash from input MD5 md5 = MD5.Create(); byte[] inputBytes = Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } public static byte[] ToByte(this Stream input) { using (MemoryStream ms = new MemoryStream()) { input.CopyTo(ms); return ms.ToArray(); } } public static string SimpleCodeString(this string st) { if (st == null) return ""; return string.Join("", st.ConvertToBase64().Reverse()).Replace("=", "*@!").Replace("1", "___").Replace("2", "_1_1_"); } public static string SimpleDeCodeString(this string st) { if (st.IsNullOrEmpty()) return ""; return string.Join("", st.Replace("_1_1_", "2").Replace("___", "1").Replace("*@!", "=").Reverse()).ConvertBase64ToString(); } public static string SetValisQueryString(this string st) { return st; } public static byte[] EnCodeString(this string str) { var bytes = Encoding.UTF8.GetBytes(str); for (int i = 0; i < bytes.Length; i++) { bytes[i] += 14; } return bytes; } public static byte[] EnCodeStringForSearchLike(this string str) { var bytes = Encoding.UTF8.GetBytes(str); for (int i = 0; i < bytes.Length; i++) { bytes[i] += 14; } var b = Encoding.UTF8.GetBytes("%"); var finalBytes = new byte[bytes.Length + 2]; finalBytes[0] = b[0]; finalBytes[finalBytes.Length - 1] = b[0]; for (int i = 0; i < bytes.Length; i++) finalBytes[i + 1] = bytes[i]; return finalBytes; } public static string DeCodeString(this byte[] byteArray) { if (byteArray == null) return ""; for (int i = 0; i < byteArray.Length; i++) { byteArray[i] -= 14; } var bytes = Encoding.UTF8.GetString(byteArray); return bytes; } public static string StripHTML(this string input) { return Regex.Replace(input, "<.*?>", string.Empty); } public static string SubStrFromStartEnd(this string str, int startindex = 0, int minesLenght = 0) { return str.Substring(startindex, str.Length - minesLenght); } public static string SubStrWithMax(this string str, int maxLength = 50, string continueStr = "") { if (str.Length < maxLength) return str; return str.Substring(0, maxLength) + continueStr; } public static IList CastToList(this IEnumerable source) { return new List(source.Cast()); } //public static T Cast2(this object obj) //{ // return (T)obj; //} public static T CastTo(this object value, T targetType) { // targetType above is just for compiler magic // to infer the type to cast x to return (T)value; } public static string RemoveFirstLines(this string text, int linesCount) { var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount); return string.Join(Environment.NewLine, lines.ToArray()); } public static string RemoveEndLines(this string text, int linesCount) { var lines = Regex.Split(text, "\r\n|\r|\n").Reverse().Skip(linesCount).Reverse(); return string.Join(Environment.NewLine, lines.ToArray()); } public static string GetPropertiesValues(this object obj) { if (obj == null) return "null"; StringBuilder sb = new StringBuilder(); List props = obj.GetType().GetProperties().ToList(); foreach (var p in props) { sb.Append(p.Name).Append(": ").Append(p.GetValue(obj, null)); sb.AppendLine(); } return sb.ToString(); } //public static IEnumerable Filter(this IEnumerable source, string searchStr) //{ // var propsToCheck = typeof(T).GetProperties().Where(a => a.PropertyType == typeof(string)); // var filter = propsToCheck.Aggregate(string.Empty, (s, p) => (s == string.Empty ? string.Empty : string.Format("{0} OR ", s)) + string.Format("{0} == @0", p.Name)); // var filtered = source.AsQueryable().Where(filter, searchStr); // return filtered; //} /// /// فرمت تاریخ صحیح است؟ /// /// تاریخ /// public static bool HasDateFormat(this string date) { return PersianDate.HasDateFormat(date); } /// /// فرمت زمان معتبر است؟ /// /// زمان /// public static bool HasTimeFormat(this string time) { return PersianDate.HasTimeFormat(time); } /// /// تبدیل رشته زمان به دقیقه /// /// زمان /// public static int ConvertTimeToMinutes(this string time) { //if (!time.HasTimeFormat()) // return 0; try { var hm = time.Split(':').Select(i => i.ToInt(0).Value).ToArray(); return hm[0] * 60 + hm[1]; } catch { return 0; } } /// /// تبدیل دقیقه به رشته زمان /// /// دقیقه /// public static string ConvertMinutesToTime(this int minutes) { if (minutes < 0) return ""; return string.Format("{0:D2}:{1:D2}", minutes / 60, minutes % 60); } public static object Copy(this object entity, object distEntity, List excludeCopyField = null, int level = 0/*, ILogger logger*/) { if (level > 5) return null; if (excludeCopyField == null) excludeCopyField = new List(); var obj1Properties = entity.GetType().GetProperties(); var obj2Properties = distEntity.GetType().GetProperties(); try { foreach (var obj1prop in obj1Properties) { if (excludeCopyField.Contains(obj1prop.Name)) continue; var destProp = obj2Properties.FirstOrDefault(x => x.Name == obj1prop.Name);// && x.PropertyType == obj1prop.PropertyType); //logger.LogInformation("---> " + obj1prop.Name); if (destProp != null) { object srcEnt = obj1prop.GetValue(entity, null); //logger.LogInformation("------> srcEnt is null: " + (srcEnt == null)); if (srcEnt != null) { bool isNullable = destProp.PropertyType.IsGenericType;// && destProp.PropertyType.GetGenericTypeDefinition() == typeof(Nullable); if (isNullable || destProp.PropertyType.IsPrimitive || destProp.PropertyType == typeof(String)) { destProp.SetValue(distEntity, srcEnt); } else { object destEnt = Activator.CreateInstance(destProp.PropertyType); //logger.LogCritical("=====> destEnt is null: " + (destEnt == null)); if (destEnt != null) { var a = srcEnt.Copy(destEnt, excludeCopyField, level + 1); destProp.SetValue(distEntity, a); } } } } } } catch { return null; } return distEntity; } public static string CorrectPersianString(this string str) { return str.Replace("ك", "ک").Replace("ي", "ی").Replace("ﯼ", "ی").Replace("ى", "ی"); } } public class SearchTokenVM { public string KeySearch { set; get; } } public class RoleParam { public int RoleId { set; get; } } }