using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using AutoMapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using xCommons.Constants;
using xCommons.Helpers;
using xExceptions.Attributes;
using xExceptions.Constants;
namespace xCommons.Extensions
{
public static partial class CommonExtensions
{
///
/// Conert XMLNode to String ...
///
///
///
///
public static string ToString(this XmlNode node, int indentation = 2)
{
//
using (var sw = new StringWriter())
{
//
using (var xw = new XmlTextWriter(sw))
{
xw.Formatting = System.Xml.Formatting.Indented;
xw.Indentation = indentation;
node.WriteContentTo(xw);
}
//
return sw.ToString();
}
}
///
/// Converts a Json String to Dictionary of String Mappings
///
/// Json String
///
public static Dictionary JSONToDictionary(this string source)
{
//
try
{
return JsonConvert.DeserializeObject>(source);
}
catch
{
return null;
}
}
///
/// Convert properties of specific Class instance to Dictionary ...
///
/// class instance
///
public static Dictionary ToDictionary(this T source) where T : class
{
//
var result = new Dictionary();
//
if (source.IsNull())
{
return result;
}
//
PropertyInfo[] propertyInfos = source.GetType().GetProperties();
if (!propertyInfos.HasChild())
{
return result;
}
//
foreach (PropertyInfo propertyInfo in propertyInfos)
{
result.Add(
propertyInfo.Name,
propertyInfo
.GetValue(source, null)
.ToString()
);
}
//
return result;
}
///
/// run specific task and retrieve result ...
///
///
public static void RunTask(this Task source)
{
source.
GetAwaiter()
.GetResult();
}
///
/// run specific task and retrieve result ...
///
///
public static T RunTask(this Task source)
{
return source.
GetAwaiter()
.GetResult();
}
///
/// Convert XML String to Json Object ...
///
///
///
public static string ToJSON(this string source)
{
//
var result = string.Empty;
try
{
//
result = XMLToJSONHelper.ToJSON(source);
//
// Handle Removing Additional Values ...
result = result.Replace("s:", "").Replace("a:", "");
}
catch { }
//
return result;
}
///
/// Convert object to Json ...
///
///
///
public static string ToJSON(this T value)
where T : class
{
//
if (value.IsNull())
{
return string.Empty;
}
//
var setting = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
//
return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting);
}
///
/// Convert to Json With Support of Camel Casing
///
///
///
///
public static string ToJSON(this T value, bool camelCase = false)
{
//
if (value.IsNull())
{
return string.Empty;
}
//
var setting = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None,
};
//
if (camelCase)
{
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
//
return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting);
}
///
/// Map to Dynamic Object ...
///
///
///
public static dynamic ToDynamicObject(this string source)
{
return JsonConvert.DeserializeObject(source);
}
///
/// Map to Dynamic Object ...
///
///
///
public static dynamic ToDynamicObject(this object source)
{
//
var dMapConfig = new MapperConfiguration(b => { });
var dMapper = dMapConfig.CreateMapper();
//
return dMapper.Map(source);
}
///
/// Parse From Dynamic Object ...
///
///
///
///
public static T FromDynamicObject(this object source)
where T : class
{
//
var dMapConfig = new MapperConfiguration(b => { });
var dMapper = dMapConfig.CreateMapper();
dynamic dSource = source;
//
return dMapper.Map(dSource);
}
///
/// Convert Type of Object to Safe Type
///
///
///
///
public static T ConvertTo(this object source)
{
//
T result = default(T);
//
try
{
//
T item = (T)Convert.ChangeType(source, typeof(T));
//
result = item;
}
catch { }
//
return result;
}
///
/// Convert an Instance to another Instance
/// using AutoMapper dynamic Convertion
///
///
///
///
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)
where T : class
where E : class
{
//
if (source.IsNull())
{
return null;
}
//
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;
}
///
/// Convert Using Auto Mapper ...
///
///
///
///
///
public static IEnumerable MapConvert(this IEnumerable source)
{
//
if (source.IsNull())
{
return null;
}
//
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;
}
///
/// Convert Using Auto Mapper ...
///
///
///
///
///
public static ICollection MapConvert(this ICollection source)
{
//
if (source.IsNull())
{
return null;
}
//
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;
}
///
/// Convert Using Auto Mapper ...
///
///
///
///
///
public static IList MapConvert(this IList source)
{
//
if (source.IsNull())
{
return null;
}
//
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;
}
///
/// Convert Using Auto Mapper ...
///
///
///
///
///
///
public static IDictionary MapConvert(this IDictionary source)
{
//
if (source.IsNull())
{
return null;
}
//
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;
}
///
/// Convert a Type to Static Type
///
///
///
///
public static T ToStatic(this object source)
{
//
var entity = Activator.CreateInstance();
//
var properties = source as IDictionary;
//
if (properties == null)
{
return entity;
}
//
foreach (var entry in properties)
{
//
var propertyInfo = entity.GetType().GetProperty(entry.Key);
if (propertyInfo != null)
{
propertyInfo.SetValue(entity, entry.Value, null);
}
}
//
return entity;
}
///
/// Convert From Json String ...
///
///
///
///
public static T FromJSON(this string value)
{
return JsonConvert.DeserializeObject(value);
}
///
/// Convert From Json String ...
///
///
///
///
public static object FromJSON(
this string value,
Type type
)
{
return JsonConvert
.DeserializeObject(value, type);
}
///
/// Search a Json String for Specific Node ...
///
///
///
///
public static List FindTokens(this JToken containerToken, string name)
{
List matches = new List();
FindTokens(containerToken, name, matches);
return matches;
}
///
/// Convert to MD5 Bytes ...
///
///
///
public static byte[] ToMd5Bytes(this string source)
{
return new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(source));
}
///
/// Convert to MD5 String ...
///
///
///
public static string ToMd5String(this string source)
{
//
// string representation (similar to UNIX format)
return BitConverter.ToString(source.ToMd5Bytes())
// without dashes
.Replace("-", string.Empty)
// make lowercase
.ToLower();
}
///
/// Check a String is MD5 String or not ...
///
///
///
public static bool IsMD5String(this string source)
{
//
if (String.IsNullOrEmpty(source))
{
return false;
}
//
return Regex.IsMatch(source, "^[0-9a-fA-F]{32}$", RegexOptions.Compiled);
}
///
/// Convert an string to Byte array Representation ...
///
///
///
public static byte[] ToBytes(this string source)
{
return Encoding.UTF8.GetBytes(source);
}
///
/// Converts Byte Array to String Value ...
///
///
///
public static string FromBytes(this byte[] source)
{
//
var result = Encoding.UTF8.GetString(source, 0, source.Length);
return result;
}
///
/// Check object is Null ...
///
///
///
public static bool IsNull(this object source)
{
return source == null;
}
///
/// Check collection Has Childs ...
///
///
///
///
public static bool HasChild(this IList source)
{
return !source.IsNull() && source.Count() > 0;
}
///
/// Check collection Has Childs ...
///
///
///
///
public static bool HasChild(this ICollection source)
{
return !source.IsNull() && source.Count() > 0;
}
///
/// Check collection Has Childs ...
///
///
///
///
public static bool HasChild(this IEnumerable source)
{
return !source.IsNull() && source.Count() > 0;
}
///
/// Select Async ...
///
///
///
///
///
///
public static async Task> SelectAsync(
this IEnumerable source, Func> method
)
{
return await Task.WhenAll(source.Select(async s => await method(s)));
}
///
/// Converts an Enumerable to Async Enumerable ...
///
///
///
///
///
public static async IAsyncEnumerable ToAsyncEnumerable(
this IEnumerable source,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
foreach (var item in source)
{
//
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
//
yield return item;
}
}
///
/// Converts an Stream to Model AsyncEnumerator ...
///
///
///
///
///
public static async IAsyncEnumerable ToModelAsyncEnumerable(
this Stream source,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
// Validate Stream ...
if (source.IsNull())
{
yield break;
}
//
while (source.CanRead)
{
//
var model = await source
.ReadModelFromStream(cancellationToken);
//
yield return model;
}
}
///
/// Converts an Stream to String AsyncEnumerator ...
/// using Read Line of Stream Reader ...S
///
///
///
///
public static async IAsyncEnumerable ToStringAsyncEnumerable(
this Stream source,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
// Validate Stream ...
if (source.IsNull())
{
yield break;
}
//
while (source.CanRead)
{
//
var json = await source
.ReadJsonFromStream(cancellationToken);
//
yield return json;
}
}
///
/// Write a Model to Stream ...
///
/// an Stream to Write ...
/// a Model instance to Write ...
///
///
///
public static async Task WriteModelToStream(
this Stream source,
T model,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (source.IsNull() || model.IsNull())
{
return;
}
//
// Extract Json of Model ...
var json = model.ToJSON(true);
//
await source.WriteJsonToStream(
json: json,
cancellationToken: cancellationToken
);
}
///
/// Write a Json String to Stream ...
///
/// an Stream to Write ...
/// json string to write ...
///
///
public static async Task WriteJsonToStream(
this Stream source,
string json,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (source.IsNull() || json.IsNullOrEmpty())
{
return;
}
//
using (var streamWriter = new StreamWriter(stream: source))
{
//
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
//
await jsonWriter.WriteRawAsync(json, cancellationToken);
await jsonWriter.FlushAsync(cancellationToken);
}
}
}
///
/// Read a Json Model From Stream ...
///
///
///
///
///
public static async Task ReadModelFromStream(
this Stream source,
CancellationToken cancellationToken = default
)
{
//
T result = default(T);
//
var json = await source.ReadJsonFromStream(cancellationToken);
if (!json.IsNullOrEmpty())
{
//
try
{
result = json.FromJSON();
}
catch
{ }
}
//
return result;
}
///
/// Reading Json String From Stream ...
///
/// an Stream to Write ...
///
///
public static async Task ReadJsonFromStream(
this Stream source,
CancellationToken cancellationToken = default
)
{
//
var result = string.Empty;
//
// Validate Args ...
if (source.IsNull())
{
return result;
}
//
using (var streamReader = new StreamReader(source))
{
//
result = await Task.Run(() =>
{
return streamReader.ReadLine();
},
cancellationToken);
}
//
return result;
}
///
/// Update a Collection item ...
///
///
///
///
///
///
public static IList Update(
this IList source,
T sourceItem,
T updateWith
)
{
//
var result = new List();
//
// Validate Args ...
if (!source.HasChild() ||
updateWith.IsNull() ||
sourceItem.IsNull()
)
{
return result;
}
//
// Extract Item from source ...
result = source
.Except(new List() { sourceItem })
.ToList();
result.Add(updateWith);
//
return source;
}
///
/// Update a Collection item ...
///
///
///
///
///
///
public static ICollection Update(
this ICollection source,
T sourceItem,
T updateWith
)
{
//
var result = new List();
//
// Validate Args ...
if (!source.HasChild() ||
updateWith.IsNull() ||
sourceItem.IsNull()
)
{
return result;
}
//
// Extract Item from source ...
result = source
.Except(new List() { sourceItem })
.ToList();
result.Add(updateWith);
//
return source;
}
///
/// Update a Collection item ...
///
///
///
///
///
///
public static IEnumerable Update(
this IEnumerable source,
T sourceItem,
T updateWith
)
{
//
var result = new List();
//
// Validate Args ...
if (!source.HasChild() ||
updateWith.IsNull() ||
sourceItem.IsNull()
)
{
return result;
}
//
// Extract Item from source ...
result = source
.Except(new List() { sourceItem })
.ToList();
result.Add(updateWith);
//
return source;
}
///
/// Select and Retrieve Nth Childs of given List ...
///
///
///
///
///
///
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
{
return result;
}
}
//
var index = 0;
foreach (var item in source)
{
//
result.Add(item);
index++;
//
if (index >= n)
{
break;
}
}
//
return result;
}
///
/// Select and Retrieve Nth Childs of given List ...
///
///
///
///
///
///
public static IEnumerable GetNthItems(this ICollection source, int n, bool throwException = false)
{
return source.ToList().GetNthItems(
n: n,
throwException: throwException
);
}
///
/// Select and Retrieve Nth Childs of given List ...
///
///
///
///
///
///
public static IEnumerable GetNthItems(this IEnumerable source, int n, bool throwException = false)
{
return source.ToList().GetNthItems(
n: n,
throwException: throwException
);
}
///
/// Check an string is Null or Empty ...
///
///
///
public static bool IsNullOrEmpty(this string sourse)
{
return string.IsNullOrEmpty(sourse);
}
///
/// Get string Value Attribute of an Enum ...
///
///
///
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;
}
///
/// Extracts digit's of an string ...
///
///
///
public static string GetDigits(this string source)
{
try
{
//
Regex regexObj = new Regex(@"[^\d]");
return regexObj.Replace(source, "");
}
catch
{
return null;
}
}
///
/// Check an string is contains only digits ...
///
///
///
public static bool IsDigits(this string source)
{
return (source.GetDigits() != null &&
source.GetDigits().ToString() == source);
}
///
/// Convert to normal string, Trim and ToLower ...
///
///
///
public static string ToNormalString(this string source)
{
//
if (source.IsNullOrEmpty())
{
return string.Empty;
}
//
return source.Trim().ToLowerInvariant();
}
///
/// Capitalize an string ...
///
///
///
public static string Capitalize(this string source)
{
//
if (source.IsNullOrEmpty())
{
return string.Empty;
}
//
var result = "";
if (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();
}
//
return result;
}
///
/// Summarize a Text ...
///
///
///
///
///
public static string SummarizeContent(
this string source,
int maxAllowedLength = 0,
string endsWith = ""
)
{
//
var result = string.Empty;
if (source.IsNullOrEmpty() || maxAllowedLength <= 0)
{
//
result = source;
return result;
}
//
// Pattern of Links ...
var pattern = @"(?:[!]\[(.*?)\]\(.*?\))";
//
// Apply Summarization ...
//
// Replace Markdown Links using RegExp ...
result = Regex.Replace(source, pattern, "");
//
// Do Summarization if Length bigger than MaxLength ...
if (result.Length > maxAllowedLength)
{
result = result.Substring(0, maxAllowedLength);
}
//
// Apply EndsWith if Provided ...
if (!endsWith.IsNullOrEmpty() &&
!result.EndsWith(endsWith))
{
result += endsWith;
}
//
return result;
}
///
/// Check an string is a Valid Representation of PhoneNumber ...
///
///
///
public static bool IsValidMobileNumber(this string source)
{
//
// Validating Mobile Numbers ...
var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance();
try
{
//
var mPhoneNumber = phoneNumberUtil.Parse(source, null);
if (phoneNumberUtil.IsValidNumber(mPhoneNumber))
{
//
return true;
}
//
return false;
}
catch
{
//
return false;
}
}
///
/// Check an string is Valid Representation of Email Address ...
///
///
///
public static bool IsValidEmail(this string source)
{
try
{
var addr = new System.Net.Mail.MailAddress(source);
return addr.Address == source;
}
catch
{
return false;
}
}
///
/// Check an string is Valid Representation of URL Address ...
///
///
///
public static bool IsValidUrl(this string url)
{
return Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);
}
///
/// check a URL has / at the end, if not add one ...
///
///
///
public static string NormalizeUrl(this string url)
{
return url.EndsWith("/") ? url : url + "/";
}
///
/// Check an string is GUID or not ...
///
///
///
public static bool IsGuid(this string source)
{
//
// Validate Args ...
if (source.IsNullOrEmpty())
{
return false;
}
//
Guid guid;
var result = Guid.TryParse(source, out guid);
//
return result;
}
///
/// Check Specific Guid string is Default Guid or not ...
///
///
///
public static bool IsDefaultGuid(this string guid)
{
//
if (!guid.IsGuid())
{
return false;
}
//
var empty = Guid.Empty.ToString();
return guid == empty;
}
///
/// Check Specific Guid is Default Guid or not ...
///
///
///
public static bool IsDefaultGuid(this Guid guid)
{
//
var empty = Guid.Empty;
return guid == empty;
}
///
/// Parse an String to related Enumerable Items ...
///
///
///
///
///
public static IEnumerable ParseListString(
this string source,
char? separator = null
)
{
//
if (!separator.HasValue)
{
separator = CommonConstants.DEFAULT_LIST_SEPERATOR;
}
//
var list = source.Split(separator.Value);
var result = new Collection();
//
foreach (var s in list)
{
//
try
{
//
T item = (T)Convert.ChangeType(s, typeof(T));
//
result.Add(item);
}
catch { }
}
//
return result;
}
///
/// Converts a List String Representation to GUid List ...
///
///
///
///
public static IEnumerable ParseListGuid(
this string list,
char? separator = null
)
{
//
var result = new List();
//
if (!separator.HasValue)
{
separator = CommonConstants.DEFAULT_LIST_SEPERATOR;
}
//
if (list.IsNullOrEmpty())
{
return result;
}
//
var items = list.Split(separator.Value);
items.ToList().ForEach(i =>
{
//
if (!i.IsNullOrEmpty() && i.IsGuid() && !i.IsDefaultGuid())
{
//
var gID = new Guid(i);
result.Add(gID);
}
});
//
return result;
}
///
/// Convert a List to List String ...
///
///
///
///
///
public static string ToListString(
this IEnumerable source,
char? separator = null
)
{
//
if (!separator.HasValue)
{
separator = CommonConstants.DEFAULT_LIST_SEPERATOR;
}
//
if (!source.HasChild())
{
return string.Empty;
}
//
string result = String.Join(
separator
.ToString(),
source
);
//
return result;
}
///
/// get default value of a Type
///
///
///
///
public static T Default(this T source)
where T : class
{
return default(T);
}
///
/// Check if an object is Null or Default Value
///
///
///
///
public static bool IsNullOrDefault(this T source)
where T : class
{
return Equals(source, default(T));
}
///
/// convert a timestamp to ISO String representation ...
///
///
///
public static string ISODateString(this long timestamp)
{
//
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)
{
//
var result = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
return result.DateTime;
}
public static DateTime FromTimestamp(this string source)
{
//
var timestamp = Int64.Parse(source);
var time = timestamp.FromTimestamp();
return time;
}
///
/// Check a Date Time is Expired or not
///
///
///
public static bool IsExPired(this DateTime source)
{
//
if (source.IsNull())
{
return true;
}
//
var currentDate = DateTime.UtcNow;
var isExpired = currentDate >= source;
//
return isExpired;
}
public static bool IsExpired(this long source)
{
var time = source.FromTimestamp();
return time.IsExPired();
}
public static bool IsExpired(this string source)
{
//
var time = DateTime.Parse(source);
return time.IsExPired();
}
///
/// Determines a File Type is Image Kind or not
///
///
///
public static bool IsImageKind(this XFileType source)
{
//
var imageKind = new Collection() {
XFileType.Image,
XFileType.CoverImage,
XFileType.ProfileImasge
};
//
return imageKind.Contains(source);
}
///
/// Encode String as Url
///
///
///
public static string ToUrlEncoded(this string source)
{
return HttpUtility.UrlEncode(source);
}
///
/// Decode Url String
///
///
///
public static string ToUrlDecoded(this string source)
{
return HttpUtility.UrlDecode(source);
}
///
/// Convert an Object to string for use in HttpParams
///
///
///
///
public static string ToHttpParamString(this object value, CultureInfo cultureInfo)
{
//
if (value is Enum)
{
//
string name = Enum.GetName(value.GetType(), value);
if (name != null)
{
//
var field = IntrospectionExtensions
.GetTypeInfo(value.GetType())
.GetDeclaredField(name);
//
if (field != null)
{
//
var attribute = CustomAttributeExtensions
.GetCustomAttribute(field, typeof(EnumMemberAttribute))
as EnumMemberAttribute;
//
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)
{
//
var array = Enumerable.OfType