生成二维码

/// <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);
}

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

  1. java和js生成二维码

    1. java生成二维码 1.1 依赖jar包配置(使用maven依赖) <dependency> <groupId>com.google.zxing</groupId& ...

  2. 从Scratch到Python——Python生成二维码

    # Python利用pyqrcode模块生成二维码 import pyqrcode import sys number = pyqrcode.create('从Scratch到Python--Pyth ...

  3. JS生成二维码,支持中文字符

    一.使用jquery-qrcode生成二维码 先简单说一下jquery-qrcode,这个开源的三方库(可以从https://github.com/jeromeetienne/jquery-qrcod ...

  4. iOS开发——生成二维码——工具类

    啥也不说,直接上源码,拷过去就能用.生成二维码的工具类使用方法在ProduceQRCode.h里有示例说明 分别将下面的ProduceQRCode.h和ProduceQRCode.m对应的代码考到自己 ...

  5. Java中使用google.zxing快捷生成二维码(附工具类源码)

    移动互联网时代,基于手机端的各种活动扫码和收付款码层出不穷:那我们如何在Java中生成自己想要的二维码呢?下面就来讲讲在Java开发中使用 google.zxing 生成二维码. 一般情况下,Java ...

  6. php用类生成二维码

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/qq1355541448/article/details/28630289 百度云盘里面已经有了.引用 ...

  7. PHP基于phpqrcode类生成二维码的方法详解

    前期准备: 1.phpqrcode类文件下载,下载地址:https://sourceforge.net/projects/phpqrcode/2.PHP环境必须开启支持GD2扩展库支持(一般情况下都是 ...

  8. php+qrcode类+生成二维码方法

    //生成二维码 public function qrcode() { $data = input(); if(!$data['param']){ return json(['code ' => ...

  9. 【java工具类】生成二维码

    /** * 生成二维码图片 * @param text 扫描二维码后跳转的url * @param width 图片宽度 * @param height 图片高度 * @param filePath ...

随机推荐

  1. linux系统——hosts文件修改

    1. 关于/etc/host,主机名和IP配置文件 Hosts - The static table lookup for host name(主机名查询静态表) Linux 的/etc/hosts是 ...

  2. [暑假集训--数论]poj2773 Happy 2006

    Two positive integers are said to be relatively prime to each other if the Great Common Divisor (GCD ...

  3. ubuntu运行android studio出错unable to run mksdcard sdk tool

    原因:缺少lib 解决方法: sudo apt-get install lib32z1 lib32ncurses5  lib32stdc++6 完美解决.

  4. nginx和php安装文件

    #!/usr/bin/env bash echo "=============START=====================" ## php echo '[php]yum i ...

  5. jenkins 管理员账号丢失

    在jenkins 设置权限后,无法登录 参考: 如何修改jenkins配置权限   https://zhidao.baidu.com/question/497256501658876284.html

  6. hdu 4995(离散化下标+模拟)

    Revenge of kNN Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  7. HDU 1020 Encoding【连续的计数器重置】

    Encoding Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Su ...

  8. IntelliJ IDEA设置鼠标移动到方法上提示API注释

    参考: https://www.cnblogs.com/guazi/p/6474426.html(图片转自此篇文章)

  9. Linux sed 批量替换字符串和更多用法

    比如,要将目录/modules下面所有文件中的zhangsan都修改成lisi,这样做: # sed -i “s/zhangsan/lisi/g” `grep zhangsan -rl /module ...

  10. ArcGIS教程:公布地理处理服务

    要公布地理处理服务.您须要两个元素:结果 窗体中的结果和到 ArcGIS Server 的管理员或公布者连接. 要公布服务,请右键单击结果并选择共享为 > 地理处理服务.例如以下图所看到的.此操 ...