0.1.5找回添加 .gitattributes 和 .gitignore。
This commit is contained in:
63
.gitattributes
vendored
Normal file
63
.gitattributes
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
363
.gitignore
vendored
Normal file
363
.gitignore
vendored
Normal file
@@ -0,0 +1,363 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Oo]ut/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
720
Extension/Ex.cs
Normal file
720
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
Helper/AssemblyHelper.cs
Normal file
21
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
Helper/ComputerHelper.cs
Normal file
134
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
Helper/DateTimeHelper.cs
Normal file
83
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
Helper/DiskInfo.cs
Normal file
18
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
Helper/FileHelper.cs
Normal file
132
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
Helper/Html/HtmlHelper.cs
Normal file
177
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
Helper/Html/ResolveLinksHelper.cs
Normal file
85
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;
|
||||
}
|
||||
}
|
||||
137
Helper/Http/HttpClientHelper.cs
Normal file
137
Helper/Http/HttpClientHelper.cs
Normal 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
Helper/Http/IHttpHelper.cs
Normal file
18
Helper/Http/IHttpHelper.cs
Normal 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
Helper/Http/RestClientHttpHelper.cs
Normal file
79
Helper/Http/RestClientHttpHelper.cs
Normal 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
Helper/LogHelper.cs
Normal file
39
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
Helper/Md5Helper.cs
Normal file
52
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
Helper/MemoryMetrics.cs
Normal file
25
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
Helper/MemoryMetricsClient.cs
Normal file
47
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
Helper/RsaHelper.cs
Normal file
36
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
Helper/ShellHelper.cs
Normal file
36
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();
|
||||
}
|
||||
}
|
||||
21
Hua.DotNet.Code.csproj
Normal file
21
Hua.DotNet.Code.csproj
Normal file
@@ -0,0 +1,21 @@
|
||||
<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" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="Properties\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
25
Hua.Dotnet.Code.sln
Normal file
25
Hua.Dotnet.Code.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.36212.18
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hua.DotNet.Code", "Hua.DotNet.Code.csproj", "{839E442B-62EA-1AA3-8675-66245AF23185}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{839E442B-62EA-1AA3-8675-66245AF23185}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{839E442B-62EA-1AA3-8675-66245AF23185}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{839E442B-62EA-1AA3-8675-66245AF23185}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{839E442B-62EA-1AA3-8675-66245AF23185}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {523CC539-A05F-4F3B-9833-E15A0AFF3584}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
Reference in New Issue
Block a user