using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
namespace ReleaseHelper.Utils
{
public static class Functions
{
//static byte[] Encrypt(string input)
//{
// StringBuilder sb = new StringBuilder();
// int i = 0;
// int offset = Variables.Const.KEY[0];
// foreach (char c in input)
// {
// var c2 = Convert.ToChar(c + Variables.Const.KEY[i++] + offset);
// sb.Append(c2);
// }
// return Encoding.UTF8.GetBytes(sb.ToString());
//}
//static string Decrypt(byte[] input)
//{
// StringBuilder sb = new StringBuilder();
// int i = 0;
// int offset = Variables.Const.KEY[0];
// string s = Encoding.UTF8.GetString(input);
// foreach (char b in s)
// {
// sb.Append(Convert.ToChar(b - offset - Variables.Const.KEY[i++]));
// }
// return sb.ToString();
//}
//public static string LoadUserPW(string n, byte[] pwd)
//{
// return Decrypt(pwd).Substring($"{n}_".Length);
//}
//public static byte[] DumpUserPW(string n, string pwd)
//{
// return Encrypt($"{n}_{pwd}");
//}
///
/// 字符串生成MD5
///
///
///
public static string GenMd5(string s)
{
//就是比string往后一直加要好的优化容器
StringBuilder sb = new StringBuilder();
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
//将输入字符串转换为字节数组并计算哈希。
byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
//X为 十六进制 X都是大写 x都为小写
//2为 每次都是两位数
//假设有两个数10和26,正常情况十六进制显示0xA、0x1A,这样看起来不整齐,为了好看,可以指定"X2",这样显示出来就是:0x0A、0x1A。
//遍历哈希数据的每个字节
//并将每个字符串格式化为十六进制字符串。
int length = data.Length;
for (int i = 0; i < length; i++)
{
sb.Append(data[i].ToString("X2"));
}
}
return sb.ToString();
}
///
/// 获取文件的MD5码
///
/// 传入的文件名(含路径及后缀名)
///
///
public static string GenMd5HashFromFile(string fileName)
{
try
{
StringBuilder sb = new StringBuilder();
using (MD5 md5 = new MD5CryptoServiceProvider())
using (FileStream file = new FileStream(fileName, FileMode.Open))
{
byte[] retVal = md5.ComputeHash(file);
//file.Close();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("X2"));
}
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
///
/// 生成UUID
///
///
public static string GenUUID()
{
return Guid.NewGuid().ToString("N");
}
///
/// 深复制对象
///
///
///
///
///
public static T Clone(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (source == null)
{
return default;
}
IFormatter formatter = new BinaryFormatter();
//Stream stream = new MemoryStream();
using (Stream stream = new MemoryStream())
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
///
/// 生成任务id
///
///
///
public static string GenTaskId(int testId)
{
return GenTaskId(testId, Utils.Functions.GenUUID());
}
///
/// 生成任务id
///
///
///
///
public static string GenTaskId(int testId, string uuid)
{
return $"{testId}_{uuid}";
}
///
/// 返回字符串右侧指定数量的字符串
///
///
///
///
public static string RString(string txt, int length)
{
string res = string.Empty;
if (!string.IsNullOrEmpty(txt))
{
res = length > txt.Length ? txt : txt.Substring(txt.Length - length);
}
return res;
}
///
/// 复制对象
///
///
///
public static class CopyTo
{
private static readonly Func cache = GetFunc();
private static Func GetFunc()
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
List memberBindingList = new List();
foreach (var item in typeof(TOut).GetProperties())
{
if (!item.CanWrite)
continue;
MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
Expression> lambda = Expression.Lambda>(memberInitExpression, new ParameterExpression[] { parameterExpression });
return lambda.Compile();
}
public static TOut Trans(TIn tIn)
{
return cache(tIn);
}
}
///
/// 获取时间戳 13位
///
///
public static long GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds * 1000);
}
///
/// 将时间戳转换为日期类型,并格式化
///
///
///
public static string LongDateTimeToDateTimeString(string longDateTime)
{
//用来格式化long类型时间的,声明的变量
long unixDate;
DateTime start;
DateTime date;
//ENd
unixDate = long.Parse(longDateTime);
start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
date = start.AddMilliseconds(unixDate).ToLocalTime();
return date.ToString("yyyy-MM-dd HH:mm:ss");
}
///
/// 获取制定路径文件的md5值
///
///
///
public static string FileMd5(string filename)
{
string res = "";
try
{
using (FileStream file = new FileStream(filename, FileMode.Open))
using (MD5 md5 = new MD5CryptoServiceProvider())
{
byte[] retVal = md5.ComputeHash(file);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
res = sb.ToString();
}
}
catch
{
}
return res;
}
/////
///// 生成上传文件对象的名称
/////
///// 科目id
///// 文件名
/////
//public static string GenUploadImageName(int subjectId, string filename)
//{
// string fileMd5 = FileMd5(filename), objectName = string.Empty;
// if (!string.IsNullOrEmpty(fileMd5))
// {
// // 保存的文件名
// objectName = $"images/marking/{Variables.Variables.SubjectIdCode[subjectId]}/{fileMd5.Substring(0, 4)}/{fileMd5}{Path.GetExtension(filename)}";
// }
// return objectName;
//}
/////
///// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
/////
/////
//public static double GetTotalPhysicalMemory(FileSizeUnit targetUnit = FileSizeUnit.MB)
//{
// long capacity = 0;
// try
// {
// foreach (ManagementObject mo1 in new ManagementClass("Win32_PhysicalMemory").GetInstances().Cast())
// {
// capacity += long.Parse(mo1.Properties["Capacity"].Value.ToString());
// }
// }
// catch (Exception ex)
// {
// capacity = -1;
// Console.WriteLine(ex.Message);
// }
// return ToFileFormat(capacity, targetUnit);
//}
/////
///// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
/////
/////
//public static double GetAvailablePhysicalMemory(FileSizeUnit targetUnit = FileSizeUnit.MB)
//{
// long capacity = 0;
// try
// {
// foreach (ManagementObject mo1 in new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory").GetInstances().Cast())
// {
// capacity += long.Parse(mo1.Properties["AvailableBytes"].Value.ToString());
// }
// }
// catch (Exception ex)
// {
// capacity = -1;
// Console.WriteLine(ex.Message);
// }
// return ToFileFormat(capacity, targetUnit);
//}
/////
///// 根据指定的文件大小单位,对输入的文件大小(字节表示)进行转换。
/////
///// 文件文件大小,单位为字节。
///// 目标单位。
/////
//private static double ToFileFormat(long filesize, FileSizeUnit targetUnit = FileSizeUnit.MB)
//{
// double size;
// switch (targetUnit)
// {
// case FileSizeUnit.KB: size = filesize / 1024.0; break;
// case FileSizeUnit.MB: size = filesize / 1024.0 / 1024; break;
// case FileSizeUnit.GB: size = filesize / 1024.0 / 1024 / 1024; break;
// case FileSizeUnit.TB: size = filesize / 1024.0 / 1024 / 1024 / 1024; break;
// case FileSizeUnit.PB: size = filesize / 1024.0 / 1024 / 1024 / 1024 / 1024; break;
// default: size = filesize; break;
// }
// return size;
//}
/////
///// 文件大小单位,包括从B至PB共六个单位。
/////
//public enum FileSizeUnit
//{
// B,
// KB,
// MB,
// GB,
// TB,
// PB
//}
}
}