生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间

时间:2023-03-09 03:28:32
生成二维码  加密解密类  TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型)  COOKIE帮助类  数据类型转换  截取字符串  根据IP获取地点  生成随机字符  UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME  是否包含中文    生成秘钥方式之一  计算某一年 某一周 的起始时间和结束时间

生成二维码

/// <summary>
/// 生成二维码
/// </summary>
public static class QRcodeUtils
{
private static string QrSaveUrl = "/img/QRcodeFile/";

/// <summary>
///生成二维码
/// </summary>
/// <param name="QrContent">二维码内容</param>
static void Generate(string QrContent)
{
//创建二维码生成类
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode = qrEncoder.Encode(QrContent);
//输出显示在控制台
for (int j = 0; j < qrCode.Matrix.Height; j++)
{
for (int i = 0; i < qrCode.Matrix.Width; i++)
{
char charToPoint = qrCode.Matrix[i, j] ? '█' : ' ';
Console.Write(charToPoint);
}
Console.WriteLine();
}
}

/// <summary>
/// 生成图片
/// </summary>
/// <param name="QrContent">二维码内容</param>
/// <param name="saveUrl">生成二维码保存路径</param>
static string GenerateIMG(string QrContent, string saveUrl)
{
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode = qrEncoder.Encode(QrContent);

//保存成png文件
string firstName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string lastName = new Random().Next(100, 999).ToString();
string fullName = firstName + lastName;
string fileUrl = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, QrSaveUrl, fullName);
string resultUrl = QrSaveUrl + fullName;

GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
using (FileStream stream = new FileStream(fileUrl, FileMode.Create))
{
render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
return resultUrl;
}
}

/// <summary>
/// 生成中文二维码
/// </summary>
/// <param name="QrContent">二维码内容</param>
/// <param name="QrText">中文</param>
static void GenerateTEXT(string QrContent, string QrText)
{
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode = qrEncoder.Encode(QrText);

//保存成png文件
string firstName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string lastName = new Random().Next(100, 999).ToString();
string fullName = firstName + lastName;
string fileUrl = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, QrSaveUrl, fullName);
string resultUrl = QrSaveUrl + fullName;
GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

Bitmap map = new Bitmap(500, 500);
Graphics g = Graphics.FromImage(map);
g.FillRectangle(Brushes.Red, 0, 0, 500, 500);
render.Draw(g, qrCode.Matrix, new Point(20, 20));
map.Save(fileUrl, ImageFormat.Png);
}

/// <summary>
/// 设置二维码大小
/// </summary>
/// <param name="QrContent">二维码内容</param>
/// <param name="QrText">中文</param>
static void SetGenerateSIZE(string QrContent, string QrText)
{
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode = qrEncoder.Encode(QrText);

//保存成png文件
string firstName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string lastName = new Random().Next(100, 999).ToString();
string fullName = firstName + lastName;
string fileUrl = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, QrSaveUrl, fullName);
string resultUrl = QrSaveUrl + fullName;

//ModuleSize 设置图片大小 
//QuietZoneModules 设置周边padding
/*
* 5----150*150 padding:5
* 10----300*300 padding:10
*/
GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(10, QuietZoneModules.Two), Brushes.Black, Brushes.White);

Point padding = new Point(10, 10);
DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
Bitmap map = new Bitmap(dSize.CodeWidth + padding.X, dSize.CodeWidth + padding.Y);
Graphics g = Graphics.FromImage(map);
render.Draw(g, qrCode.Matrix, padding);
map.Save(fileUrl, ImageFormat.Png);
}
}

加密解密类

public static class EncryptUtils
{

/// <summary>
/// 解析二次加密后的token
/// </summary>
/// <param name="token"></param>
/// <param name="userId">返回解密后的Userid,如果是-1就需要调用Auth重新验证</param>
/// <returns></returns>
public static int DecryptToken(string token)
{
if (string.IsNullOrEmpty(token))
{
return -1;
}

if (token.Contains("DXoY1U2iK=") && token.Contains("sFd4DsAf82aS5+"))
{
var tokenSplit = token.Split(new string[] { "DXoY1U2iK=", "sFd4DsAf82aS5+" }, StringSplitOptions.RemoveEmptyEntries);
if (tokenSplit.Length < 3)
{
return -1;
}
else
{
var timeStr = SOA.Api.ProjectTool.DESEncryptHelper.Base64Decrypt(tokenSplit[1], "159862");
var userStr = SOA.Api.ProjectTool.DESEncryptHelper.Base64Decrypt(tokenSplit[2], "2674536");
DateTime time;
if (!DateTime.TryParse(timeStr, out time))
{
return -1;
}
if (time < DateTime.Now)
{
return -1;
}
int userId2;
if (!int.TryParse(userStr, out userId2))
{
return -1;
}
return userId2;
}
}
else
{
return -1;
}
}

public static string Md5Code(string str)
{
StringBuilder PwdSb = new StringBuilder();
string cl = str;
MD5 md5 = MD5.Create();//实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i < s.Length; i++)
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
//pwd = pwd + s[i].ToString("X2");
PwdSb.Append(s[i].ToString("X2"));
}
return PwdSb.ToString();
}

/// <summary>
/// GB2312编码方式 MD5加密
/// </summary>
/// <param name="encypStr"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string GetMD5(string encypStr, string charset)
{
string retStr;
MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

//创建md5对象
byte[] inputBye;
byte[] outputBye;

//使用GB2312编码方式把字符串转化为字节数组.
try
{
inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
}
catch (Exception ex)
{
inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
}
outputBye = m5.ComputeHash(inputBye);

retStr = System.BitConverter.ToString(outputBye);
retStr = retStr.Replace("-", "").ToUpper();
return retStr;
}

/// <summary> 
/// Base64加密 
/// </summary> 
/// <param name="Message"></param> 
/// <returns></returns> 
public static string Base64Code(string Message)
{
byte[] bytes = Encoding.Default.GetBytes(Message);
return Convert.ToBase64String(bytes);
}

/// <summary> 
/// Base64解密 
/// </summary> 
/// <param name="Message"></param> 
/// <returns></returns> 
public static string Base64Decode(string Message)
{
byte[] bytes = Convert.FromBase64String(Message);
return Encoding.Default.GetString(bytes);
}

}

TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型)

/// <summary>
/// Table转换成实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static T ToEntity<T>(this DataTable table) where T : class, new()
{
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
return default(T);
}
var entity = (T)Activator.CreateInstance(typeof(T));
var row = table.Rows[0];
var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);

foreach (var property in properties)
{
if (table.Columns.Contains(property.Name))
{
if (!IsNullOrDBNull(row[property.Name]))
{
property.SetValue(entity, HackType(row[property.Name], property.PropertyType), null);
}
}
}
return entity;
}

/// <summary>
/// Table转换成实体集合(可转换成对象和值类型)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable table)
{
var list = new List<T>();
var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
for (var i = 0; i < table.Rows.Count; i++)
{
var row = table.Rows[i];
T entity;
var tType = typeof(T);
if (!(tType == typeof(string)) && (tType.IsClass || tType.IsGenericType))
{
entity = (T)Activator.CreateInstance(typeof(T));
foreach (var property in properties)
{
if (table.Columns.Contains(property.Name))
{
if (!IsNullOrDBNull(row[property.Name]))
{
property.SetValue(entity, HackType(row[property.Name], property.PropertyType), null);
}
}
}
}
else
{
//entity = default(T);
entity = ConvertUtils.To(row[0], default(T));
}
list.Add(entity);
}
return list;
}

COOKIE帮助类

/// <summary>
/// Cookie帮助类
/// </summary>
public class CookieUtils
{
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Path = "/";
cookie.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/// <summary>
/// 删除Cookie对象
/// </summary>
/// <param name="CookiesName">Cookie对象名称</param>
public static void DelCookie(string CookiesName)
{
HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
objCookie.Expires = DateTime.Now.AddYears(-5);
HttpContext.Current.Response.Cookies.Add(objCookie);
}
}

数据类型转换

/// <summary>
/// 数据类型转换
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="value">源数据</param>
/// <param name="defaultValue">默认值</param>
/// <returns>结果</returns>
public static T To<T>(object value, T defaultValue)
{
/* T obj;
try {
if (value == null) {
return defaultValue;
}
obj = (T)Convert.ChangeType(value, typeof(T));
if (obj == null) {
obj = defaultValue;
}
} catch {
obj = defaultValue;
}
return obj;*/
T obj = default(T);
try
{
if (value == null)
{
return defaultValue;
}
var valueType = value.GetType();
var targetType = typeof(T);
tag1:
if (valueType == targetType)
{
return (T)value;
}
if (targetType.IsEnum)
{
if (value is string)
{
return (T)System.Enum.Parse(targetType, value as string);
}
else
{
return (T)System.Enum.ToObject(targetType, value);
}
}
if (targetType == typeof(Guid) && value is string)
{
object obj1 = new Guid(value as string);
return (T)obj1;

}
if (targetType == typeof(DateTime) && value is string)
{
DateTime d1;
if (DateTime.TryParse(value as string, out d1))
{
object obj1 = d1;
return (T)obj1;
}

}
if (targetType.IsGenericType)
{
if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = Nullable.GetUnderlyingType(targetType);
goto tag1;
}
}
if (value is IConvertible)
{
obj = (T)Convert.ChangeType(value, typeof(T));
}

if (obj == null)
{
obj = defaultValue;
}
}
catch
{
obj = defaultValue;
}
return obj;
}

截取字符串

/// <summary>
/// 截取字符串
/// </summary>
/// <param name="text">需要截取的字符串</param>
/// <param name="maxLength">长度</param>
/// <param name="ishaspoint">是否需要省略号</param>
/// <returns>string</returns>
public static string substr(string text, int maxLength, bool ishaspoint)
{
if (text.Length > maxLength)
{
if (ishaspoint)
return text.Substring(0, maxLength) + "...";
else
return text.Substring(0, maxLength);
}
else return text;
}

根据IP获取地点

#region 根据ip获取地点
/// 获取Ip归属地
/// </summary>
/// <param name="ip">ip</param>
/// <returns>归属地</returns>
public static string GetIpAddress(string ip)
{
JavaScriptSerializer Jss = new JavaScriptSerializer();
//http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.192.3.42 调用新浪的接口
string address = string.Empty;
try
{
string reText = WebRequestPostOrGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip, "");
Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(reText);
address = DicText["city"].ToString();
//Log.Loger("city:" + address, true);
}
catch { }
return address;
}
#endregion

生成随机字符

#region 生成随机字符
/// <summary>
/// 生成随机字符
/// </summary>
/// <param name="iLength">生成字符串的长度</param>
/// <returns>返回随机字符串</returns>
public static string GetRandCode(int iLength)
{
string sCode = "";
if (iLength == 0)
{
iLength = 4;
}
string codeSerial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] arr = codeSerial.Split(',');
int randValue = -1;
Random rand = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i < iLength; i++)
{
randValue = rand.Next(0, arr.Length - 1);
sCode += arr[randValue];
}
return sCode;
}
#endregion

UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME

/// <summary>
/// unix时间转换为datetime
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime UnixTimeToTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}

/// <summary>
/// datetime转换为unixtime
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}

是否包含中文

public static bool HasChinese(string str)
{
return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
}

生成秘钥方式之一

public static string Secretkey()
{
var Secretkey = Guid.NewGuid().ToString("N")
.Remove(25, 1)
.Remove(23, 1)
.Remove(20, 1)
.Remove(18, 1)
.Remove(15, 1)
.Remove(13, 1)
.Remove(3, 1)
.Remove(1, 1);
return Secretkey;
}

计算某一年 某一周 的起始时间和结束时间

/// <summary>
/// 计算某一年 某一周 的起始时间和结束时间
/// </summary>
/// <param name="year"></param>
/// <param name="week"></param>
/// <param name="first"></param>
/// <param name="last"></param>
/// <returns></returns>
public static bool CalcWeekDay(int year, int week, out DateTime first, out DateTime last)
{
first = DateTime.MinValue;
last = DateTime.MinValue;
//年份超限 
if (year < 1700 || year > 9999) return false;
//周数错误 
if (week < 1 || week > 53) return false;
//指定年范围 
DateTime start = new DateTime(year, 1, 1);
DateTime end = new DateTime(year, 12, 31);
int startWeekDay = (int)start.DayOfWeek;

if (week == 1)
{
first = start;
last = start.AddDays(6 - startWeekDay);
}
else
{
//周的起始日期 
first = start.AddDays((7 - startWeekDay) + (week - 2) * 7);
last = first.AddDays(6);
if (last > end)
{
last = end;
}
}
return (first <= end);
}