using Apewer; using Apewer.Internals; using Apewer.Source; using Apewer.Surface; using Apewer.Web; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; #if NETFX || NETCORE using System.Windows.Forms; #endif /// <summary>扩展方法。</summary> public static class Extensions { #region Class Utility /// <summary>克隆对象,创建新对象。可指定包含对象的属性和字段。</summary> public static T Clone<T>(this T @this, T failed = default(T), bool properties = true, bool fields = false) where T : new() { return ClassUtility.Clone(@this, failed, properties, fields); } /// <summary>解析源对象。</summary> public static Dictionary<string, string> GetOrigin(this TextSet @this) { return ClassUtility.GetOrigin(@this); } /// <summary>解析源对象。</summary> public static Dictionary<string, object> GetOrigin(this ObjectSet @this) { return ClassUtility.GetOrigin(@this); } /// <summary>解析源对象。</summary> public static Dictionary<string, T> GetOrigin<T>(this ObjectSet<T> @this) { return ClassUtility.GetOrigin(@this); } /// <summary>调用 Get 方法。</summary> public static object Get(this PropertyInfo @this, object instance) { return ClassUtility.InvokeGet<object>(instance, @this); } /// <summary>调用 Set 方法。</summary> public static void Set(this PropertyInfo @this, object instance, object value) { ClassUtility.InvokeSet<object>(instance, @this, value); } /// <summary>调用 Get 方法。</summary> public static T Get<T>(this PropertyInfo @this, object instance) { return ClassUtility.InvokeGet<T>(instance, @this); } /// <summary>调用 Set 方法。</summary> public static void Set<T>(this PropertyInfo @this, object instance, T value) { ClassUtility.InvokeSet<T>(instance, @this, value); } /// <summary>调用方法。</summary> /// <exception cref="ArgumentException"></exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="MethodAccessException"></exception> /// <exception cref="NotSupportedException"></exception> /// <exception cref="TargetException"></exception> /// <exception cref="TargetInvocationException"></exception> /// <exception cref="TargetParameterCountException"></exception> public static object Invoke(this MethodInfo @this, object instace, params object[] parameters) { return ClassUtility.InvokeMethod(instace, @this, parameters); } /// <summary>遍历公开属性。</summary> public static void ForEachProperties(this Type @this, Action<PropertyInfo> action) { ClassUtility.ForEachPublicProperties(@this, action); } /// <summary>判断静态属性。</summary> public static bool IsStatic(this PropertyInfo @this) { return ClassUtility.IsStatic(@this); } /// <summary>判断类型。</summary> public static bool TypeEquals<T>(this object @this) { return ClassUtility.TypeEquals(@this, typeof(T)); } #endregion #region Number private static bool Equals<T>(this T @this, T value) where T : IComparable<T> => @this.CompareTo(value) == 0; /// <summary></summary> public static bool IsZero(this decimal @this) => @this.Equals(0M); /// <summary></summary> public static bool IsZero(this double @this) => @this.Equals(0D); /// <summary></summary> public static bool IsZero(this float @this) => @this.Equals(0F); /// <summary></summary> public static bool NotZero(this decimal @this) => !@this.Equals(0M); /// <summary></summary> public static bool NotZero(this double @this) => !@this.Equals(0D); /// <summary></summary> public static bool NotZero(this float @this) => !@this.Equals(0F); /// <summary>约束值范围,若源值不在范围中,则修改为接近的值。</summary> public static T RestrictValue<T>(this T @this, T min, T max) where T : IComparable => NumberUtility.RestrictValue<T>(@this, min, max); /// <summary></summary> [CLSCompliant(false)] public static Byte ToByte(this IConvertible @this) => @this.ToByte(null); /// <summary></summary> [CLSCompliant(false)] public static Int32 ToInt32(this IConvertible @this) => @this.ToInt32(null); /// <summary></summary> [CLSCompliant(false)] public static Int64 ToInt64(this IConvertible @this) => @this.ToInt64(null); /// <summary></summary> [CLSCompliant(false)] public static Double ToDouble(this IConvertible @this) => @this.ToDouble(null); /// <summary></summary> [CLSCompliant(false)] public static Decimal ToDecimal(this IConvertible @this) => @this.ToDecimal(null); #endregion #region String、StringBuilder /// <summary></summary> public static Int32 ToInt32(this string @this) => TextUtility.GetInt32(@this); /// <summary></summary> public static Int64 ToInt64(this string @this) => TextUtility.GetInt64(@this); /// <summary></summary> public static Decimal ToDecimal(this string @this) => TextUtility.GetDecimal(@this); /// <summary></summary> public static Double ToDouble(this string @this) => TextUtility.GetDouble(@this); /// <summary>将文本转换为字节数组,默认为 UTF-8。</summary> public static byte[] ToBinary(this string @this, Encoding encoding = null) => TextUtility.ToBinary(@this, encoding); /// <summary>验证字符串为 NULL、为空或仅含空白。</summary> public static bool IsEmpty(this string @this) => TextUtility.IsEmpty(@this); /// <summary>验证字符串为 NULL、为空或仅含空白。</summary> public static bool NotEmpty(this string @this) => TextUtility.NotEmpty(@this); /// <summary>验证字符串为 NULL、为空或无实际内容。</summary> /// <param name="this"></param> /// <param name="allCases">所有情况,包含全角。</param> public static bool IsBlank(this string @this, bool allCases = false) => TextUtility.IsBlank(@this, allCases); /// <summary>验证字符串含有实际内容。</summary> /// <param name="this"></param> /// <param name="allCases">所有情况,包含全角。</param> public static bool NotBlank(this string @this, bool allCases = false) => TextUtility.NotBlank(@this, allCases); /// <summary>将文本转换为字节数组,默认为 UTF-8。</summary> public static byte[] GetBytes(this string @this, Encoding encoding = null) => TextUtility.ToBinary(@this, encoding); /// <summary>用指定的分隔符拆分文本。</summary> public static string[] Split(this string @this, string separator) => TextUtility.Split(@this, separator); /// <summary>使用多个分隔符切分字符串,得到多个子字符串。</summary> public static string[] Split(this string @this, params char[] separators) => TextUtility.Split(@this, separators); /// <summary>返回此字符串的安全键副本。</summary> public static string SafeKey(this string @this, int maxLength = 255) => TextUtility.SafeKey(@this, maxLength); /// <summary>移除字符串前后的空白。</summary> public static string SafeTrim(this string @this) => TextUtility.Trim(@this); /// <summary>移除字符串前后的空白。</summary> /// <param name="this"></param> /// <param name="allCases">所有情况,全角空格将被去除。</param> public static string SafeTrim(this string @this, bool allCases) => TextUtility.Trim(@this, allCases); /// <summary>返回此字符串转换为小写形式的副本。</summary> public static string SafeLower(this string @this) => TextUtility.ToLower(@this); /// <summary>返回此字符串转换为大写形式的副本。</summary> public static string SafeUpper(this string @this) => TextUtility.ToUpper(@this); /// <summary>约束字符串用于 Key。</summary> public static string RestrictKey(this string @this) => TextUtility.RestrictGuid(TextUtility.ToLower(@this)); /// <summary>约束字符串长度范围,超出的部分将被截取去除。</summary> public static string RestrictLength(this string @this, int length) => TextModifier.RestrictLength(@this, length); /// <summary>约束字符串长度为 32,超出的部分将被截取去除。</summary> public static string Restrict32(this string @this) => TextModifier.RestrictLength(@this, 32); /// <summary>约束字符串长度为 255,超出的部分将被截取去除。</summary> public static string Restrict255(this string @this) => TextModifier.RestrictLength(@this, 255); /// <summary>约束字符串长度为 2000,超出的部分将被截取去除。</summary> public static string Restrict2000(this string @this) => TextModifier.RestrictLength(@this, 2000); /// <summary>追加字符串。</summary> public static string Append(this string @this, params object[] text) => TextUtility.Merge(@this, TextUtility.Merge(text)); /// <summary>追加文本。</summary> public static void Append(this StringBuilder @this, params object[] text) => TextUtility.Append(@this, text); /// <summary>防注入处理,去除会引发代码注入的字符。可限定字符串长度。</summary> public static string AntiInject(this string @this, int length = -1, string blacklist = null) => TextUtility.AntiInject(@this, length, blacklist); /// <summary>将 Base64 字符串转换为字节数组。</summary> public static byte[] AntiBase64(this string @this) => BinaryUtility.FromBase64(@this); /// <summary>对 URL 编码。</summary> public static string EncodeUrl(this string @this) => UrlEncoding.Encode(@this); /// <summary>对 URL 解码。</summary> public static string DecodeUrl(this string @this) => UrlEncoding.Decode(@this); #endregion #region Byte[] /// <summary>将字节数组格式化为大写十六进制字符串。<para>例:D41D8CD98F00B204E9800998ECF8427E</para></summary> public static string ToX2(this byte[] @this) => BinaryUtility.ToX2(@this); /// <summary>克隆字节数组。当源为 NULL 时,将获取零元素字节数组。</summary> public static byte[] Clone(this byte[] @this) => BinaryUtility.Clone(@this); /// <summary>确定此字节数组实例的开头是否与指定的字节数组匹配。</summary> public static bool StartsWith(this byte[] @this, params byte[] head) => BinaryUtility.StartsWith(@this, head); /// <summary>确定此字节数组实例的结尾是否与指定的字节数组匹配。</summary> public static bool EndsWith(this byte[] @this, params byte[] head) => BinaryUtility.EndsWith(@this, head); /// <summary>将字节数组转换为 Base64 字符串。</summary> public static string ToBase64(this byte[] @this) => BinaryUtility.ToBase64(@this); /// <summary>获取 MD5 值。</summary> public static byte[] GetMD5(params byte[] @this) => BinaryUtility.MD5(@this); /// <summary>获取 SHA1 值。</summary> public static byte[] GetSHA1(params byte[] @this) => BinaryUtility.SHA1(@this); #if !NET20 /// <summary>获取 SHA256 值。</summary> public static byte[] GetSHA256(params byte[] @this) => BinaryUtility.SHA256(@this); #endif /// <summary>将字节数组转换为文本,默认为 UTF-8。</summary> public static string GetString(this byte[] @this, Encoding encoding = null) => TextUtility.FromBinary(@this, encoding); /// <summary>将字节数组转换为文本,默认为 UTF-8。</summary> public static string ToText(this byte[] @this, Encoding encoding = null) => TextUtility.FromBinary(@this, encoding); /// <summary>为文本数据添加 BOM 字节,若已存在则忽略。</summary> public static byte[] AddTextBom(this byte[] @this) => BinaryUtility.AddTextBom(@this); /// <summary>去除文本数据的 BOM 字节,若不存在则忽略。</summary> public static byte[] WipeTextBom(this byte[] @this) => BinaryUtility.WipeTextBom(@this); /// <summary>为字节数组增加字节。</summary> public static byte[] Append(this byte[] @this, params byte[] bytes) => BinaryUtility.Append(@this, bytes); /// <summary>检查字节数组是 UTF-8 文本,默认最多检测 1MB 数据。</summary> /// <param name="bytes">要检查的字节数组。</param> /// <param name="checkLength">检查的最大字节长度,指定为 0 将不限制检查长度。</param> public static bool IsUTF8(this byte[] @this, int checkLength = 1048576) => BinaryUtility.IsUTF8(@this, checkLength, null); /// <summary>检查字节数组包含 UTF-8 BOM 头。</summary> public static bool ContainsBOM(this byte[] @this) => BinaryUtility.ContainsBOM(@this); #endregion #region DateTime /// <summary>获取毫秒时间戳。</summary> public static long GetStamp(this DateTime @this) => DateTimeUtility.GetStamp(@this); /// <summary>获取毫秒时间戳。</summary> public static long ToStamp(this DateTime @this) => DateTimeUtility.ToStamp(@this); /// <summary>转换为易于阅读的文本。</summary> public static string ToLucid(this DateTime @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => DateTimeUtility.ToLucid(@this, date, time, seconds, milliseconds); /// <summary>转换为紧凑的文本。</summary> public static string ToCompact(this DateTime @this, bool date = true, bool time = true, bool seconds = true, bool milliseconds = true) => DateTimeUtility.ToCompact(@this, date, time, seconds, milliseconds); /// <summary>当前 DateTime 为闰年。</summary> public static bool IsLeapYear(this DateTime @this) => DateTimeUtility.IsLeapYear(DateTimeUtility.GetDateTime(@this).Year); #endregion #region Json /// <summary>生成 JSON 对象,失败时返回 NULL。</summary> /// <param name="this">将要解析的对象。</param> /// <param name="lowerCase">在 Json 中将属性名称转换为小写。</param> /// <param name="depth">解析深度。</param> /// <param name="force">强制解析所有属性,忽略 Serializable 特性。</param> public static Json ToJson(this IDictionary @this, bool lowerCase = false, int depth = -1, bool force = false) => Json.Parse(@this, lowerCase, depth, force); /// <summary>解析实现 IList 的对象为 Json 对象,失败时返回 Null。</summary> /// <param name="this">将要解析的对象。</param> /// <param name="lowerCase">在 Json 中将属性名称转换为小写。</param> /// <param name="depth">解析深度。</param> /// <param name="force">强制解析所有属性,忽略 Serializable 特性。</param> public static Json ToJson(this IList @this, bool lowerCase = false, int depth = -1, bool force = false) => Json.Parse(@this, lowerCase, depth, force); /// <summary> /// <para>解析对象为 Json 对象,包含所有公共属性,失败时返回 Null。</para> /// <para>String 对象将解析文本;Json 对象将返回实例;String 对象将解析文本;实现 IDictionary 或 IList 的对象将解析内容。</para> /// </summary> /// <param name="this">将要解析的对象。</param> /// <param name="lowerCase">在 Json 中将属性名称转换为小写。</param> /// <param name="depth">解析深度。</param> /// <param name="force">强制解析所有属性,忽略 Serializable 特性。</param> /// <exception cref="System.Exception"></exception> public static Json ToJson(object @this, bool lowerCase = false, int depth = -1, bool force = false) => Json.Parse(@this, lowerCase, depth, force); /// <summary>填充类型实例,失败时返回 NULL 值。</summary> /// <param name="this">将要解析的对象。</param> /// <param name="ignoreCase">忽略属性名称大小写。</param> /// <param name="ignoreChars">忽略的属性名称字符。</param> /// <param name="force">强制填充,忽略 <typeparamref name="T"/> 的 Serializable 特性。</param> public static T FillObject<T>(this Json @this, bool ignoreCase = true, string ignoreChars = null, bool force = false) where T : class, new() => Json.FillObject<T>(@this, ignoreCase, ignoreChars, force); /// <summary>填充类型实例,失败时返回 NULL 值。</summary> /// <param name="this">将要解析的对象。</param> /// <param name="ignoreCase">忽略属性名称大小写。</param> /// <param name="ignoreChars">忽略的属性名称字符。</param> /// <param name="force">强制填充,忽略 <typeparamref name="T"/> 的 Serializable 特性。</param> public static List<T> FillArray<T>(this Json @this, bool ignoreCase = true, string ignoreChars = null, bool force = false) where T : class, new() => Json.FillArray<T>(@this, ignoreCase, ignoreChars, force); /// <summary>设置属性名称为小写。</summary> public static Json ToLower(this Json @this) => Json.ToLower(@this); #endregion #region Stream /// <summary>重置流的位置到开始位置。</summary> public static bool ResetPosition(this Stream @this) => StreamHelper.ResetPosition(@this); /// <summary>读取源流中的数据,并将数据写入目标流,获取写入的字节数。</summary> public static long Read(this Stream @this, Stream destination, Action<long> progress = null) => BinaryUtility.Read(@this, destination, progress); /// <summary>读取源流中的数据,获取写入的字节。</summary> public static byte[] Read(this Stream @this, bool dispose = false) => BinaryUtility.Read(@this, dispose); /// <summary>向流写入数据。</summary> /// <param name="this">源流。</param> /// <param name="bytes">要写入的数据。</param> public static long Write(this Stream @this, params byte[] bytes) => BinaryUtility.Write(@this, bytes); /// <summary>读取源流中的数据,并将数据写入当前流,获取写入的字节数。</summary> /// <param name="this">目标流。</param> /// <param name="source">源流。</param> public static long Write(this Stream @this, Stream source) => StreamHelper.Read(source, @this); /// <summary>获取 MD5 值。</summary> public static byte[] MD5(this Stream @this) => BinaryUtility.MD5(@this); /// <summary>获取 SHA1 值。</summary> public static byte[] SHA1(this Stream @this) => BinaryUtility.SHA1(@this); #if !NET20 /// <summary>获取 SHA256 值。</summary> public static byte[] SHA256(this Stream @this) => BinaryUtility.SHA256(@this); #endif #endregion #region Type /// <summary>判断指定类型具有特性。</summary> public static bool ContainsAttribute<T>(this Type @this, bool inherit = false) where T : Attribute => ClassUtility.ContainsAttribute<T>(@this, inherit); #endregion #region IEnumerable、Array、List、Dictionary /// <summary></summary> public static IList<T> Add<T>(this IList<T> @this, IEnumerable<T> items) { if (@this != null && items != null) { foreach (var item in items) @this.Add(item); } return @this; } /// <summary></summary> public static IList<T> Add<T>(this IList<T> @this, params T[] items) => Add<T>(@this, items as IEnumerable<T>); /// <summary></summary> public static bool IsEmpty<T>(this IEnumerable<T> @this) => ClassUtility.IsEmpty(@this); /// <summary></summary> public static bool NotEmpty<T>(this IEnumerable<T> @this) => ClassUtility.NotEmpty(@this); /// <summary></summary> public static bool Contains<T>(this IEnumerable<T> @this, T cell) => ClassUtility.Contains(@this, cell); /// <summary>获取集合中元素的数量。</summary> public static int Count<T>(this IEnumerable<T> @this) => ClassUtility.Count(@this); /// <summary>对元素去重,且去除 NULL 值。</summary> public static T[] Distinct<T>(this IEnumerable<T> @this) => ClassUtility.Distinct(@this); /// <summary></summary> public static List<T> Sub<T>(this IEnumerable<T> @this, long start = 0, long count = -1, Func<T> stuffer = null) => ClassUtility.Sub<T>(@this, start, count, stuffer); /// <summary>安全转换为 List<<typeparamref name="T"/>> 对象。可指定排除 NULL 值元素。</summary> /// <typeparam name="T"></typeparam> public static List<T> SafeList<T>(this IEnumerable<T> @this, bool excludeNull = false) => ClassUtility.ToList<T>(@this, excludeNull); /// <summary>升序排序。</summary> public static List<T> SortAscend<T>(this List<T> @this) where T : IComparable<T> => SortUtility.AscendT(@this); /// <summary>降序排序。</summary> public static List<T> SortDescend<T>(this List<T> @this) where T : IComparable<T> => SortUtility.DescendT<T>(@this); /// <summary>对 Key 排序。</summary> public static Dictionary<string, string> SortKey(this Dictionary<string, string> @this, bool ascend = true) => SortHelper.DictionaryStringString(@this, true, ascend); /// <summary>对 Value 排序。</summary> public static Dictionary<string, string> SortValue(this Dictionary<string, string> @this, bool ascend = true) => SortHelper.DictionaryStringString(@this, false, ascend); /// <summary>对 Key 排序。</summary> public static Dictionary<string, double> SortKey(this Dictionary<string, double> @this, bool ascend = true) => SortHelper.DictionaryStringDouble(@this, true, ascend); /// <summary>对 Value 排序。</summary> public static Dictionary<string, double> SortValue(this Dictionary<string, double> @this, bool ascend = true) => SortHelper.DictionaryStringDouble(@this, false, ascend); /// <summary>获取列表中的第一个 Item 对象。可指定失败时的默认返回值。</summary> public static T SafeFirst<T>(this IList<T> @this, T failed = default(T)) => (@this == null || @this.Count < 1) ? failed : @this[0]; /// <summary>添加元素。</summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="this"></param> /// <param name="key"></param> /// <param name="value"></param> public static bool Add<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> @this, TKey key, TValue value) { if (@this == null) return false; @this.Add(new KeyValuePair<TKey, TValue>(key, value)); return true; } #endregion #region Source /// <summary>为记录的 Key 属性设置新值。</summary> public static void SetNewKey(this Record @this) => Record.SetNewKey(@this); /// <summary>修补基本属性。</summary> public static void FixProperties(this Record @this) => Record.FixProperties(@this); /// <summary></summary> public static DateTime DateTime(this IQuery @this, int row, string column) => Query.DateTime(@this, row, column); /// <summary></summary> public static Int32 Int32(this IQuery @this, int row, string column) => @this == null ? 0 : ToInt32(@this.Text(row, column)); /// <summary></summary> public static Int64 Int64(this IQuery @this, int row, string column) => @this == null ? 0L : ToInt64(@this.Text(row, column)); /// <summary></summary> public static Decimal Decimal(this IQuery @this, int row, string column) => @this == null ? 0M : ToDecimal(@this.Text(row, column)); /// <summary></summary> public static Double Double(this IQuery @this, int row, string column) => @this == null ? 0D : ToDouble(@this.Text(row, column)); #endregion #region Web API #if NETFX /// <summary>获取查询字符串。</summary> public static string QueryString(this ApiRequest @this, string name, bool decode = false) => PageUtility.QueryString(name, decode); /// <summary>获取表单。</summary> public static string Form(this ApiRequest @this, string name) => PageUtility.RequestForm(name); #endif #if NETFX || NETCORE /// <summary>获取 URL 查询段,不存在的段为 NULL 值。可要求解码。</summary> public static string GetSegmentalUrl(this ApiRequest @this, int index = 3, bool decode = false) => WebUtility.GetSegmentalUrl(@this, index, decode); /// <summary>获取 URL 查询段,不存在的段为 NULL 值。可要求解码。</summary> public static string GetSegmental(this Uri @this, int index = 3, bool decode = false) => WebUtility.GetSegmental(@this, index, decode); /// <summary>获取参数,指定可能的参数名,从 URL 中获取参数时将解码。</summary> public static string GetParameter(this ApiRequest @this, params string[] names) => WebUtility.GetParameter(@this, names); /// <summary>设置 status 为 error,并设置 message 的内容。</summary> public static void Error(this ApiResponse @this, string message = "未知错误。") => ApiInternals.RespondError(@this, message); /// <summary>设置 status 为 error,并设置 message 的内容。</summary> public static void Error(this ApiResponse @this, Exception exception) => ApiInternals.RespondError(@this, exception); /// <summary>输出 UTF-8 文本。</summary> public static void Text(this ApiResponse @this, string content, string type = "text/plain") => ApiInternals.RespondText(@this, content, type); /// <summary>输出字节数组。</summary> public static void Binary(this ApiResponse @this, byte[] content, string type = "application/octet-stream") => ApiInternals.RespondBinary(@this, content, type); /// <summary>输出二进制。</summary> public static void Binary(this ApiResponse @this, Stream content, string type = "application/octet-stream") => ApiInternals.RespondBinary(@this, content, type); /// <summary>输出文件。</summary> public static void File(this ApiResponse @this, Stream stream, string name, string type = "application/octet-stream") => ApiInternals.RespondFile(@this, stream, name, type); /// <summary>重定向。</summary> public static void Redirect(this ApiResponse @this, string url) => ApiInternals.RespondRedirect(@this, url); /// <summary></summary> /// <typeparam name="T"></typeparam> /// <param name="this"></param> /// <returns></returns> public static T Use<T>(this ApiController @this) where T : ApiController, new() { var current = @this; var target = new T(); if (current != null) { target.Request = current.Request; target.Response = current.Response; target.AfterInitialized?.Invoke(); } return target; } /// <summary>设置响应,当发生错误时设置响应。返回错误信息。</summary> public static string Respond(this ApiResponse @this, IList list, bool lower = true, int depth = -1, bool force = false) => WebUtility.Respond(@this, list, lower, depth, force); /// <summary>设置响应,当发生错误时设置响应。返回错误信息。</summary> public static string Respond(this ApiResponse @this, Record record, bool lower = true) => WebUtility.Respond(@this, record, lower); #endif #endregion #region Surface #if NETFX || NETCORE /// <summary></summary> public static void Invoke(this Control @this, Action action, bool async = false) => FormsUtility.Invoke(@this, action, async); #endif #endregion }