.net 公共基础类
using WL.Infrastructure.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D; namespace WL.Infrastructure.Common
{
public class Common
{
private static int seed = 1;
private static int key_seed = 1;
private static int noseed = 1;
private static int domseed = 1;
private static int geseed = 1;
/// <summary>
/// 取得客户端真实IP。如果有代理则取第一个非内网地址
/// </summary>
public static string IPAddress
{
get
{
string result = String.Empty; result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (result != null && result != String.Empty)
{
//可能有代理;
if (result.IndexOf(".") == -1) //没有“.”肯定是非IPv4格式;
result = null;
else
{
if (result.IndexOf(",") != -1)
{
//有“,”,估计多个代理。取第一个不是内网的IP。;
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i < temparyip.Length; i++)
{
if (IsIPAddress(temparyip[i])
&& temparyip[i].Substring(0, 3) != "10."
&& temparyip[i].Substring(0, 7) != "192.168"
&& temparyip[i].Substring(0, 7) != "172.16.")
{
return temparyip[i]; //找到不是内网的地址 ;
}
}
}
else if (IsIPAddress(result)) //代理即是IP格式;
return result;
else
result = null; //代理中的内容 非IP,取IP ;
} } string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (null == result || result == String.Empty)
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (result == null || result == String.Empty)
result = HttpContext.Current.Request.UserHostAddress;
if (result == "::1")
{
result = "127.0.0.1";
}
return result;
}
}
/// <summary>
/// 绕过cnd获取真实ip
/// </summary>
/// <returns></returns>
public static string GetUserIp()
{
string userIP = "未获取用户IP"; try
{
if (HttpContext.Current == null
|| HttpContext.Current.Request == null
|| HttpContext.Current.Request.ServerVariables == null)
return ""; string CustomerIP = ""; //CDN加速后取到的IP
CustomerIP = HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
if (!string.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
} CustomerIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!String.IsNullOrEmpty(CustomerIP))
return CustomerIP; if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
CustomerIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (CustomerIP == null)
CustomerIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
CustomerIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (string.Compare(CustomerIP, "unknown", true) == 0)
return HttpContext.Current.Request.UserHostAddress;
return CustomerIP;
}
catch { } return userIP;
}
/**/
/// <summary>
/// 判断是否是IP地址格式 0.0.0.0
/// </summary>
/// <param name="str1">待判断的IP地址</param>
/// <returns>true or false</returns>
public static bool IsIPAddress(string str1)
{
if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false; string regformat = @"^/d{1,3}[/.]/d{1,3}[/.]/d{1,3}[/.]/d{1,3}$"; Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str1);
}
/// <summary>
/// 时间转换时间戳
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static string ConvertDateTimeInt(string time)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
DateTime dtNow = DateTime.Parse(time);
TimeSpan toNow = dtNow.Subtract(dtStart);
string timeStamp = toNow.Ticks.ToString();
timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
return timeStamp;
}
/// <summary>
/// 时间戳转换时间
/// </summary>
/// <param name="datestr"></param>
/// <returns></returns>
public static DateTime ConvertDate(string datestr)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(datestr + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
DateTime dtResult = dtStart.Add(toNow);
return dtResult;
}
/// <summary>
/// 转换时间
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static string ConvertDateTimeInt_flot(string time)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
DateTime dtNow = DateTime.Parse(time);
TimeSpan toNow = dtNow.Subtract(dtStart);
string timeStamp = toNow.Ticks.ToString();
timeStamp = timeStamp.Substring(0, timeStamp.Length - 4);
return timeStamp;
}
/// <summary>
/// 上传
/// </summary>
/// <param name="_rootPath"></param>
/// <param name="_file"></param>
/// <param name="_filename"></param>
/// <param name="type_s"></param>
/// <returns></returns>
public static string FileUploader(string _rootPath, HttpPostedFileBase _file, string _filename = null, string type_s = "")
{
string sFileName = _filename;
if (_file != null)
{
string _filePath = _file.FileName;
if (_filePath != string.Empty)
{
string _fileType = _filePath.Substring(_filePath.LastIndexOf("."));
string sFileRoot = _rootPath;
if (!System.IO.Directory.Exists(sFileRoot))
System.IO.Directory.CreateDirectory(sFileRoot);
if (sFileName == null)
{
if (type_s != "")
{
sFileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + type_s;
}
else
{
sFileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + _fileType;
}
}
else
{
if (type_s != "")
{
sFileName = sFileName + type_s;
}
else
{
sFileName = sFileName + _fileType;
}
}
string sFilePath = sFileRoot + "\\" + sFileName;
_file.SaveAs(sFilePath);
}
}
return sFileName;
}
/// <summary>
/// 根据路径把文件转换成数据流
/// </summary>
/// <param name="strpath"></param>
/// <returns></returns>
public static byte[] Returnbyte(string strpath)
{
// 以二进制方式读文件
FileStream fsMyfile = new FileStream(strpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
// 创建一个二进制数据流读入器,和打开的文件关联
BinaryReader brMyfile = new BinaryReader(fsMyfile);
// 把文件指针重新定位到文件的开始
brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
byte[] bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString()));
// 关闭以上new的各个对象
brMyfile.Close();
return bytes;
}
public static void DeleteFile(string filepatch)
{
FileInfo file = new FileInfo(filepatch);//指定文件路径
if (file.Exists)//判断文件是否存在
{
file.Attributes = FileAttributes.Normal;//将文件属性设置为普通,比方说只读文件设置为普通
file.Delete();//删除文件
}
}
/// 取得某月的第一天
/// </summary>
/// <param name="datetime">要取得月份第一天的时间</param>
/// <returns></returns>
private DateTime FirstDayOfMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day);
}
/// <summary>
/// 取得某月的最后一天
/// </summary>
/// <param name="datetime">要取得月份最后一天的时间</param>
/// <returns></returns>
private DateTime LastDayOfMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
} /// <summary>
/// 取得上个月第一天
/// </summary>
/// <param name="datetime">要取得上个月第一天的当前时间</param>
/// <returns></returns>
public DateTime FirstDayOfPreviousMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
} /// <summary>
/// 取得上个月的最后一天
/// </summary>
/// <param name="datetime">要取得上个月最后一天的当前时间</param>
/// <returns></returns>
public DateTime LastDayOfPrdviousMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddDays(-1);
} /// <summary>
/// 取得上周的第一天
/// </summary>
/// <param name="datetime">要取得上周最后一天的当前时间</param>
/// <returns></returns>
public static DateTime FirstDayOfPrdviousWeek(DateTime datetime)
{
//星期一为第一天
int weeknow = Convert.ToInt32(datetime.DayOfWeek); //因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。
weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
int daydiff = (-1) * weeknow; //本周第一天
string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
return Convert.ToDateTime(FirstDay);
} /// <summary>
/// 取得上周的最后一天
/// </summary>
/// <param name="datetime">要取得上周最后一天的当前时间</param>
/// <returns></returns>
public static DateTime LastDayOfPrdviousWeek(DateTime datetime)
{
//星期天为最后一天
int weeknow = Convert.ToInt32(datetime.DayOfWeek);
weeknow = (weeknow == 0 ? 7 : weeknow);
int daydiff = (7 - weeknow); //本周最后一天
string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
return Convert.ToDateTime(LastDay);
} /// <summary>
/// 判断字符串是否为正整数
/// </summary>
/// <param name="str">要判断的字符串对象</param>
/// <returns></returns>
public static bool IsInt(string str)
{
bool isInt = false;
if (!string.IsNullOrEmpty(str))
{
isInt = Regex.IsMatch(str, @"^(0|([1-9]\d*))$");
}
return isInt;
} /// <summary>
/// 判断是否为DateTime
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static bool IsDateTime(string strDate)
{
try
{
DateTime.Parse(strDate);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 生成单号
/// </summary>
/// <param name="channel"></param>
/// <returns></returns>
public static string GetOrderNo()
{
if (seed == int.MaxValue)
{
seed = 1;
}
seed++;
string tbout_trade_no = "";
string guid = Guid.NewGuid().ToString();
string last = guid.Replace("-", "");
char[] cc = last.ToCharArray();
StringBuilder sb = new StringBuilder(4);
Random rd = new Random((unchecked((int)DateTime.Now.Ticks + seed)));
for (int i = 0; i < 6; i++)
{
sb.Append(cc[rd.Next(cc.Length)]);
} tbout_trade_no = sb + "-" + DateTime.Now.ToString("yyyyMMddHHmmssff");
return tbout_trade_no;
}
/// <summary>
/// 生成密匙
/// </summary>
/// <param name="mch_id"></param>
/// <returns></returns>
public static string GetGGAPIKey(string num_id)
{
if (key_seed == int.MaxValue)
{
key_seed = 1;
}
key_seed++;
string key = "";
char[] constant = {'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'};
StringBuilder sb = new StringBuilder(4);
for (int i = 0; i < 5; i++)
{
Random rd = new Random((unchecked((int)DateTime.Now.Ticks + i)));
sb.Append(constant[rd.Next(62)]);
}
key = MD5.Md5UTF8(num_id + sb).ToLower();
return key;
}
/// <summary>
/// PostUTF8格式的JSON
/// </summary>
/// <param name="json"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string PostUtf8Json(string json, string url, int timeout = 1000000)
{
byte[] encodebytes = System.Text.Encoding.UTF8.GetBytes(json);
HttpHelper helper = new HttpHelper();
HttpItem item = new HttpItem();
item.URL = url;
item.Timeout = timeout;
item.Method = "POST";
item.PostdataByte = encodebytes;
item.PostEncoding = Encoding.UTF8;
item.PostDataType = PostDataType.Byte;
HttpResult result = helper.GetHtml(item);
string msg = "";
if ((int)result.StatusCode < 400)
{
msg = result.Html;
if (msg == "操作超时")
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
msg = "";
}
}
else
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
}
return msg;
}
/// <summary>
/// PostUTF8格式的Form
/// </summary>
/// <param name="json"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string PostUtf8Form(string json, string url, int timeout = 1000000)
{
byte[] encodebytes = System.Text.Encoding.UTF8.GetBytes(json);
HttpHelper helper = new HttpHelper();
HttpItem item = new HttpItem();
item.URL = url;
item.Timeout = timeout;
item.Method = "POST";
item.Allowautoredirect = true;
item.ContentType = "application/x-www-form-urlencoded";
item.PostdataByte = encodebytes;
item.PostEncoding = Encoding.UTF8;
item.PostDataType = PostDataType.Byte;
HttpResult result = helper.GetHtml(item);
string msg = "";
if ((int)result.StatusCode < 400)
{
msg = result.Html;
if (msg == "操作超时")
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
msg = "";
}
}
else
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
}
return msg;
}
/// <summary>
/// PostGB2312格式的表单
/// </summary>
/// <param name="json"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string PostGB2312Form(string json, string url, int timeout = 5000)
{
byte[] encodebytes = System.Text.Encoding.GetEncoding("GB2312").GetBytes(json);
HttpHelper helper = new HttpHelper();
HttpItem item = new HttpItem();
item.URL = url;
item.Timeout = timeout;
item.Method = "POST";
item.Allowautoredirect = true;
item.ContentType = "application/x-www-form-urlencoded";
item.PostdataByte = encodebytes;
item.PostEncoding = Encoding.GetEncoding("GB2312");
item.PostDataType = PostDataType.Byte;
HttpResult result = helper.GetHtml(item);
string msg = "";
if ((int)result.StatusCode < 400)
{
msg = result.Html;
if (msg == "操作超时")
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
msg = "";
}
}
else
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
}
return msg;
}
/// <summary>
/// PostUTF8格式的JSON
/// </summary>
/// <param name="json"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string PostUtf8File(byte[] encodebytes, string url, int timeout = 1000000)
{
//byte[] encodebytes = System.Text.Encoding.UTF8.GetBytes(json);
HttpHelper helper = new HttpHelper();
HttpItem item = new HttpItem();
item.URL = url;
item.Timeout = timeout;
item.Method = "POST";
item.ContentType = "multipart/form-data";
item.PostdataByte = encodebytes;
item.PostEncoding = Encoding.UTF8;
item.PostDataType = PostDataType.Byte;
HttpResult result = helper.GetHtml(item);
string msg = "";
if ((int)result.StatusCode < 400)
{
msg = result.Html;
if (msg == "操作超时")
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
msg = "";
}
}
else
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
}
return msg;
}
/// <summary>
/// Get格式
/// </summary>
/// <param name="json"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string GetUrl(string url, int timeout = 1000000)
{
HttpHelper helper = new HttpHelper();
HttpItem item = new HttpItem();
item.Timeout = timeout;
item.URL = url;
HttpResult result = helper.GetHtml(item);
string msg = "";
if ((int)result.StatusCode < 400)
{
msg = result.Html;
if (msg == "操作超时")
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
msg = "";
}
}
else
{
//LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
}
return msg;
}
/// <summary>
/// 生成随机字符串
/// </summary>
/// <returns></returns>
public static string get_noce_str()
{
if (noseed == int.MaxValue)
{
noseed = 1;
}
noseed++;
char[] constant = {'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'};
StringBuilder sb = new StringBuilder(16);
Random rd = new Random((unchecked((int)DateTime.Now.Ticks + noseed)));
for (int i = 0; i < 16; i++)
{
sb.Append(constant[rd.Next(62)]);
}
return sb.ToString();
}
/// <summary>
/// 生成6位邀请码
/// </summary>
/// <returns></returns>
public static string get_generate_str()
{
if (geseed == int.MaxValue)
{
geseed = 1;
}
geseed++;
char[] constant = {'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'};
StringBuilder sb = new StringBuilder(6);
Random rd = new Random((unchecked((int)DateTime.Now.Ticks + geseed)));
for (int i = 0; i < 6; i++)
{
sb.Append(constant[rd.Next(62)]);
}
return sb.ToString();
}
/// <summary>
/// 生成6位订单号
/// </summary>
/// <returns></returns>
public static string Nrandom()
{
if (domseed == int.MaxValue)
{
domseed = 1;
}
domseed++;
string rm = "";
Random rd = new Random((unchecked((int)DateTime.Now.Ticks + domseed)));
for (int i = 0; i < 6; i++)
{
rm += rd.Next(0, 9).ToString();
}
return rm;
}
/// <summary>
/// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode
/// </summary>
/// <param name="sArray">需要拼接的数组</param>
/// <param name="code">字符编码</param>
/// <returns>拼接完成以后的字符串</returns>
public static string CreateLinkStringA(SortedDictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
foreach (KeyValuePair<string, string> temp in dicArray)
{
prestr.Append(temp.Key + "=" + temp.Value + "&");
} //去掉最後一個&字符
int nLen = prestr.Length;
prestr.Remove(nLen - 1, 1); return prestr.ToString();
}
/// <summary>
/// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode
/// </summary>
/// <param name="sArray">需要拼接的数组</param>
/// <param name="code">字符编码</param>
/// <returns>拼接完成以后的字符串</returns>
public static string CreateLinkStringB(Dictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
foreach (KeyValuePair<string, string> temp in dicArray)
{
prestr.Append(temp.Key + "=" + temp.Value + "&");
} //去掉最後一個&字符
int nLen = prestr.Length;
prestr.Remove(nLen - 1, 1); return prestr.ToString();
}
/// <summary>
/// 把数组所有元素,按照“参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode
/// </summary>
/// <param name="sArray">需要拼接的数组</param>
/// <param name="code">字符编码</param>
/// <returns>拼接完成以后的字符串</returns>
public static string CreateLinkStringC(Dictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
foreach (KeyValuePair<string, string> temp in dicArray)
{
prestr.Append(temp.Value);
}
return prestr.ToString();
}
/// <summary>
/// 多余字段用指定字符串代替
/// </summary>
/// <param name="MaxLength">字符串最大长度</param>
/// <param name="ReplaceRemark">超出时代替的符号</param>
/// <param name="value">要转换的字符串</param>
/// <returns></returns>
public static string Overflow(int MaxLength, string ReplaceRemark, string value)
{
if (value.Length > MaxLength)
{
return value = value.Remove(MaxLength) + ReplaceRemark;
}
return value;
} /// <summary>
/// 每隔n个字符插入n个字符
/// </summary>
/// <param name="input">源字符串</param>
/// <param name="interval">间隔字符数</param>
/// <param name="value">待插入值</param>
/// <returns>返回新生成字符串</returns>
public static string InsertFormat(string input, int interval, string value)
{
for (int i = interval; i < input.Length; i += interval + value.Length)
input = input.Insert(i, value);
return input;
} /// <summary>
/// 手机号码隐藏中间4位
/// </summary>
/// <param name="phone"></param>
/// <returns></returns>
public static string HidePhone(string phone)
{
return Regex.Replace(phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
/// <summary>
/// 判断是否带http,flase=有,ture=没有
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static bool IsHttp(string url)
{
string reg = @"^(http(s)?:\/\/)?(www\.)?[\w-]+(\.\w{2,4})?\.\w{2,4}?(\/)?$";
Regex r = new Regex(reg);
//给网址去所有空格
string urlStr = url.Trim();
Match m = r.Match(urlStr); //判断是否带http://
if (!m.Success)
return false;
return true;
}
#region 得到一周的周一和周日的日期
/// <summary>
/// 计算本周的周一日期
/// </summary>
/// <returns></returns>
public static DateTime GetMondayDate()
{
return GetMondayDate(DateTime.Now);
}
/// <summary>
/// 计算本周周日的日期
/// </summary>
/// <returns></returns>
public static DateTime GetSundayDate()
{
return GetSundayDate(DateTime.Now);
}
/// <summary>
/// 计算某日起始日期(礼拜一的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜一日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime GetMondayDate(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Monday;
if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Subtract(ts);
}
/// <summary>
/// 计算某日结束日期(礼拜日的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜日日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime GetSundayDate(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Sunday;
if (i != 0) i = 7 - i;// 因为枚举原因,Sunday排在最前,相减间隔要被7减。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Add(ts);
}
#endregion
}
public class ValidateCode
{
public ValidateCode()
{
}
/// <summary>
/// 验证码的最大长度
/// </summary>
public int MaxLength
{
get { return 10; }
}
/// <summary>
/// 验证码的最小长度
/// </summary>
public int MinLength
{
get { return 1; }
}
/// <summary>
/// 生成验证码
/// </summary>
/// <param name="length">指定验证码的长度</param>
/// <returns></returns>
public string CreateValidateCode(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
string validateNumberStr = "";
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
int[] seeks = new int[length];
for (int i = 0; i < length; i++)
{
beginSeek += 10000;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = 0; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = 1 * (int)Math.Pow(10, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = 0; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(0, numLength - 1);
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
}
//生成验证码
for (int i = 0; i < length; i++)
{
validateNumberStr += validateNums[i].ToString();
}
return validateNumberStr;
}
/// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="context">要输出到的page对象</param>
/// <param name="validateNum">验证码</param>
public void CreateValidateGraphic(string validateCode, HttpContext context)
{
Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, font, brush, 3, 2);
//画图片的前景干扰点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(stream.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
/// <summary>
/// 得到验证码图片的长度
/// </summary>
/// <param name="validateNumLength">验证码的长度</param>
/// <returns></returns>
public static int GetImageWidth(int validateNumLength)
{
return (int)(validateNumLength * 12.0);
}
/// <summary>
/// 得到验证码的高度
/// </summary>
/// <returns></returns>
public static double GetImageHeight()
{
return 22.5;
} //C# MVC 升级版
/// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="containsPage">要输出到的page对象</param>
/// <param name="validateNum">验证码</param>
public byte[] CreateValidateGraphic(string validateCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, font, brush, 3, 2);
//画图片的前景干扰点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
}
.net 公共基础类的更多相关文章
- PageBase 公共基础类
PageBase 公共基础类 using System; using System.Collections.Generic; using System.Linq; using System.Web; ...
- D3.js 制作中国地图 .net 公共基础类
D3.js 制作中国地图 from: http://d3.decembercafe.org/pages/map/index.html GeoJSON is a format for encoding ...
- SFTP环境搭建及客户代码调用公共方法封装
一.背景 在开发应用软件的过程中,广泛使用FTP在各子系统间传送文本数据.但FTP存在安全问题,开放到外网存在安全漏洞,容易被攻击.替换方案是使用SFTP,SFTP提供更高的安全性,当然传输的效率也会 ...
- FTP环境搭建及客户代码调用公共方法封装
一.背景 大型系统架构往往被分解为多个独立可运行的组件, 以满足性能.可靠性.可扩展性的需求.多个组件间的数据交互往往采用两种方式:小量数据通过Sock函数.RMI.WebService等接口方式传递 ...
- TestNG 搭建测试框架 自动化测试
框架层级及基本组件: 参考:https://www.cnblogs.com/jier888/p/8998724.html Java作为开发语言 Maven管理项目及Jar包 Testng作为测试 ...
- Hibernate里面如何使用DetachedCriteriaCriteria 实现多条件分页查询
WEB层: // 获取分页的请求参数 String start = request.getParameter("start"); String page = request.get ...
- Web框架——XWAF的代码结构和运行机制(4)
XWAF是一套基于Servlet和java反射技术的Web应用程序框架,它利用Servlet运行机制在服务器上加载和运行,接管客户端请求,依靠ServletRequest对象获取用户请求信息,使用Se ...
- OOD沉思录 --- 继承
一,继承只应被用来为特化层次结构建模 实际上也就是要满足LSP原则,水果类<-榴莲的继承是特化 二,派生类必须知道他们的基类,基类不应当知道他们的派生类 复用的前提 三,基类中的所有 ...
- spring mvc:练习:表单验证(javaConfig配置和注解)
使用Spring表单标签, 表单验证使用 JSR303 的验证注解,hibernate-validators,提供了使用MessageSource和访问静态资源(如CSS,JavaScript,图片) ...
随机推荐
- PIL库图像处理
PIL有如下几个模块 Image模块.ImageChops模块.ImageCrackCode模块 ImageDraw模块.ImageEnhance模块.ImageFile模块 ImageFileIO模 ...
- JS 实现版本号比较功能
js实现一个客户端版本号的统计,目前该功能可以实现版本号中数字版本的统计,例如2.2.3 <2.2.3.1, 1.2.3<2.0.0,原理就是从高版本号到次版本号依次比较 if (!Arr ...
- Java语言中的面向对象特性
面向对象的基本特征 1.封装性 封装性就是把对象的属性和服务结合成一个独立的相同单位,并尽可能隐蔽对象的内部细节,包含两个含义: ◇ 把对象的全部属性和全部服务结合在一起,形成一个不可分割的独立单位( ...
- 解析Java分布式系统中的缓存架构(上)
作者 陈彩华 文章转载交流请联系 caison@aliyun.com 本文主要介绍大型分布式系统中缓存的相关理论,常见的缓存组件以及应用场景. 1 缓存概述 2 缓存的分类 缓存主要分为以下四类 2. ...
- Transaction rolled back because it has been marked as rollback-only
出现这种错误的原因 1.接口A 调用了接口B 2.接口B报异常了,没有在B里面进行try catch捕获 3.接口A对 接口B进行了try catch捕获 因为接口B报异常 会把当前事物A接口的事物( ...
- SpringCache学习实践
1. SpringCache学习实践 1.1. 引用 <dependency> <groupId>org.springframework.boot</groupId> ...
- 如何将一个文本内容通过PHP 以表格的方式输入到页面上
如何将一个文本内容通过PHP 以表格的方式输入到页面上 <?php //读取文本内容 $contents = file_get_contents("names.txt"); ...
- win7 Host文件修改后无效的解决办法
win7 Host文件修改后无效的解决办法 正常情况下hosts文件随时修改随时生效,如果出现修改后不生效的情况,首先确定文件是ascii编码,以windows格式为换行符,然后依次采用如下方法 1 ...
- Kubernetes集群搭建之CNI-Flanneld部署篇
本次系列使用的所需部署包版本都使用的目前最新的或最新稳定版,安装包地址请到公众号内回复[K8s实战]获取 Flannel是CoreOS提供用于解决Dokcer集群跨主机通讯的覆盖网络工具.它的主要思路 ...
- Ocelot简易教程(五)之集成IdentityServer认证以及授权
Ocelot简易教程目录 Ocelot简易教程(一)之Ocelot是什么 Ocelot简易教程(二)之快速开始1 Ocelot简易教程(二)之快速开始2 Ocelot简易教程(三)之主要特性及路由详解 ...