添加项目文件。
This commit is contained in:
39
Hua.Dotnet.Code.sln
Normal file
39
Hua.Dotnet.Code.sln
Normal file
@@ -0,0 +1,39 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.36212.18
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{7FAF528A-A606-4558-9300-4E62DC6B36F1}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hua.DotNet.Code", "src\Hua.Dotnet.Code\Hua.DotNet.Code.csproj", "{2ADCA6AB-5E13-35AD-57F0-9C010636F1EC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hua.Dotnet.Code.Test", "test\Hua.Dotnet.Code.Test\Hua.Dotnet.Code.Test.csproj", "{B6421CF3-CB5F-89D4-C388-BD8E27089990}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{2ADCA6AB-5E13-35AD-57F0-9C010636F1EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2ADCA6AB-5E13-35AD-57F0-9C010636F1EC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2ADCA6AB-5E13-35AD-57F0-9C010636F1EC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2ADCA6AB-5E13-35AD-57F0-9C010636F1EC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B6421CF3-CB5F-89D4-C388-BD8E27089990}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B6421CF3-CB5F-89D4-C388-BD8E27089990}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B6421CF3-CB5F-89D4-C388-BD8E27089990}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B6421CF3-CB5F-89D4-C388-BD8E27089990}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{2ADCA6AB-5E13-35AD-57F0-9C010636F1EC} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{B6421CF3-CB5F-89D4-C388-BD8E27089990} = {7FAF528A-A606-4558-9300-4E62DC6B36F1}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {523CC539-A05F-4F3B-9833-E15A0AFF3584}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
720
src/Hua.Dotnet.Code/Extension/Ex.cs
Normal file
720
src/Hua.Dotnet.Code/Extension/Ex.cs
Normal file
@@ -0,0 +1,720 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Hua.DotNet.Code.Extension;
|
||||
|
||||
public static class Ex
|
||||
{
|
||||
private class ParameterRebinder : ExpressionVisitor
|
||||
{
|
||||
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
|
||||
|
||||
private ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
|
||||
{
|
||||
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
|
||||
}
|
||||
|
||||
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
|
||||
{
|
||||
return new ParameterRebinder(map).Visit(exp);
|
||||
}
|
||||
|
||||
protected override Expression VisitParameter(ParameterExpression p)
|
||||
{
|
||||
if (map.TryGetValue(p, out ParameterExpression value))
|
||||
{
|
||||
p = value;
|
||||
}
|
||||
return base.VisitParameter(p);
|
||||
}
|
||||
}
|
||||
|
||||
public static long ToLong(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return long.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
public static long ToLong(this string str, long defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return long.Parse(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static int ToInt(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Convert.ToInt32(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static int ToInt(this object? str, int defaultValue)
|
||||
{
|
||||
if (str == null)
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
try
|
||||
{
|
||||
return Convert.ToInt32(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static short ToShort(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return short.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static short ToShort(this object str, short defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return short.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static decimal ToDecimal(this object str, decimal defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return decimal.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static decimal ToDecimal(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return decimal.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool ToBool(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return bool.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool ToBool(this object str, bool result)
|
||||
{
|
||||
try
|
||||
{
|
||||
return bool.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static float ToFloat(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return float.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0f;
|
||||
}
|
||||
}
|
||||
|
||||
public static float ToFloat(this object str, float result)
|
||||
{
|
||||
try
|
||||
{
|
||||
return float.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static Guid ToGuid(this string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new Guid(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Guid.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime ToDateTime(this string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
if (str.Contains("-") || str.Contains("/"))
|
||||
{
|
||||
return DateTime.Parse(str);
|
||||
}
|
||||
return str.Length switch
|
||||
{
|
||||
4 => DateTime.ParseExact(str, "yyyy", CultureInfo.CurrentCulture),
|
||||
6 => DateTime.ParseExact(str, "yyyyMM", CultureInfo.CurrentCulture),
|
||||
8 => DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture),
|
||||
10 => DateTime.ParseExact(str, "yyyyMMddHH", CultureInfo.CurrentCulture),
|
||||
12 => DateTime.ParseExact(str, "yyyyMMddHHmm", CultureInfo.CurrentCulture),
|
||||
14 => DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.CurrentCulture),
|
||||
_ => DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.CurrentCulture),
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime ToDateTime(this string str, DateTime? defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
return defaultValue.GetValueOrDefault();
|
||||
}
|
||||
if (str.Contains("-") || str.Contains("/"))
|
||||
{
|
||||
return DateTime.Parse(str);
|
||||
}
|
||||
return str.Length switch
|
||||
{
|
||||
4 => DateTime.ParseExact(str, "yyyy", CultureInfo.CurrentCulture),
|
||||
6 => DateTime.ParseExact(str, "yyyyMM", CultureInfo.CurrentCulture),
|
||||
8 => DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture),
|
||||
10 => DateTime.ParseExact(str, "yyyyMMddHH", CultureInfo.CurrentCulture),
|
||||
12 => DateTime.ParseExact(str, "yyyyMMddHHmm", CultureInfo.CurrentCulture),
|
||||
14 => DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.CurrentCulture),
|
||||
_ => DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.CurrentCulture),
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue.GetValueOrDefault();
|
||||
}
|
||||
}
|
||||
|
||||
public static string ToString(this object? obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (obj == null) ? string.Empty : obj.ToString();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public static string ToStrings<T>(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (obj is IEnumerable<T> values)
|
||||
{
|
||||
return string.Join(",", values);
|
||||
}
|
||||
return obj.ToString();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public static double ToDouble(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return double.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
public static double ToDouble(this object str, double defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return double.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
|
||||
{
|
||||
return from object item in source
|
||||
select (TResult)Convert.ChangeType(item, typeof(TResult));
|
||||
}
|
||||
|
||||
public static string Description(this object obj)
|
||||
{
|
||||
object obj2 = obj;
|
||||
Type type = obj2.GetType();
|
||||
if (!type.IsEnum)
|
||||
{
|
||||
return type.GetCustomAttribute<DescriptionAttribute>()?.Description ?? type.Name;
|
||||
}
|
||||
return type.GetFields().First((FieldInfo m) => m.Name == Enum.GetName(type, obj2)).GetCustomAttribute<DescriptionAttribute>()?.Description ?? type.Name;
|
||||
}
|
||||
|
||||
public static string Description(this PropertyInfo value)
|
||||
{
|
||||
return value.GetCustomAttribute<DescriptionAttribute>()?.Description ?? value.Name;
|
||||
}
|
||||
|
||||
public static string? DisplayName(this Enum enumValue)
|
||||
{
|
||||
string name = enumValue.ToString();
|
||||
return enumValue.GetType().GetField(name)?.GetCustomAttribute<DisplayAttribute>()?.Name;
|
||||
}
|
||||
|
||||
public static string DisplayName(this object obj)
|
||||
{
|
||||
object obj2 = obj;
|
||||
Type type = obj2.GetType();
|
||||
if (!type.IsEnum)
|
||||
{
|
||||
return type.GetCustomAttribute<DisplayAttribute>()?.Name ?? type.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? type.Name;
|
||||
}
|
||||
return type.GetFields().First((FieldInfo m) => m.Name == Enum.GetName(type, obj2)).GetCustomAttribute<DisplayAttribute>()?.Name ?? type.Name;
|
||||
}
|
||||
|
||||
public static string DisplayName(this PropertyInfo value)
|
||||
{
|
||||
return value.GetCustomAttribute<DisplayAttribute>()?.Name ?? value.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? value.Name;
|
||||
}
|
||||
|
||||
public static Dictionary<int, string> Dictionary(this Type enumType)
|
||||
{
|
||||
Dictionary<int, string> dictionary = new Dictionary<int, string>();
|
||||
Type typeFromHandle = typeof(DescriptionAttribute);
|
||||
FieldInfo[] fields = enumType.GetFields();
|
||||
foreach (FieldInfo fieldInfo in fields)
|
||||
{
|
||||
if (fieldInfo.FieldType.IsEnum)
|
||||
{
|
||||
int key = (int)enumType.InvokeMember(fieldInfo.Name, BindingFlags.GetField, null, null, null);
|
||||
object[] customAttributes = fieldInfo.GetCustomAttributes(typeFromHandle, inherit: true);
|
||||
string value = ((customAttributes.Length == 0) ? fieldInfo.Name : ((DescriptionAttribute)customAttributes[0]).Description);
|
||||
dictionary.Add(key, value);
|
||||
}
|
||||
}
|
||||
return dictionary;
|
||||
}
|
||||
|
||||
public static Expression Property(this Expression expression, string propertyName)
|
||||
{
|
||||
return Expression.Property(expression, propertyName);
|
||||
}
|
||||
|
||||
public static Expression AndAlso(this Expression left, Expression right)
|
||||
{
|
||||
return Expression.AndAlso(left, right);
|
||||
}
|
||||
|
||||
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
|
||||
{
|
||||
return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
|
||||
}
|
||||
|
||||
public static Expression GreaterThan(this Expression left, Expression right)
|
||||
{
|
||||
return Expression.GreaterThan(left, right);
|
||||
}
|
||||
|
||||
public static Expression<T> ToLambda<T>(this Expression body, params ParameterExpression[] parameters)
|
||||
{
|
||||
return Expression.Lambda<T>(body, parameters);
|
||||
}
|
||||
|
||||
public static Expression<Func<T, bool>> True<T>()
|
||||
{
|
||||
return (T param) => true;
|
||||
}
|
||||
|
||||
public static Expression<Func<T, bool>> False<T>()
|
||||
{
|
||||
return (T param) => false;
|
||||
}
|
||||
|
||||
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
|
||||
{
|
||||
return first.Compose(second, Expression.AndAlso);
|
||||
}
|
||||
|
||||
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
|
||||
{
|
||||
return first.Compose(second, Expression.OrElse);
|
||||
}
|
||||
|
||||
private static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
|
||||
{
|
||||
Expression<T> second2 = second;
|
||||
Expression arg = ParameterRebinder.ReplaceParameters(first.Parameters.Select((ParameterExpression f, int i) => new
|
||||
{
|
||||
f = f,
|
||||
s = second2.Parameters[i]
|
||||
}).ToDictionary(p => p.s, p => p.f), second2.Body);
|
||||
return Expression.Lambda<T>(merge(first.Body, arg), first.Parameters);
|
||||
}
|
||||
|
||||
public static string ToSmallCamelCase(string name)
|
||||
{
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.Append(name.Substring(0, 1).ToLower());
|
||||
for (int i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
stringBuilder.Append(name.Substring(0, 1).ToLower());
|
||||
}
|
||||
else if (name[i] >= 'A' && name[i] <= 'Z')
|
||||
{
|
||||
stringBuilder.Append("_" + name.Substring(i, 1).ToLower());
|
||||
}
|
||||
else
|
||||
{
|
||||
stringBuilder.Append(name[i]);
|
||||
}
|
||||
}
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
public static string UnderScoreToCamelCase(this string underscore)
|
||||
{
|
||||
string[] array = underscore.Split('_');
|
||||
if (array.Length == 1)
|
||||
{
|
||||
return underscore;
|
||||
}
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.Append(array[0]);
|
||||
for (int i = 1; i < array.Length; i++)
|
||||
{
|
||||
stringBuilder.Append(array[i].FirstCharToUp());
|
||||
}
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
public static string FirstCharToUp(this string str)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
{
|
||||
return str.Substring(0, 1).ToUpper() + str.Substring(1, str.Length - 1);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public static string FirstCharToLower(this string str)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
{
|
||||
return str.Substring(0, 1).ToLower() + str.Substring(1, str.Length - 1);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public static string ConvertToPascal(this string fieldName, string fieldDelimiter)
|
||||
{
|
||||
string empty = string.Empty;
|
||||
if (fieldName.Contains(fieldDelimiter))
|
||||
{
|
||||
return fieldName.ToLower().Split(fieldDelimiter.ToCharArray()).Aggregate(empty, (string current, string t) => current + t.Substring(0, 1).ToUpper() + t.Substring(1, t.Length - 1));
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(fieldName))
|
||||
{
|
||||
return fieldName;
|
||||
}
|
||||
if (fieldName.Length == 1)
|
||||
{
|
||||
return fieldName.ToUpper();
|
||||
}
|
||||
if (fieldName.Length == fieldName.CountUpper())
|
||||
{
|
||||
return fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1, fieldName.Length - 1).ToLower();
|
||||
}
|
||||
return fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1, fieldName.Length - 1);
|
||||
}
|
||||
|
||||
public static string ConvertToCamel(this string fieldName, string fieldDelimiter)
|
||||
{
|
||||
string text = fieldName.ConvertToPascal(fieldDelimiter);
|
||||
if (text.Length == 1)
|
||||
{
|
||||
return text.ToLower();
|
||||
}
|
||||
return text.Substring(0, 1).ToLower() + text.Substring(1, text.Length - 1);
|
||||
}
|
||||
|
||||
public static string ToSbc(this string input)
|
||||
{
|
||||
char[] array = input.ToCharArray();
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
if (array[i] == ' ')
|
||||
{
|
||||
array[i] = '\u3000';
|
||||
}
|
||||
else if (array[i] < '\u007f')
|
||||
{
|
||||
array[i] = (char)(array[i] + 65248);
|
||||
}
|
||||
}
|
||||
return new string(array);
|
||||
}
|
||||
|
||||
public static string ToDbc(this string input)
|
||||
{
|
||||
char[] array = input.ToCharArray();
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
if (array[i] == '\u3000')
|
||||
{
|
||||
array[i] = ' ';
|
||||
}
|
||||
else if (array[i] > '\uff00' && array[i] < '⦅')
|
||||
{
|
||||
array[i] = (char)(array[i] - 65248);
|
||||
}
|
||||
}
|
||||
return new string(array);
|
||||
}
|
||||
|
||||
public static string HtmlToTxt(this string strHtml)
|
||||
{
|
||||
string[] obj = new string[15]
|
||||
{
|
||||
"<script[^>]*?>.*?</script>", "<(\\/\\srcStr*)?!?((\\w+:)?\\w+)(\\w+(\\srcStr*=?\\srcStr*(([\"'])(\\\\[\"'tbnr]|[^\\7])*?\\7|\\w+)|.{0})|\\srcStr)*?(\\/\\srcStr*)?>", "([\\r\\n])[\\srcStr]+", "&(quot|#34);", "&(amp|#38);", "&(lt|#60);", "&(gt|#62);", "&(nbsp|#160);", "&(iexcl|#161);", "&(cent|#162);",
|
||||
"&(pound|#163);", "&(copy|#169);", "&#(\\d+);", "-->", "<!--.*\\n"
|
||||
};
|
||||
_ = obj[0];
|
||||
return obj.Select((string t) => new Regex(t, RegexOptions.IgnoreCase)).Aggregate(strHtml, (string current, Regex regex) => regex.Replace(current, string.Empty)).Replace("<", "")
|
||||
.Replace(">", "")
|
||||
.Replace("\r\n", "");
|
||||
}
|
||||
|
||||
public static string Base64Encode(this string src)
|
||||
{
|
||||
return Convert.ToBase64String(Encoding.UTF8.GetBytes(src));
|
||||
}
|
||||
|
||||
public static string Base64DeCode(this string src)
|
||||
{
|
||||
byte[] bytes = Convert.FromBase64String(src);
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
public static bool HasChinese(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, "[\\u4e00-\\u9fa5]");
|
||||
}
|
||||
|
||||
public static string TrimStartStr(this string s, string searchStr)
|
||||
{
|
||||
string text = s;
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return text;
|
||||
}
|
||||
if (s.Length < searchStr.Length)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
if (s.IndexOf(searchStr, 0, searchStr.Length, StringComparison.Ordinal) > -1)
|
||||
{
|
||||
text = s.Substring(searchStr.Length, s.Length - searchStr.Length);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
public static string TrimEndStr(this string srcStr, string desStr)
|
||||
{
|
||||
return srcStr.Substring(0, srcStr.Length - desStr.Length);
|
||||
}
|
||||
|
||||
public static string ReplaceFirstStr(this string input, string oldValue, string? newValue)
|
||||
{
|
||||
return new Regex(oldValue, RegexOptions.Multiline).Replace(input, newValue ?? "", 1);
|
||||
}
|
||||
|
||||
public static List<string> GetSubStringList(this string oStr, char split)
|
||||
{
|
||||
return (from s in oStr.Split(split)
|
||||
where !string.IsNullOrEmpty(s) && s != split.ToString()
|
||||
select s).ToList();
|
||||
}
|
||||
|
||||
public static string[]? SplitMulti(this string str, string splitStr)
|
||||
{
|
||||
string[] result = null;
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
{
|
||||
result = new Regex(splitStr).Split(str);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string SubstringBetween(this string src, string startStr, string endStr)
|
||||
{
|
||||
string result = string.Empty;
|
||||
try
|
||||
{
|
||||
int num = src.IndexOf(startStr, StringComparison.Ordinal);
|
||||
if (num == -1)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
string text = src.Substring(num + startStr.Length);
|
||||
int num2 = text.IndexOf(endStr, StringComparison.Ordinal);
|
||||
if (num2 == -1)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
result = text.Remove(num2);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("MidStrEx Err:" + ex.Message);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static bool IsMatch(this string str, string express)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Regex regex = new Regex(express);
|
||||
if (str.Length != 0)
|
||||
{
|
||||
return regex.IsMatch(str);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsNullOrEmpty(this string str)
|
||||
{
|
||||
return string.IsNullOrEmpty(str);
|
||||
}
|
||||
|
||||
public static bool IsNullOrEmpty(object? data)
|
||||
{
|
||||
if (data == null || (data is string && string.IsNullOrEmpty(data.ToString().Trim())))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return data is DBNull;
|
||||
}
|
||||
|
||||
public static int CountUpper(this string str)
|
||||
{
|
||||
int num = 0;
|
||||
char[] array = str.ToCharArray();
|
||||
foreach (char c in array)
|
||||
{
|
||||
if (c >= 'A' && c <= 'Z')
|
||||
{
|
||||
num++;
|
||||
}
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
public static bool IsNullOrEmpty<T>(T t)
|
||||
{
|
||||
if (t == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (!(t is string))
|
||||
{
|
||||
return t is DBNull;
|
||||
}
|
||||
if (string.IsNullOrEmpty(t.ToString().Trim()))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return t is DBNull;
|
||||
}
|
||||
|
||||
public static List<PropertyInfo>? GetProperties<T>(this T t)
|
||||
{
|
||||
return t?.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
|
||||
}
|
||||
}
|
||||
21
src/Hua.Dotnet.Code/Helper/AssemblyHelper.cs
Normal file
21
src/Hua.Dotnet.Code/Helper/AssemblyHelper.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public static class AssemblyHelper
|
||||
{
|
||||
public static List<Assembly> GetAllAssembliesInFolder(string folderPath, SearchOption searchOption)
|
||||
{
|
||||
return (from s in Directory.EnumerateFiles(folderPath, "*.*", searchOption)
|
||||
where s.EndsWith(".dll") || s.EndsWith(".exe")
|
||||
select s).Select(Assembly.LoadFile).ToList();
|
||||
}
|
||||
|
||||
public static string? InformationalVersion(this Assembly assembly)
|
||||
{
|
||||
return assembly?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
}
|
||||
}
|
||||
134
src/Hua.Dotnet.Code/Helper/ComputerHelper.cs
Normal file
134
src/Hua.Dotnet.Code/Helper/ComputerHelper.cs
Normal file
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Hua.DotNet.Code.Extension;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class ComputerHelper
|
||||
{
|
||||
public static MemoryMetrics GetComputerInfo()
|
||||
{
|
||||
try
|
||||
{
|
||||
MemoryMetricsClient memoryMetricsClient = new MemoryMetricsClient();
|
||||
MemoryMetrics memoryMetrics = (IsUnix() ? memoryMetricsClient.GetUnixMetrics() : memoryMetricsClient.GetWindowsMetrics());
|
||||
memoryMetrics.FreeRam = Math.Round(memoryMetrics.Free / 1024.0, 2) + "GB";
|
||||
memoryMetrics.UsedRam = Math.Round(memoryMetrics.Used / 1024.0, 2) + "GB";
|
||||
memoryMetrics.TotalRAM = Math.Round(memoryMetrics.Total / 1024.0, 2) + "GB";
|
||||
memoryMetrics.RAMRate = Math.Ceiling(100.0 * memoryMetrics.Used / memoryMetrics.Total).ToString(CultureInfo.InvariantCulture) + "%";
|
||||
memoryMetrics.CPURate = Math.Ceiling(GetCPURate().ToDouble()) + "%";
|
||||
return memoryMetrics;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log("获取内存使用出错,msg=" + ex.Message + "," + ex.StackTrace);
|
||||
}
|
||||
return new MemoryMetrics();
|
||||
}
|
||||
|
||||
public static List<DiskInfo> GetDiskInfos()
|
||||
{
|
||||
List<DiskInfo> list = new List<DiskInfo>();
|
||||
if (IsUnix())
|
||||
{
|
||||
try
|
||||
{
|
||||
string[] array = ShellHelper.Bash("df -m / | awk '{print $2,$3,$4,$5,$6}'").Split('\n');
|
||||
if (array.Length == 0)
|
||||
{
|
||||
return list;
|
||||
}
|
||||
string[] array2 = array[1].Split(' ', '\u0001');
|
||||
if (array2.Length == 0)
|
||||
{
|
||||
return list;
|
||||
}
|
||||
DiskInfo item = new DiskInfo
|
||||
{
|
||||
DiskName = "/",
|
||||
TotalSize = long.Parse(array2[0]) / 1024,
|
||||
Used = long.Parse(array2[1]) / 1024,
|
||||
AvailableFreeSpace = long.Parse(array2[2]) / 1024,
|
||||
AvailablePercent = decimal.Parse(array2[3].Replace("%", ""))
|
||||
};
|
||||
list.Add(item);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log("获取磁盘信息出错了" + ex.Message);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
DriveInfo[] drives = DriveInfo.GetDrives();
|
||||
foreach (DriveInfo driveInfo in drives)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiskInfo diskInfo = new DiskInfo
|
||||
{
|
||||
DiskName = driveInfo.Name,
|
||||
TypeName = driveInfo.DriveType.ToString(),
|
||||
TotalSize = driveInfo.TotalSize / 1024 / 1024 / 1024,
|
||||
AvailableFreeSpace = driveInfo.AvailableFreeSpace / 1024 / 1024 / 1024
|
||||
};
|
||||
diskInfo.Used = diskInfo.TotalSize - diskInfo.AvailableFreeSpace;
|
||||
diskInfo.AvailablePercent = decimal.Ceiling((decimal)diskInfo.Used / (decimal)diskInfo.TotalSize * 100m);
|
||||
list.Add(diskInfo);
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
LogHelper.Log("获取磁盘信息出错了" + ex2.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static bool IsUnix()
|
||||
{
|
||||
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static string GetCPURate()
|
||||
{
|
||||
if (IsUnix())
|
||||
{
|
||||
return ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'").Trim();
|
||||
}
|
||||
return ShellHelper.Cmd("wmic", "cpu get LoadPercentage").Replace("LoadPercentage", string.Empty).Trim();
|
||||
}
|
||||
|
||||
public static string GetRunTime()
|
||||
{
|
||||
string result = string.Empty;
|
||||
try
|
||||
{
|
||||
if (IsUnix())
|
||||
{
|
||||
string str = ShellHelper.Bash("uptime -s").Trim();
|
||||
result = DateTimeHelper.FormatTime((DateTime.Now - str.ToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
|
||||
}
|
||||
else
|
||||
{
|
||||
string[] array = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value").Split('=', '\u0001');
|
||||
if (array.Length == 2)
|
||||
{
|
||||
result = DateTimeHelper.FormatTime((DateTime.Now - array[1].Split('.')[0].ToDateTime()).TotalMilliseconds.ToString(CultureInfo.InvariantCulture).Split('.')[0].ToLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log("获取runTime出错" + ex.Message);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
83
src/Hua.Dotnet.Code/Helper/DateTimeHelper.cs
Normal file
83
src/Hua.Dotnet.Code/Helper/DateTimeHelper.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public static class DateTimeHelper
|
||||
{
|
||||
public static DateTime GetBeginTime(DateTime? dateTime, int days = 0)
|
||||
{
|
||||
if (dateTime == DateTime.MinValue || !dateTime.HasValue)
|
||||
{
|
||||
return DateTime.Now.AddDays(days);
|
||||
}
|
||||
return dateTime ?? DateTime.Now;
|
||||
}
|
||||
|
||||
public static DateTime ToLocalTimeDateBySeconds(long unix)
|
||||
{
|
||||
return DateTimeOffset.FromUnixTimeSeconds(unix).ToLocalTime().DateTime;
|
||||
}
|
||||
|
||||
public static long ToUnixTimestampBySeconds(DateTime dt)
|
||||
{
|
||||
return new DateTimeOffset(dt).ToUnixTimeSeconds();
|
||||
}
|
||||
|
||||
public static DateTime ToLocalTimeDateByMilliseconds(long unix)
|
||||
{
|
||||
return DateTimeOffset.FromUnixTimeMilliseconds(unix).ToLocalTime().DateTime;
|
||||
}
|
||||
|
||||
public static long ToUnixTimestampByMilliseconds(DateTime dt)
|
||||
{
|
||||
return new DateTimeOffset(dt).ToUnixTimeMilliseconds();
|
||||
}
|
||||
|
||||
public static string FormatTime(long ms)
|
||||
{
|
||||
int num = 1000;
|
||||
int num2 = num * 60;
|
||||
int num3 = num2 * 60;
|
||||
int num4 = num3 * 24;
|
||||
long num5 = ms / num4;
|
||||
long num6 = (ms - num5 * num4) / num3;
|
||||
long num7 = (ms - num5 * num4 - num6 * num3) / num2;
|
||||
long num8 = (ms - num5 * num4 - num6 * num3 - num7 * num2) / num;
|
||||
long num9 = ms - num5 * num4 - num6 * num3 - num7 * num2 - num8 * num;
|
||||
string text = ((num5 < 10) ? ("0" + num5) : (num5.ToString() ?? ""));
|
||||
string text2 = ((num6 < 10) ? ("0" + num6) : (num6.ToString() ?? ""));
|
||||
string text3 = ((num7 < 10) ? ("0" + num7) : (num7.ToString() ?? ""));
|
||||
string text4 = ((num8 < 10) ? ("0" + num8) : (num8.ToString() ?? ""));
|
||||
string text5 = ((num9 < 10) ? ("0" + num9) : (num9.ToString() ?? ""));
|
||||
text5 = ((num9 < 100) ? ("0" + text5) : (text5 ?? ""));
|
||||
return $"{text} 天 {text2} 小时 {text3} 分 {text4} 秒";
|
||||
}
|
||||
|
||||
public static long GetUnixTimeStamp(DateTime dt)
|
||||
{
|
||||
return ((DateTimeOffset)dt).ToUnixTimeMilliseconds();
|
||||
}
|
||||
|
||||
public static DateTime GetDayMinDate(DateTime dt)
|
||||
{
|
||||
return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0);
|
||||
}
|
||||
|
||||
public static DateTime GetDayMaxDate(DateTime dt)
|
||||
{
|
||||
return new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 59);
|
||||
}
|
||||
|
||||
public static string FormatDateTime(DateTime? dt)
|
||||
{
|
||||
if (dt.HasValue)
|
||||
{
|
||||
if (dt.Value.Year == DateTime.Now.Year)
|
||||
{
|
||||
return dt.Value.ToString("MM-dd HH:mm");
|
||||
}
|
||||
return dt.Value.ToString("yyyy-MM-dd HH:mm");
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
18
src/Hua.Dotnet.Code/Helper/DiskInfo.cs
Normal file
18
src/Hua.Dotnet.Code/Helper/DiskInfo.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class DiskInfo
|
||||
{
|
||||
public string DiskName { get; set; }
|
||||
|
||||
public string TypeName { get; set; }
|
||||
|
||||
public long TotalFree { get; set; }
|
||||
|
||||
public long TotalSize { get; set; }
|
||||
|
||||
public long Used { get; set; }
|
||||
|
||||
public long AvailableFreeSpace { get; set; }
|
||||
|
||||
public decimal AvailablePercent { get; set; }
|
||||
}
|
||||
132
src/Hua.Dotnet.Code/Helper/FileHelper.cs
Normal file
132
src/Hua.Dotnet.Code/Helper/FileHelper.cs
Normal file
@@ -0,0 +1,132 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class FileHelper
|
||||
{
|
||||
public static string GetDirPath(string path = "")
|
||||
{
|
||||
string text = DateTime.Now.ToString("yyyyMMdd");
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
text = Path.Combine(path, text);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string HashFileName(string str = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
str = Guid.NewGuid().ToString();
|
||||
}
|
||||
return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(str)), 4, 8).Replace("-", "");
|
||||
}
|
||||
|
||||
public static void DeleteDirectory(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(file))
|
||||
{
|
||||
return;
|
||||
}
|
||||
new DirectoryInfo(file).Attributes = (FileAttributes)0;
|
||||
string[] fileSystemEntries = Directory.GetFileSystemEntries(file);
|
||||
foreach (string text in fileSystemEntries)
|
||||
{
|
||||
if (File.Exists(text))
|
||||
{
|
||||
File.SetAttributes(file, FileAttributes.Normal);
|
||||
File.Delete(text);
|
||||
}
|
||||
else
|
||||
{
|
||||
DeleteDirectory(text);
|
||||
}
|
||||
}
|
||||
Directory.Delete(file);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool ZipGenCode(string zipPath, string genCodePath, string zipFileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(zipPath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
CreateDirectory(genCodePath);
|
||||
string text = Path.Combine(zipPath, zipFileName);
|
||||
if (File.Exists(text))
|
||||
{
|
||||
File.Delete(text);
|
||||
}
|
||||
ZipFile.CreateFromDirectory(genCodePath, text);
|
||||
DeleteDirectory(genCodePath);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log("压缩文件出错。", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CreateDirectory(string path)
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
{
|
||||
path = path.Replace("\\", "/").Replace("//", "/");
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(path))
|
||||
{
|
||||
Directory.CreateDirectory(path);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log("创建文件夹出错了", ex.Message);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void WriteAndSave(string path, string content)
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
{
|
||||
path = path.Replace("\\", "/").Replace("//", "/");
|
||||
}
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path) ?? string.Empty);
|
||||
}
|
||||
LogHelper.Log("开始写入文件,Path=" + path);
|
||||
try
|
||||
{
|
||||
using FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
|
||||
using StreamWriter streamWriter = new StreamWriter(fileStream);
|
||||
streamWriter.Write(content);
|
||||
streamWriter.Flush();
|
||||
streamWriter.Close();
|
||||
fileStream.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Log("写入文件出错了:", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
177
src/Hua.Dotnet.Code/Helper/Html/HtmlHelper.cs
Normal file
177
src/Hua.Dotnet.Code/Helper/Html/HtmlHelper.cs
Normal file
@@ -0,0 +1,177 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper.Html;
|
||||
|
||||
public class HtmlHelper
|
||||
{
|
||||
private static readonly Regex paragraphStartRegex = new Regex("<p>", RegexOptions.IgnoreCase);
|
||||
|
||||
private static readonly Regex paragraphEndRegex = new Regex("</p>", RegexOptions.IgnoreCase);
|
||||
|
||||
private static string EnsureOnlyAllowedHtml(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
MatchCollection matchCollection = Regex.Matches(text, "<.*?>", RegexOptions.IgnoreCase);
|
||||
for (int num = matchCollection.Count - 1; num >= 0; num--)
|
||||
{
|
||||
if (!IsValidTag(text.Substring(matchCollection[num].Index + 1, matchCollection[num].Length - 1).Trim().ToLower(), "br,hr,b,i,u,a,div,ol,ul,li,blockquote,img,span,p,em,strong,font,pre,h1,h2,h3,h4,h5,h6,address,cite"))
|
||||
{
|
||||
text = text.Remove(matchCollection[num].Index, matchCollection[num].Length);
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
private static bool IsValidTag(string tag, string tags)
|
||||
{
|
||||
string[] array = tags.Split(',');
|
||||
if (tag.IndexOf("javascript") >= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (tag.IndexOf("vbscript") >= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (tag.IndexOf("onclick") >= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
char[] anyOf = new char[4] { ' ', '>', '/', '\t' };
|
||||
int num = tag.IndexOfAny(anyOf, 1);
|
||||
if (num > 0)
|
||||
{
|
||||
tag = tag.Substring(0, num);
|
||||
}
|
||||
if (tag[0] == '/')
|
||||
{
|
||||
tag = tag.Substring(1);
|
||||
}
|
||||
string[] array2 = array;
|
||||
foreach (string text in array2)
|
||||
{
|
||||
if (tag == text)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string FormatText(string text, bool stripTags, bool convertPlainTextToHtml, bool allowHtml, bool allowBBCode, bool resolveLinks, bool addNoFollowTag)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (stripTags)
|
||||
{
|
||||
text = StripTags(text);
|
||||
}
|
||||
text = ((!allowHtml) ? HttpUtility.HtmlEncode(text) : EnsureOnlyAllowedHtml(text));
|
||||
if (convertPlainTextToHtml)
|
||||
{
|
||||
text = ConvertPlainTextToHtml(text);
|
||||
}
|
||||
if (resolveLinks)
|
||||
{
|
||||
text = ResolveLinksHelper.FormatText(text);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
text = $"Text cannot be formatted. Error: {ex.Message}";
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string StripTags(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
text = Regex.Replace(text, "(>)(\\r|\\n)*(<)", "><");
|
||||
text = Regex.Replace(text, "(<[^>]*>)([^<]*)", "$2");
|
||||
text = Regex.Replace(text, "(&#x?[0-9]{2,4};|"|&| |<|>|€|©|®|‰|‡|†|‹|›|„|”|“|‚|’|‘|—|–|‏|‎|‍|‌| | | |˜|ˆ|Ÿ|š|Š)", "@");
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string ReplaceAnchorTags(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
text = Regex.Replace(text, "<a\\b[^>]+>([^<]*(?:(?!</a)<[^<]*)*)</a>", "$1", RegexOptions.IgnoreCase);
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string ConvertPlainTextToHtml(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
text = text.Replace("\r\n", "<br />");
|
||||
text = text.Replace("\r", "<br />");
|
||||
text = text.Replace("\n", "<br />");
|
||||
text = text.Replace("\t", " ");
|
||||
text = text.Replace(" ", " ");
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string ConvertHtmlToPlainText(string text, bool decode = false, bool replaceAnchorTags = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
if (decode)
|
||||
{
|
||||
text = HttpUtility.HtmlDecode(text);
|
||||
}
|
||||
text = text.Replace("<br>", "\n");
|
||||
text = text.Replace("<br >", "\n");
|
||||
text = text.Replace("<br />", "\n");
|
||||
text = text.Replace(" ", "\t");
|
||||
text = text.Replace(" ", " ");
|
||||
if (replaceAnchorTags)
|
||||
{
|
||||
text = ReplaceAnchorTags(text);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string ConvertPlainTextToParagraph(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
text = paragraphStartRegex.Replace(text, string.Empty);
|
||||
text = paragraphEndRegex.Replace(text, "\n");
|
||||
text = text.Replace("\r\n", "\n").Replace("\r", "\n");
|
||||
text += "\n\n";
|
||||
text = text.Replace("\n\n", "\n");
|
||||
string[] array = text.Split(new char[1] { '\n' });
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
string[] array2 = array;
|
||||
foreach (string text2 in array2)
|
||||
{
|
||||
if (text2 != null && text2.Trim().Length > 0)
|
||||
{
|
||||
stringBuilder.AppendFormat("<p>{0}</p>\n", text2);
|
||||
}
|
||||
}
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
}
|
||||
85
src/Hua.Dotnet.Code/Helper/Html/ResolveLinksHelper.cs
Normal file
85
src/Hua.Dotnet.Code/Helper/Html/ResolveLinksHelper.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper.Html;
|
||||
|
||||
public class ResolveLinksHelper
|
||||
{
|
||||
private static readonly Regex regex = new Regex("((http://|https://|www\\.)([A-Z0-9.\\-]{1,})\\.[0-9A-Z?;~&\\(\\)#,=\\-_\\./\\+]{2,})", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
private const string link = "<a href=\"{0}{1}\" rel=\"nofollow\">{2}</a>";
|
||||
|
||||
private const int MAX_LENGTH = 50;
|
||||
|
||||
private static string ShortenUrl(string url, int max)
|
||||
{
|
||||
if (url.Length <= max)
|
||||
{
|
||||
return url;
|
||||
}
|
||||
int num = url.IndexOf("://");
|
||||
if (num > -1)
|
||||
{
|
||||
url = url.Substring(num + 3);
|
||||
}
|
||||
if (url.Length <= max)
|
||||
{
|
||||
return url;
|
||||
}
|
||||
int num2 = url.IndexOf("/") + 1;
|
||||
int num3 = url.LastIndexOf("/");
|
||||
if (num2 < num3)
|
||||
{
|
||||
url = url.Remove(num2, num3 - num2);
|
||||
url = url.Insert(num2, "...");
|
||||
}
|
||||
if (url.Length <= max)
|
||||
{
|
||||
return url;
|
||||
}
|
||||
int num4 = url.IndexOf("?");
|
||||
if (num4 > -1)
|
||||
{
|
||||
url = url.Substring(0, num4);
|
||||
}
|
||||
if (url.Length <= max)
|
||||
{
|
||||
return url;
|
||||
}
|
||||
int num5 = url.IndexOf("#");
|
||||
if (num5 > -1)
|
||||
{
|
||||
url = url.Substring(0, num5);
|
||||
}
|
||||
if (url.Length <= max)
|
||||
{
|
||||
return url;
|
||||
}
|
||||
num2 = url.LastIndexOf("/") + 1;
|
||||
num3 = url.LastIndexOf(".");
|
||||
if (num3 - num2 > 10)
|
||||
{
|
||||
string text = url.Substring(num2, num3 - num2);
|
||||
int num6 = url.Length - max + 3;
|
||||
if (text.Length > num6)
|
||||
{
|
||||
url = url.Replace(text, "..." + text.Substring(num6));
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
public static string FormatText(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
CultureInfo invariantCulture = CultureInfo.InvariantCulture;
|
||||
foreach (Match item in regex.Matches(text))
|
||||
{
|
||||
text = (item.Value.Contains("://") ? text.Replace(item.Value, string.Format(invariantCulture, "<a href=\"{0}{1}\" rel=\"nofollow\">{2}</a>", string.Empty, item.Value, ShortenUrl(item.Value, 50))) : text.Replace(item.Value, string.Format(invariantCulture, "<a href=\"{0}{1}\" rel=\"nofollow\">{2}</a>", "http://", item.Value, ShortenUrl(item.Value, 50))));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
138
src/Hua.Dotnet.Code/Helper/Http/HttpClientHelper.cs
Normal file
138
src/Hua.Dotnet.Code/Helper/Http/HttpClientHelper.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper.Http;
|
||||
|
||||
public class HttpClientHelper : IHttpHelper
|
||||
{
|
||||
private readonly ILogger<HttpClientHelper> _logger;
|
||||
|
||||
public HttpClientHandler Handler { get; set; }
|
||||
|
||||
public Dictionary<string, string> Headers { get; set; }
|
||||
|
||||
public HttpClientHelper(ILogger<HttpClientHelper> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public virtual HttpClient GetHttpClient()
|
||||
{
|
||||
HttpClient httpClient = ((Handler == null) ? new HttpClient() : new HttpClient(Handler));
|
||||
if (Headers == null)
|
||||
{
|
||||
return httpClient;
|
||||
}
|
||||
foreach (KeyValuePair<string, string> header in Headers)
|
||||
{
|
||||
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public TOut? Get<TOut>(string url, int timeOut = 10)
|
||||
{
|
||||
return GetAsync<TOut>(url, timeOut).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public TOut? Post<TIn, TOut>(string url, TIn input, int timeOut = 3)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpClient httpClient = GetHttpClient();
|
||||
httpClient.Timeout = new TimeSpan(0, 0, timeOut);
|
||||
_logger.LogInformation("Post:" + url + "\n[" + JsonConvert.SerializeObject((object)input) + "]");
|
||||
HttpResponseMessage result = httpClient.PostAsync(url, JsonContent.Create(input)).GetAwaiter().GetResult();
|
||||
string result2 = Task.FromResult(result.Content.ReadAsStringAsync()).Result.Result;
|
||||
_logger.LogInformation(result2);
|
||||
if (result.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogError($"Error[{result.StatusCode}]:{url}\t{result2}");
|
||||
}
|
||||
return result.Content.ReadFromJsonAsync<TOut>().Result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(url);
|
||||
_logger.LogError(ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<TOut?> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 3, CancellationToken? cts = null) where TIn : class where TOut : class
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpClient httpClient = GetHttpClient();
|
||||
httpClient.Timeout = new TimeSpan(0, 0, timeOut);
|
||||
_logger.LogInformation("Post:" + url + "\n[" + JsonConvert.SerializeObject((object)input) + "]");
|
||||
HttpResponseMessage result = await httpClient.PostAsync(url, JsonContent.Create(input));
|
||||
string text = await result.Content.ReadAsStringAsync();
|
||||
_logger.LogInformation(text);
|
||||
if (result.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogError($"Error[{result.StatusCode}]:{url}\t{text}");
|
||||
}
|
||||
return await result.Content.ReadFromJsonAsync<TOut>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(url);
|
||||
_logger.LogError(ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10,CancellationToken? cts = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpClient httpClient = GetHttpClient();
|
||||
httpClient.Timeout = new TimeSpan(0, 10, timeOut);
|
||||
_logger.LogDebug("Get:" + url);
|
||||
HttpResponseMessage result = await httpClient.GetAsync(url);
|
||||
string arg = await result.Content.ReadAsStringAsync();
|
||||
if (result.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogDebug($"Error[{result.StatusCode}]:{url}\t{arg}");
|
||||
}
|
||||
return await result.Content.ReadFromJsonAsync<TOut>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(url);
|
||||
_logger.LogError(ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public bool DownloadFile(string url, string localPath)
|
||||
{
|
||||
ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true;
|
||||
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
|
||||
Stream stream = new FileStream(localPath, FileMode.CreateNew);
|
||||
try
|
||||
{
|
||||
Stream obj = (httpWebRequest?.GetResponse() as HttpWebResponse)?.GetResponseStream();
|
||||
stream.Close();
|
||||
obj?.Close();
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
19
src/Hua.Dotnet.Code/Helper/Http/IHttpHelper.cs
Normal file
19
src/Hua.Dotnet.Code/Helper/Http/IHttpHelper.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper.Http;
|
||||
|
||||
public interface IHttpHelper
|
||||
{
|
||||
HttpClientHandler Handler { get; set; }
|
||||
|
||||
Dictionary<string, string> Headers { get; set; }
|
||||
|
||||
Task<TOut?> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 10,CancellationToken? cts = null) where TIn : class where TOut : class;
|
||||
|
||||
Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10, CancellationToken? cts = null);
|
||||
|
||||
bool DownloadFile(string url, string fileFullName);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using RestSharp;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper.Http
|
||||
{
|
||||
public class RestClientHttpHelperTests
|
||||
{
|
||||
[Test]
|
||||
public void DownloadFile_ShouldReturnTrue_WhenDownloadSucceeds()
|
||||
{
|
||||
// Arrange
|
||||
var loggerMock = new Mock<ILogger<RestClientHttpHelper>>();
|
||||
var helper = new RestClientHttpHelper(loggerMock.Object);
|
||||
var testUrl = "https://example.com/testfile.txt";
|
||||
var testFilePath = Path.GetTempFileName();
|
||||
|
||||
var restClientMock = new Mock<RestClient>();
|
||||
var responseData = System.Text.Encoding.UTF8.GetBytes("Test content");
|
||||
restClientMock.Setup(c => c.DownloadData(It.IsAny<RestRequest>())).Returns(responseData);
|
||||
|
||||
var type = helper.GetType();
|
||||
var getHttpClientMethod = type.GetMethod("GetHttpClient", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
|
||||
var mockGetter = new Func<RestClient>(() => restClientMock.Object);
|
||||
|
||||
var mockMethod = mockGetter.Method;
|
||||
var mockInstance = mockGetter.Target;
|
||||
|
||||
var proxy = new DynamicProxy(helper, getHttpClientMethod, mockMethod, mockInstance);
|
||||
|
||||
// Act
|
||||
var result = helper.DownloadFile(testUrl, testFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.True);
|
||||
Assert.That(File.Exists(testFilePath), Is.True);
|
||||
File.Delete(testFilePath);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DownloadFile_ShouldReturnFalse_WhenDownloadFails()
|
||||
{
|
||||
// Arrange
|
||||
var loggerMock = new Mock<ILogger<RestClientHttpHelper>>();
|
||||
var helper = new RestClientHttpHelper(loggerMock.Object);
|
||||
var testUrl = "https://example.com/nonexistentfile.txt";
|
||||
var testFilePath = Path.GetTempFileName();
|
||||
|
||||
var restClientMock = new Mock<RestClient>();
|
||||
restClientMock.Setup(c => c.DownloadData(It.IsAny<RestRequest>())).Returns((byte[])null);
|
||||
|
||||
var type = helper.GetType();
|
||||
var getHttpClientMethod = type.GetMethod("GetHttpClient", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
|
||||
var mockGetter = new Func<RestClient>(() => restClientMock.Object);
|
||||
|
||||
var mockMethod = mockGetter.Method;
|
||||
var mockInstance = mockGetter.Target;
|
||||
|
||||
var proxy = new DynamicProxy(helper, getHttpClientMethod, mockMethod, mockInstance);
|
||||
|
||||
// Act
|
||||
var result = helper.DownloadFile(testUrl, testFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.False);
|
||||
Assert.That(File.Exists(testFilePath), Is.False);
|
||||
}
|
||||
}
|
||||
|
||||
public class DynamicProxy
|
||||
{
|
||||
private readonly object _target;
|
||||
private readonly System.Reflection.MethodInfo _originalMethod;
|
||||
private readonly System.Reflection.MethodInfo _mockMethod;
|
||||
private readonly object _mockInstance;
|
||||
|
||||
public DynamicProxy(object target, System.Reflection.MethodInfo originalMethod, System.Reflection.MethodInfo mockMethod, object mockInstance)
|
||||
{
|
||||
_target = target;
|
||||
_originalMethod = originalMethod;
|
||||
_mockMethod = mockMethod;
|
||||
_mockInstance = mockInstance;
|
||||
}
|
||||
|
||||
public object Invoke(object[] parameters)
|
||||
{
|
||||
return _mockMethod.Invoke(_mockInstance, parameters);
|
||||
}
|
||||
}
|
||||
}
|
||||
93
src/Hua.Dotnet.Code/Helper/Http/RestClientHttpHelper.cs
Normal file
93
src/Hua.Dotnet.Code/Helper/Http/RestClientHttpHelper.cs
Normal file
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using RestSharp;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper.Http;
|
||||
|
||||
public class RestClientHttpHelper : IHttpHelper
|
||||
{
|
||||
private ILogger<RestClientHttpHelper> _logger;
|
||||
|
||||
public HttpClientHandler Handler { get; set; }
|
||||
|
||||
public Dictionary<string, string> Headers { get; set; }
|
||||
|
||||
public RestClientHttpHelper(ILogger<RestClientHttpHelper> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected virtual RestClient GetHttpClient()
|
||||
{
|
||||
var val = ((Handler == null) ? new RestClient() : new RestClient((HttpMessageHandler)Handler, true));
|
||||
if (Headers == null)
|
||||
{
|
||||
return val;
|
||||
}
|
||||
foreach (KeyValuePair<string, string> header in Headers)
|
||||
{
|
||||
val.AddDefaultHeader(header.Key, header.Value);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
public async Task<TOut> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 10, CancellationToken? cts = null) where TIn : class where TOut : class
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = GetHttpClient();
|
||||
var request = new RestRequest(url, Method.Post).AddJsonBody<TIn>(input, "application/json");
|
||||
request.Timeout = TimeSpan.FromSeconds(timeOut);
|
||||
await client.PostAsync(request, cts ?? CancellationToken.None);
|
||||
return await client.PostAsync<TOut>(request, cts??CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(url);
|
||||
_logger.LogError(ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10, CancellationToken? cts = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
using RestClient httpClient = GetHttpClient();
|
||||
var val = new RestRequest(url,Method.Get);
|
||||
return await httpClient.GetAsync<TOut>(val, cts ?? CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(url);
|
||||
_logger.LogError(ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public bool DownloadFile(string url, string fileFullName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = GetHttpClient();
|
||||
var request = new RestRequest(url, Method.Get);
|
||||
var response = client.DownloadData(request);
|
||||
if (response != null)
|
||||
{
|
||||
System.IO.File.WriteAllBytes(fileFullName, response);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("下载文件失败: {0}", ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/Hua.Dotnet.Code/Helper/LogHelper.cs
Normal file
39
src/Hua.Dotnet.Code/Helper/LogHelper.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class LogHelper
|
||||
{
|
||||
private static string LogFileName => $"Log{DateTime.Now:yyyy_MM_dd}.log";
|
||||
|
||||
public static void Log(string title)
|
||||
{
|
||||
Log(title, string.Empty);
|
||||
}
|
||||
|
||||
public static void Log(Exception e)
|
||||
{
|
||||
Log(e.Message, e.StackTrace);
|
||||
}
|
||||
|
||||
public static void Log<T>(string title)
|
||||
{
|
||||
Log<T>(title, string.Empty);
|
||||
}
|
||||
|
||||
public static void Log<T>(string title, string? msg)
|
||||
{
|
||||
Log(title, typeof(T).FullName + " \t " + msg);
|
||||
}
|
||||
|
||||
public static void Log(string title, string? msg)
|
||||
{
|
||||
using FileStream fileStream = new FileStream(LogFileName, FileMode.OpenOrCreate);
|
||||
TextWriterTraceListener textWriterTraceListener = new TextWriterTraceListener(fileStream);
|
||||
textWriterTraceListener.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:FFF}\t [{title}]\t{msg}");
|
||||
textWriterTraceListener.Close();
|
||||
fileStream.Close();
|
||||
}
|
||||
}
|
||||
52
src/Hua.Dotnet.Code/Helper/Md5Helper.cs
Normal file
52
src/Hua.Dotnet.Code/Helper/Md5Helper.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public static class Md5Helper
|
||||
{
|
||||
public static string EnCode(string text)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(text))
|
||||
{
|
||||
return EnCode(Encoding.Unicode.GetBytes(text));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string EnCode(byte[] data)
|
||||
{
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
try
|
||||
{
|
||||
MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider();
|
||||
byte[] inArray = mD5CryptoServiceProvider.ComputeHash(data);
|
||||
mD5CryptoServiceProvider.Clear();
|
||||
return Convert.ToBase64String(inArray);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static string Md5Sum(string text)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(text))
|
||||
{
|
||||
return Md5Sum(Encoding.UTF8.GetBytes(text));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string Md5Sum(byte[] bs)
|
||||
{
|
||||
return MD5.Create().ComputeHash(bs).Aggregate("", (string current, byte t) => current + Convert.ToString(t, 16).PadLeft(2, '0'))
|
||||
.PadLeft(32, '0');
|
||||
}
|
||||
}
|
||||
25
src/Hua.Dotnet.Code/Helper/MemoryMetrics.cs
Normal file
25
src/Hua.Dotnet.Code/Helper/MemoryMetrics.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class MemoryMetrics
|
||||
{
|
||||
[JsonIgnore]
|
||||
public double Total { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public double Used { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public double Free { get; set; }
|
||||
|
||||
public string UsedRam { get; set; }
|
||||
|
||||
public string CPURate { get; set; }
|
||||
|
||||
public string TotalRAM { get; set; }
|
||||
|
||||
public string RAMRate { get; set; }
|
||||
|
||||
public string FreeRam { get; set; }
|
||||
}
|
||||
47
src/Hua.Dotnet.Code/Helper/MemoryMetricsClient.cs
Normal file
47
src/Hua.Dotnet.Code/Helper/MemoryMetricsClient.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class MemoryMetricsClient
|
||||
{
|
||||
public MemoryMetrics GetWindowsMetrics()
|
||||
{
|
||||
string text = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
|
||||
MemoryMetrics memoryMetrics = new MemoryMetrics();
|
||||
string[] array = text.Trim().Split('\n', '\u0001');
|
||||
if (array.Length == 0)
|
||||
{
|
||||
return memoryMetrics;
|
||||
}
|
||||
string[] array2 = array[0].Split('=', '\u0001');
|
||||
string[] array3 = array[1].Split('=', '\u0001');
|
||||
memoryMetrics.Total = Math.Round(double.Parse(array3[1]) / 1024.0, 0);
|
||||
memoryMetrics.Free = Math.Round(double.Parse(array2[1]) / 1024.0, 0);
|
||||
memoryMetrics.Used = memoryMetrics.Total - memoryMetrics.Free;
|
||||
return memoryMetrics;
|
||||
}
|
||||
|
||||
public MemoryMetrics GetUnixMetrics()
|
||||
{
|
||||
string text = ShellHelper.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
|
||||
MemoryMetrics memoryMetrics = new MemoryMetrics();
|
||||
string[] array = text.Split('\n', '\u0001');
|
||||
if (array.Length == 0)
|
||||
{
|
||||
return memoryMetrics;
|
||||
}
|
||||
if (array.Length == 0)
|
||||
{
|
||||
return memoryMetrics;
|
||||
}
|
||||
string[] array2 = array[1].Split(' ', '\u0001');
|
||||
if (array2.Length < 3)
|
||||
{
|
||||
return memoryMetrics;
|
||||
}
|
||||
memoryMetrics.Total = double.Parse(array2[0]);
|
||||
memoryMetrics.Used = double.Parse(array2[1]);
|
||||
memoryMetrics.Free = double.Parse(array2[2]);
|
||||
return memoryMetrics;
|
||||
}
|
||||
}
|
||||
36
src/Hua.Dotnet.Code/Helper/RsaHelper.cs
Normal file
36
src/Hua.Dotnet.Code/Helper/RsaHelper.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public class RsaHelper
|
||||
{
|
||||
private static RSA? _Rsa;
|
||||
|
||||
private static void InitRsa()
|
||||
{
|
||||
if (_Rsa == null)
|
||||
{
|
||||
_Rsa = RSA.Create();
|
||||
}
|
||||
}
|
||||
|
||||
public static string Encrypt(string str)
|
||||
{
|
||||
InitRsa();
|
||||
return Convert.ToBase64String(_Rsa.Encrypt(Encoding.UTF8.GetBytes(str), RSAEncryptionPadding.Pkcs1));
|
||||
}
|
||||
|
||||
public static string Decrypt(string enStr)
|
||||
{
|
||||
InitRsa();
|
||||
return Encoding.UTF8.GetString(_Rsa.Decrypt(Convert.FromBase64String(enStr), RSAEncryptionPadding.Pkcs1));
|
||||
}
|
||||
|
||||
public static string PublicKey()
|
||||
{
|
||||
InitRsa();
|
||||
return _Rsa.ToXmlString(includePrivateParameters: false);
|
||||
}
|
||||
}
|
||||
36
src/Hua.Dotnet.Code/Helper/ShellHelper.cs
Normal file
36
src/Hua.Dotnet.Code/Helper/ShellHelper.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Hua.DotNet.Code.Helper;
|
||||
|
||||
public static class ShellHelper
|
||||
{
|
||||
public static string Bash(string command)
|
||||
{
|
||||
string text = command.Replace("\"", "\\\"");
|
||||
Process process = new Process();
|
||||
process.StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = "/bin/bash",
|
||||
Arguments = "-c \"" + text + "\"",
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
process.Start();
|
||||
string result = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
process.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Cmd(string fileName, string args)
|
||||
{
|
||||
using Process process = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
RedirectStandardOutput = true
|
||||
});
|
||||
return process.StandardOutput.ReadToEnd();
|
||||
}
|
||||
}
|
||||
27
src/Hua.Dotnet.Code/Hua.DotNet.Code.csproj
Normal file
27
src/Hua.Dotnet.Code/Hua.DotNet.Code.csproj
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>Hua.DotNet.Code</AssemblyName>
|
||||
<GenerateAssemblyInfo>False</GenerateAssemblyInfo>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<LangVersion>11.0</LangVersion>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup />
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.6" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="RestSharp" Version="112.1.0" />
|
||||
<PackageReference Include="System.Net.Http.Json" Version="9.0.6" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NUnit" Version="4.3.2" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="4.9.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="Properties\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
24
test/Hua.Dotnet.Code.Test/Hua.Dotnet.Code.Test.csproj
Normal file
24
test/Hua.Dotnet.Code.Test/Hua.Dotnet.Code.Test.csproj
Normal file
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="NUnit" Version="3.14.0" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="NUnit.Framework" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
16
test/Hua.Dotnet.Code.Test/UnitTest1.cs
Normal file
16
test/Hua.Dotnet.Code.Test/UnitTest1.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace Hua.Dotnet.Code.Test
|
||||
{
|
||||
public class Tests
|
||||
{
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test1()
|
||||
{
|
||||
Assert.Pass();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user