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;
namespace Competition.Common.Util
{
///
/// 接口状态码
///
public enum APICode
{
///
/// 成功
///
Success,
///
/// 失败
///
Fail
}
///
/// 工具类
///
public class Tool
{
private static string appkey = "bridge-fenglin0903";
private static int vs = 0;
///
/// 获取当前时间戳13位
///
///
public static long GetTimestamp()
{
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
return (long)ts.TotalMilliseconds; //精确到毫秒
//return (long)ts.TotalSeconds;//获取10位
}
///
/// 获取带状态码的JSON字符串
///
///
///
///
public static object GetJsonWithCode(APICode code, object dataObj)
{
return new { code = (int)code, state = code.ToString(), data = dataObj };
}
///
/// 将c# DateTime时间格式转换为Unix时间戳格式
///
/// 时间
/// long
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;
}
///
/// 时间戳转换为DATETIME格式
///
/// 时间戳字符串
///
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);
}
///
/// md5密码加密
///
/// 待加密字符串
///
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;
}
///
/// 图片转成base64
///
///
///
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)
{
return "";
}
}
/////
///// 生成图片
/////
///// 名称
///// 起点
///// 终点
///// 型号长度
///// 生成图片后的路径
///// wwwroot文件
//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(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);//绘图区域框,0:x方向开始位置,20:y方向开始位置,宽和高是矩形的宽和高
// 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;
// }
//}
///
/// 生成图片
///
/// 名称
/// 起点
/// 终点
/// 型号长度
/// 生成图片后的路径
/// wwwroot文件
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())
{
//paint.Color = SKColors.Black;
//paint.TextSize = 30;
//// 在底图上绘制文本
//canvas.DrawText(name, 100, 100, paint);
//canvas.DrawText(start, 100, 150, paint);
//canvas.DrawText(end, 100, 200, paint);
// 获取当前操作系统的平台
PlatformID platform = Environment.OSVersion.Platform;
SKTypeface typeface = SKTypeface.FromFile("");
// 判断操作系统平台
if (platform == PlatformID.Win32NT || platform == PlatformID.Win32S || platform == PlatformID.Win32Windows || platform == PlatformID.WinCE)
{
//Console.WriteLine("Windows 操作系统");
// 加载自定义中文字体
typeface = SKTypeface.FromFile("C:\\Windows\\Fonts\\msyh.ttc");
}
else
{
typeface = SKTypeface.FromFile("/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, 100))
using (var outputStream = System.IO.File.OpenWrite(root_path + path))
{
data.SaveTo(outputStream);
}
}
}
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));
}
///
/// 角色
///
public static Dictionary DicRole = new Dictionary()
{
{"0","超级管理员"} , {"1","管理员"} , {"2","学员"}
};
///
/// 新ID
///
///
///
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;
}
}
///
/// 判断是否能使用
///
///
public static bool CheckClose()
{
try
{
vs = zKeyAccess.KeyUtil.GetAccess(appkey);
if (vs <= 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return true;
}
}
}
}