From 0c1b3632b4ca4393d946dc78d979d5e65fc9e2a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A9=99=E5=AD=90?= <454313500@qq.com> Date: Sat, 23 Oct 2021 13:41:58 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=8D=E5=AD=90=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Yi.Framework.ApiMicroservice/Startup.cs | 24 +- .../Helper/Base32Helper.cs | 101 ++++ .../Helper/ConsoleHelper.cs | 54 ++ .../Yi.Framework.Common/Helper/DateHelper.cs | 58 ++ .../Yi.Framework.Common/Helper/FileHelper.cs | 395 ++++++++++++++ .../Yi.Framework.Common/Helper/HtmlHelper.cs | 24 + .../Yi.Framework.Common/Helper/IpHelper.cs | 51 ++ .../Yi.Framework.Common/Helper/JsonHelper.cs | 498 ++++++++++++++++++ .../Yi.Framework.Common/Helper/MD5Hepler.cs | 67 +++ .../Yi.Framework.Common/Helper/RSAHelper.cs | 390 ++++++++++++++ .../Helper/SerializeHelper.cs | 35 ++ .../Helper/StringHelper.cs | 111 ++++ .../Helper/UnicodeHelper.cs | 47 ++ .../Yi.Framework.Common/Helper/UrlHelper.cs | 23 + .../Yi.Framework.Common/Helper/XmlHelper.cs | 51 ++ .../Models/AxiosUrlsModel.cs | 16 + .../Yi.Framework.Core/TaskJob/visitJob.cs | 2 +- .../Yi.Framework.Model/DbInit/DataSeed.cs | 24 + .../MiddlewareExtend/ConsulRegiterExtend.cs | 6 +- .../MiddlewareExtend/DbSeedInitExtend.cs | 31 ++ 20 files changed, 1987 insertions(+), 21 deletions(-) create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/Base32Helper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/ConsoleHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/DateHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/FileHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/HtmlHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/IpHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/JsonHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/MD5Hepler.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/RSAHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/SerializeHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/StringHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/UnicodeHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/UrlHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Helper/XmlHelper.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Models/AxiosUrlsModel.cs create mode 100644 Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs index a72da2aa..bb5a833f 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs @@ -1,24 +1,9 @@ using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; -using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.OpenApi.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common.IOCOptions; -using Yi.Framework.Interface; -using Yi.Framework.Model; -using Yi.Framework.Service; -using Yi.Framework.WebCore; -using Yi.Framework.WebCore.FilterExtend; using Yi.Framework.WebCore.MiddlewareExtend; using Yi.Framework.WebCore.Utility; @@ -97,7 +82,7 @@ namespace Yi.Framework.ApiMicroservice #endregion // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env,DbContext _Db) { //if (env.IsDevelopment()) { @@ -149,7 +134,12 @@ namespace Yi.Framework.ApiMicroservice #region //Consul服务注入 #endregion - //await app.UseConsulService(); + //app.UseConsulService(); + + #region + //数据库种子注入 + #endregion + app.UseDbSeedInitService(_Db); #region //Endpoints注入 diff --git a/Yi.Framework/Yi.Framework.Common/Helper/Base32Helper.cs b/Yi.Framework/Yi.Framework.Common/Helper/Base32Helper.cs new file mode 100644 index 00000000..3d422caa --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/Base32Helper.cs @@ -0,0 +1,101 @@ +锘縰sing System; +using System.Text; + +namespace Yi.Framework.Common.Helper +{ + public sealed class Base32Helper + { + + // the valid chars for the encoding + private static string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP"; + + /// + /// Converts an array of bytes to a Base32-k string. + /// + public static string ToString(byte[] bytes) + { + StringBuilder sb = new StringBuilder(); // holds the base32 chars + byte index; + int hi = 5; + int currentByte = 0; + + while (currentByte < bytes.Length) + { + // do we need to use the next byte? + if (hi > 8) + { + // get the last piece from the current byte, shift it to the right + // and increment the byte counter + index = (byte)(bytes[currentByte++] >> (hi - 5)); + if (currentByte != bytes.Length) + { + // if we are not at the end, get the first piece from + // the next byte, clear it and shift it to the left + index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index); + } + + hi -= 3; + } + else if (hi == 8) + { + index = (byte)(bytes[currentByte++] >> 3); + hi -= 3; + } + else + { + + // simply get the stuff from the current byte + index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3); + hi += 5; + } + + sb.Append(ValidChars[index]); + } + + return sb.ToString(); + } + + + /// + /// Converts a Base32-k string into an array of bytes. + /// + /// + /// Input string s contains invalid Base32-k characters. + /// + public static byte[] FromBase32String(string str) + { + int numBytes = str.Length * 5 / 8; + byte[] bytes = new Byte[numBytes]; + + // all UPPERCASE chars + str = str.ToUpper(); + + int bit_buffer; + int currentCharIndex; + int bits_in_buffer; + + if (str.Length < 3) + { + bytes[0] = (byte)(ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5); + return bytes; + } + + bit_buffer = (ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5); + bits_in_buffer = 10; + currentCharIndex = 2; + for (int i = 0; i < bytes.Length; i++) + { + bytes[i] = (byte)bit_buffer; + bit_buffer >>= 8; + bits_in_buffer -= 8; + while (bits_in_buffer < 8 && currentCharIndex < str.Length) + { + bit_buffer |= ValidChars.IndexOf(str[currentCharIndex++]) << bits_in_buffer; + bits_in_buffer += 5; + } + } + + return bytes; + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/ConsoleHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/ConsoleHelper.cs new file mode 100644 index 00000000..50a9688f --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/ConsoleHelper.cs @@ -0,0 +1,54 @@ +锘縰sing System; + +namespace Yi.Framework.Common.Helper +{ + public static class ConsoleHelper + { + public static void WriteColorLine(string str, ConsoleColor color) + { + ConsoleColor currentForeColor = Console.ForegroundColor; + Console.ForegroundColor = color; + Console.WriteLine(str); + Console.ForegroundColor = currentForeColor; + } + + /// + /// 鎵撳嵃閿欒淇℃伅 + /// + /// 寰呮墦鍗扮殑瀛楃涓 + /// 鎯宠鎵撳嵃鐨勯鑹 + public static void WriteErrorLine(this string str, ConsoleColor color = ConsoleColor.Red) + { + WriteColorLine(str, color); + } + + /// + /// 鎵撳嵃璀﹀憡淇℃伅 + /// + /// 寰呮墦鍗扮殑瀛楃涓 + /// 鎯宠鎵撳嵃鐨勯鑹 + public static void WriteWarningLine(this string str, ConsoleColor color = ConsoleColor.Yellow) + { + WriteColorLine(str, color); + } + /// + /// 鎵撳嵃姝e父淇℃伅 + /// + /// 寰呮墦鍗扮殑瀛楃涓 + /// 鎯宠鎵撳嵃鐨勯鑹 + public static void WriteInfoLine(this string str, ConsoleColor color = ConsoleColor.White) + { + WriteColorLine(str, color); + } + /// + /// 鎵撳嵃鎴愬姛鐨勪俊鎭 + /// + /// 寰呮墦鍗扮殑瀛楃涓 + /// 鎯宠鎵撳嵃鐨勯鑹 + public static void WriteSuccessLine(this string str, ConsoleColor color = ConsoleColor.Green) + { + WriteColorLine(str, color); + } + + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/DateHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/DateHelper.cs new file mode 100644 index 00000000..0e31e4c7 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/DateHelper.cs @@ -0,0 +1,58 @@ +锘縰sing System; + +namespace Yi.Framework.Common.Helper +{ + public class DateHelper + { + public static DateTime StampToDateTime(string time) + { + time = time.Substring(0, 10); + double timestamp = Convert.ToInt64(time); + System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); + dateTime = dateTime.AddSeconds(timestamp).ToLocalTime(); + return dateTime; + } + + public static string TimeSubTract(DateTime time1,DateTime time2) + { + TimeSpan subTract = time1.Subtract(time2); + return $"{subTract.Days} 澶 {subTract.Hours} 鏃 {subTract.Minutes} 鍒 "; + } + /// + /// 鏃堕棿鎴宠浆鏈湴鏃堕棿-鏃堕棿鎴崇簿纭埌绉 + /// + public static DateTime ToLocalTimeDateBySeconds(long unix) + { + var dto = DateTimeOffset.FromUnixTimeSeconds(unix); + return dto.ToLocalTime().DateTime; + } + + /// + /// 鏃堕棿杞椂闂存埑Unix-鏃堕棿鎴崇簿纭埌绉 + /// + public static long ToUnixTimestampBySeconds(DateTime dt) + { + DateTimeOffset dto = new DateTimeOffset(dt); + return dto.ToUnixTimeSeconds(); + } + + + /// + /// 鏃堕棿鎴宠浆鏈湴鏃堕棿-鏃堕棿鎴崇簿纭埌姣 + /// + public static DateTime ToLocalTimeDateByMilliseconds(long unix) + { + var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix); + return dto.ToLocalTime().DateTime; + } + + /// + /// 鏃堕棿杞椂闂存埑Unix-鏃堕棿鎴崇簿纭埌姣 + /// + public static long ToUnixTimestampByMilliseconds(DateTime dt) + { + DateTimeOffset dto = new DateTimeOffset(dt); + return dto.ToUnixTimeMilliseconds(); + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/FileHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/FileHelper.cs new file mode 100644 index 00000000..72128b2a --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/FileHelper.cs @@ -0,0 +1,395 @@ +锘縰sing System; +using System.IO; +using System.Linq; +using System.Text; + +namespace Yi.Framework.Common.Helper +{ + public class FileHelper : IDisposable + { + + private bool _alreadyDispose = false; + + #region 鏋勯犲嚱鏁 + public FileHelper() + { + // + // TODO: 鍦ㄦ澶勬坊鍔犳瀯閫犲嚱鏁伴昏緫 + // + } + ~FileHelper() + { + Dispose(); ; + } + + protected virtual void Dispose(bool isDisposing) + { + if (_alreadyDispose) return; + _alreadyDispose = true; + } + #endregion + + #region IDisposable 鎴愬憳 + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + #endregion + + #region 鍙栧緱鏂囦欢鍚庣紑鍚 + /**************************************** + * 鍑芥暟鍚嶇О锛欸etPostfixStr + * 鍔熻兘璇存槑锛氬彇寰楁枃浠跺悗缂鍚 + * 鍙 鏁帮細filename:鏂囦欢鍚嶇О + * 璋冪敤绀哄垪锛 + * string filename = "aaa.aspx"; + * string s = EC.FileObj.GetPostfixStr(filename); + *****************************************/ + /// + /// 鍙栧悗缂鍚 + /// + /// 鏂囦欢鍚 + /// .gif|.html鏍煎紡 + public static string GetPostfixStr(string filename) + { + int start = filename.LastIndexOf("."); + int length = filename.Length; + string postfix = filename.Substring(start, length - start); + return postfix; + } + #endregion + + #region 鏍规嵁鏂囦欢澶у皬鑾峰彇鎸囧畾鍓嶇紑鐨勫彲鐢ㄦ枃浠跺悕 + /// + /// 鏍规嵁鏂囦欢澶у皬鑾峰彇鎸囧畾鍓嶇紑鐨勫彲鐢ㄦ枃浠跺悕 + /// + /// 鏂囦欢澶 + /// 鏂囦欢鍓嶇紑 + /// 鏂囦欢澶у皬(1m) + /// 鏂囦欢鍚庣紑(.log) + /// 鍙敤鏂囦欢鍚 + public static string GetAvailableFileWithPrefixOrderSize(string folderPath, string prefix, int size = 1 * 1024 * 1024, string ext = ".log") + { + var allFiles = new DirectoryInfo(folderPath); + var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d=>d.Name).ToList(); + + if (selectFiles.Count > 0) + { + return selectFiles.FirstOrDefault().FullName; + } + + return Path.Combine(folderPath, $@"{prefix}_{DateTime.Now.DateToTimeStamp()}.log"); + } + public static string GetAvailableFileNameWithPrefixOrderSize(string _contentRoot, string prefix, int size = 1 * 1024 * 1024, string ext = ".log") + { + var folderPath = Path.Combine(_contentRoot, "Log"); + if (!Directory.Exists(folderPath)) + { + Directory.CreateDirectory(folderPath); + } + + var allFiles = new DirectoryInfo(folderPath); + var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList(); + + if (selectFiles.Count > 0) + { + return selectFiles.FirstOrDefault().Name.Replace(".log",""); + } + + return $@"{prefix}_{DateTime.Now.DateToTimeStamp()}"; + } + #endregion + + #region 鍐欐枃浠 + /**************************************** + * 鍑芥暟鍚嶇О锛歐riteFile + * 鍔熻兘璇存槑锛氬啓鏂囦欢,浼氳鐩栨帀浠ュ墠鐨勫唴瀹 + * 鍙 鏁帮細Path:鏂囦欢璺緞,Strings:鏂囨湰鍐呭 + * 璋冪敤绀哄垪锛 + * string Path = Server.MapPath("Default2.aspx"); + * string Strings = "杩欐槸鎴戝啓鐨勫唴瀹瑰晩"; + * EC.FileObj.WriteFile(Path,Strings); + *****************************************/ + /// + /// 鍐欐枃浠 + /// + /// 鏂囦欢璺緞 + /// 鏂囦欢鍐呭 + public static void WriteFile(string Path, string Strings) + { + if (!File.Exists(Path)) + { + FileStream f = File.Create(Path); + f.Close(); + } + StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312")); + f2.Write(Strings); + f2.Close(); + f2.Dispose(); + } + + /// + /// 鍐欐枃浠 + /// + /// 鏂囦欢璺緞 + /// 鏂囦欢鍐呭 + /// 缂栫爜鏍煎紡 + public static void WriteFile(string Path, string Strings, Encoding encode) + { + if (!File.Exists(Path)) + { + FileStream f = File.Create(Path); + f.Close(); + } + StreamWriter f2 = new StreamWriter(Path, false, encode); + f2.Write(Strings); + f2.Close(); + f2.Dispose(); + } + #endregion + + #region 璇绘枃浠 + /**************************************** + * 鍑芥暟鍚嶇О锛歊eadFile + * 鍔熻兘璇存槑锛氳鍙栨枃鏈唴瀹 + * 鍙 鏁帮細Path:鏂囦欢璺緞 + * 璋冪敤绀哄垪锛 + * string Path = Server.MapPath("Default2.aspx"); + * string s = EC.FileObj.ReadFile(Path); + *****************************************/ + /// + /// 璇绘枃浠 + /// + /// 鏂囦欢璺緞 + /// + public static string ReadFile(string Path) + { + string s = ""; + if (!File.Exists(Path)) + s = "涓嶅瓨鍦ㄧ浉搴旂殑鐩綍"; + else + { + StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312")); + s = f2.ReadToEnd(); + f2.Close(); + f2.Dispose(); + } + + return s; + } + + /// + /// 璇绘枃浠 + /// + /// 鏂囦欢璺緞 + /// 缂栫爜鏍煎紡 + /// + public static string ReadFile(string Path, Encoding encode) + { + string s = ""; + if (!File.Exists(Path)) + s = "涓嶅瓨鍦ㄧ浉搴旂殑鐩綍"; + else + { + StreamReader f2 = new StreamReader(Path, encode); + s = f2.ReadToEnd(); + f2.Close(); + f2.Dispose(); + } + + return s; + } + #endregion + + #region 杩藉姞鏂囦欢 + /**************************************** + * 鍑芥暟鍚嶇О锛欶ileAdd + * 鍔熻兘璇存槑锛氳拷鍔犳枃浠跺唴瀹 + * 鍙 鏁帮細Path:鏂囦欢璺緞,strings:鍐呭 + * 璋冪敤绀哄垪锛 + * string Path = Server.MapPath("Default2.aspx"); + * string Strings = "鏂拌拷鍔犲唴瀹"; + * EC.FileObj.FileAdd(Path, Strings); + *****************************************/ + /// + /// 杩藉姞鏂囦欢 + /// + /// 鏂囦欢璺緞 + /// 鍐呭 + public static void FileAdd(string Path, string strings) + { + StreamWriter sw = File.AppendText(Path); + sw.Write(strings); + sw.Flush(); + sw.Close(); + } + #endregion + + #region 鎷疯礉鏂囦欢 + /**************************************** + * 鍑芥暟鍚嶇О锛欶ileCoppy + * 鍔熻兘璇存槑锛氭嫹璐濇枃浠 + * 鍙 鏁帮細OrignFile:鍘熷鏂囦欢,NewFile:鏂版枃浠惰矾寰 + * 璋冪敤绀哄垪锛 + * string orignFile = Server.MapPath("Default2.aspx"); + * string NewFile = Server.MapPath("Default3.aspx"); + * EC.FileObj.FileCoppy(OrignFile, NewFile); + *****************************************/ + /// + /// 鎷疯礉鏂囦欢 + /// + /// 鍘熷鏂囦欢 + /// 鏂版枃浠惰矾寰 + public static void FileCoppy(string orignFile, string NewFile) + { + File.Copy(orignFile, NewFile, true); + } + + #endregion + + #region 鍒犻櫎鏂囦欢 + /**************************************** + * 鍑芥暟鍚嶇О锛欶ileDel + * 鍔熻兘璇存槑锛氬垹闄ゆ枃浠 + * 鍙 鏁帮細Path:鏂囦欢璺緞 + * 璋冪敤绀哄垪锛 + * string Path = Server.MapPath("Default3.aspx"); + * EC.FileObj.FileDel(Path); + *****************************************/ + /// + /// 鍒犻櫎鏂囦欢 + /// + /// 璺緞 + public static void FileDel(string Path) + { + File.Delete(Path); + } + #endregion + + #region 绉诲姩鏂囦欢 + /**************************************** + * 鍑芥暟鍚嶇О锛欶ileMove + * 鍔熻兘璇存槑锛氱Щ鍔ㄦ枃浠 + * 鍙 鏁帮細OrignFile:鍘熷璺緞,NewFile:鏂版枃浠惰矾寰 + * 璋冪敤绀哄垪锛 + * string orignFile = Server.MapPath("../璇存槑.txt"); + * string NewFile = Server.MapPath("http://www.cnblogs.com/璇存槑.txt"); + * EC.FileObj.FileMove(OrignFile, NewFile); + *****************************************/ + /// + /// 绉诲姩鏂囦欢 + /// + /// 鍘熷璺緞 + /// 鏂拌矾寰 + public static void FileMove(string orignFile, string NewFile) + { + File.Move(orignFile, NewFile); + } + #endregion + + #region 鍦ㄥ綋鍓嶇洰褰曚笅鍒涘缓鐩綍 + /**************************************** + * 鍑芥暟鍚嶇О锛欶olderCreate + * 鍔熻兘璇存槑锛氬湪褰撳墠鐩綍涓嬪垱寤虹洰褰 + * 鍙 鏁帮細OrignFolder:褰撳墠鐩綍,NewFloder:鏂扮洰褰 + * 璋冪敤绀哄垪锛 + * string orignFolder = Server.MapPath("test/"); + * string NewFloder = "new"; + * EC.FileObj.FolderCreate(OrignFolder, NewFloder); + *****************************************/ + /// + /// 鍦ㄥ綋鍓嶇洰褰曚笅鍒涘缓鐩綍 + /// + /// 褰撳墠鐩綍 + /// 鏂扮洰褰 + public static void FolderCreate(string orignFolder, string NewFloder) + { + Directory.SetCurrentDirectory(orignFolder); + Directory.CreateDirectory(NewFloder); + } + #endregion + + #region 閫掑綊鍒犻櫎鏂囦欢澶圭洰褰曞強鏂囦欢 + /**************************************** + * 鍑芥暟鍚嶇О锛欴eleteFolder + * 鍔熻兘璇存槑锛氶掑綊鍒犻櫎鏂囦欢澶圭洰褰曞強鏂囦欢 + * 鍙 鏁帮細dir:鏂囦欢澶硅矾寰 + * 璋冪敤绀哄垪锛 + * string dir = Server.MapPath("test/"); + * EC.FileObj.DeleteFolder(dir); + *****************************************/ + /// + /// 閫掑綊鍒犻櫎鏂囦欢澶圭洰褰曞強鏂囦欢 + /// + /// + /// + public static void DeleteFolder(string dir) + { + if (Directory.Exists(dir)) //濡傛灉瀛樺湪杩欎釜鏂囦欢澶瑰垹闄や箣 + { + foreach (string d in Directory.GetFileSystemEntries(dir)) + { + if (File.Exists(d)) + File.Delete(d); //鐩存帴鍒犻櫎鍏朵腑鐨勬枃浠 + else + DeleteFolder(d); //閫掑綊鍒犻櫎瀛愭枃浠跺す + } + Directory.Delete(dir); //鍒犻櫎宸茬┖鏂囦欢澶 + } + + } + #endregion + + #region 灏嗘寚瀹氭枃浠跺す涓嬮潰鐨勬墍鏈夊唴瀹筩opy鍒扮洰鏍囨枃浠跺す涓嬮潰 鏋滅洰鏍囨枃浠跺す涓哄彧璇诲睘鎬у氨浼氭姤閿欍 + /**************************************** + * 鍑芥暟鍚嶇О锛欳opyDir + * 鍔熻兘璇存槑锛氬皢鎸囧畾鏂囦欢澶逛笅闈㈢殑鎵鏈夊唴瀹筩opy鍒扮洰鏍囨枃浠跺す涓嬮潰 鏋滅洰鏍囨枃浠跺す涓哄彧璇诲睘鎬у氨浼氭姤閿欍 + * 鍙 鏁帮細srcPath:鍘熷璺緞,aimPath:鐩爣鏂囦欢澶 + * 璋冪敤绀哄垪锛 + * string srcPath = Server.MapPath("test/"); + * string aimPath = Server.MapPath("test1/"); + * EC.FileObj.CopyDir(srcPath,aimPath); + *****************************************/ + /// + /// 鎸囧畾鏂囦欢澶逛笅闈㈢殑鎵鏈夊唴瀹筩opy鍒扮洰鏍囨枃浠跺す涓嬮潰 + /// + /// 鍘熷璺緞 + /// 鐩爣鏂囦欢澶 + public static void CopyDir(string srcPath, string aimPath) + { + try + { + // 妫鏌ョ洰鏍囩洰褰曟槸鍚︿互鐩綍鍒嗗壊瀛楃缁撴潫濡傛灉涓嶆槸鍒欐坊鍔犱箣 + if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) + aimPath += Path.DirectorySeparatorChar; + // 鍒ゆ柇鐩爣鐩綍鏄惁瀛樺湪濡傛灉涓嶅瓨鍦ㄥ垯鏂板缓涔 + if (!Directory.Exists(aimPath)) + Directory.CreateDirectory(aimPath); + // 寰楀埌婧愮洰褰曠殑鏂囦欢鍒楄〃锛岃閲岄潰鏄寘鍚枃浠朵互鍙婄洰褰曡矾寰勭殑涓涓暟缁 + //濡傛灉浣犳寚鍚慶opy鐩爣鏂囦欢涓嬮潰鐨勬枃浠惰屼笉鍖呭惈鐩綍璇蜂娇鐢ㄤ笅闈㈢殑鏂规硶 + //string[] fileList = Directory.GetFiles(srcPath); + string[] fileList = Directory.GetFileSystemEntries(srcPath); + //閬嶅巻鎵鏈夌殑鏂囦欢鍜岀洰褰 + foreach (string file in fileList) + { + //鍏堝綋浣滅洰褰曞鐞嗗鏋滃瓨鍦ㄨ繖涓洰褰曞氨閫掑綊Copy璇ョ洰褰曚笅闈㈢殑鏂囦欢 + + if (Directory.Exists(file)) + CopyDir(file, aimPath + Path.GetFileName(file)); + //鍚﹀垯鐩存帴Copy鏂囦欢 + else + File.Copy(file, aimPath + Path.GetFileName(file), true); + } + + } + catch (Exception ee) + { + throw new Exception(ee.ToString()); + } + } + #endregion + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/HtmlHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/HtmlHelper.cs new file mode 100644 index 00000000..1e1e0086 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/HtmlHelper.cs @@ -0,0 +1,24 @@ +锘縩amespace Yi.Framework.Common.Helper +{ + public static class HtmlHelper + { + #region 鍘婚櫎瀵屾枃鏈腑鐨凥TML鏍囩 + /// + /// 鍘婚櫎瀵屾枃鏈腑鐨凥TML鏍囩 + /// + /// + /// + /// + public static string ReplaceHtmlTag(string html, int length = 0) + { + string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", ""); + strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", ""); + + if (length > 0 && strText.Length > length) + return strText.Substring(0, length); + + return strText; + } + #endregion + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/IpHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/IpHelper.cs new file mode 100644 index 00000000..b39d112a --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/IpHelper.cs @@ -0,0 +1,51 @@ +锘縰sing System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; + +namespace Yi.Framework.Common.Helper +{ + public class IpHelper + { + /// + /// 鑾峰彇褰撳墠IP鍦板潃 + /// + /// + /// + public static string GetCurrentIp(string preferredNetworks) + { + var instanceIp = "127.0.0.1"; + + try + { + // 鑾峰彇鍙敤缃戝崱 + var nics = NetworkInterface.GetAllNetworkInterfaces()?.Where(network => network.OperationalStatus == OperationalStatus.Up); + + // 鑾峰彇鎵鏈夊彲鐢ㄧ綉鍗P淇℃伅 + var ipCollection = nics?.Select(x => x.GetIPProperties())?.SelectMany(x => x.UnicastAddresses); + + foreach (var ipadd in ipCollection) + { + if (!IPAddress.IsLoopback(ipadd.Address) && ipadd.Address.AddressFamily == AddressFamily.InterNetwork) + { + if (string.IsNullOrEmpty(preferredNetworks)) + { + instanceIp = ipadd.Address.ToString(); + break; + } + + if (!ipadd.Address.ToString().StartsWith(preferredNetworks)) continue; + instanceIp = ipadd.Address.ToString(); + break; + } + } + } + catch + { + // ignored + } + + return instanceIp; + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/JsonHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/JsonHelper.cs new file mode 100644 index 00000000..0bea6671 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/JsonHelper.cs @@ -0,0 +1,498 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Text.Json; + +namespace Yi.Framework.Common.Helper +{ + public class JsonHelper + { + /// + /// 杞崲瀵硅薄涓篔SON鏍煎紡鏁版嵁 + /// + /// + /// 瀵硅薄 + /// 瀛楃鏍煎紡鐨凧SON鏁版嵁 + public static string GetJSON(object obj) + { + string result = String.Empty; + try + { + JsonSerializer.Serialize(""); + System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = + new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); + using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) + { + serializer.WriteObject(ms, obj); + result = System.Text.Encoding.UTF8.GetString(ms.ToArray()); + } + } + catch (Exception) + { + throw; + } + return result; + } + /// + /// 杞崲List鐨勬暟鎹负JSON鏍煎紡 + /// + /// + /// 鍒楄〃鍊 + /// JSON鏍煎紡鏁版嵁 + public string JSON(List vals) + { + System.Text.StringBuilder st = new System.Text.StringBuilder(); + try + { + System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); + + foreach (T city in vals) + { + using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) + { + s.WriteObject(ms, city); + st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray())); + } + } + } + catch (Exception) + { + } + + return st.ToString(); + } + /// + /// JSON鏍煎紡瀛楃杞崲涓篢绫诲瀷鐨勫璞 + /// + /// + /// + /// + public static T ParseFormByJson(string jsonStr) + { + T obj = Activator.CreateInstance(); + using (System.IO.MemoryStream ms = + new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr))) + { + System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = + new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); + return (T)serializer.ReadObject(ms); + } + } + + public string JSON1(List vals) + { + System.Text.StringBuilder st = new System.Text.StringBuilder(); + try + { + System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(SendData)); + + foreach (SendData city in vals) + { + using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) + { + s.WriteObject(ms, city); + st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray())); + } + } + } + catch (Exception) + { + } + + return st.ToString(); + } + + private static bool IsJsonStart(ref string json) + { + if (!string.IsNullOrEmpty(json)) + { + json = json.Trim('\r', '\n', ' '); + if (json.Length > 1) + { + char s = json[0]; + char e = json[json.Length - 1]; + return (s == '{' && e == '}') || (s == '[' && e == ']'); + } + } + return false; + } + public static bool IsJson(string json) + { + int errIndex; + return IsJson(json, out errIndex); + } + public static bool IsJson(string json, out int errIndex) + { + errIndex = 0; + if (IsJsonStart(ref json)) + { + CharState cs = new CharState(); + char c; + for (int i = 0; i < json.Length; i++) + { + c = json[i]; + if (SetCharState(c, ref cs) && cs.childrenStart)//璁剧疆鍏抽敭绗﹀彿鐘舵併 + { + string item = json.Substring(i); + int err; + int length = GetValueLength(item, true, out err); + cs.childrenStart = false; + if (err > 0) + { + errIndex = i + err; + return false; + } + i = i + length - 1; + } + if (cs.isError) + { + errIndex = i; + return false; + } + } + + return !cs.arrayStart && !cs.jsonStart; + } + return false; + } + + /// + /// 鑾峰彇鍊肩殑闀垮害锛堝綋Json鍊煎祵濂椾互"{"鎴"["寮澶存椂锛 + /// + private static int GetValueLength(string json, bool breakOnErr, out int errIndex) + { + errIndex = 0; + int len = 0; + if (!string.IsNullOrEmpty(json)) + { + CharState cs = new CharState(); + char c; + for (int i = 0; i < json.Length; i++) + { + c = json[i]; + if (!SetCharState(c, ref cs))//璁剧疆鍏抽敭绗﹀彿鐘舵併 + { + if (!cs.jsonStart && !cs.arrayStart)//json缁撴潫锛屽張涓嶆槸鏁扮粍锛屽垯閫鍑恒 + { + break; + } + } + else if (cs.childrenStart)//姝e父瀛楃锛屽肩姸鎬佷笅銆 + { + int length = GetValueLength(json.Substring(i), breakOnErr, out errIndex);//閫掑綊瀛愬硷紝杩斿洖涓涓暱搴︺傘傘 + cs.childrenStart = false; + cs.valueStart = 0; + //cs.state = 0; + i = i + length - 1; + } + if (breakOnErr && cs.isError) + { + errIndex = i; + return i; + } + if (!cs.jsonStart && !cs.arrayStart)//璁板綍褰撳墠缁撴潫浣嶇疆銆 + { + len = i + 1;//闀垮害姣旂储寮+1 + break; + } + } + } + return len; + } + + /// + /// 璁剧疆瀛楃鐘舵(杩斿洖true鍒欎负鍏抽敭璇嶏紝杩斿洖false鍒欏綋涓烘櫘閫氬瓧绗﹀鐞嗭級 + /// + private static bool SetCharState(char c, ref CharState cs) + { + cs.CheckIsError(c); + switch (c) + { + case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}] + #region 澶ф嫭鍙 + if (cs.keyStart <= 0 && cs.valueStart <= 0) + { + cs.keyStart = 0; + cs.valueStart = 0; + if (cs.jsonStart && cs.state == 1) + { + cs.childrenStart = true; + } + else + { + cs.state = 0; + } + cs.jsonStart = true;//寮濮嬨 + return true; + } + #endregion + break; + case '}': + #region 澶ф嫭鍙风粨鏉 + if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.jsonStart) + { + cs.jsonStart = false;//姝e父缁撴潫銆 + cs.state = 0; + cs.keyStart = 0; + cs.valueStart = 0; + cs.setDicValue = true; + return true; + } + // cs.isError = !cs.jsonStart && cs.state == 0; + #endregion + break; + case '[': + #region 涓嫭鍙峰紑濮 + if (!cs.jsonStart) + { + cs.arrayStart = true; + return true; + } + else if (cs.jsonStart && cs.state == 1) + { + cs.childrenStart = true; + return true; + } + #endregion + break; + case ']': + #region 涓嫭鍙风粨鏉 + if (cs.arrayStart && !cs.jsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//杩欐牱缁撴潫銆 + { + cs.keyStart = 0; + cs.valueStart = 0; + cs.arrayStart = false; + return true; + } + #endregion + break; + case '"': + case '\'': + #region 寮曞彿 + if (cs.jsonStart || cs.arrayStart) + { + if (cs.state == 0)//key闃舵,鏈夊彲鑳芥槸鏁扮粍["aa",{}] + { + if (cs.keyStart <= 0) + { + cs.keyStart = (c == '"' ? 3 : 2); + return true; + } + else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"')) + { + if (!cs.escapeChar) + { + cs.keyStart = -1; + return true; + } + else + { + cs.escapeChar = false; + } + } + } + else if (cs.state == 1 && cs.jsonStart)//鍊奸樁娈靛繀椤绘槸Json寮濮嬩簡銆 + { + if (cs.valueStart <= 0) + { + cs.valueStart = (c == '"' ? 3 : 2); + return true; + } + else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"')) + { + if (!cs.escapeChar) + { + cs.valueStart = -1; + return true; + } + else + { + cs.escapeChar = false; + } + } + + } + } + #endregion + break; + case ':': + #region 鍐掑彿 + if (cs.jsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0) + { + if (cs.keyStart == 1) + { + cs.keyStart = -1; + } + cs.state = 1; + return true; + } + // cs.isError = !cs.jsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1); + #endregion + break; + case ',': + #region 閫楀彿 //["aa",{aa:12,}] + + if (cs.jsonStart) + { + if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1) + { + cs.state = 0; + cs.keyStart = 0; + cs.valueStart = 0; + //if (cs.valueStart == 1) + //{ + // cs.valueStart = 0; + //} + cs.setDicValue = true; + return true; + } + } + else if (cs.arrayStart && cs.keyStart <= 2) + { + cs.keyStart = 0; + //if (cs.keyStart == 1) + //{ + // cs.keyStart = -1; + //} + return true; + } + #endregion + break; + case ' ': + case '\r': + case '\n'://[ "a",\r\n{} ] + case '\0': + case '\t': + if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.jsonStart && + { + return true;//璺宠繃绌烘牸銆 + } + break; + default: //鍊煎紑澶淬傘 + if (c == '\\') //杞箟绗﹀彿 + { + if (cs.escapeChar) + { + cs.escapeChar = false; + } + else + { + cs.escapeChar = true; + return true; + } + } + else + { + cs.escapeChar = false; + } + if (cs.jsonStart || cs.arrayStart) // Json 鎴栨暟缁勫紑濮嬩簡銆 + { + if (cs.keyStart <= 0 && cs.state == 0) + { + cs.keyStart = 1;//鏃犲紩鍙风殑 + } + else if (cs.valueStart <= 0 && cs.state == 1 && cs.jsonStart)//鍙湁Json寮濮嬫墠鏈夊笺 + { + cs.valueStart = 1;//鏃犲紩鍙风殑 + } + } + break; + } + return false; + } + } + /// + /// 瀛楃鐘舵 + /// + public class CharState + { + internal bool jsonStart = false;//浠 "{"寮濮嬩簡... + internal bool setDicValue = false;// 鍙互璁剧疆瀛楀吀鍊间簡銆 + internal bool escapeChar = false;//浠"\"杞箟绗﹀彿寮濮嬩簡 + /// + /// 鏁扮粍寮濮嬨愪粎绗竴寮澶存墠绠椼戯紝鍊煎祵濂楃殑浠ャ恈hildrenStart銆戞潵鏍囪瘑銆 + /// + internal bool arrayStart = false;//浠"[" 绗﹀彿寮濮嬩簡 + internal bool childrenStart = false;//瀛愮骇宓屽寮濮嬩簡銆 + /// + /// 銆0 鍒濆鐘舵侊紝鎴 閬囧埌鈥,鈥濋楀彿銆戯紱銆1 閬囧埌鈥滐細鈥濆啋鍙枫 + /// + internal int state = 0; + + /// + /// 銆-1 鍙栧肩粨鏉熴戙0 鏈紑濮嬨戙1 鏃犲紩鍙峰紑濮嬨戙2 鍗曞紩鍙峰紑濮嬨戙3 鍙屽紩鍙峰紑濮嬨 + /// + internal int keyStart = 0; + /// + /// 銆-1 鍙栧肩粨鏉熴戙0 鏈紑濮嬨戙1 鏃犲紩鍙峰紑濮嬨戙2 鍗曞紩鍙峰紑濮嬨戙3 鍙屽紩鍙峰紑濮嬨 + /// + internal int valueStart = 0; + internal bool isError = false;//鏄惁璇硶閿欒銆 + + internal void CheckIsError(char c)//鍙綋鎴愪竴绾у鐞嗭紙鍥犱负GetLength浼氶掑綊鍒版瘡涓涓瓙椤瑰鐞嗭級 + { + if (keyStart > 1 || valueStart > 1) + { + return; + } + //绀轰緥 ["aa",{"bbbb":123,"fff","ddd"}] + switch (c) + { + case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}] + isError = jsonStart && state == 0;//閲嶅寮濮嬮敊璇 鍚屾椂涓嶆槸鍊煎鐞嗐 + break; + case '}': + isError = !jsonStart || (keyStart != 0 && state == 0);//閲嶅缁撴潫閿欒 鎴栬 鎻愬墠缁撴潫{"aa"}銆傛甯哥殑鏈墈} + break; + case '[': + isError = arrayStart && state == 0;//閲嶅寮濮嬮敊璇 + break; + case ']': + isError = !arrayStart || jsonStart;//閲嶅寮濮嬮敊璇 鎴栬 Json 鏈粨鏉 + break; + case '"': + case '\'': + isError = !(jsonStart || arrayStart); //json 鎴栨暟缁勫紑濮嬨 + if (!isError) + { + //閲嶅寮濮 [""",{"" "}] + isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1); + } + if (!isError && arrayStart && !jsonStart && c == '\'')//['aa',{}] + { + isError = true; + } + break; + case ':': + isError = !jsonStart || state == 1;//閲嶅鍑虹幇銆 + break; + case ',': + isError = !(jsonStart || arrayStart); //json 鎴栨暟缁勫紑濮嬨 + if (!isError) + { + if (jsonStart) + { + isError = state == 0 || (state == 1 && valueStart > 1);//閲嶅鍑虹幇銆 + } + else if (arrayStart)//["aa,] [,] [{},{}] + { + isError = keyStart == 0 && !setDicValue; + } + } + break; + case ' ': + case '\r': + case '\n'://[ "a",\r\n{} ] + case '\0': + case '\t': + break; + default: //鍊煎紑澶淬傘 + isError = (!jsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);// + break; + } + //if (isError) + //{ + + //} + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/MD5Hepler.cs b/Yi.Framework/Yi.Framework.Common/Helper/MD5Hepler.cs new file mode 100644 index 00000000..f0d382eb --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/MD5Hepler.cs @@ -0,0 +1,67 @@ +锘縰sing System; +using System.Security.Cryptography; +using System.Text; + +namespace Yi.Framework.Common.Helper +{ + public class MD5Helper + { + /// + /// 16浣峂D5鍔犲瘑 + /// + /// + /// + public static string MD5Encrypt16(string password) + { + var md5 = new MD5CryptoServiceProvider(); + string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8); + t2 = t2.Replace("-", string.Empty); + return t2; + } + + /// + /// 32浣峂D5鍔犲瘑 + /// + /// + /// + public static string MD5Encrypt32(string password = "") + { + string pwd = string.Empty; + try + { + if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password)) + { + MD5 md5 = MD5.Create(); //瀹炰緥鍖栦竴涓猰d5瀵瑰儚 + // 鍔犲瘑鍚庢槸涓涓瓧鑺傜被鍨嬬殑鏁扮粍锛岃繖閲岃娉ㄦ剰缂栫爜UTF8/Unicode绛夌殑閫夋嫨銆 + byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); + // 閫氳繃浣跨敤寰幆锛屽皢瀛楄妭绫诲瀷鐨勬暟缁勮浆鎹负瀛楃涓诧紝姝ゅ瓧绗︿覆鏄父瑙勫瓧绗︽牸寮忓寲鎵寰 + foreach (var item in s) + { + // 灏嗗緱鍒扮殑瀛楃涓蹭娇鐢ㄥ崄鍏繘鍒剁被鍨嬫牸寮忋傛牸寮忓悗鐨勫瓧绗︽槸灏忓啓鐨勫瓧姣嶏紝濡傛灉浣跨敤澶у啓锛圶锛夊垯鏍煎紡鍚庣殑瀛楃鏄ぇ鍐欏瓧绗 + pwd = string.Concat(pwd, item.ToString("X2")); + } + } + } + catch + { + throw new Exception($"閿欒鐨 password 瀛楃涓:銆恵password}銆"); + } + return pwd; + } + + /// + /// 64浣峂D5鍔犲瘑 + /// + /// + /// + public static string MD5Encrypt64(string password) + { + // 瀹炰緥鍖栦竴涓猰d5瀵瑰儚 + // 鍔犲瘑鍚庢槸涓涓瓧鑺傜被鍨嬬殑鏁扮粍锛岃繖閲岃娉ㄦ剰缂栫爜UTF8/Unicode绛夌殑閫夋嫨銆 + MD5 md5 = MD5.Create(); + byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); + return Convert.ToBase64String(s); + } + + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/RSAHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/RSAHelper.cs new file mode 100644 index 00000000..f439b544 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/RSAHelper.cs @@ -0,0 +1,390 @@ +锘縰sing System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Yi.Framework.Common.Helper +{ + /// + /// RSA鍔犺В瀵 浣跨敤OpenSSL鐨勫叕閽ュ姞瀵/绉侀挜瑙e瘑 + /// 鍏閽ヨ浣跨敤openssl鐢熸垚 + /// + public class RSAHelper + { + public readonly RSA _privateKeyRsaProvider; + public readonly RSA _publicKeyRsaProvider; + private readonly HashAlgorithmName _hashAlgorithmName; + private readonly Encoding _encoding; + + /// + /// 瀹炰緥鍖朢SAHelper + /// + /// 鍔犲瘑绠楁硶绫诲瀷 RSA SHA1;RSA2 SHA256 瀵嗛挜闀垮害鑷冲皯涓2048 + /// 缂栫爜绫诲瀷 + /// 绉侀挜 + /// 鍏挜 + public RSAHelper(RSAType rsaType, Encoding encoding, string privateKey, string publicKey = null) + { + _encoding = encoding; + if (!string.IsNullOrEmpty(privateKey)) + { + _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey); + } + + if (!string.IsNullOrEmpty(publicKey)) + { + _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey); + } + + _hashAlgorithmName = rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256; + } + + #region 浣跨敤绉侀挜绛惧悕 + + /// + /// 浣跨敤绉侀挜绛惧悕 + /// + /// 鍘熷鏁版嵁 + /// + public string Sign(string data) + { + byte[] dataBytes = _encoding.GetBytes(data); + + var signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); + + return Convert.ToBase64String(signatureBytes); + } + + #endregion + + #region 浣跨敤鍏挜楠岀 + + /// + /// 浣跨敤鍏挜楠岀 + /// + /// 鍘熷鏁版嵁 + /// 绛惧悕 + /// + public bool Verify(string data, string sign) + { + byte[] dataBytes = _encoding.GetBytes(data); + byte[] signBytes = Convert.FromBase64String(sign); + + var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); + + return verify; + } + + #endregion + + #region 瑙e瘑 + /// + /// 绉侀挜瑙e瘑(鍘) + /// + /// 瑙e瘑瀛楃涓(base64) + /// + + //public string Decrypt(string cipherText) + //{ + // if (_privateKeyRsaProvider == null) + // { + // throw new Exception("_privateKeyRsaProvider is null"); + // } + // return _encoding.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1)); + //} + /// + /// 绉侀挜瑙e瘑(鏀寔澶ч噺鏁版嵁) + /// + /// + /// + public string Decrypt(string cipherText) + { + if (_privateKeyRsaProvider == null) + { + throw new Exception("_privateKeyRsaProvider is null"); + } + var bufferSize = (_privateKeyRsaProvider.KeySize / 8); + byte[] buffer = new byte[bufferSize];//寰呰В瀵嗗潡 + using (MemoryStream msInput = new MemoryStream(Convert.FromBase64String(cipherText))) + { + using (MemoryStream msOutput = new MemoryStream()) + { + int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0) + { + byte[] dataToEnc = new byte[readLen]; + Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = _privateKeyRsaProvider.Decrypt(dataToEnc, RSAEncryptionPadding.Pkcs1); + msOutput.Write(encData, 0, encData.Length); + } + byte[] result = msOutput.ToArray(); + return _encoding.GetString(result); + } + } + } + + #endregion + + #region 鍔犲瘑 + + /// + /// 鍏挜鍔犲瘑(鍘) + /// + /// + /// + //public string Encrypt(string text) + //{ + // if (_publicKeyRsaProvider == null) + // { + // throw new Exception("_publicKeyRsaProvider is null"); + // } + // return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1)); + //} + /// + /// 鍏挜鍔犲瘑(鏀寔澶ч噺鏁版嵁) + /// + /// + /// + public string Encrypt(string text) + { + if (_publicKeyRsaProvider == null) + { + throw new Exception("_publicKeyRsaProvider is null"); + } + var bufferSize = (_publicKeyRsaProvider.KeySize / 8 - 11); + byte[] buffer = new byte[bufferSize];//寰呭姞瀵嗗潡 + + using (MemoryStream msInput = new MemoryStream(_encoding.GetBytes(text))) + { + using (MemoryStream msOutput = new MemoryStream()) + { + int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0) + { + byte[] dataToEnc = new byte[readLen]; + Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = _publicKeyRsaProvider.Encrypt(dataToEnc, RSAEncryptionPadding.Pkcs1); + msOutput.Write(encData, 0, encData.Length); + } + byte[] result = msOutput.ToArray(); + return Convert.ToBase64String(result); + } + } + } + + #endregion + + #region 浣跨敤绉侀挜鍒涘缓RSA瀹炰緥 + /// + /// 浣跨敤绉侀挜鍒涘缓RSA瀹炰緥 + /// + /// + /// + private RSA CreateRsaProviderFromPrivateKey(string privateKey) + { + var privateKeyBits = Convert.FromBase64String(privateKey); + + var rsa = RSA.Create(); + var rsaParameters = new RSAParameters(); + + using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits))) + { + byte bt = 0; + ushort twobytes = 0; + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + else + throw new Exception("Unexpected value read binr.ReadUInt16()"); + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) + throw new Exception("Unexpected version"); + + bt = binr.ReadByte(); + if (bt != 0x00) + throw new Exception("Unexpected value read binr.ReadByte()"); + + rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); + } + + rsa.ImportParameters(rsaParameters); + return rsa; + } + + #endregion + + #region 浣跨敤鍏挜鍒涘缓RSA瀹炰緥 + /// + /// 浣跨敤鍏挜鍒涘缓RSA瀹炰緥 + /// + /// + /// + public RSA CreateRsaProviderFromPublicKey(string publicKeyString) + { + // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" + byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; + byte[] seq = new byte[15]; + + var x509Key = Convert.FromBase64String(publicKeyString); + + // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ + using (MemoryStream mem = new MemoryStream(x509Key)) + { + using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading + { + byte bt = 0; + ushort twobytes = 0; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + seq = binr.ReadBytes(15); //read the Sequence OID + if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8203) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + bt = binr.ReadByte(); + if (bt != 0x00) //expect null byte next + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + byte lowbyte = 0x00; + byte highbyte = 0x00; + + if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81) + lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus + else if (twobytes == 0x8202) + { + highbyte = binr.ReadByte(); //advance 2 bytes + lowbyte = binr.ReadByte(); + } + else + return null; + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order + int modsize = BitConverter.ToInt32(modint, 0); + + int firstbyte = binr.PeekChar(); + if (firstbyte == 0x00) + { //if first byte (highest order) of modulus is zero, don't include it + binr.ReadByte(); //skip this null byte + modsize -= 1; //reduce modulus buffer size by 1 + } + + byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes + + if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data + return null; + int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) + byte[] exponent = binr.ReadBytes(expbytes); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + var rsa = RSA.Create(); + RSAParameters rsaKeyInfo = new RSAParameters + { + Modulus = modulus, + Exponent = exponent + }; + rsa.ImportParameters(rsaKeyInfo); + + return rsa; + } + + } + } + + #endregion + + #region 瀵煎叆瀵嗛挜绠楁硶 + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) + return 0; + bt = binr.ReadByte(); + + if (bt == 0x81) + count = binr.ReadByte(); + else + if (bt == 0x82) + { + var highbyte = binr.ReadByte(); + var lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; + } + + while (binr.ReadByte() == 0x00) + { + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + return count; + } + + private bool CompareBytearrays(byte[] a, byte[] b) + { + if (a.Length != b.Length) + return false; + int i = 0; + foreach (byte c in a) + { + if (c != b[i]) + return false; + i++; + } + return true; + } + + #endregion + + } + + /// + /// RSA绠楁硶绫诲瀷 + /// + public enum RSAType + { + /// + /// SHA1 + /// + RSA = 0, + /// + /// RSA2 瀵嗛挜闀垮害鑷冲皯涓2048 + /// SHA256 + /// + RSA2 + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/SerializeHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/SerializeHelper.cs new file mode 100644 index 00000000..9a5aee9b --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/SerializeHelper.cs @@ -0,0 +1,35 @@ +锘縰sing Newtonsoft.Json; +using System.Text; + +namespace Yi.Framework.Common.Helper +{ + public class SerializeHelper + { + /// + /// 搴忓垪鍖 + /// + /// + /// + public static byte[] Serialize(object item) + { + var jsonString = JsonConvert.SerializeObject(item); + + return Encoding.UTF8.GetBytes(jsonString); + } + /// + /// 鍙嶅簭鍒楀寲 + /// + /// + /// + /// + public static TEntity Deserialize(byte[] value) + { + if (value == null) + { + return default(TEntity); + } + var jsonString = Encoding.UTF8.GetString(value); + return JsonConvert.DeserializeObject(jsonString); + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/StringHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/StringHelper.cs new file mode 100644 index 00000000..b4287ed5 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/StringHelper.cs @@ -0,0 +1,111 @@ +锘縰sing System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Yi.Framework.Common.Helper +{ + public class StringHelper + { + /// + /// 鏍规嵁鍒嗛殧绗﹁繑鍥炲墠n鏉℃暟鎹 + /// + /// 鏁版嵁鍐呭 + /// 鍒嗛殧绗 + /// 鍓峮鏉 + /// 鏄惁鍊掑簭锛堥粯璁alse锛 + /// + public static List GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false) + { + if (string.IsNullOrEmpty(content)) + { + return new List() { }; + } + + if (string.IsNullOrEmpty(separator)) + { + throw new ArgumentException("message", nameof(separator)); + } + + var dataArray = content.Split(separator).Where(d => !string.IsNullOrEmpty(d)).ToArray(); + if (isDesc) + { + Array.Reverse(dataArray); + } + + if (top > 0) + { + dataArray = dataArray.Take(top).ToArray(); + } + + return dataArray.ToList(); + } + /// + /// 鏍规嵁瀛楁鎷兼帴get鍙傛暟 + /// + /// + /// + public static string GetPars(Dictionary dic) + { + + StringBuilder sb = new StringBuilder(); + string urlPars = null; + bool isEnter = false; + foreach (var item in dic) + { + sb.Append($"{(isEnter ? "&" : "")}{item.Key}={item.Value}"); + isEnter = true; + } + urlPars = sb.ToString(); + return urlPars; + } + /// + /// 鏍规嵁瀛楁鎷兼帴get鍙傛暟 + /// + /// + /// + public static string GetPars(Dictionary dic) + { + + StringBuilder sb = new StringBuilder(); + string urlPars = null; + bool isEnter = false; + foreach (var item in dic) + { + sb.Append($"{(isEnter ? "&" : "")}{item.Key}={item.Value}"); + isEnter = true; + } + urlPars = sb.ToString(); + return urlPars; + } + /// + /// 鑾峰彇涓涓狦UID + /// + /// 鏍煎紡-榛樿涓篘 + /// + public static string GetGUID(string format="N") { + return Guid.NewGuid().ToString(format); + } + /// + /// 鏍规嵁GUID鑾峰彇19浣嶇殑鍞竴鏁板瓧搴忓垪 + /// + /// + public static long GetGuidToLongID() + { + byte[] buffer = Guid.NewGuid().ToByteArray(); + return BitConverter.ToInt64(buffer, 0); + } + /// + /// 鑾峰彇瀛楃涓叉渶鍚嶺琛 + /// + /// + /// + /// + public static string GetCusLine(string resourceStr, int length) { + string[] arrStr = resourceStr.Split("\r\n"); + return string.Join("", (from q in arrStr select q).Skip(arrStr.Length - length + 1).Take(length).ToArray()); + } + + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/UnicodeHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/UnicodeHelper.cs new file mode 100644 index 00000000..d6d96f75 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/UnicodeHelper.cs @@ -0,0 +1,47 @@ +锘縰sing System; +using System.Text; +using System.Text.RegularExpressions; + +namespace Yi.Framework.Common.Helper +{ + public static class UnicodeHelper + { + /// + /// 瀛楃涓茶浆Unicode鐮 + /// + /// The to unicode. + /// Value. + public static string StringToUnicode(string value) + { + byte[] bytes = Encoding.Unicode.GetBytes(value); + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < bytes.Length; i += 2) + { + // 鍙栦袱涓瓧绗︼紝姣忎釜瀛楃閮芥槸鍙冲榻愩 + stringBuilder.AppendFormat("u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0')); + } + return stringBuilder.ToString(); + } + + /// + /// Unicode杞瓧绗︿覆 + /// + /// The to string. + /// Unicode. + public static string UnicodeToString(string unicode) + { + unicode = unicode.Replace("%", "\\"); + + return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace( + unicode, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16))); + + //string resultStr = ""; + //string[] strList = unicode.Split('u'); + //for (int i = 1; i < strList.Length; i++) + //{ + // resultStr += (char)int.Parse(strList[i], System.Globalization.NumberStyles.HexNumber); + //} + //return resultStr; + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/UrlHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/UrlHelper.cs new file mode 100644 index 00000000..6ebd30c0 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/UrlHelper.cs @@ -0,0 +1,23 @@ +锘縩amespace Yi.Framework.Common.Helper +{ + public class UrlHelper + { + /// + /// UrlEncode缂栫爜 + /// + /// url + /// + public static string UrlEncode(string url) { + return System.Web.HttpUtility.UrlEncode(url, System.Text.Encoding.UTF8); + } + /// + /// UrlEncode瑙g爜 + /// + /// 鏁版嵁 + /// + public static string UrlDecode(string data) + { + return System.Web.HttpUtility.UrlDecode(data, System.Text.Encoding.UTF8); + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Helper/XmlHelper.cs b/Yi.Framework/Yi.Framework.Common/Helper/XmlHelper.cs new file mode 100644 index 00000000..44133350 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Helper/XmlHelper.cs @@ -0,0 +1,51 @@ +锘縰sing System; +using System.Collections.Generic; +using System.IO; +using System.Xml.Serialization; + +namespace Yi.Framework.Common.Helper +{ + public class XmlHelper + { + /// + /// 杞崲瀵硅薄涓篔SON鏍煎紡鏁版嵁 + /// + /// + /// 瀵硅薄 + /// 瀛楃鏍煎紡鐨凧SON鏁版嵁 + public static string GetXML(object obj) + { + try + { + XmlSerializer xs = new XmlSerializer(typeof(T)); + + using (TextWriter tw = new StringWriter()) + { + xs.Serialize(tw, obj); + return tw.ToString(); + } + } + catch (Exception) + { + return string.Empty; + } + } + + /// + /// Xml鏍煎紡瀛楃杞崲涓篢绫诲瀷鐨勫璞 + /// + /// + /// + /// + public static T ParseFormByXml(string xml,string rootName="root") + { + XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName)); + StringReader reader = new StringReader(xml); + + T res = (T)serializer.Deserialize(reader); + reader.Close(); + reader.Dispose(); + return res; + } + } +} diff --git a/Yi.Framework/Yi.Framework.Common/Models/AxiosUrlsModel.cs b/Yi.Framework/Yi.Framework.Common/Models/AxiosUrlsModel.cs new file mode 100644 index 00000000..f5cdacb8 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Models/AxiosUrlsModel.cs @@ -0,0 +1,16 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Yi.Framework.Common.Models +{ + public class AxiosUrlsModel + { + public string get { get; set; } + public string update { get; set; } + public string del { get; set; } + public string add { get; set; } + } +} diff --git a/Yi.Framework/Yi.Framework.Core/TaskJob/visitJob.cs b/Yi.Framework/Yi.Framework.Core/TaskJob/visitJob.cs index 0a0e4c09..58b39434 100644 --- a/Yi.Framework/Yi.Framework.Core/TaskJob/visitJob.cs +++ b/Yi.Framework/Yi.Framework.Core/TaskJob/visitJob.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Yi.Framework.Core.TaskJob { - class visitJob + class VisitJob { } } diff --git a/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs b/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs new file mode 100644 index 00000000..406563f8 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs @@ -0,0 +1,24 @@ +锘縰sing Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Yi.Framework.Model.Models; + +namespace Yi.Framework.Model.DbInit +{ + public class DataSeed + { + public async static Task SeedAsync(DbContext _Db) + { + if (!_Db.Set().Any()) + { + await _Db.Set().AddAsync(new user { username = "admin", password = "123" }); + } + await _Db.SaveChangesAsync(); + + Console.WriteLine(nameof(DbContext) + ":鏁版嵁搴撶敤鎴峰垵濮嬫垚鍔燂紒"); + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs index e275c04d..90d08025 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs @@ -23,7 +23,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend /// /// /// - public static async Task UseConsulService(this IApplicationBuilder app) + public static void UseConsulService(this IApplicationBuilder app) { var consulRegisterOption= Appsettings.app("ConsulRegisterOption"); @@ -34,7 +34,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend c.Datacenter = consulClientOption.Datacenter; })) { - await client.Agent.ServiceRegister(new AgentServiceRegistration() + client.Agent.ServiceRegister(new AgentServiceRegistration() { ID = $"{consulRegisterOption.IP}-{consulRegisterOption.Port}-{Guid.NewGuid()}",//鍞竴Id Name = consulRegisterOption.GroupName,//缁勫悕绉-Group @@ -48,7 +48,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend Timeout = TimeSpan.FromSeconds(consulRegisterOption.Timeout), DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulRegisterOption.DeregisterCriticalServiceAfter) } - }); + }).Wait(); Console.WriteLine($"{JsonConvert.SerializeObject(consulRegisterOption)} 瀹屾垚娉ㄥ唽"); } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs new file mode 100644 index 00000000..24219d1c --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs @@ -0,0 +1,31 @@ +锘縰sing log4net; +using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Yi.Framework.Model.DbInit; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + public static class DbSeedInitExtend + { + private static readonly ILog log = LogManager.GetLogger(typeof(DbSeedInitExtend)); + public static void UseDbSeedInitService(this IApplicationBuilder app, DbContext _Db) + { + if (app == null) throw new ArgumentNullException(nameof(app)); + + try + { + DataSeed.SeedAsync(_Db).Wait(); + } + catch (Exception e) + { + log.Error($"Error occured seeding the Database.\n{e.Message}"); + throw; + } + } + } +}