From 9f733c65ad20f1a753338bb481598c6b768db43a Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 17 Jul 2025 07:58:13 +0330 Subject: [PATCH] Last ... --- Extensions/CommonExtensions.cs | 854 ++++++++++++++++++++------------- 1 file changed, 515 insertions(+), 339 deletions(-) diff --git a/Extensions/CommonExtensions.cs b/Extensions/CommonExtensions.cs index 807e131..89a5f64 100644 --- a/Extensions/CommonExtensions.cs +++ b/Extensions/CommonExtensions.cs @@ -21,26 +21,31 @@ using xCommons.Helpers; using xExceptions.Attributes; using xExceptions.Constants; -namespace xCommons.Extensions { - public static partial class CommonExtensions { +namespace xCommons.Extensions +{ + public static partial class CommonExtensions + { /// /// Conert XMLNode to String ... /// /// /// /// - public static string ToString (this XmlNode node, int indentation = 2) { + public static string ToString(this XmlNode node, int indentation = 2) + { // - using (var sw = new StringWriter ()) { + using (var sw = new StringWriter()) + { // - using (var xw = new XmlTextWriter (sw)) { + using (var xw = new XmlTextWriter(sw)) + { xw.Formatting = System.Xml.Formatting.Indented; xw.Indentation = indentation; - node.WriteContentTo (xw); + node.WriteContentTo(xw); } // - return sw.ToString (); + return sw.ToString(); } } @@ -49,11 +54,15 @@ namespace xCommons.Extensions { /// /// Json String /// - public static Dictionary JSONToDictionary (this string source) { + public static Dictionary JSONToDictionary(this string source) + { // - try { - return JsonConvert.DeserializeObject> (source); - } catch { + try + { + return JsonConvert.DeserializeObject>(source); + } + catch + { return null; } } @@ -63,28 +72,32 @@ namespace xCommons.Extensions { /// /// class instance /// - public static Dictionary ToDictionary (this T source) where T : class { + public static Dictionary ToDictionary(this T source) where T : class + { // - var result = new Dictionary (); + var result = new Dictionary(); // - if (source.IsNull ()) { + if (source.IsNull()) + { return result; } // - PropertyInfo[] propertyInfos = source.GetType ().GetProperties (); - if (!propertyInfos.HasChild ()) { + PropertyInfo[] propertyInfos = source.GetType().GetProperties(); + if (!propertyInfos.HasChild()) + { return result; } // - foreach (PropertyInfo propertyInfo in propertyInfos) { - result.Add ( + foreach (PropertyInfo propertyInfo in propertyInfos) + { + result.Add( propertyInfo.Name, propertyInfo - .GetValue (source, null) - .ToString () + .GetValue(source, null) + .ToString() ); } @@ -96,20 +109,22 @@ namespace xCommons.Extensions { /// run specific task and retrieve result ... /// /// - public static void RunTask (this Task source) { + public static void RunTask(this Task source) + { source. - GetAwaiter () - .GetResult (); + GetAwaiter() + .GetResult(); } /// /// run specific task and retrieve result ... /// /// - public static T RunTask (this Task source) { + public static T RunTask(this Task source) + { return source. - GetAwaiter () - .GetResult (); + GetAwaiter() + .GetResult(); } /// @@ -117,17 +132,20 @@ namespace xCommons.Extensions { /// /// /// - public static string ToJSON (this string source) { + public static string ToJSON(this string source) + { // var result = string.Empty; - try { + try + { // - result = XMLToJSONHelper.ToJSON (source); + result = XMLToJSONHelper.ToJSON(source); // // Handle Removing Additional Values ... - result = result.Replace ("s:", "").Replace ("a:", ""); - } catch { } + result = result.Replace("s:", "").Replace("a:", ""); + } + catch { } // return result; @@ -138,21 +156,24 @@ namespace xCommons.Extensions { /// /// /// - public static string ToJSON (this T value) - where T : class { + public static string ToJSON(this T value) + where T : class + { // - if (value.IsNull ()) { + if (value.IsNull()) + { return string.Empty; } // - var setting = new JsonSerializerSettings { + var setting = new JsonSerializerSettings + { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.None }; // - return JsonConvert.SerializeObject (value, Newtonsoft.Json.Formatting.None, setting); + return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting); } /// @@ -161,25 +182,29 @@ namespace xCommons.Extensions { /// /// /// - public static string ToJSON (this T value, bool camelCase = false) { + public static string ToJSON(this T value, bool camelCase = false) + { // - if (value.IsNull ()) { + if (value.IsNull()) + { return string.Empty; } // - var setting = new JsonSerializerSettings { + var setting = new JsonSerializerSettings + { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.None, }; // - if (camelCase) { - setting.ContractResolver = new CamelCasePropertyNamesContractResolver (); + if (camelCase) + { + setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); } // - return JsonConvert.SerializeObject (value, Newtonsoft.Json.Formatting.None, setting); + return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting); } /// @@ -187,8 +212,9 @@ namespace xCommons.Extensions { /// /// /// - public static dynamic ToDynamicObject (this string source) { - return JsonConvert.DeserializeObject (source); + public static dynamic ToDynamicObject(this string source) + { + return JsonConvert.DeserializeObject(source); } /// @@ -196,13 +222,14 @@ namespace xCommons.Extensions { /// /// /// - public static dynamic ToDynamicObject (this object source) { + public static dynamic ToDynamicObject(this object source) + { // - var dMapConfig = new MapperConfiguration (b => { }); - var dMapper = dMapConfig.CreateMapper (); + var dMapConfig = new MapperConfiguration(b => { }); + var dMapper = dMapConfig.CreateMapper(); // - return dMapper.Map (source); + return dMapper.Map(source); } /// @@ -211,15 +238,16 @@ namespace xCommons.Extensions { /// /// /// - public static T FromDynamicObject (this object source) - where T : class { + public static T FromDynamicObject(this object source) + where T : class + { // - var dMapConfig = new MapperConfiguration (b => { }); - var dMapper = dMapConfig.CreateMapper (); + var dMapConfig = new MapperConfiguration(b => { }); + var dMapper = dMapConfig.CreateMapper(); dynamic dSource = source; // - return dMapper.Map (dSource); + return dMapper.Map(dSource); } /// @@ -228,18 +256,21 @@ namespace xCommons.Extensions { /// /// /// - public static T ConvertTo (this object source) { + public static T ConvertTo(this object source) + { // - T result = default (T); + T result = default(T); // - try { + try + { // - T item = (T) Convert.ChangeType (source, typeof (T)); + T item = (T)Convert.ChangeType(source, typeof(T)); // result = item; - } catch { } + } + catch { } // return result; @@ -252,43 +283,48 @@ namespace xCommons.Extensions { /// /// /// - public static T MapConvert (this T source) - where T : class { - // - if (source.IsNull ()) { - return null; - } - - // - var dSource = (object) source.ToDynamicObject (); - return dSource.FromDynamicObject (); - } - - /// - /// Convert Using Auto Mapper ... - /// - /// - /// - /// - /// - public static T MapConvert (this E source) + public static T MapConvert(this T source) where T : class - where E : class { + { // - if (source.IsNull ()) { + if (source.IsNull()) + { return null; } // - var dMapConfig = new MapperConfiguration (b => { - b.CreateMap () - .ReverseMap (); - }); - var dMapper = dMapConfig.CreateMapper (); + var dSource = (object)source.ToDynamicObject(); + return dSource.FromDynamicObject(); + } + + /// + /// Convert Using Auto Mapper ... + /// + /// + /// + /// + /// + public static T MapConvert(this E source) + where T : class + where E : class + { + // + if (source.IsNull()) + { + return null; + } // - var dSource = (object) dMapper.Map (source); - var result = dMapper.Map (dSource); + var dMapConfig = new MapperConfiguration(b => + { + b.CreateMap() + .ReverseMap(); + }); + var dMapper = dMapConfig.CreateMapper(); + + // + var dSource = (object)dMapper.Map(source); + var result = dMapper.Map(dSource); // return result; @@ -301,22 +337,25 @@ namespace xCommons.Extensions { /// /// /// - public static IEnumerable MapConvert (this IEnumerable source) { + public static IEnumerable MapConvert(this IEnumerable source) + { // - if (source.IsNull ()) { + if (source.IsNull()) + { return null; } // - var dMapConfig = new MapperConfiguration (b => { - b.CreateMap () - .ReverseMap (); + var dMapConfig = new MapperConfiguration(b => + { + b.CreateMap() + .ReverseMap(); }); - var dMapper = dMapConfig.CreateMapper (); + var dMapper = dMapConfig.CreateMapper(); // - var dSource = (object) dMapper.Map (source); - var result = dMapper.Map> (dSource); + var dSource = (object)dMapper.Map(source); + var result = dMapper.Map>(dSource); // return result; @@ -329,22 +368,25 @@ namespace xCommons.Extensions { /// /// /// - public static ICollection MapConvert (this ICollection source) { + public static ICollection MapConvert(this ICollection source) + { // - if (source.IsNull ()) { + if (source.IsNull()) + { return null; } // - var dMapConfig = new MapperConfiguration (b => { - b.CreateMap () - .ReverseMap (); + var dMapConfig = new MapperConfiguration(b => + { + b.CreateMap() + .ReverseMap(); }); - var dMapper = dMapConfig.CreateMapper (); + var dMapper = dMapConfig.CreateMapper(); // - var dSource = (object) dMapper.Map (source); - var result = dMapper.Map> (dSource); + var dSource = (object)dMapper.Map(source); + var result = dMapper.Map>(dSource); // return result; @@ -357,22 +399,25 @@ namespace xCommons.Extensions { /// /// /// - public static IList MapConvert (this IList source) { + public static IList MapConvert(this IList source) + { // - if (source.IsNull ()) { + if (source.IsNull()) + { return null; } // - var dMapConfig = new MapperConfiguration (b => { - b.CreateMap () - .ReverseMap (); + var dMapConfig = new MapperConfiguration(b => + { + b.CreateMap() + .ReverseMap(); }); - var dMapper = dMapConfig.CreateMapper (); + var dMapper = dMapConfig.CreateMapper(); // - var dSource = (object) dMapper.Map (source); - var result = dMapper.Map> (dSource); + var dSource = (object)dMapper.Map(source); + var result = dMapper.Map>(dSource); // return result; @@ -386,22 +431,25 @@ namespace xCommons.Extensions { /// /// /// - public static IDictionary MapConvert (this IDictionary source) { + public static IDictionary MapConvert(this IDictionary source) + { // - if (source.IsNull ()) { + if (source.IsNull()) + { return null; } // - var dMapConfig = new MapperConfiguration (b => { - b.CreateMap () - .ReverseMap (); + var dMapConfig = new MapperConfiguration(b => + { + b.CreateMap() + .ReverseMap(); }); - var dMapper = dMapConfig.CreateMapper (); + var dMapper = dMapConfig.CreateMapper(); // - var dSource = (object) dMapper.Map (source); - var result = dMapper.Map> (dSource); + var dSource = (object)dMapper.Map(source); + var result = dMapper.Map>(dSource); // return result; @@ -413,24 +461,28 @@ namespace xCommons.Extensions { /// /// /// - public static T ToStatic (this object source) { + public static T ToStatic(this object source) + { // - var entity = Activator.CreateInstance (); + var entity = Activator.CreateInstance(); // var properties = source as IDictionary; // - if (properties == null) { + if (properties == null) + { return entity; } // - foreach (var entry in properties) { + foreach (var entry in properties) + { // - var propertyInfo = entity.GetType ().GetProperty (entry.Key); - if (propertyInfo != null) { - propertyInfo.SetValue (entity, entry.Value, null); + var propertyInfo = entity.GetType().GetProperty(entry.Key); + if (propertyInfo != null) + { + propertyInfo.SetValue(entity, entry.Value, null); } } @@ -444,8 +496,9 @@ namespace xCommons.Extensions { /// /// /// - public static T FromJSON (this string value) { - return JsonConvert.DeserializeObject (value); + public static T FromJSON(this string value) + { + return JsonConvert.DeserializeObject(value); } /// @@ -454,12 +507,13 @@ namespace xCommons.Extensions { /// /// /// - public static object FromJSON ( + public static object FromJSON( this string value, Type type - ) { + ) + { return JsonConvert - .DeserializeObject (value, type); + .DeserializeObject(value, type); } /// @@ -468,9 +522,10 @@ namespace xCommons.Extensions { /// /// /// - public static List FindTokens (this JToken containerToken, string name) { - List matches = new List (); - FindTokens (containerToken, name, matches); + public static List FindTokens(this JToken containerToken, string name) + { + List matches = new List(); + FindTokens(containerToken, name, matches); return matches; } @@ -479,8 +534,9 @@ namespace xCommons.Extensions { /// /// /// - public static byte[] ToMd5Bytes (this string source) { - return new MD5CryptoServiceProvider ().ComputeHash (Encoding.UTF8.GetBytes (source)); + public static byte[] ToMd5Bytes(this string source) + { + return new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(source)); } /// @@ -488,14 +544,15 @@ namespace xCommons.Extensions { /// /// /// - public static string ToMd5String (this string source) { + public static string ToMd5String(this string source) + { // // string representation (similar to UNIX format) - return BitConverter.ToString (source.ToMd5Bytes ()) + return BitConverter.ToString(source.ToMd5Bytes()) // without dashes - .Replace ("-", string.Empty) + .Replace("-", string.Empty) // make lowercase - .ToLower (); + .ToLower(); } /// @@ -503,14 +560,16 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsMD5String (this string source) { + public static bool IsMD5String(this string source) + { // - if (String.IsNullOrEmpty (source)) { + if (String.IsNullOrEmpty(source)) + { return false; } // - return Regex.IsMatch (source, "^[0-9a-fA-F]{32}$", RegexOptions.Compiled); + return Regex.IsMatch(source, "^[0-9a-fA-F]{32}$", RegexOptions.Compiled); } /// @@ -518,8 +577,9 @@ namespace xCommons.Extensions { /// /// /// - public static byte[] ToBytes (this string source) { - return Encoding.UTF8.GetBytes (source); + public static byte[] ToBytes(this string source) + { + return Encoding.UTF8.GetBytes(source); } /// @@ -527,7 +587,8 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsNull (this object source) { + public static bool IsNull(this object source) + { return source == null; } @@ -537,8 +598,9 @@ namespace xCommons.Extensions { /// /// /// - public static bool HasChild (this IList source) { - return !source.IsNull () && source.Count () > 0; + public static bool HasChild(this IList source) + { + return !source.IsNull() && source.Count() > 0; } /// @@ -547,8 +609,9 @@ namespace xCommons.Extensions { /// /// /// - public static bool HasChild (this ICollection source) { - return !source.IsNull () && source.Count () > 0; + public static bool HasChild(this ICollection source) + { + return !source.IsNull() && source.Count() > 0; } /// @@ -557,8 +620,9 @@ namespace xCommons.Extensions { /// /// /// - public static bool HasChild (this IEnumerable source) { - return !source.IsNull () && source.Count () > 0; + public static bool HasChild(this IEnumerable source) + { + return !source.IsNull() && source.Count() > 0; } /// @@ -569,29 +633,31 @@ namespace xCommons.Extensions { /// /// /// - public static IList Update ( + public static IList Update( this IList source, T sourceItem, T updateWith - ) { + ) + { // - var result = new List (); + var result = new List(); // // Validate Args ... - if (!source.HasChild () || - updateWith.IsNull () || - sourceItem.IsNull () - ) { + if (!source.HasChild() || + updateWith.IsNull() || + sourceItem.IsNull() + ) + { return result; } // // Extract Item from source ... result = source - .Except (new List () { sourceItem }) - .ToList (); - result.Add (updateWith); + .Except(new List() { sourceItem }) + .ToList(); + result.Add(updateWith); // return source; @@ -605,29 +671,31 @@ namespace xCommons.Extensions { /// /// /// - public static ICollection Update ( + public static ICollection Update( this ICollection source, T sourceItem, T updateWith - ) { + ) + { // - var result = new List (); + var result = new List(); // // Validate Args ... - if (!source.HasChild () || - updateWith.IsNull () || - sourceItem.IsNull () - ) { + if (!source.HasChild() || + updateWith.IsNull() || + sourceItem.IsNull() + ) + { return result; } // // Extract Item from source ... result = source - .Except (new List () { sourceItem }) - .ToList (); - result.Add (updateWith); + .Except(new List() { sourceItem }) + .ToList(); + result.Add(updateWith); // return source; @@ -641,29 +709,31 @@ namespace xCommons.Extensions { /// /// /// - public static IEnumerable Update ( + public static IEnumerable Update( this IEnumerable source, T sourceItem, T updateWith - ) { + ) + { // - var result = new List (); + var result = new List(); // // Validate Args ... - if (!source.HasChild () || - updateWith.IsNull () || - sourceItem.IsNull () - ) { + if (!source.HasChild() || + updateWith.IsNull() || + sourceItem.IsNull() + ) + { return result; } // // Extract Item from source ... result = source - .Except (new List () { sourceItem }) - .ToList (); - result.Add (updateWith); + .Except(new List() { sourceItem }) + .ToList(); + result.Add(updateWith); // return source; @@ -677,26 +747,33 @@ namespace xCommons.Extensions { /// /// /// - public static IEnumerable GetNthItems (this IList source, int n, bool throwException = false) { + public static IEnumerable GetNthItems(this IList source, int n, bool throwException = false) + { // - var result = new List (); - if (n < 1 || n > source.Count || source.IsNull () || !source.HasChild ()) { - if (throwException) { - throw XException.InvalidArgs.ToException (); - } else { + var result = new List(); + if (n < 1 || n > source.Count || source.IsNull() || !source.HasChild()) + { + if (throwException) + { + throw XException.InvalidArgs.ToException(); + } + else + { return result; } } // var index = 0; - foreach (var item in source) { + foreach (var item in source) + { // - result.Add (item); + result.Add(item); index++; // - if (index >= n) { + if (index >= n) + { break; } } @@ -713,8 +790,9 @@ namespace xCommons.Extensions { /// /// /// - public static IEnumerable GetNthItems (this ICollection source, int n, bool throwException = false) { - return source.ToList ().GetNthItems ( + public static IEnumerable GetNthItems(this ICollection source, int n, bool throwException = false) + { + return source.ToList().GetNthItems( n: n, throwException: throwException ); @@ -728,8 +806,9 @@ namespace xCommons.Extensions { /// /// /// - public static IEnumerable GetNthItems (this IEnumerable source, int n, bool throwException = false) { - return source.ToList ().GetNthItems ( + public static IEnumerable GetNthItems(this IEnumerable source, int n, bool throwException = false) + { + return source.ToList().GetNthItems( n: n, throwException: throwException ); @@ -740,8 +819,9 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsNullOrEmpty (this string sourse) { - return string.IsNullOrEmpty (sourse); + public static bool IsNullOrEmpty(this string sourse) + { + return string.IsNullOrEmpty(sourse); } /// @@ -749,10 +829,11 @@ namespace xCommons.Extensions { /// /// /// - public static string GetStringValue (this Enum source) { - var type = source.GetType (); - var fieldInfo = type.GetField (source.ToString ()); - var attributes = fieldInfo.GetCustomAttributes (typeof (StringValueAttribute), false) as StringValueAttribute[]; + public static string GetStringValue(this Enum source) + { + var type = source.GetType(); + var fieldInfo = type.GetField(source.ToString()); + var attributes = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[]; return attributes != null && attributes.Length > 0 ? attributes[0].StringValue : null; @@ -763,12 +844,16 @@ namespace xCommons.Extensions { /// /// /// - public static string GetDigits (this string source) { - try { + public static string GetDigits(this string source) + { + try + { // - Regex regexObj = new Regex (@"[^\d]"); - return regexObj.Replace (source, ""); - } catch { + Regex regexObj = new Regex(@"[^\d]"); + return regexObj.Replace(source, ""); + } + catch + { return null; } } @@ -778,9 +863,10 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsDigits (this string source) { - return (source.GetDigits () != null && - source.GetDigits ().ToString () == source); + public static bool IsDigits(this string source) + { + return (source.GetDigits() != null && + source.GetDigits().ToString() == source); } /// @@ -788,14 +874,16 @@ namespace xCommons.Extensions { /// /// /// - public static string ToNormalString (this string source) { + public static string ToNormalString(this string source) + { // - if (source.IsNullOrEmpty ()) { + if (source.IsNullOrEmpty()) + { return string.Empty; } // - return source.Trim ().ToLowerInvariant (); + return source.Trim().ToLowerInvariant(); } /// @@ -803,23 +891,28 @@ namespace xCommons.Extensions { /// /// /// - public static string Capitalize (this string source) { + public static string Capitalize(this string source) + { // - if (source.IsNullOrEmpty ()) { + if (source.IsNullOrEmpty()) + { return string.Empty; } // var result = ""; - if (source.Length > 1) { + if (source.Length > 1) + { // - var firstCharr = source.Substring (0, 1); - var otherParts = source.Substring (1, source.Length - 1); + var firstCharr = source.Substring(0, 1); + var otherParts = source.Substring(1, source.Length - 1); // - result = firstCharr.ToUpperInvariant () + otherParts; - } else { - result = source.ToUpperInvariant (); + result = firstCharr.ToUpperInvariant() + otherParts; + } + else + { + result = source.ToUpperInvariant(); } // @@ -831,21 +924,26 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsValidMobileNumber (this string source) { + public static bool IsValidMobileNumber(this string source) + { // // Validating Mobile Numbers ... - var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance (); - try { + var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance(); + try + { // - var mPhoneNumber = phoneNumberUtil.Parse (source, null); - if (phoneNumberUtil.IsValidNumber (mPhoneNumber)) { + var mPhoneNumber = phoneNumberUtil.Parse(source, null); + if (phoneNumberUtil.IsValidNumber(mPhoneNumber)) + { // return true; } // return false; - } catch { + } + catch + { // return false; @@ -857,11 +955,15 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsValidEmail (this string source) { - try { - var addr = new System.Net.Mail.MailAddress (source); + public static bool IsValidEmail(this string source) + { + try + { + var addr = new System.Net.Mail.MailAddress(source); return addr.Address == source; - } catch { + } + catch + { return false; } } @@ -871,8 +973,9 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsValidUrl (this string url) { - return Uri.IsWellFormedUriString (url, UriKind.RelativeOrAbsolute); + public static bool IsValidUrl(this string url) + { + return Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute); } /// @@ -880,8 +983,9 @@ namespace xCommons.Extensions { /// /// /// - public static string NormalizeUrl (this string url) { - return url.EndsWith ("/") ? url : url + "/"; + public static string NormalizeUrl(this string url) + { + return url.EndsWith("/") ? url : url + "/"; } /// @@ -889,16 +993,18 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsGuid (this string source) { + public static bool IsGuid(this string source) + { // // Validate Args ... - if (source.IsNullOrEmpty ()) { + if (source.IsNullOrEmpty()) + { return false; } // Guid guid; - var result = Guid.TryParse (source, out guid); + var result = Guid.TryParse(source, out guid); // return result; @@ -909,14 +1015,16 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsDefaultGuid (this string guid) { + public static bool IsDefaultGuid(this string guid) + { // - if (!guid.IsGuid ()) { + if (!guid.IsGuid()) + { return false; } // - var empty = Guid.Empty.ToString (); + var empty = Guid.Empty.ToString(); return guid == empty; } @@ -925,7 +1033,8 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsDefaultGuid (this Guid guid) { + public static bool IsDefaultGuid(this Guid guid) + { // var empty = Guid.Empty; return guid == empty; @@ -938,29 +1047,34 @@ namespace xCommons.Extensions { /// /// /// - public static IEnumerable ParseListString ( + public static IEnumerable ParseListString( this string source, char? separator = null - ) { + ) + { // - if (!separator.HasValue) { + if (!separator.HasValue) + { separator = CommonConstants.DEFAULT_LIST_SEPERATOR; } // - var list = source.Split (separator.Value); - var result = new Collection (); + var list = source.Split(separator.Value); + var result = new Collection(); // - foreach (var s in list) { + foreach (var s in list) + { // - try { + try + { // - T item = (T) Convert.ChangeType (s, typeof (T)); + T item = (T)Convert.ChangeType(s, typeof(T)); // - result.Add (item); - } catch { } + result.Add(item); + } + catch { } } // @@ -974,24 +1088,27 @@ namespace xCommons.Extensions { /// /// /// - public static string ToListString ( + public static string ToListString( this IEnumerable source, char? separator = null - ) { + ) + { // - if (!separator.HasValue) { + if (!separator.HasValue) + { separator = CommonConstants.DEFAULT_LIST_SEPERATOR; } // - if (!source.HasChild ()) { + if (!source.HasChild()) + { return string.Empty; } // - string result = String.Join ( + string result = String.Join( separator - .ToString (), + .ToString(), source ); @@ -1005,9 +1122,10 @@ namespace xCommons.Extensions { /// /// /// - public static T Default (this T source) - where T : class { - return default (T); + public static T Default(this T source) + where T : class + { + return default(T); } /// @@ -1016,9 +1134,10 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsNullOrDefault (this T source) - where T : class { - return Equals (source, default (T)); + public static bool IsNullOrDefault(this T source) + where T : class + { + return Equals(source, default(T)); } /// @@ -1026,23 +1145,38 @@ namespace xCommons.Extensions { /// /// /// - public static string ISODateString (this long timestamp) { + public static string ISODateString(this long timestamp) + { // - var time = timestamp.FromTimestamp (); - var result = time.ToString ("o"); + var time = timestamp.FromTimestamp(); + var result = time.ToString("o"); // return result; } + /// + /// Converts a DateTime to Unix Like Long ... + /// + /// + /// + public static long ToTimestamp( + this DateTime source + ) + { + return new DateTimeOffset(source) + .ToUnixTimeMilliseconds(); + } + /// /// convert timestamp to DateTime ... /// /// /// - public static DateTime FromTimestamp (this long timestamp) { + public static DateTime FromTimestamp(this long timestamp) + { // - var result = DateTimeOffset.FromUnixTimeMilliseconds (timestamp); + var result = DateTimeOffset.FromUnixTimeMilliseconds(timestamp); return result.DateTime; } @@ -1051,9 +1185,11 @@ namespace xCommons.Extensions { /// /// /// - public static bool IsExPired (this DateTime source) { + public static bool IsExPired(this DateTime source) + { // - if (source == null) { + if (source == null) + { return true; } @@ -1064,22 +1200,27 @@ namespace xCommons.Extensions { // return isExpired; } + public static bool IsExpired(this long source) + { + return source.FromTimestamp().IsExPired(); + } /// /// Determines a File Type is Image Kind or not /// /// /// - public static bool IsImageKind (this XFileType source) { + public static bool IsImageKind(this XFileType source) + { // - var imageKind = new Collection () { + var imageKind = new Collection() { XFileType.Image, XFileType.CoverImage, XFileType.ProfileImasge }; // - return imageKind.Contains (source); + return imageKind.Contains(source); } /// @@ -1087,8 +1228,9 @@ namespace xCommons.Extensions { /// /// /// - public static string ToUrlEncoded (this string source) { - return HttpUtility.UrlEncode (source); + public static string ToUrlEncoded(this string source) + { + return HttpUtility.UrlEncode(source); } /// @@ -1096,8 +1238,9 @@ namespace xCommons.Extensions { /// /// /// - public static string ToUrlDecoded (this string source) { - return HttpUtility.UrlDecode (source); + public static string ToUrlDecoded(this string source) + { + return HttpUtility.UrlDecode(source); } /// @@ -1106,45 +1249,56 @@ namespace xCommons.Extensions { /// /// /// - public static string ToHttpParamString (this object value, CultureInfo cultureInfo) { + public static string ToHttpParamString(this object value, CultureInfo cultureInfo) + { // - if (value is Enum) { + if (value is Enum) + { // - string name = Enum.GetName (value.GetType (), value); - if (name != null) { + string name = Enum.GetName(value.GetType(), value); + if (name != null) + { // var field = IntrospectionExtensions - .GetTypeInfo (value.GetType ()) - .GetDeclaredField (name); + .GetTypeInfo(value.GetType()) + .GetDeclaredField(name); // - if (field != null) { + if (field != null) + { // var attribute = CustomAttributeExtensions - .GetCustomAttribute (field, typeof (EnumMemberAttribute)) + .GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute; // - if (attribute != null) { + if (attribute != null) + { return attribute.Value != null ? attribute.Value : name; } } } - } else if (value is bool) { - return System.Convert.ToString (value, cultureInfo).ToLowerInvariant (); - } else if (value is byte[]) { - return System.Convert.ToBase64String ((byte[]) value); - } else if (value != null && value.GetType ().IsArray) { + } + else if (value is bool) + { + return System.Convert.ToString(value, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[]) + { + return System.Convert.ToBase64String((byte[])value); + } + else if (value != null && value.GetType().IsArray) + { // - var array = Enumerable.OfType ((Array) value); - return string.Join (",", Enumerable - .Select ( + var array = Enumerable.OfType((Array)value); + return string.Join(",", Enumerable + .Select( array, - o => o.ToHttpParamString (cultureInfo))); + o => o.ToHttpParamString(cultureInfo))); } // - return System.Convert.ToString (value, cultureInfo); + return System.Convert.ToString(value, cultureInfo); } /// @@ -1152,10 +1306,11 @@ namespace xCommons.Extensions { /// /// /// - public static string AsHttpParamString (this object value) { + public static string AsHttpParamString(this object value) + { return System.Uri - .EscapeDataString (value - .ToHttpParamString (CultureInfo.InvariantCulture)); + .EscapeDataString(value + .ToHttpParamString(CultureInfo.InvariantCulture)); } /// @@ -1164,54 +1319,59 @@ namespace xCommons.Extensions { /// /// /// - public static long GenerateDateTimeOffset (this string offsetProvider) { + public static long GenerateDateTimeOffset(this string offsetProvider) + { // - if (offsetProvider.IsNullOrEmpty ()) { + if (offsetProvider.IsNullOrEmpty()) + { return 0; } // var mExpireValue = 0; - var mExpireValueStr = offsetProvider.GetDigits (); - var mExpireUnit = offsetProvider.Replace (mExpireValueStr, ""); - if (mExpireValueStr.IsNullOrEmpty () || mExpireUnit.IsNullOrEmpty ()) { + var mExpireValueStr = offsetProvider.GetDigits(); + var mExpireUnit = offsetProvider.Replace(mExpireValueStr, ""); + if (mExpireValueStr.IsNullOrEmpty() || mExpireUnit.IsNullOrEmpty()) + { return 0; } // - var isParsed = int.TryParse (mExpireValueStr, out mExpireValue); - if (!isParsed) { + var isParsed = int.TryParse(mExpireValueStr, out mExpireValue); + if (!isParsed) + { return 0; } // DateTime? date = null; - switch (mExpireUnit) { + switch (mExpireUnit) + { case "d": - date = DateTime.UtcNow.AddDays (mExpireValue); + date = DateTime.UtcNow.AddDays(mExpireValue); break; case "h": - date = DateTime.UtcNow.AddHours (mExpireValue); + date = DateTime.UtcNow.AddHours(mExpireValue); break; case "m": - date = DateTime.UtcNow.AddMinutes (mExpireValue); + date = DateTime.UtcNow.AddMinutes(mExpireValue); break; case "s": - date = DateTime.UtcNow.AddSeconds (mExpireValue); + date = DateTime.UtcNow.AddSeconds(mExpireValue); break; case "ms": default: - date = DateTime.UtcNow.AddMilliseconds (mExpireValue); + date = DateTime.UtcNow.AddMilliseconds(mExpireValue); break; } // - var result = !date.HasValue ? 0 : new DateTimeOffset (date.Value) - .ToUnixTimeMilliseconds (); + var result = !date.HasValue ? 0 : new DateTimeOffset(date.Value) + .ToUnixTimeMilliseconds(); // return result; @@ -1219,61 +1379,77 @@ namespace xCommons.Extensions { // #region Int Id Extensions ... - public static bool IsValidIntId (this int source) { + public static bool IsValidIntId(this int source) + { return source > 0; } - public static void ValidateIntId (this int source) { + public static void ValidateIntId(this int source) + { // - if (!source.IsValidIntId ()) { - XException.InvalidArgs.Throw (); + if (!source.IsValidIntId()) + { + XException.InvalidArgs.Throw(); } } #endregion // #region StringExtensions for Identity Server ... - public static string EnsureTrailingSlash (this string input) { - if (!input.EndsWith ("/")) { + public static string EnsureTrailingSlash(this string input) + { + if (!input.EndsWith("/")) + { return input + "/"; } return input; } - public static bool IsMissing (this string value) { - return string.IsNullOrWhiteSpace (value); + public static bool IsMissing(this string value) + { + return string.IsNullOrWhiteSpace(value); } - public static bool IsPresent (this string value) { - return !string.IsNullOrWhiteSpace (value); + public static bool IsPresent(this string value) + { + return !string.IsNullOrWhiteSpace(value); } - public static string Sha256 (this string input) { - if (input.IsMissing ()) return string.Empty; + public static string Sha256(this string input) + { + if (input.IsMissing()) return string.Empty; - using (var sha = SHA256.Create ()) { - var bytes = Encoding.UTF8.GetBytes (input); - var hash = sha.ComputeHash (bytes); + using (var sha = SHA256.Create()) + { + var bytes = Encoding.UTF8.GetBytes(input); + var hash = sha.ComputeHash(bytes); - return Convert.ToBase64String (hash); + return Convert.ToBase64String(hash); } } #endregion // #region Private ... - private static void FindTokens (JToken containerToken, string name, List matches) { - if (containerToken.Type == JTokenType.Object) { - foreach (JProperty child in containerToken.Children ()) { - if (child.Name == name) { - matches.Add (child.Value); + private static void FindTokens(JToken containerToken, string name, List matches) + { + if (containerToken.Type == JTokenType.Object) + { + foreach (JProperty child in containerToken.Children()) + { + if (child.Name == name) + { + matches.Add(child.Value); } - FindTokens (child.Value, name, matches); + FindTokens(child.Value, name, matches); } - } else if (containerToken.Type == JTokenType.Array) { - foreach (JToken child in containerToken.Children ()) { - FindTokens (child, name, matches); + } + else if (containerToken.Type == JTokenType.Array) + { + foreach (JToken child in containerToken.Children()) + { + FindTokens(child, name, matches); } } }