CompetitionAPI_dotnet/Competition.Common/Util/Tool.cs

692 lines
29 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SkiaSharp;
using Microsoft.VisualBasic;
using Org.BouncyCastle.Utilities.Collections;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using static NPOI.HSSF.Util.HSSFColor;
using System.Net.Http;
using System.Text.RegularExpressions;
namespace Competition.Common.Util
{
/// <summary>
/// 接口状态码
/// </summary>
public enum APICode
{
/// <summary>
/// 成功
/// </summary>
Success,
/// <summary>
/// 失败
/// </summary>
Fail,
/// <summary>
/// token失效
/// </summary>
TokenFail
}
/// <summary>
/// 工具类
/// </summary>
public class Tool
{
private static string appkey = "bridge-fenglin0903";
private static int vs = 0;
/// <summary>
/// 获取当前时间戳13位
/// </summary>
/// <returns></returns>
public static long GetTimestamp()
{
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
return (long)ts.TotalMilliseconds; //精确到毫秒
//return (long)ts.TotalSeconds;//获取10位
}
/// <summary>
/// 获取带状态码的JSON字符串
/// </summary>
/// <param name="code"></param>
/// <param name="dataObj"></param>
/// <returns></returns>
public static object GetJsonWithCode(APICode code, object dataObj)
{
return new { code = (int)code, state = code.ToString(), data = dataObj };
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
public static long DateTimeToTimestamp(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
}
/// <summary>
/// 时间戳转换为DATETIME格式
/// </summary>
/// <param name="timeStamp">时间戳字符串</param>
/// <returns></returns>
public static DateTime GetDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
string ts = timeStamp + "0000000";
if (timeStamp.Length == 13)
{
ts = timeStamp + "0000";
}
long lTime = long.Parse(ts);
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
/// <summary>
/// md5密码加密
/// </summary>
/// <param name="passWord">待加密字符串</param>
/// <returns></returns>
public static string GetMD5(string passWord)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bt = Encoding.Default.GetBytes(passWord);//将待加密字符转为 字节型数组
byte[] resualt = md5.ComputeHash(bt);//将字节数组转为加密的字节数组
string pwds = BitConverter.ToString(resualt).Replace("-", "");
passWord = pwds;
return passWord;
}
///// <summary>
///// 图片转成base64
///// </summary>
///// <param name="Imagefilename"></param>
///// <returns></returns>
//public static string img_to_base64(string Imagefilename)
//{
// try
// {
// using (MemoryStream memoryStream = new MemoryStream())
// {
// Bitmap file = new Bitmap(Imagefilename);
// file.Save(memoryStream, file.RawFormat);
// file.Dispose();
// byte[] imageBytes = memoryStream.ToArray();
// return Convert.ToBase64String(imageBytes);
// }
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
//}
/// <summary>
/// 图片转成base64
/// </summary>
/// <param name="Imagefilename"></param>
/// <returns></returns>
public static string img_to_base64(string Imagefilename)
{
try
{
// 加载图片
using var stream = new FileStream(Imagefilename, FileMode.Open);
using var image = SKBitmap.Decode(stream);
// 创建位图副本的内存流用于转换为Base64
using var bitmapStream = new MemoryStream();
image.Encode(SKEncodedImageFormat.Jpeg, 90).SaveTo(bitmapStream);
// 获取内存流中的字节数据
byte[] imageBytes = bitmapStream.ToArray();
// 将字节数据转换为Base64字符串
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="file">需要删除的文件路径</param>
/// <returns></returns>
public static bool DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (System.IO.File.Exists(f))
{
//如果有子文件删除文件
System.IO.File.Delete(f);
//Console.WriteLine(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
return true;
}
catch (Exception ex) // 异常处理
{
return false;
}
}
/// <summary>
/// 根据总分和数量计算出第一个值是多少,和其余值是多少
/// </summary>
/// <param name="score"></param>
/// <param name="numberOfQuestions"></param>
/// <returns></returns>
public static decimal TransFormation(decimal score, int numberOfQuestions, out decimal otherQuestionScore)
{
// 计算基本的每题分数,这里先不考虑余数
decimal baseScorePerQuestion = score / numberOfQuestions;
// 计算剩余的分数,这部分将被加到第一题上
decimal remainingScore = score - (baseScorePerQuestion * numberOfQuestions);
// 确保每份分数只保留3位小数
decimal scorePerQuestionRounded = Math.Round(baseScorePerQuestion, 3, MidpointRounding.AwayFromZero);
// 第一题分数加上所有剩余的分数由于之前已经四舍五入这里直接加剩余Score即可
decimal firstQuestionScore = scorePerQuestionRounded + remainingScore;
// 其他题目分数保持为四舍五入后的基本分数
otherQuestionScore = scorePerQuestionRounded;
// 由于直接加剩余Score可能造成轻微的浮点运算误差这里再次校正以确保总和正确
if (Math.Abs(firstQuestionScore + (otherQuestionScore * (numberOfQuestions - 1)) - score) > 0.0001m)
{
// 这里理论上不应该进入,但如果因为浮点运算误差导致不等,可以通过直接赋值确保总和正确
firstQuestionScore = score - (otherQuestionScore * (numberOfQuestions - 1));
}
return firstQuestionScore;
}
///// <summary>
///// 生成图片
///// </summary>
///// <param name="name">名称</param>
///// <param name="start">起点</param>
///// <param name="end">终点</param>
///// <param name="model_length">型号长度</param>
///// <param name="path">生成图片后的路径</param>
///// <param name="root_path">wwwroot文件</param>
//public static string GeneratePictures(string name, string start, string end, string model_length, string path, string root_path)
//{
// try
// {
// Font LabelFont = new Font("Adobe 黑体 Std R", 50); //设置字体、字号、是否加粗
// SolidBrush labelColor = new SolidBrush(Color.Black);//设置字体颜色
// MemoryStream ms = new MemoryStream(File.ReadAllBytes(Path.Combine(root_path, "Img", "BaseMap.jpg")));//底图
// Image imgSource = Image.FromStream(ms);//底图
// Graphics graphics = Graphics.FromImage(imgSource);//设置画图对象
// StringFormat sf = new StringFormat();//位置对象
// sf.Alignment = StringAlignment.Near;//左对齐,使用时看一下注释,尝试一下,和矩形框有关系
// //sf.Alignment = StringAlignment.Center;//居中
// //sf.Alignment = StringAlignment.Near;//右对齐
// Rectangle rt1 = new Rectangle(240, 155, imgSource.Width, imgSource.Height);//绘图区域框0x方向开始位置20y方向开始位置宽和高是矩形的宽和高
// graphics.DrawString(name, LabelFont, labelColor, rt1, sf);
// Rectangle rt2 = new Rectangle(240, 230, imgSource.Width, imgSource.Height);
// graphics.DrawString(start, LabelFont, labelColor, rt2, sf);
// Rectangle rt3 = new Rectangle(240, 305, imgSource.Width, imgSource.Height);
// graphics.DrawString(end, LabelFont, labelColor, rt3, sf);
// Rectangle rt4 = new Rectangle(360, 380, imgSource.Width, imgSource.Height);
// graphics.DrawString(model_length, LabelFont, labelColor, rt4, sf);
// Rectangle rt5 = new Rectangle(360, 455, imgSource.Width, imgSource.Height);
// graphics.DrawString("配电工程处", LabelFont, labelColor, rt5, sf);
// Rectangle rt6 = new Rectangle(240, 530, imgSource.Width, imgSource.Height);
// graphics.DrawString("2019年8月16日", LabelFont, labelColor, rt6, sf);
// //graphics.DrawString("另一种写法我在x、y位置", LabelFont, labelColor, x, y);//相对于左上角的x、y坐标
// imgSource.Save(root_path + path);
// imgSource.Dispose();
// graphics.Dispose();
// return "true";
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
//}
/// <summary>
/// 生成图片
/// </summary>
/// <param name="name">名称</param>
/// <param name="start">起点</param>
/// <param name="end">终点</param>
/// <param name="model_length">型号长度</param>
/// <param name="path">生成图片后的路径</param>
/// <param name="root_path">wwwroot文件</param>
public static bool GeneratePictures(string name, string start, string end, string model_length, string path, string root_path)
{
try
{
// 加载底图
using (var inputStream = System.IO.File.OpenRead(root_path + "/Img/BaseMap.jpg"))
using (var original = SKBitmap.Decode(inputStream))
{
// 创建一个新的位图对象,用于绘制
using (var bitmap = new SKBitmap(original.Width, original.Height))
{
// 将底图绘制到新的位图对象上
using (var canvas = new SKCanvas(bitmap))
{
canvas.DrawBitmap(original, 0, 0);
}
// 在新的位图对象上绘制文本
using (var canvas = new SKCanvas(bitmap))
{
using (var paint = new SKPaint())
{
// 获取当前操作系统的平台
PlatformID platform = Environment.OSVersion.Platform;
SKTypeface typeface = SKTypeface.FromFile("");
// 判断操作系统平台
if (platform == PlatformID.Win32NT || platform == PlatformID.Win32S || platform == PlatformID.Win32Windows || platform == PlatformID.WinCE)
{
// 加载自定义中文字体
typeface = SKTypeface.FromFile(Path.Combine("C:" + Path.DirectorySeparatorChar, "Windows", "Fonts", "msyh.ttc"));
}
else
{
typeface = SKTypeface.FromFile(Path.Combine("" + Path.DirectorySeparatorChar, "usr", "share", "fonts", "msyh.ttc"));
}
//
paint.Typeface = typeface;
paint.Color = SKColors.Black;
paint.TextSize = 50;
// 在底图上绘制中文文本
canvas.DrawText(name, 240, 195, paint);
canvas.DrawText(start, 240, 270, paint);
canvas.DrawText(end, 240, 345, paint);
canvas.DrawText(model_length, 360, 420, paint);
canvas.DrawText("配电工程处", 360, 495, paint);
canvas.DrawText("2019年8月16日", 240, 570, paint);
}
}
// 将位图保存为图片文件
using (var image = SKImage.FromBitmap(bitmap))
using (var data = image.Encode(SKEncodedImageFormat.Png, 85))
using (var outputStream = System.IO.File.OpenWrite(root_path + path))
{
data.SaveTo(outputStream);
}
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public static bool CopyAndRenameImage(string sourcePath, string destinationPath)
{
try
{
// 使用File.Copy方法复制图片
File.Copy(sourcePath, destinationPath, true); // 第三个参数为true表示如果目标文件存在则覆盖
return true;
}
catch (Exception ex)
{
}
return false;
}
public static DataTable ExcelToDataTable(Stream fs, string suffix, string sheetName, int startRow, bool isFirstRowColumn, bool cshz)
{
DataTable dataTable = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int cellCount = 0;
// int startRow = 0;
try
{
// 2007版本
if (suffix == ".xlsx")
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (suffix == ".xls")
workbook = new HSSFWorkbook(fs);
if (workbook != null)
{
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet则尝试获取第一个sheet
{
if (cshz)
{
return null;
}
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(startRow);//第一行
int rowindex = 0; //搜索空行,并跳过
while (firstRow == null && rowindex < rowCount)
{
rowindex++;
firstRow = sheet.GetRow(rowindex);
} //如果全为空行则返回null值
if (rowindex == rowCount) return null;
cellCount = firstRow.LastCellNum;//列数
startRow = firstRow.RowNum;
// 构建datatable的列
if (isFirstRowColumn)
{
//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.ToString() != null)
{
column = new DataColumn(cell.ToString());
dataTable.Columns.Add(column);
}
}
}
startRow++;
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
}
// 填充行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue;
cellCount = row.LastCellNum; //全文行之间的列数不一样的话,继续添加列
if (cellCount > dataTable.Columns.Count)
{
for (int c = dataTable.Columns.Count; c < cellCount; c++)
{
column = new DataColumn("column" + (c + 1));
dataTable.Columns.Add(column);
}
}
dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
// CellType(Unknown = -1, Numeric = 0, String = 1, Formula = 2, Blank = 3, Boolean = 4, Error = 5,)
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
// 对时间格式2015.12.5、2015 / 12 / 5、2015 - 12 - 5等的处理
if (format == 14 || format == 31 || format == 57 || format == 58)
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
}
return dataTable;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return null;
}
}
public static string GetNumber()
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var NewId = "";
NewId = string.Format("{0}{1}{2}", array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First());
return NewId;
}
public static string GetLongId()
{
return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0));
}
/// <summary>
/// 角色
/// </summary>
public static Dictionary<string, string> DicRole = new Dictionary<string, string>()
{
{"0","超级管理员"} , {"1","管理员"} , {"2","学员"}
};
/// <summary>
/// 新ID
/// </summary>
/// <param name="flag"></param>
/// <returns></returns>
public static string GetNewId(string flag)
{
string NewId = string.Format("{0}{1}", flag.ToUpper(), GetNewId());
return NewId;
}
private static object lockObject = new object();
public static string GetNewId(bool sync = true)
{
var d = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var NewId = "";
if (!sync)
{
NewId = string.Format("{0}{1}{2}{3}{4}", DateTime.Now.ToString("yyyyMMddHHmmssffff"), d.Next(0, 1000).ToString().PadLeft(3, '0'), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First());
return NewId;
}
lock (lockObject)
{
System.Threading.Thread.Sleep(1);
NewId = string.Format("{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
return NewId;
}
}
private static Object Lockobj = new object();
public static string GetId(string preifx = "")
{
lock (Lockobj)
{
Thread.Sleep(1);
var val = preifx + ConvertDateTimeInt(DateTime.Now);
return string.Format("{0}{1}", val, DateTime.Now.ToString("fff"));
}
}
/// <summary>
/// DateTime时间格式转换为10位不带毫秒的Unix时间戳
/// </summary>
/// <returns>Unix时间戳格式</returns>
public static long ConvertDateTimeInt(DateTime dt)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
return (long)(dt - startTime).TotalSeconds;
}
public static string GetNextId(string Id, int Position)
{
return string.Format("{0}{1}", Id, Position.ToString().PadLeft(3, '0'));
}
/// <summary>
/// 判断是否能使用
/// </summary>
/// <returns></returns>
public static bool CheckClose()
{
try
{
vs = zKeyAccess.KeyUtil.GetAccess(appkey);
if (vs <= 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return true;
}
}
#region
/// <summary>
/// 根据属性名称获取值
/// </summary>
/// <param name="obj">对象实例</param>
/// <param name="strAttribute">属性名</param>
/// <returns>object</returns>
private static object GetValueByStrAttribute(object obj, string strAttribute)
{
System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
if (null == propertyInfoName)
{
throw new Exception("属性名:" + strAttribute + " 不存在!");
}
return propertyInfoName.GetValue(obj, null);
}
#endregion
#region
/// <summary>
/// 根据属性名称设置值
/// </summary>
/// <param name="obj">对象实例</param>
/// <param name="strAttribute">属性名</param>
/// <param name="value">值</param>
public static void SetValueByStrAttribute(object obj, string strAttribute, object value)
{
System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
if (null != propertyInfoName)
{
if (propertyInfoName.PropertyType == typeof(Nullable<Int32>) || propertyInfoName.PropertyType == typeof(Int32))
{
int int_value = 0;
if (int.TryParse(value.ToString(), out int_value))
{
propertyInfoName.SetValue(obj, int_value, null);
}
}
else if (propertyInfoName.PropertyType == typeof(Nullable<decimal>) || propertyInfoName.PropertyType == typeof(decimal))
{
decimal decimal_value = 0;
if (decimal.TryParse(value.ToString(), out decimal_value))
{
propertyInfoName.SetValue(obj, decimal_value, null);
}
propertyInfoName.SetValue(obj, decimal_value, null);
}
else
{
propertyInfoName.SetValue(obj, value, null);
}
}
}
#endregion
}
}