种子数据
This commit is contained in:
@@ -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<75><6C><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
//await app.UseConsulService();
|
||||
//app.UseConsulService();
|
||||
|
||||
#region
|
||||
//<2F><><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseDbSeedInitService(_Db);
|
||||
|
||||
#region
|
||||
//Endpointsע<73><D7A2>
|
||||
|
||||
101
Yi.Framework/Yi.Framework.Common/Helper/Base32Helper.cs
Normal file
101
Yi.Framework/Yi.Framework.Common/Helper/Base32Helper.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
using 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";
|
||||
|
||||
/// <summary>
|
||||
/// Converts an array of bytes to a Base32-k string.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Converts a Base32-k string into an array of bytes.
|
||||
/// </summary>
|
||||
/// <exception cref="System.ArgumentException">
|
||||
/// Input string <paramref name="s">s</paramref> contains invalid Base32-k characters.
|
||||
/// </exception>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
54
Yi.Framework/Yi.Framework.Common/Helper/ConsoleHelper.cs
Normal file
54
Yi.Framework/Yi.Framework.Common/Helper/ConsoleHelper.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 打印错误信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteErrorLine(this string str, ConsoleColor color = ConsoleColor.Red)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 打印警告信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteWarningLine(this string str, ConsoleColor color = ConsoleColor.Yellow)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
/// <summary>
|
||||
/// 打印正常信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteInfoLine(this string str, ConsoleColor color = ConsoleColor.White)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
/// <summary>
|
||||
/// 打印成功的信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteSuccessLine(this string str, ConsoleColor color = ConsoleColor.Green)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
58
Yi.Framework/Yi.Framework.Common/Helper/DateHelper.cs
Normal file
58
Yi.Framework/Yi.Framework.Common/Helper/DateHelper.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using 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} 分 ";
|
||||
}
|
||||
/// <summary>
|
||||
/// 时间戳转本地时间-时间戳精确到秒
|
||||
/// </summary>
|
||||
public static DateTime ToLocalTimeDateBySeconds(long unix)
|
||||
{
|
||||
var dto = DateTimeOffset.FromUnixTimeSeconds(unix);
|
||||
return dto.ToLocalTime().DateTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间转时间戳Unix-时间戳精确到秒
|
||||
/// </summary>
|
||||
public static long ToUnixTimestampBySeconds(DateTime dt)
|
||||
{
|
||||
DateTimeOffset dto = new DateTimeOffset(dt);
|
||||
return dto.ToUnixTimeSeconds();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 时间戳转本地时间-时间戳精确到毫秒
|
||||
/// </summary>
|
||||
public static DateTime ToLocalTimeDateByMilliseconds(long unix)
|
||||
{
|
||||
var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix);
|
||||
return dto.ToLocalTime().DateTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间转时间戳Unix-时间戳精确到毫秒
|
||||
/// </summary>
|
||||
public static long ToUnixTimestampByMilliseconds(DateTime dt)
|
||||
{
|
||||
DateTimeOffset dto = new DateTimeOffset(dt);
|
||||
return dto.ToUnixTimeMilliseconds();
|
||||
}
|
||||
}
|
||||
}
|
||||
395
Yi.Framework/Yi.Framework.Common/Helper/FileHelper.cs
Normal file
395
Yi.Framework/Yi.Framework.Common/Helper/FileHelper.cs
Normal file
@@ -0,0 +1,395 @@
|
||||
using 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 取得文件后缀名
|
||||
/****************************************
|
||||
* 函数名称:GetPostfixStr
|
||||
* 功能说明:取得文件后缀名
|
||||
* 参 数:filename:文件名称
|
||||
* 调用示列:
|
||||
* string filename = "aaa.aspx";
|
||||
* string s = EC.FileObj.GetPostfixStr(filename);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 取后缀名
|
||||
/// </summary>
|
||||
/// <param name="filename">文件名</param>
|
||||
/// <returns>.gif|.html格式</returns>
|
||||
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 根据文件大小获取指定前缀的可用文件名
|
||||
/// <summary>
|
||||
/// 根据文件大小获取指定前缀的可用文件名
|
||||
/// </summary>
|
||||
/// <param name="folderPath">文件夹</param>
|
||||
/// <param name="prefix">文件前缀</param>
|
||||
/// <param name="size">文件大小(1m)</param>
|
||||
/// <param name="ext">文件后缀(.log)</param>
|
||||
/// <returns>可用文件名</returns>
|
||||
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 写文件
|
||||
/****************************************
|
||||
* 函数名称:WriteFile
|
||||
* 功能说明:写文件,会覆盖掉以前的内容
|
||||
* 参 数:Path:文件路径,Strings:文本内容
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default2.aspx");
|
||||
* string Strings = "这是我写的内容啊";
|
||||
* EC.FileObj.WriteFile(Path,Strings);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 写文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="Strings">文件内容</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="Strings">文件内容</param>
|
||||
/// <param name="encode">编码格式</param>
|
||||
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 读文件
|
||||
/****************************************
|
||||
* 函数名称:ReadFile
|
||||
* 功能说明:读取文本内容
|
||||
* 参 数:Path:文件路径
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default2.aspx");
|
||||
* string s = EC.FileObj.ReadFile(Path);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 读文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="encode">编码格式</param>
|
||||
/// <returns></returns>
|
||||
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 追加文件
|
||||
/****************************************
|
||||
* 函数名称:FileAdd
|
||||
* 功能说明:追加文件内容
|
||||
* 参 数:Path:文件路径,strings:内容
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default2.aspx");
|
||||
* string Strings = "新追加内容";
|
||||
* EC.FileObj.FileAdd(Path, Strings);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 追加文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="strings">内容</param>
|
||||
public static void FileAdd(string Path, string strings)
|
||||
{
|
||||
StreamWriter sw = File.AppendText(Path);
|
||||
sw.Write(strings);
|
||||
sw.Flush();
|
||||
sw.Close();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 拷贝文件
|
||||
/****************************************
|
||||
* 函数名称:FileCoppy
|
||||
* 功能说明:拷贝文件
|
||||
* 参 数:OrignFile:原始文件,NewFile:新文件路径
|
||||
* 调用示列:
|
||||
* string orignFile = Server.MapPath("Default2.aspx");
|
||||
* string NewFile = Server.MapPath("Default3.aspx");
|
||||
* EC.FileObj.FileCoppy(OrignFile, NewFile);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 拷贝文件
|
||||
/// </summary>
|
||||
/// <param name="OrignFile">原始文件</param>
|
||||
/// <param name="NewFile">新文件路径</param>
|
||||
public static void FileCoppy(string orignFile, string NewFile)
|
||||
{
|
||||
File.Copy(orignFile, NewFile, true);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 删除文件
|
||||
/****************************************
|
||||
* 函数名称:FileDel
|
||||
* 功能说明:删除文件
|
||||
* 参 数:Path:文件路径
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default3.aspx");
|
||||
* EC.FileObj.FileDel(Path);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 删除文件
|
||||
/// </summary>
|
||||
/// <param name="Path">路径</param>
|
||||
public static void FileDel(string Path)
|
||||
{
|
||||
File.Delete(Path);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 移动文件
|
||||
/****************************************
|
||||
* 函数名称:FileMove
|
||||
* 功能说明:移动文件
|
||||
* 参 数:OrignFile:原始路径,NewFile:新文件路径
|
||||
* 调用示列:
|
||||
* string orignFile = Server.MapPath("../说明.txt");
|
||||
* string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
|
||||
* EC.FileObj.FileMove(OrignFile, NewFile);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 移动文件
|
||||
/// </summary>
|
||||
/// <param name="OrignFile">原始路径</param>
|
||||
/// <param name="NewFile">新路径</param>
|
||||
public static void FileMove(string orignFile, string NewFile)
|
||||
{
|
||||
File.Move(orignFile, NewFile);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 在当前目录下创建目录
|
||||
/****************************************
|
||||
* 函数名称:FolderCreate
|
||||
* 功能说明:在当前目录下创建目录
|
||||
* 参 数:OrignFolder:当前目录,NewFloder:新目录
|
||||
* 调用示列:
|
||||
* string orignFolder = Server.MapPath("test/");
|
||||
* string NewFloder = "new";
|
||||
* EC.FileObj.FolderCreate(OrignFolder, NewFloder);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 在当前目录下创建目录
|
||||
/// </summary>
|
||||
/// <param name="OrignFolder">当前目录</param>
|
||||
/// <param name="NewFloder">新目录</param>
|
||||
public static void FolderCreate(string orignFolder, string NewFloder)
|
||||
{
|
||||
Directory.SetCurrentDirectory(orignFolder);
|
||||
Directory.CreateDirectory(NewFloder);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 递归删除文件夹目录及文件
|
||||
/****************************************
|
||||
* 函数名称:DeleteFolder
|
||||
* 功能说明:递归删除文件夹目录及文件
|
||||
* 参 数:dir:文件夹路径
|
||||
* 调用示列:
|
||||
* string dir = Server.MapPath("test/");
|
||||
* EC.FileObj.DeleteFolder(dir);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 递归删除文件夹目录及文件
|
||||
/// </summary>
|
||||
/// <param name="dir"></param>
|
||||
/// <returns></returns>
|
||||
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 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
|
||||
/****************************************
|
||||
* 函数名称:CopyDir
|
||||
* 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
|
||||
* 参 数:srcPath:原始路径,aimPath:目标文件夹
|
||||
* 调用示列:
|
||||
* string srcPath = Server.MapPath("test/");
|
||||
* string aimPath = Server.MapPath("test1/");
|
||||
* EC.FileObj.CopyDir(srcPath,aimPath);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 指定文件夹下面的所有内容copy到目标文件夹下面
|
||||
/// </summary>
|
||||
/// <param name="srcPath">原始路径</param>
|
||||
/// <param name="aimPath">目标文件夹</param>
|
||||
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);
|
||||
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
|
||||
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
|
||||
//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
|
||||
}
|
||||
}
|
||||
24
Yi.Framework/Yi.Framework.Common/Helper/HtmlHelper.cs
Normal file
24
Yi.Framework/Yi.Framework.Common/Helper/HtmlHelper.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class HtmlHelper
|
||||
{
|
||||
#region 去除富文本中的HTML标签
|
||||
/// <summary>
|
||||
/// 去除富文本中的HTML标签
|
||||
/// </summary>
|
||||
/// <param name="html"></param>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
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
|
||||
}
|
||||
}
|
||||
51
Yi.Framework/Yi.Framework.Common/Helper/IpHelper.cs
Normal file
51
Yi.Framework/Yi.Framework.Common/Helper/IpHelper.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class IpHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前IP地址
|
||||
/// </summary>
|
||||
/// <param name="preferredNetworks"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetCurrentIp(string preferredNetworks)
|
||||
{
|
||||
var instanceIp = "127.0.0.1";
|
||||
|
||||
try
|
||||
{
|
||||
// 获取可用网卡
|
||||
var nics = NetworkInterface.GetAllNetworkInterfaces()?.Where(network => network.OperationalStatus == OperationalStatus.Up);
|
||||
|
||||
// 获取所有可用网卡IP信息
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
498
Yi.Framework/Yi.Framework.Common/Helper/JsonHelper.cs
Normal file
498
Yi.Framework/Yi.Framework.Common/Helper/JsonHelper.cs
Normal file
@@ -0,0 +1,498 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class JsonHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 转换对象为JSON格式数据
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类</typeparam>
|
||||
/// <param name="obj">对象</param>
|
||||
/// <returns>字符格式的JSON数据</returns>
|
||||
public static string GetJSON<T>(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;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换List<T>的数据为JSON格式
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类</typeparam>
|
||||
/// <param name="vals">列表值</param>
|
||||
/// <returns>JSON格式数据</returns>
|
||||
public string JSON<T>(List<T> 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();
|
||||
}
|
||||
/// <summary>
|
||||
/// JSON格式字符转换为T类型的对象
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="jsonStr"></param>
|
||||
/// <returns></returns>
|
||||
public static T ParseFormByJson<T>(string jsonStr)
|
||||
{
|
||||
T obj = Activator.CreateInstance<T>();
|
||||
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<SendData>(List<SendData> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取值的长度(当Json值嵌套以"{"或"["开头时)
|
||||
/// </summary>
|
||||
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)//正常字符,值状态下。
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理)
|
||||
/// </summary>
|
||||
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;//正常结束。
|
||||
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;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 字符状态
|
||||
/// </summary>
|
||||
public class CharState
|
||||
{
|
||||
internal bool jsonStart = false;//以 "{"开始了...
|
||||
internal bool setDicValue = false;// 可以设置字典值了。
|
||||
internal bool escapeChar = false;//以"\"转义符号开始了
|
||||
/// <summary>
|
||||
/// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。
|
||||
/// </summary>
|
||||
internal bool arrayStart = false;//以"[" 符号开始了
|
||||
internal bool childrenStart = false;//子级嵌套开始了。
|
||||
/// <summary>
|
||||
/// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】
|
||||
/// </summary>
|
||||
internal int state = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】
|
||||
/// </summary>
|
||||
internal int keyStart = 0;
|
||||
/// <summary>
|
||||
/// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】
|
||||
/// </summary>
|
||||
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)
|
||||
//{
|
||||
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
Yi.Framework/Yi.Framework.Common/Helper/MD5Hepler.cs
Normal file
67
Yi.Framework/Yi.Framework.Common/Helper/MD5Hepler.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class MD5Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// 16位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 32位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt32(string password = "")
|
||||
{
|
||||
string pwd = string.Empty;
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
MD5 md5 = MD5.Create(); //实例化一个md5对像
|
||||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
|
||||
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
|
||||
foreach (var item in s)
|
||||
{
|
||||
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
|
||||
pwd = string.Concat(pwd, item.ToString("X2"));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new Exception($"错误的 password 字符串:【{password}】");
|
||||
}
|
||||
return pwd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 64位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt64(string password)
|
||||
{
|
||||
// 实例化一个md5对像
|
||||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||||
MD5 md5 = MD5.Create();
|
||||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
|
||||
return Convert.ToBase64String(s);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
390
Yi.Framework/Yi.Framework.Common/Helper/RSAHelper.cs
Normal file
390
Yi.Framework/Yi.Framework.Common/Helper/RSAHelper.cs
Normal file
@@ -0,0 +1,390 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// RSA加解密 使用OpenSSL的公钥加密/私钥解密
|
||||
/// 公私钥请使用openssl生成
|
||||
/// </summary>
|
||||
public class RSAHelper
|
||||
{
|
||||
public readonly RSA _privateKeyRsaProvider;
|
||||
public readonly RSA _publicKeyRsaProvider;
|
||||
private readonly HashAlgorithmName _hashAlgorithmName;
|
||||
private readonly Encoding _encoding;
|
||||
|
||||
/// <summary>
|
||||
/// 实例化RSAHelper
|
||||
/// </summary>
|
||||
/// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
|
||||
/// <param name="encoding">编码类型</param>
|
||||
/// <param name="privateKey">私钥</param>
|
||||
/// <param name="publicKey">公钥</param>
|
||||
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 使用私钥签名
|
||||
|
||||
/// <summary>
|
||||
/// 使用私钥签名
|
||||
/// </summary>
|
||||
/// <param name="data">原始数据</param>
|
||||
/// <returns></returns>
|
||||
public string Sign(string data)
|
||||
{
|
||||
byte[] dataBytes = _encoding.GetBytes(data);
|
||||
|
||||
var signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);
|
||||
|
||||
return Convert.ToBase64String(signatureBytes);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 使用公钥验签
|
||||
|
||||
/// <summary>
|
||||
/// 使用公钥验签
|
||||
/// </summary>
|
||||
/// <param name="data">原始数据</param>
|
||||
/// <param name="sign">签名</param>
|
||||
/// <returns></returns>
|
||||
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 解密
|
||||
/// <summary>
|
||||
/// 私钥解密(原)
|
||||
/// </summary>
|
||||
/// <param name="cipherText">解密字符串(base64)</param>
|
||||
/// <returns></returns>
|
||||
|
||||
//public string Decrypt(string cipherText)
|
||||
//{
|
||||
// if (_privateKeyRsaProvider == null)
|
||||
// {
|
||||
// throw new Exception("_privateKeyRsaProvider is null");
|
||||
// }
|
||||
// return _encoding.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
|
||||
//}
|
||||
/// <summary>
|
||||
/// 私钥解密(支持大量数据)
|
||||
/// </summary>
|
||||
/// <param name="cipherText"></param>
|
||||
/// <returns></returns>
|
||||
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 加密
|
||||
|
||||
/// <summary>
|
||||
/// 公钥加密(原)
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
//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));
|
||||
//}
|
||||
/// <summary>
|
||||
/// 公钥加密(支持大量数据)
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
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实例
|
||||
/// <summary>
|
||||
/// 使用私钥创建RSA实例
|
||||
/// </summary>
|
||||
/// <param name="privateKey"></param>
|
||||
/// <returns></returns>
|
||||
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实例
|
||||
/// <summary>
|
||||
/// 使用公钥创建RSA实例
|
||||
/// </summary>
|
||||
/// <param name="publicKeyString"></param>
|
||||
/// <returns></returns>
|
||||
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
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RSA算法类型
|
||||
/// </summary>
|
||||
public enum RSAType
|
||||
{
|
||||
/// <summary>
|
||||
/// SHA1
|
||||
/// </summary>
|
||||
RSA = 0,
|
||||
/// <summary>
|
||||
/// RSA2 密钥长度至少为2048
|
||||
/// SHA256
|
||||
/// </summary>
|
||||
RSA2
|
||||
}
|
||||
}
|
||||
35
Yi.Framework/Yi.Framework.Common/Helper/SerializeHelper.cs
Normal file
35
Yi.Framework/Yi.Framework.Common/Helper/SerializeHelper.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class SerializeHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 序列化
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] Serialize(object item)
|
||||
{
|
||||
var jsonString = JsonConvert.SerializeObject(item);
|
||||
|
||||
return Encoding.UTF8.GetBytes(jsonString);
|
||||
}
|
||||
/// <summary>
|
||||
/// 反序列化
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static TEntity Deserialize<TEntity>(byte[] value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return default(TEntity);
|
||||
}
|
||||
var jsonString = Encoding.UTF8.GetString(value);
|
||||
return JsonConvert.DeserializeObject<TEntity>(jsonString);
|
||||
}
|
||||
}
|
||||
}
|
||||
111
Yi.Framework/Yi.Framework.Common/Helper/StringHelper.cs
Normal file
111
Yi.Framework/Yi.Framework.Common/Helper/StringHelper.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class StringHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据分隔符返回前n条数据
|
||||
/// </summary>
|
||||
/// <param name="content">数据内容</param>
|
||||
/// <param name="separator">分隔符</param>
|
||||
/// <param name="top">前n条</param>
|
||||
/// <param name="isDesc">是否倒序(默认false)</param>
|
||||
/// <returns></returns>
|
||||
public static List<string> GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(content))
|
||||
{
|
||||
return new List<string>() { };
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据字段拼接get参数
|
||||
/// </summary>
|
||||
/// <param name="dic"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetPars(Dictionary<string, object> 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;
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据字段拼接get参数
|
||||
/// </summary>
|
||||
/// <param name="dic"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetPars(Dictionary<string, string> 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;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取一个GUID
|
||||
/// </summary>
|
||||
/// <param name="format">格式-默认为N</param>
|
||||
/// <returns></returns>
|
||||
public static string GetGUID(string format="N") {
|
||||
return Guid.NewGuid().ToString(format);
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据GUID获取19位的唯一数字序列
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static long GetGuidToLongID()
|
||||
{
|
||||
byte[] buffer = Guid.NewGuid().ToByteArray();
|
||||
return BitConverter.ToInt64(buffer, 0);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取字符串最后X行
|
||||
/// </summary>
|
||||
/// <param name="resourceStr"></param>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
47
Yi.Framework/Yi.Framework.Common/Helper/UnicodeHelper.cs
Normal file
47
Yi.Framework/Yi.Framework.Common/Helper/UnicodeHelper.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class UnicodeHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 字符串转Unicode码
|
||||
/// </summary>
|
||||
/// <returns>The to unicode.</returns>
|
||||
/// <param name="value">Value.</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unicode转字符串
|
||||
/// </summary>
|
||||
/// <returns>The to string.</returns>
|
||||
/// <param name="unicode">Unicode.</param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
23
Yi.Framework/Yi.Framework.Common/Helper/UrlHelper.cs
Normal file
23
Yi.Framework/Yi.Framework.Common/Helper/UrlHelper.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class UrlHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// UrlEncode编码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <returns></returns>
|
||||
public static string UrlEncode(string url) {
|
||||
return System.Web.HttpUtility.UrlEncode(url, System.Text.Encoding.UTF8);
|
||||
}
|
||||
/// <summary>
|
||||
/// UrlEncode解码
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
/// <returns></returns>
|
||||
public static string UrlDecode(string data)
|
||||
{
|
||||
return System.Web.HttpUtility.UrlDecode(data, System.Text.Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
}
|
||||
51
Yi.Framework/Yi.Framework.Common/Helper/XmlHelper.cs
Normal file
51
Yi.Framework/Yi.Framework.Common/Helper/XmlHelper.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class XmlHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 转换对象为JSON格式数据
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类</typeparam>
|
||||
/// <param name="obj">对象</param>
|
||||
/// <returns>字符格式的JSON数据</returns>
|
||||
public static string GetXML<T>(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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Xml格式字符转换为T类型的对象
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="xml"></param>
|
||||
/// <returns></returns>
|
||||
public static T ParseFormByXml<T>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
16
Yi.Framework/Yi.Framework.Common/Models/AxiosUrlsModel.cs
Normal file
16
Yi.Framework/Yi.Framework.Common/Models/AxiosUrlsModel.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using 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; }
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Core.TaskJob
|
||||
{
|
||||
class visitJob
|
||||
class VisitJob
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
24
Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs
Normal file
24
Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using 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<user>().Any())
|
||||
{
|
||||
await _Db.Set<user>().AddAsync(new user { username = "admin", password = "123" });
|
||||
}
|
||||
await _Db.SaveChangesAsync();
|
||||
|
||||
Console.WriteLine(nameof(DbContext) + ":数据库用户初始成功!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
/// <param name="app"></param>
|
||||
/// <param name="healthService"></param>
|
||||
/// <returns></returns>
|
||||
public static async Task UseConsulService(this IApplicationBuilder app)
|
||||
public static void UseConsulService(this IApplicationBuilder app)
|
||||
{
|
||||
var consulRegisterOption= Appsettings.app<ConsulRegisterOption>("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)} 完成注册");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user