0.1.5找回添加 .gitattributes 和 .gitignore。

This commit is contained in:
2025-06-24 11:33:16 +08:00
commit f4acbffd32
21 changed files with 2311 additions and 0 deletions
+21
View 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
View 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
View 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
View 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
View 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
View 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};|&quot;|&amp;|&nbsp;|&lt;|&gt;|&euro;|&copy;|&reg;|&permil;|&Dagger;|&dagger;|&lsaquo;|&rsaquo;|&bdquo;|&rdquo;|&ldquo;|&sbquo;|&rsquo;|&lsquo;|&mdash;|&ndash;|&rlm;|&lrm;|&zwj;|&zwnj;|&thinsp;|&emsp;|&ensp;|&tilde;|&circ;|&Yuml;|&scaron;|&Scaron;)", "@");
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", "&nbsp;&nbsp;");
text = text.Replace(" ", "&nbsp;&nbsp;");
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("&nbsp;&nbsp;", "\t");
text = text.Replace("&nbsp;&nbsp;", " ");
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
View 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;
}
}
+137
View File
@@ -0,0 +1,137 @@
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.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) where TIn : class where TOut : class
{
_ = 2;
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)
{
_ = 2;
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;
}
}
}
+18
View File
@@ -0,0 +1,18 @@
using System.Collections.Generic;
using System.Net.Http;
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) where TIn : class where TOut : class;
Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10);
bool DownloadFile(string url, string fileFullName);
}
+79
View File
@@ -0,0 +1,79 @@
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;
}
public virtual RestClient GetHttpClient()
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Expected O, but got Unknown
RestClient val = ((Handler == null) ? new RestClient() : new RestClient((HttpMessageHandler)Handler, true));
if (Headers == null)
{
return val;
}
foreach (KeyValuePair<string, string> header in Headers)
{
RestClientExtensions.AddDefaultHeader(val, header.Key, header.Value);
}
return val;
}
public async Task<TOut> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 10) where TIn : class where TOut : class
{
try
{
RestClient client = GetHttpClient();
RestRequest request = RestRequestExtensions.AddJsonBody<TIn>(new RestRequest(url, (Method)0), input, "application/json");
request.Timeout = TimeSpan.FromSeconds(timeOut);
await RestClientExtensions.PostAsync(client, request, CancellationToken.None);
return await RestClientExtensions.PostAsync<TOut>(client, request, default(CancellationToken));
}
catch (Exception ex)
{
_logger.LogError(url);
_logger.LogError(ex.Message);
throw ex;
}
}
public async Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10)
{
try
{
RestClient httpClient = GetHttpClient();
RestRequest val = new RestRequest(url, (Method)0);
return await RestClientExtensions.GetAsync<TOut>(httpClient, val, default(CancellationToken));
}
catch (Exception ex)
{
_logger.LogError(url);
_logger.LogError(ex.Message);
throw ex;
}
}
public bool DownloadFile(string url, string fileFullName)
{
throw new NotImplementedException();
}
}
+39
View 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
View 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
View 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
View 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
View 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
View 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();
}
}