1899 lines
69 KiB
C#
1899 lines
69 KiB
C#
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Linq;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Collections.Specialized;
|
||
using System.Configuration;
|
||
using System.Data;
|
||
using System.Diagnostics;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.Security;
|
||
using System.Reflection;
|
||
using System.Security.Cryptography;
|
||
using System.Security.Cryptography.X509Certificates;
|
||
using System.ServiceModel;
|
||
using System.ServiceModel.Channels;
|
||
using System.ServiceModel.Web;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Web;
|
||
using System.Web.Script.Serialization;
|
||
using System.Web.UI.WebControls;
|
||
using System.Xml;
|
||
using System.Xml.Serialization;
|
||
|
||
namespace WX.CRM.Common
|
||
{
|
||
public static class Utility
|
||
{
|
||
/// <summary>
|
||
/// 获取配置文件中的设置
|
||
/// </summary>
|
||
/// <param name="key"></param>
|
||
/// <returns></returns>
|
||
public static string GetSettingByKey(string key)
|
||
{
|
||
return ConfigurationManager.AppSettings[key];
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取配置文件中的设置
|
||
/// </summary>
|
||
/// <param name="key"></param>
|
||
/// <returns></returns>
|
||
public static string GetSettingOrNullByKey(string key)
|
||
{
|
||
return ConfigurationManager.AppSettings[key] == null ? "" : ConfigurationManager.AppSettings[key];
|
||
}
|
||
|
||
/// <summary>
|
||
/// DataTable 转list
|
||
/// </summary>
|
||
/// <typeparam name="TResult"></typeparam>
|
||
/// <param name="dt"></param>
|
||
/// <returns></returns>
|
||
public static List<TResult> ToList<TResult>(this DataTable dt) where TResult : class, new()
|
||
{
|
||
//创建一个属性的列表
|
||
List<PropertyInfo> prlist = new List<PropertyInfo>();
|
||
//获取TResult的类型实例 反射的入口
|
||
Type t = typeof(TResult);
|
||
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
|
||
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
|
||
//创建返回的集合
|
||
List<TResult> oblist = new List<TResult>();
|
||
foreach (DataRow row in dt.Rows)
|
||
{
|
||
//创建TResult的实例
|
||
TResult ob = new TResult();
|
||
//找到对应的数据,并赋值
|
||
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
|
||
//放入到返回的集合中.
|
||
oblist.Add(ob);
|
||
}
|
||
return oblist;
|
||
}
|
||
|
||
/// <summary>
|
||
/// List 转为DataTable
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="entitys"></param>
|
||
/// <returns></returns>
|
||
public static DataTable ToDataTable<T>(List<T> entitys)
|
||
{
|
||
//检查实体集合不能为空
|
||
if (entitys == null || entitys.Count < 1)
|
||
{
|
||
throw new Exception("需转换的集合为空");
|
||
}
|
||
|
||
//取出第一个实体的所有Propertie
|
||
Type entityType = entitys[0].GetType();
|
||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||
|
||
//生成DataTable的structure
|
||
//生产代码中,应将生成的DataTable结构Cache起来,此处略
|
||
DataTable dt = new DataTable();
|
||
for (int i = 0; i < entityProperties.Length; i++)
|
||
{
|
||
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
|
||
dt.Columns.Add(entityProperties[i].Name);
|
||
}
|
||
|
||
//将所有entity添加到DataTable中
|
||
foreach (object entity in entitys)
|
||
{
|
||
//检查所有的的实体都为同一类型
|
||
if (entity.GetType() != entityType)
|
||
{
|
||
throw new Exception("要转换的集合元素类型不一致");
|
||
}
|
||
object[] entityValues = new object[entityProperties.Length];
|
||
for (int i = 0; i < entityProperties.Length; i++)
|
||
{
|
||
entityValues[i] = entityProperties[i].GetValue(entity, null);
|
||
}
|
||
dt.Rows.Add(entityValues);
|
||
}
|
||
return dt;
|
||
}
|
||
|
||
/// <summary>
|
||
/// List 转为DataTable需要指定类型
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="entitys"></param>
|
||
/// <returns></returns>
|
||
public static DataTable ToOracleDataTable<T>(List<T> entitys)
|
||
{
|
||
//检查实体集合不能为空
|
||
if (entitys == null || entitys.Count < 1)
|
||
{
|
||
throw new Exception("需转换的集合为空");
|
||
}
|
||
|
||
//取出第一个实体的所有Propertie
|
||
Type entityType = entitys[0].GetType();
|
||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||
|
||
//生成DataTable的structure
|
||
//生产代码中,应将生成的DataTable结构Cache起来,此处略
|
||
DataTable dt = new DataTable();
|
||
for (int i = 0; i < entityProperties.Length; i++)
|
||
{
|
||
Type colType = entityProperties[i].PropertyType;
|
||
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
|
||
{
|
||
colType = colType.GetGenericArguments()[0];
|
||
}
|
||
dt.Columns.Add(entityProperties[i].Name, colType);
|
||
// dt.Columns.Add(entityProperties[i].Name);
|
||
}
|
||
|
||
//将所有entity添加到DataTable中
|
||
foreach (object entity in entitys)
|
||
{
|
||
//检查所有的的实体都为同一类型
|
||
if (entity.GetType() != entityType)
|
||
{
|
||
throw new Exception("要转换的集合元素类型不一致");
|
||
}
|
||
object[] entityValues = new object[entityProperties.Length];
|
||
for (int i = 0; i < entityProperties.Length; i++)
|
||
{
|
||
entityValues[i] = entityProperties[i].GetValue(entity, null);
|
||
}
|
||
dt.Rows.Add(entityValues);
|
||
}
|
||
return dt;
|
||
}
|
||
|
||
/// <summary>
|
||
/// List 转为DataTable需要指定类型
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="entitys"></param>
|
||
/// <returns></returns>
|
||
public static DataTable ToOracleDataTableToUpper<T>(List<T> entitys)
|
||
{
|
||
//检查实体集合不能为空
|
||
if (entitys == null || entitys.Count < 1)
|
||
{
|
||
throw new Exception("需转换的集合为空");
|
||
}
|
||
|
||
//取出第一个实体的所有Propertie
|
||
Type entityType = entitys[0].GetType();
|
||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||
|
||
//生成DataTable的structure
|
||
//生产代码中,应将生成的DataTable结构Cache起来,此处略
|
||
DataTable dt = new DataTable();
|
||
for (int i = 0; i < entityProperties.Length; i++)
|
||
{
|
||
Type colType = entityProperties[i].PropertyType;
|
||
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
|
||
{
|
||
colType = colType.GetGenericArguments()[0];
|
||
}
|
||
dt.Columns.Add(entityProperties[i].Name.ToUpper(), colType);
|
||
// dt.Columns.Add(entityProperties[i].Name);
|
||
}
|
||
|
||
//将所有entity添加到DataTable中
|
||
foreach (object entity in entitys)
|
||
{
|
||
//检查所有的的实体都为同一类型
|
||
if (entity.GetType() != entityType)
|
||
{
|
||
throw new Exception("要转换的集合元素类型不一致");
|
||
}
|
||
object[] entityValues = new object[entityProperties.Length];
|
||
for (int i = 0; i < entityProperties.Length; i++)
|
||
{
|
||
entityValues[i] = entityProperties[i].GetValue(entity, null);
|
||
}
|
||
dt.Rows.Add(entityValues);
|
||
}
|
||
return dt;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 把DataTable转成 List集合, 存每一行,集合中放的是键值对字典,存每一列
|
||
/// </summary>
|
||
/// <param name="dt">数据表</param>
|
||
/// <returns></returns>
|
||
public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
|
||
{
|
||
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
|
||
|
||
foreach (DataRow dr in dt.Rows)
|
||
{
|
||
Dictionary<string, object> dic = new Dictionary<string, object>();
|
||
foreach (DataColumn dc in dt.Columns)
|
||
{
|
||
dic.Add(dc.ColumnName, dr[dc.ColumnName].ToString());
|
||
}
|
||
list.Add(dic);
|
||
}
|
||
return list;
|
||
}
|
||
|
||
#region IP
|
||
|
||
/// <summary>
|
||
/// 获取IP
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static string GetIp()
|
||
{
|
||
string user_IP = string.Empty;
|
||
if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
|
||
{
|
||
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
|
||
{
|
||
user_IP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
|
||
}
|
||
}
|
||
else if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
|
||
{
|
||
user_IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
|
||
}
|
||
return user_IP;
|
||
}
|
||
|
||
#endregion IP
|
||
|
||
public static string GetClientIp()
|
||
{
|
||
try
|
||
{
|
||
OperationContext context = OperationContext.Current;
|
||
MessageProperties essageProperties = context.IncomingMessageProperties;
|
||
RemoteEndpointMessageProperty endpointProperty = essageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
|
||
return endpointProperty.Address;
|
||
}
|
||
catch
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
|
||
public static string GetClassAndMethodName(int treeId)
|
||
{
|
||
try
|
||
{
|
||
StackTrace trace = new StackTrace();
|
||
MethodBase methodBase = trace.GetFrame(treeId).GetMethod();
|
||
|
||
return methodBase.ReflectedType.Name + "/" + methodBase.Name;
|
||
}
|
||
catch
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
|
||
#region 加密 解密
|
||
|
||
// DES加密偏移量,必须是>=8位长的字符串
|
||
private static string iv = "1234567890";
|
||
|
||
// DES加密的私钥,必须是8位长的字符串DES
|
||
private static string key = "12345678";
|
||
|
||
/// <summary>
|
||
/// 对字符串加密后进行编码
|
||
/// </summary>
|
||
/// <param name="sourceString"></param>
|
||
/// <returns></returns>
|
||
public static string EncryptUrlEncode(string sourceString)
|
||
{
|
||
sourceString = Encrypt(sourceString);
|
||
|
||
return HttpUtility.UrlEncode(sourceString, Encoding.UTF8);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 对字符串解码后解密
|
||
/// </summary>
|
||
/// <param name="sourceString"></param>
|
||
/// <returns></returns>
|
||
public static string DecryptUrlDecode(string sourceString)
|
||
{
|
||
if (sourceString.IndexOf("%") > -1)
|
||
sourceString = HttpUtility.UrlDecode(sourceString, Encoding.UTF8);
|
||
|
||
return Decrypt(sourceString);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 对字符串进行DES加密
|
||
/// </summary>
|
||
/// <param name="sourceString">待加密的字符串</param>
|
||
/// <returns>加密后的BASE64编码的字符串</returns>
|
||
public static string Encrypt(string sourceString)
|
||
{
|
||
if (string.IsNullOrEmpty(sourceString))
|
||
{
|
||
return string.Empty;
|
||
}
|
||
else
|
||
{
|
||
byte[] btKey = Encoding.Default.GetBytes(key);
|
||
byte[] btIV = Encoding.Default.GetBytes(iv);
|
||
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
|
||
using (MemoryStream ms = new MemoryStream())
|
||
{
|
||
byte[] inData = Encoding.Default.GetBytes(sourceString);
|
||
try
|
||
{
|
||
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
|
||
{
|
||
cs.Write(inData, 0, inData.Length);
|
||
cs.FlushFinalBlock();
|
||
}
|
||
|
||
return Convert.ToBase64String(ms.ToArray());
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 对DES加密后的字符串进行解密
|
||
/// </summary>
|
||
/// <param name="encryptedString">待解密的字符串</param>
|
||
/// <returns>解密后的字符串</returns>
|
||
public static string Decrypt(string encryptedString)
|
||
{
|
||
if (string.IsNullOrEmpty(encryptedString))
|
||
{
|
||
return string.Empty;
|
||
}
|
||
else
|
||
{
|
||
byte[] btKey = Encoding.Default.GetBytes(key);
|
||
byte[] btIV = Encoding.Default.GetBytes(iv);
|
||
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
|
||
|
||
using (MemoryStream ms = new MemoryStream())
|
||
{
|
||
byte[] inData = Convert.FromBase64String(encryptedString);
|
||
try
|
||
{
|
||
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
|
||
{
|
||
cs.Write(inData, 0, inData.Length);
|
||
cs.FlushFinalBlock();
|
||
}
|
||
|
||
return Encoding.Default.GetString(ms.ToArray());
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
public static string Left(string sSource, int iLength)
|
||
{
|
||
return sSource.Substring(0, iLength > sSource.Length ? sSource.Length : iLength);
|
||
}
|
||
|
||
public static string Right(string sSource, int iLength)
|
||
{
|
||
return sSource.Substring(iLength > sSource.Length ? 0 : sSource.Length - iLength);
|
||
}
|
||
|
||
/// <summary>
|
||
/// md5加密
|
||
/// </summary>
|
||
/// <param name="message"></param>
|
||
/// <returns></returns>
|
||
public static string EncryptMD5(string input)
|
||
{
|
||
string output = null;
|
||
if (string.IsNullOrEmpty(input))
|
||
{
|
||
output = input;
|
||
}
|
||
else
|
||
{
|
||
output = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "MD5");
|
||
output = output.ToLower();
|
||
}
|
||
return output;
|
||
}
|
||
|
||
public static string UserMd5(string str)
|
||
{
|
||
var cl = str;
|
||
var result = string.Empty;
|
||
var md5 = MD5.Create();//实例化一个md5对像
|
||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||
var s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
|
||
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
|
||
for (int i = 0; i < s.Length; i++)
|
||
{
|
||
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
|
||
result = result + s[i].ToString("x2");
|
||
}
|
||
return result;
|
||
}
|
||
|
||
///// <summary>
|
||
///// DES加密方法
|
||
///// </summary>
|
||
///// <param name="strPlain">明文</param>
|
||
///// <param name="strDESKey">密钥</param>
|
||
///// <param name="strDESIV">向量</param>
|
||
///// <returns>密文</returns>
|
||
//public static string EncryptDES(string source, string _DESKey)
|
||
//{
|
||
// StringBuilder sb = new StringBuilder();
|
||
// using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
|
||
// {
|
||
// byte[] key = ASCIIEncoding.ASCII.GetBytes(_DESKey);
|
||
// byte[] iv = ASCIIEncoding.ASCII.GetBytes(_DESKey);
|
||
// byte[] dataByteArray = Encoding.UTF8.GetBytes(source);
|
||
// des.Mode = System.Security.Cryptography.CipherMode.CBC;
|
||
// des.Key = key;
|
||
// des.IV = iv;
|
||
// string encrypt = "";
|
||
// using (MemoryStream ms = new MemoryStream())
|
||
// using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
|
||
// {
|
||
// cs.Write(dataByteArray, 0, dataByteArray.Length);
|
||
// cs.FlushFinalBlock();
|
||
// //輸出資料
|
||
// foreach (byte b in ms.ToArray())
|
||
// {
|
||
// sb.AppendFormat("{0:X2}", b);
|
||
// }
|
||
// encrypt = sb.ToString();
|
||
// }
|
||
// return encrypt;
|
||
// }
|
||
|
||
//}
|
||
|
||
/// <summary>
|
||
/// 进行DES解密。
|
||
/// </summary>
|
||
/// <param name="pToDecrypt">要解密的串</param>
|
||
/// <param name="sKey">密钥,且必须为8位。</param>
|
||
/// <returns>已解密的字符串。</returns>
|
||
public static string DecryptDES(string source, string sKey)
|
||
{
|
||
byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source);
|
||
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
|
||
{
|
||
des.Mode = CipherMode.ECB;
|
||
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8));
|
||
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8));
|
||
System.IO.MemoryStream ms = new System.IO.MemoryStream();
|
||
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
|
||
{
|
||
cs.Write(inputByteArray, 0, inputByteArray.Length);
|
||
cs.FlushFinalBlock();
|
||
cs.Close();
|
||
}
|
||
string str = Encoding.UTF8.GetString(ms.ToArray());
|
||
ms.Close();
|
||
return str;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取16位md5加密
|
||
/// </summary>
|
||
/// <param name="source">待解密的字符串</param>
|
||
/// <returns></returns>
|
||
public static string Get16MD5(string source)
|
||
{
|
||
using (MD5 md5Hash = MD5.Create())
|
||
{
|
||
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
|
||
//转换成字符串,并取9到25位
|
||
string sBuilder = BitConverter.ToString(data, 4, 8);
|
||
//BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
|
||
sBuilder = sBuilder.Replace("-", "");
|
||
return sBuilder.ToString().ToUpper();
|
||
}
|
||
}
|
||
|
||
#endregion 加密 解密
|
||
|
||
/// <summary>
|
||
///时间格式化
|
||
/// </summary>
|
||
/// <param name="dt">返回字符串的类型(默认4)
|
||
///例子: 2014/05/08 19:14:17
|
||
///type=1 2014/05/08 没有时分秒
|
||
///type=2 2014/05/08 19:14 没有秒
|
||
///type=3 14/05/08 19:14 没有年前两位和秒
|
||
///type=4 05/08 19:14 没有年和秒
|
||
/// </param>
|
||
/// <returns></returns>
|
||
public static string ToUnityString(this DateTime dt, int type = 4)
|
||
{
|
||
if (dt == DateTime.MinValue)
|
||
return "";
|
||
string formartStr = string.Empty;
|
||
switch (type)
|
||
{
|
||
case 1: formartStr = "yyyy/MM/dd"; break;
|
||
case 2: formartStr = "yyyy/MM/dd HH:mm"; break;
|
||
case 3: formartStr = "yy/MM/dd HH:mm"; break;
|
||
case 4: formartStr = "MM/dd HH:mm"; break;
|
||
case 5: formartStr = "yyyyMM"; break;
|
||
case 6: formartStr = "yyyy-MM-dd HH:mm:ss"; break;
|
||
}
|
||
return dt.ToString(formartStr);
|
||
}
|
||
|
||
/// <summary>
|
||
///时间格式化
|
||
/// </summary>
|
||
/// <param name="dt">返回字符串的类型(默认4)
|
||
///例子: 2014/05/08 19:14:17
|
||
///type=1 2014/05/08 没有时分秒
|
||
///type=2 2014/05/08 19:14 没有秒
|
||
///type=3 14/05/08 19:14 没有年前两位和秒
|
||
///type=4 05/08 19:14 没有年和秒
|
||
/// </param>
|
||
/// <returns></returns>
|
||
public static string ToUnityString(this DateTime? dt, int type = 4)
|
||
{
|
||
if (dt == null || dt.Value == DateTime.MinValue)
|
||
return "";
|
||
string formartStr = string.Empty;
|
||
switch (type)
|
||
{
|
||
case 1: formartStr = "yyyy/MM/dd"; break;
|
||
case 2: formartStr = "yyyy/MM/dd HH:mm"; break;
|
||
case 3: formartStr = "yy/MM/dd HH:mm"; break;
|
||
case 4: formartStr = "MM/dd HH:mm"; break;
|
||
case 5: formartStr = "yyyyMM"; break;
|
||
case 6: formartStr = "yyyy-MM-dd HH:mm:ss"; break;
|
||
}
|
||
return dt.Value.ToString(formartStr);
|
||
}
|
||
|
||
#region 枚举
|
||
|
||
public static IList<ListItem> GetItemFromEnum<T>()
|
||
{
|
||
IList<ListItem> list = new List<ListItem>();
|
||
ListItem item;
|
||
string[] names = Enum.GetNames(typeof(T));
|
||
foreach (int i in Enum.GetValues(typeof(T)))
|
||
{
|
||
item = new ListItem();
|
||
item.Text = names[i];
|
||
item.Value = i.ToString();
|
||
list.Add(item);
|
||
}
|
||
return list;
|
||
}
|
||
|
||
public static string GetEnumName<T>(int i)
|
||
{
|
||
string name = null;
|
||
string[] names = Enum.GetNames(typeof(T));
|
||
if (i < names.Length)
|
||
{
|
||
name = names[i];
|
||
}
|
||
return name;
|
||
}
|
||
|
||
//重构,不是0 1 2 3 的枚举也能绑定
|
||
public static IList<ListItem> GetListItemFromEnum<T>()
|
||
{
|
||
IList<ListItem> list = new List<ListItem>();
|
||
ListItem item;
|
||
foreach (int i in Enum.GetValues(typeof(T)))
|
||
{
|
||
item = new ListItem();
|
||
item.Text = Enum.GetName(typeof(T), i);
|
||
item.Value = i.ToString();
|
||
list.Add(item);
|
||
}
|
||
return list;
|
||
}
|
||
|
||
public static string GetEnumNameByValue<T>(int i)
|
||
{
|
||
string name = Enum.GetName(typeof(T), i);
|
||
return name;
|
||
}
|
||
|
||
public static string GetCheckEnumNameByValue<T>(int i)
|
||
{
|
||
string name = i.ToString();
|
||
if (Enum.IsDefined(typeof(T), i))
|
||
name = Enum.GetName(typeof(T), i);
|
||
return name;
|
||
}
|
||
|
||
#endregion 枚举
|
||
|
||
#region JSON
|
||
|
||
public static T JSONToObject<T>(string json)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
serializer.MaxJsonLength = int.MaxValue;
|
||
T t = serializer.Deserialize<T>(json);
|
||
return t;
|
||
}
|
||
|
||
public static string ConvertToJSON<T>(IList<T> list)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
string json = serializer.Serialize(list);
|
||
return json;
|
||
}
|
||
|
||
public static string ConvertToJSON<T>(T obj)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
|
||
string json = serializer.Serialize(obj);
|
||
return json;
|
||
}
|
||
|
||
public static string ObjectToJson<T>(T t)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
serializer.MaxJsonLength = 10240000;
|
||
string json = serializer.Serialize(t);
|
||
return json;
|
||
}
|
||
|
||
public static string ObjectToJsonAndConvertTime<T>(IList<T> t)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
serializer.MaxJsonLength = 10240000;
|
||
serializer.RegisterConverters(new JavaScriptConverter[] { new DateTimeConverter<T>() });
|
||
string json = serializer.Serialize(t);
|
||
return json;
|
||
}
|
||
|
||
public static string ObjectToJsonAndConvertTime<T>(T t)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
serializer.MaxJsonLength = 10240000;
|
||
serializer.RegisterConverters(new JavaScriptConverter[] { new DateTimeConverter<T>() });
|
||
string json = serializer.Serialize(t);
|
||
return json;
|
||
}
|
||
|
||
public static T MAXJSONToObject<T>(string json)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
serializer.MaxJsonLength = int.MaxValue;
|
||
T t = serializer.Deserialize<T>(json);
|
||
return t;
|
||
}
|
||
|
||
public static string ToJson(this object data)
|
||
{
|
||
if (data == null) return null;
|
||
return JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.None, DefaultJsonSerializerSettings);
|
||
}
|
||
|
||
public static T ToObject<T>(this string jsonStr, params string[] name) where T : class
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrEmpty(jsonStr)) return null;
|
||
if (name == null || name.Length == 0)
|
||
return JsonConvert.DeserializeObject<T>(jsonStr);
|
||
JObject o = JObject.Parse(jsonStr);
|
||
JToken jtoken = null;
|
||
foreach (var item in name)
|
||
{
|
||
if (jsonStr.Contains(item))
|
||
jtoken = jtoken == null ? o[item] : jtoken[item];
|
||
}
|
||
string json = jtoken.ToString();
|
||
return JsonConvert.DeserializeObject<T>(json);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogHelper.Info($"Json反序列化发生错误:{ex.Message}");
|
||
return null;
|
||
}
|
||
}
|
||
|
||
private static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings
|
||
{
|
||
DateFormatHandling = DateFormatHandling.IsoDateFormat,
|
||
DateFormatString = "yyyy-MM-dd HH:mm:ss",
|
||
DateTimeZoneHandling = DateTimeZoneHandling.Local,
|
||
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
|
||
};
|
||
|
||
#endregion JSON
|
||
|
||
#region xml
|
||
|
||
public static T XMLToObject<T>(string xml)
|
||
{
|
||
byte[] buffer = Encoding.UTF8.GetBytes(xml);
|
||
MemoryStream ms = new MemoryStream(buffer);
|
||
XmlTextReader xmlReader = new XmlTextReader(ms);
|
||
XmlSerializer formatter = new XmlSerializer(typeof(T));
|
||
T obj = (T)formatter.Deserialize(xmlReader);
|
||
xmlReader.Close();
|
||
return obj;
|
||
}
|
||
|
||
public static string Serialize<T>(T obj)
|
||
{
|
||
MemoryStream MS = new MemoryStream();
|
||
XmlTextWriter xmlWriter = new XmlTextWriter(MS, Encoding.UTF8);
|
||
xmlWriter.Indentation = 4;
|
||
xmlWriter.Formatting = System.Xml.Formatting.Indented;
|
||
XmlSerializer formatter = new XmlSerializer(typeof(T));
|
||
formatter.Serialize(xmlWriter, obj);
|
||
xmlWriter.Close();
|
||
string xmlstring = Encoding.UTF8.GetString(MS.ToArray());
|
||
return xmlstring;
|
||
}
|
||
|
||
#endregion xml
|
||
|
||
#region 提交数据
|
||
|
||
/// <summary>
|
||
/// 提交数据
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="encoding"></param>
|
||
/// <returns></returns>
|
||
public static string PostData(string url, Encoding encoding)
|
||
{
|
||
HttpWebRequest request = null;
|
||
//如果是发送HTTPS请求
|
||
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
|
||
request = WebRequest.Create(url) as HttpWebRequest;
|
||
request.ProtocolVersion = HttpVersion.Version10;
|
||
}
|
||
else
|
||
{
|
||
request = WebRequest.Create(url) as HttpWebRequest;
|
||
}
|
||
//HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 提交数据
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="encoding"></param>
|
||
/// <returns></returns>
|
||
public static string PostData(string url, string param, Encoding encoding)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||
request.Method = "POST";
|
||
request.ContentType = "application/x-www-form-urlencoded";
|
||
byte[] data = encoding.GetBytes(param);
|
||
|
||
using (BinaryWriter reqStream = new BinaryWriter(request.GetRequestStream()))
|
||
{
|
||
reqStream.Write(data, 0, data.Length);
|
||
}
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
public static string PostAjaxData(string url, string param, Encoding encoding, int timeout = 10000)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||
request.Method = "POST";
|
||
request.ContentType = "application/json;charet=utf-8";
|
||
request.Headers.Add("dataType", "json");
|
||
request.Headers.Add("type", "post");
|
||
request.Timeout = timeout;
|
||
byte[] data = encoding.GetBytes(param);
|
||
|
||
using (BinaryWriter reqStream = new BinaryWriter(request.GetRequestStream()))
|
||
{
|
||
reqStream.Write(data, 0, data.Length);
|
||
}
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
public static string PostAjaxData(string url, Dictionary<string, string> headers, Encoding encoding)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||
request.Method = "POST";
|
||
request.ContentType = "application/json;charet=utf-8";
|
||
request.Headers.Add("dataType", "json");
|
||
request.Headers.Add("type", "post");
|
||
foreach (var header in headers)
|
||
{
|
||
request.Headers.Add(header.Key, header.Value);
|
||
}
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
public static string PostAjaxData(string url, string param, Dictionary<string, string> headers, Encoding encoding)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||
request.Method = "POST";
|
||
request.ContentType = "application/json;charet=utf-8";
|
||
request.Headers.Add("dataType", "json");
|
||
request.Headers.Add("type", "post");
|
||
foreach (var header in headers)
|
||
{
|
||
request.Headers.Add(header.Key, header.Value);
|
||
}
|
||
byte[] data = encoding.GetBytes(param);
|
||
|
||
using (BinaryWriter reqStream = new BinaryWriter(request.GetRequestStream()))
|
||
{
|
||
reqStream.Write(data, 0, data.Length);
|
||
}
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
public static string PostAjaxData(string url, string param, string Authorization, bool jsonContentType)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||
request.Method = "POST";
|
||
if (jsonContentType)
|
||
{
|
||
request.ContentType = "application/json;charet=utf-8";
|
||
}
|
||
//request.Headers.Add("dataType", "json");
|
||
//request.Headers.Add("type", "post");
|
||
if (!string.IsNullOrEmpty(Authorization))
|
||
{
|
||
request.Headers.Add("Authorization", Authorization);
|
||
}
|
||
byte[] data = Encoding.UTF8.GetBytes(param);
|
||
|
||
using (BinaryWriter reqStream = new BinaryWriter(request.GetRequestStream()))
|
||
{
|
||
reqStream.Write(data, 0, data.Length);
|
||
}
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取数据
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="encoding"></param>
|
||
/// <returns></returns>
|
||
public static string GetData(string Url, string RequestPara, Encoding encoding)
|
||
{
|
||
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
|
||
|
||
WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
|
||
|
||
byte[] buf = encoding.GetBytes(RequestPara);
|
||
hr.Method = "GET";
|
||
|
||
System.Net.WebResponse response = hr.GetResponse();
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
|
||
string ReturnVal = reader.ReadToEnd();
|
||
reader.Close();
|
||
response.Close();
|
||
|
||
return ReturnVal;
|
||
}
|
||
|
||
public static string GetData(string Url, string RequestPara, string Authorization, bool jsonContentType)
|
||
{
|
||
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
|
||
|
||
WebRequest request = HttpWebRequest.Create(Url + RequestPara);
|
||
|
||
byte[] buf = Encoding.UTF8.GetBytes(RequestPara);
|
||
request.Method = "GET";
|
||
if (jsonContentType)
|
||
{
|
||
request.ContentType = "application/json;charet=utf-8";
|
||
}
|
||
//request.Headers.Add("dataType", "json");
|
||
//request.Headers.Add("type", "post");
|
||
if (!string.IsNullOrEmpty(Authorization))
|
||
{
|
||
request.Headers.Add("Authorization", Authorization);
|
||
}
|
||
System.Net.WebResponse response = request.GetResponse();
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
|
||
string ReturnVal = reader.ReadToEnd();
|
||
reader.Close();
|
||
response.Close();
|
||
|
||
return ReturnVal;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 创建POST方式的HTTP请求
|
||
/// </summary>
|
||
/// <param name="url">请求的URL</param>
|
||
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
|
||
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
|
||
/// <returns></returns>
|
||
public static string HttpPostData(string url, string parameters, Encoding requestEncoding)
|
||
{
|
||
if (string.IsNullOrEmpty(url))
|
||
{
|
||
throw new ArgumentNullException("url");
|
||
}
|
||
if (requestEncoding == null)
|
||
{
|
||
throw new ArgumentNullException("requestEncoding");
|
||
}
|
||
HttpWebRequest request = null;
|
||
request = WebRequest.Create(url) as HttpWebRequest;
|
||
request.Method = "POST";
|
||
request.ContentType = "application/x-www-form-urlencoded";
|
||
// request.ContentType = "application/json";
|
||
//如果需要POST数据
|
||
if (!string.IsNullOrEmpty(parameters))
|
||
{
|
||
byte[] data = requestEncoding.GetBytes(parameters.ToString());
|
||
using (Stream stream = request.GetRequestStream())
|
||
{
|
||
stream.Write(data, 0, data.Length);
|
||
}
|
||
}
|
||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||
{
|
||
StreamReader reader = new StreamReader(response.GetResponseStream(), requestEncoding);
|
||
string result = reader.ReadToEnd();
|
||
return result;
|
||
}
|
||
}
|
||
|
||
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
|
||
{
|
||
return true; //总是接受
|
||
}
|
||
|
||
#endregion 提交数据
|
||
|
||
#region 十进制转六十四进制
|
||
|
||
private static string[] SubstrSplit(string str, int lenStep)
|
||
{
|
||
if (string.IsNullOrEmpty(str))
|
||
return null;
|
||
int L = str.Length % lenStep;
|
||
if (L > 0)
|
||
{
|
||
for (int i = 0; i < lenStep - L; i++)
|
||
{
|
||
str = "0" + str;
|
||
}
|
||
}
|
||
string tem = "";
|
||
while (str.Length >= lenStep)
|
||
{
|
||
if (str.Length > lenStep)
|
||
tem += string.Format(",{0}", str.Substring(0, lenStep));
|
||
else
|
||
tem += string.Format(",{0}", str);
|
||
str = str.Substring(lenStep);
|
||
}
|
||
tem = tem.Trim(',');
|
||
return tem.Split(',');
|
||
}
|
||
|
||
public static string Conver10To64Ext(long d10)
|
||
{
|
||
string str64 = "";
|
||
string[] fhs = "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".Split(',');
|
||
string binStr = Convert.ToString(d10, 2);
|
||
string[] bstrForLenStep = SubstrSplit(binStr, 6);
|
||
if (bstrForLenStep == null)
|
||
return "";
|
||
for (int j = 0; j < bstrForLenStep.Length; j++)
|
||
{
|
||
int index = Convert.ToInt32(bstrForLenStep[j], 2);
|
||
str64 += string.Format("{0}", fhs[index]);
|
||
}
|
||
return str64;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 根据工号生成远程邀请码(十进制字符串)
|
||
/// </summary>
|
||
/// <param name="eid"></param>
|
||
/// <param name="msg"></param>
|
||
/// <returns></returns>
|
||
public static string encyptCodeByEid(int eid)
|
||
{
|
||
string deptCode = ConfigurationManager.AppSettings["InviteDeptCode"];
|
||
DateTime curDate = System.DateTime.Now;
|
||
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
|
||
string BM = string.Format("{0}", (int)asciiEncoding.GetBytes(deptCode)[0]);
|
||
int nHH = curDate.Hour + Convert.ToInt32(curDate.Year.ToString().Substring(2, 2));
|
||
int nMM = curDate.Minute + curDate.Day;
|
||
string nLVStr = string.Format("{0}{1}{2}{3}", eid.ToString("000000"), nHH.ToString("00"), nMM.ToString("00"), BM);
|
||
Int64 _nLVStr = Convert.ToInt64(nLVStr);
|
||
string nstr_binary = Convert.ToString(_nLVStr, 2);
|
||
|
||
//除最高位,其余各位取反
|
||
char[] t = nstr_binary.ToArray();
|
||
for (int i = 1; i < t.Length; i++)
|
||
{
|
||
t[i] = t[i] == '1' ? '0' : '1';
|
||
}
|
||
string n_binstr = string.Join("", t);
|
||
|
||
Int64 n_encypt64 = Convert.ToInt64(n_binstr, 2);
|
||
return n_encypt64.ToString(); //返回十进制字符串
|
||
}
|
||
|
||
/// <summary>
|
||
/// 还原远程邀请码为明文串(验证码)
|
||
/// </summary>
|
||
/// <param name="encypCode"></param>
|
||
/// <returns></returns>
|
||
public static string decyptEncypCode(Int64 encypCode)
|
||
{
|
||
string nstr_binary = Convert.ToString(encypCode, 2);
|
||
//除最高位,其余各位取反
|
||
char[] t = nstr_binary.ToArray();
|
||
for (int i = 1; i < t.Length; i++)
|
||
{
|
||
t[i] = t[i] == '1' ? '0' : '1';
|
||
}
|
||
string n_binstr = string.Join("", t);
|
||
Int64 n_encypt64 = Convert.ToInt64(n_binstr, 2);
|
||
return n_encypt64.ToString("000000000000");
|
||
}
|
||
|
||
#endregion 十进制转六十四进制
|
||
|
||
#region unix 时间转换
|
||
|
||
/// <summary>
|
||
/// 将Unix时间戳转换为DateTime类型时间
|
||
/// </summary>
|
||
/// <param name="d">double 型数字</param>
|
||
/// <returns>DateTime</returns>
|
||
public static System.DateTime ConvertIntDateTime(double d)
|
||
{
|
||
System.DateTime time = System.DateTime.MinValue;
|
||
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
|
||
time = startTime.AddSeconds(d);
|
||
return time;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将c# DateTime时间格式转换为Unix时间戳格式
|
||
/// </summary>
|
||
/// <param name="time">时间</param>
|
||
/// <returns>double</returns>
|
||
public static double ConvertDateTimeInt(System.DateTime time)
|
||
{
|
||
double intResult = 0;
|
||
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
|
||
intResult = (time - startTime).TotalSeconds;
|
||
return intResult;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将c# DateTime时间格式转换为Unix时间戳格式
|
||
/// </summary>
|
||
/// <param name="time">时间</param>
|
||
/// <returns>double</returns>
|
||
public static long ConvertDateTimeLong(System.DateTime time)
|
||
{
|
||
double intResult = ConvertDateTimeInt(time);
|
||
return Convert.ToInt64(intResult);
|
||
}
|
||
/// <summary>
|
||
///
|
||
/// </summary>
|
||
/// <param name="timeJavaLong">java长整型日期,毫秒为单位</param>
|
||
/// <returns></returns>
|
||
public static DateTime JavaLongToDateTime(long timeJavaLong)
|
||
{
|
||
var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);
|
||
var tricks1970 = dt1970.Ticks;//1970年1月1日刻度
|
||
var timeTricks = tricks1970 + timeJavaLong * 10000;//日志日期刻度
|
||
return new DateTime(timeTricks).AddHours(8);//转化为DateTime
|
||
}
|
||
|
||
#endregion unix 时间转换
|
||
|
||
#region 检查是否手机号
|
||
|
||
/// <summary>
|
||
/// 00852+8位是香港的电话
|
||
/// </summary>
|
||
/// <param name="number"></param>
|
||
/// <returns></returns>
|
||
public static bool ChekMobile(string number)
|
||
{
|
||
string rgs = @"^(13|14|15|16|17|18|19|0085)\d{9}$";
|
||
Regex reg = new Regex(rgs);
|
||
return reg.IsMatch(number);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检查是否包含手机号码
|
||
/// </summary>
|
||
/// <param name="number"></param>
|
||
/// <returns></returns>
|
||
public static bool ContainMobile(string number)
|
||
{
|
||
string rgs = @".*(13|14|15|16|17|18|19)\d{9}.*";
|
||
Regex reg = new Regex(rgs);
|
||
return reg.IsMatch(number);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从文本中返回号码字符串
|
||
/// </summary>
|
||
/// <param name="txt"></param>
|
||
/// <returns></returns>
|
||
public static string GetMobile(string txt)
|
||
{
|
||
string rgs = @"(12|13|14|15|16|17|18|19)\d{9}";
|
||
string result = Regex.Match(txt, rgs).Value;
|
||
return result;
|
||
}
|
||
|
||
public static bool CheckIsNum(string txt)
|
||
{
|
||
string rgs = "^\\d{6,16}$";
|
||
Regex reg = new Regex(rgs);
|
||
return reg.IsMatch(txt);
|
||
}
|
||
|
||
public static bool IsNum(string txt)
|
||
{
|
||
string rgs = "^\\d+$";
|
||
Regex reg = new Regex(rgs);
|
||
return reg.IsMatch(txt);
|
||
}
|
||
|
||
public static bool IsChinese(string txt)
|
||
{
|
||
string rgs = "[\u4E00-\u9FA5]";
|
||
Regex reg = new Regex(rgs);
|
||
return reg.IsMatch(txt);
|
||
}
|
||
|
||
public static bool IsNumOrStr(string txt)
|
||
{
|
||
string rgs = "^[A-Za-z0-9]+$";
|
||
Regex reg = new Regex(rgs);
|
||
return reg.IsMatch(txt);
|
||
}
|
||
|
||
#endregion 检查是否手机号
|
||
|
||
public static string NumberSub(string number)
|
||
{
|
||
string Sub_0 = @"^(013|015|016|018|014|017|019)\d*$";
|
||
Regex reg = new Regex(Sub_0);
|
||
if (number.Length > 11 && reg.IsMatch(number))
|
||
return number.Substring(1);
|
||
return number;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 验证固定电话号码
|
||
/// </summary>
|
||
/// <param name="telcode"></param>
|
||
/// <returns></returns>
|
||
public static bool ValidateTelCode(string telcode)
|
||
{
|
||
string express = @"^(0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$";
|
||
return ValidateInput(telcode, express);
|
||
}
|
||
|
||
public static string NumberFormat(string number)
|
||
{
|
||
if (string.IsNullOrEmpty(number) || number.Length <= 6)
|
||
{
|
||
return number;
|
||
}
|
||
return number.Substring(0, 3) + new string('*', number.Length - 6) + number.Substring(number.Length - 3);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 验证固定电话号码无下滑斜杠
|
||
/// </summary>
|
||
/// <param name="telcode"></param>
|
||
/// <returns></returns>
|
||
public static bool ValidateTelCode2(string telcode)
|
||
{
|
||
string express = @"^\d{6,20}$";
|
||
return ValidateInput(telcode, express);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 验证数据
|
||
/// </summary>
|
||
/// <param name="data">需验证数据</param>
|
||
/// <param name="express">正则表达式</param>
|
||
/// <returns>符合返回为true,否则返回false</returns>
|
||
public static bool ValidateInput(string data, string express)
|
||
{
|
||
Regex reg = new Regex(express);
|
||
return reg.IsMatch(data);
|
||
}
|
||
|
||
public static Stream GetStream(string str)
|
||
{
|
||
MemoryStream ms = new MemoryStream();
|
||
StreamWriter sw = new StreamWriter(ms);
|
||
sw.AutoFlush = true;
|
||
sw.Write(str);
|
||
ms.Position = 0;
|
||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
|
||
return ms;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 先把所有的数字抽取出来,然后判断每个数字是否手机,是手机就执行替换
|
||
/// </summary>
|
||
/// <param name="txt"></param>
|
||
/// <returns></returns>
|
||
public static string ReplaceMobile(object txt)
|
||
{
|
||
if (txt == null)
|
||
{
|
||
return "";
|
||
}
|
||
if (string.IsNullOrEmpty(txt.ToString()))
|
||
{
|
||
return "";
|
||
}
|
||
var content = txt.ToString();
|
||
string numReg = @"\d+";
|
||
var result = Regex.Matches(content, numReg).Cast<Match>().Select(t => t.Value).ToList();
|
||
if (result != null && result.Count > 0)
|
||
{
|
||
foreach (var s in result)
|
||
{
|
||
if (Utility.ChekMobile(s))
|
||
{
|
||
content = content.Replace(s, GetHideMobile(s));
|
||
}
|
||
}
|
||
}
|
||
return content;
|
||
}
|
||
|
||
public static bool IsContainMobile(string txt)
|
||
{
|
||
if (string.IsNullOrEmpty(txt.ToString()))
|
||
{
|
||
return false;
|
||
}
|
||
var content = txt.ToString();
|
||
string rgs = @"\d+";
|
||
var result = Regex.Matches(content, rgs).Cast<Match>().Select(t => t.Value).ToList();
|
||
if (result != null && result.Count > 0)
|
||
{
|
||
foreach (var s in result)
|
||
{
|
||
if (Utility.ChekMobile(s))
|
||
{
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
public static bool IsContainWeixinHongBao(string txt)
|
||
{
|
||
if (string.IsNullOrEmpty(txt.ToString()))
|
||
{
|
||
return false;
|
||
}
|
||
var content = txt.ToString();
|
||
string rgs = @"(weixin:\/\/weixinhongbao)";
|
||
var result = Regex.Matches(content, rgs).Cast<Match>().Select(t => t.Value).ToList();
|
||
if (result != null && result.Count > 0)
|
||
{
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
public static string GetHideMobile(string phoneNo)
|
||
{
|
||
Regex re = new Regex(@"(\d{3})(\d{5})(\d{3})", RegexOptions.None);
|
||
phoneNo = re.Replace(phoneNo, "$1*****$3");
|
||
return phoneNo;
|
||
}
|
||
|
||
#region 时间转换
|
||
|
||
/// <summary>
|
||
/// 指定时间DateTimeKind
|
||
/// </summary>
|
||
public class DateTimeConverter<T> : JavaScriptConverter
|
||
{
|
||
private const string _dateFormat = "yyyy/MM/dd HH:mm:ss";
|
||
|
||
public override IEnumerable<Type> SupportedTypes
|
||
{
|
||
get { return new List<Type>() { typeof(T) }; }
|
||
}
|
||
|
||
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
|
||
{
|
||
Dictionary<string, object> result = new Dictionary<string, object>();
|
||
T p = (T)obj;
|
||
foreach (PropertyInfo pi in typeof(T).GetProperties())
|
||
{
|
||
if (pi.PropertyType == typeof(DateTime))
|
||
{
|
||
result[pi.Name] = ((DateTime)pi.GetValue(p, null)).ToString(_dateFormat);
|
||
}
|
||
else if (pi.PropertyType == typeof(DateTime?))
|
||
{
|
||
var value = pi.GetValue(p, null);
|
||
if (value != null)
|
||
result[pi.Name] = ((DateTime)pi.GetValue(p, null)).ToString(_dateFormat);
|
||
else
|
||
result[pi.Name] = null;
|
||
}
|
||
else
|
||
{
|
||
result[pi.Name] = pi.GetValue(p, null);
|
||
}
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
|
||
{
|
||
//需要限定无参构造函数,因此返回null。不支持json to Object。
|
||
//T p = new T();
|
||
|
||
//var props = typeof(T).GetProperties();
|
||
//foreach (string key in dictionary.Keys)
|
||
//{
|
||
// var prop = props.Where(t => t.Name == key).FirstOrDefault();
|
||
// if (prop != null)
|
||
// {
|
||
// prop.SetValue(p, dictionary[key], null);
|
||
// }
|
||
//}
|
||
//return p;
|
||
return null;
|
||
}
|
||
}
|
||
|
||
#endregion 时间转换
|
||
|
||
/// <summary>
|
||
/// 获取随机数
|
||
/// </summary>
|
||
/// <param name="codeCount"></param>
|
||
/// <returns></returns>
|
||
public static string CreateRandomSatl(int codeCount)
|
||
{
|
||
string allChar = "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,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,w,x,y,z";
|
||
string[] allCharArray = allChar.Split(',');
|
||
string randomCode = "";
|
||
int temp = -1;
|
||
Random rand = new Random();
|
||
for (int i = 0; i < codeCount; i++)
|
||
{
|
||
if (temp != -1)
|
||
{
|
||
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
|
||
}
|
||
int t = rand.Next(50);
|
||
if (temp == t)
|
||
{
|
||
return CreateRandomSatl(codeCount);
|
||
}
|
||
temp = t;
|
||
randomCode += allCharArray[t];
|
||
}
|
||
return randomCode;
|
||
}
|
||
|
||
public static string Sha512(string value)
|
||
{
|
||
SHA512 s512 = new SHA512Managed();
|
||
byte[] bit_pwd = Encoding.Default.GetBytes(value);
|
||
byte[] bit_shapsw = s512.ComputeHash(bit_pwd);
|
||
string shapsw = Convert.ToBase64String(bit_shapsw);
|
||
return shapsw;
|
||
}
|
||
|
||
public static int PasswordStrength(string password)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(password)) return -1;
|
||
//字符统计
|
||
int iNum = 0, iLtt = 0, iSym = 0;
|
||
foreach (char c in password)
|
||
{
|
||
if (c >= '0' && c <= '9') iNum++;
|
||
else if (c >= 'a' && c <= 'z') iLtt++;
|
||
else if (c >= 'A' && c <= 'Z') iLtt++;
|
||
else iSym++;
|
||
}
|
||
if (password.Length < 6) return 3; //长度小于6的密码
|
||
if (iLtt == 0 && iSym == 0) return 1; //纯数字密码
|
||
if (iNum == 0 && iSym == 0) return 2; //纯字母密码
|
||
return 0; //正确
|
||
}
|
||
|
||
public static string GetSendMsgModel(string strJson, string modelParam)
|
||
{
|
||
string key = string.Empty;
|
||
string values = string.Empty;
|
||
strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
|
||
|
||
Regex regex = new Regex(@"(?<={)[^}]+(?=})");
|
||
MatchCollection mc = regex.Matches(strJson);
|
||
Dictionary<string, string> list = new Dictionary<string, string>();
|
||
for (int i = 0; i < mc.Count; i++)
|
||
{
|
||
string strRow = mc[i].Value;
|
||
string[] strRows = strRow.Split('*');
|
||
foreach (string str in strRows)
|
||
{
|
||
string[] strCell = str.Split('#');
|
||
|
||
key = strCell[0].Replace("\"", "");
|
||
values = strCell[1].Replace("\"", "");
|
||
list.Add(key, values);
|
||
}
|
||
}
|
||
foreach (var item in list)
|
||
{
|
||
modelParam = modelParam.Replace("${" + item.Key + "}", item.Value);
|
||
}
|
||
|
||
return modelParam;
|
||
}
|
||
|
||
public static string DateEnToCn(string date)
|
||
{
|
||
string datename = "";
|
||
date = date.ToLower();
|
||
switch (date)
|
||
{//--Monday 周一 Tuesday 周二 Wednesday 周三 Thursday 周四 Friday 周五 Saturday 周六 Sunday 周日
|
||
case "monday": datename = "星期一"; break;
|
||
case "tuesday": datename = "星期二"; break;
|
||
case "wednesday": datename = "星期三"; break;
|
||
case "thursday": datename = "星期四"; break;
|
||
case "friday": datename = "星期五"; break;
|
||
case "saturday": datename = "星期六"; break;
|
||
case "sunday": datename = "星期日"; break;
|
||
}
|
||
return datename;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将c# DateTime时间格式转换为Unix时间戳格式
|
||
/// </summary>
|
||
/// <param name="time">时间</param>
|
||
/// <returns>long</returns>
|
||
public static long ConvertDateTimeToInt(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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 时间戳转为C#格式时间
|
||
/// </summary>
|
||
/// <param name="timeStamp"></param>
|
||
/// <returns></returns>
|
||
public static DateTime ConvertStringToDateTime(string timeStamp)
|
||
{
|
||
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
||
long lTime = long.Parse(timeStamp + "0000");
|
||
TimeSpan toNow = new TimeSpan(lTime);
|
||
return dtStart.Add(toNow);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取文件的MD5码
|
||
/// </summary>
|
||
/// <param name="fileName">传入的文件名(含路径及后缀名)</param>
|
||
/// <returns></returns>
|
||
public static string GetMD5HashFromFile(string fileName)
|
||
{
|
||
try
|
||
{
|
||
FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
|
||
MD5 md5 = new MD5CryptoServiceProvider();
|
||
byte[] retVal = md5.ComputeHash(file);
|
||
file.Close();
|
||
StringBuilder sb = new StringBuilder();
|
||
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 查找指定目录下的所有末级子目录
|
||
/// </summary>
|
||
/// <param name="dir">要查找的目录</param>
|
||
/// <param name="list">查找结果列表</param>
|
||
/// <param name="system">是否包含系统目录</param>
|
||
/// <param name="hidden">是否包含隐藏目录</param>
|
||
public static void GetEndDirectories(DirectoryInfo dir, List<DirectoryInfo> list, bool system = false, bool hidden = false)
|
||
{
|
||
DirectoryInfo[] sub = dir.GetDirectories();
|
||
|
||
if (sub.Length == 0)
|
||
{// 没有子目录了
|
||
list.Add(dir);
|
||
return;
|
||
}
|
||
|
||
foreach (DirectoryInfo subDir in sub)
|
||
{
|
||
// 跳过系统目录
|
||
if (!system && (subDir.Attributes & FileAttributes.System) == FileAttributes.System)
|
||
continue;
|
||
// 跳过隐藏目录
|
||
if (!hidden && (subDir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
|
||
continue;
|
||
|
||
GetEndDirectories(subDir, list);
|
||
}
|
||
}
|
||
|
||
public static bool CheckVersionExpire(string account)
|
||
{
|
||
string enkey = WX.CRM.Common.Utility.GetSettingByKey("CRMClientKey");
|
||
Interface.Security.ClientKey clientid = Interface.Security.ClientKey.GetClientKey(enkey);
|
||
Interface.Security.EncDecUtil sHelper = new Interface.Security.EncDecUtil();
|
||
|
||
var accountUseDate = GetSettingOrNullByKey("AccountUseDate");
|
||
if (!string.IsNullOrEmpty(accountUseDate))
|
||
{
|
||
var arr = sHelper.decyptData(accountUseDate, clientid.AccessKey).Split('#');
|
||
var confimAccount = arr[0];
|
||
var date = DateTime.ParseExact(arr[1], "yyyyMMdd", CultureInfo.CurrentCulture).ToString("yyyy-MM-dd");
|
||
|
||
//如果账号不正确
|
||
if (confimAccount != account)
|
||
{
|
||
return false;
|
||
}
|
||
//如果时间超过了当前时间
|
||
if (date.CompareTo(DateTime.Now) >= 0)
|
||
{
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
public static string GetParamToString(this object obj, string url = "")
|
||
{
|
||
PropertyInfo[] propertis = obj.GetType().GetProperties();
|
||
StringBuilder sb = new StringBuilder();
|
||
sb.Append(url);
|
||
sb.Append("?");
|
||
foreach (var p in propertis)
|
||
{
|
||
var v = p.GetValue(obj, null);
|
||
if (v == null)
|
||
continue;
|
||
|
||
sb.Append(p.Name);
|
||
sb.Append("=");
|
||
sb.Append(HttpUtility.UrlEncode(v.ToString()));
|
||
sb.Append("&");
|
||
}
|
||
sb.Remove(sb.Length - 1, 1);
|
||
|
||
return sb.ToString();
|
||
}
|
||
|
||
/// <summary>
|
||
/// java的byte转换成C#的byte
|
||
/// </summary>
|
||
/// <param name="javabyte"></param>
|
||
/// <returns></returns>
|
||
public static byte[] JavaByteChnageNETByte(int[] javabyte)
|
||
{
|
||
byte[] data = null;
|
||
try
|
||
{
|
||
if (javabyte == null || javabyte.Length == 0)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
data = new byte[javabyte.Length];
|
||
|
||
for (int i = 0; i < javabyte.Length; i++)
|
||
{
|
||
data[i] = (byte)(javabyte[i] & 0xff);
|
||
}
|
||
//string wochaa = System.Text.Encoding.UTF8.GetString(data);
|
||
}
|
||
catch (Exception ae) { LogHelper.Error(ae); };
|
||
return data;
|
||
}
|
||
|
||
public static string ByteToString(byte[] by)
|
||
{
|
||
if (by == null || by.Length == 0)
|
||
return null;
|
||
else
|
||
return System.Text.Encoding.UTF8.GetString(by);
|
||
}
|
||
|
||
public static string JavaByteToString(int[] javabyte)
|
||
{
|
||
return ByteToString(JavaByteChnageNETByte(javabyte));
|
||
}
|
||
|
||
public static string getSourceText(string source)
|
||
{
|
||
if (source == "1")
|
||
return "微信号推广";
|
||
else if (source == "2")
|
||
return "手机号推广";
|
||
else if (source == "3")
|
||
return "线下资源";
|
||
else if (source == "4")
|
||
return "自找资源";
|
||
else if (source == "5")
|
||
return "在线订单";
|
||
else if (source == "6")
|
||
return "企微推广";
|
||
else
|
||
return "";
|
||
}
|
||
|
||
public static int GetSoftChannelType(int ch)
|
||
{
|
||
if (ch == 1100)
|
||
{
|
||
return ch;
|
||
}
|
||
if (ch >= 2100 && ch < 2200)
|
||
{
|
||
return 2;
|
||
}
|
||
else if (ch >= 2200 && ch < 2300)
|
||
{
|
||
return 3;
|
||
}
|
||
else if (ch > 0 && ch < 2000)
|
||
{
|
||
return 1;
|
||
}
|
||
else
|
||
{
|
||
return ch;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 字符串转base64
|
||
/// </summary>
|
||
/// <param name="str"></param>
|
||
/// <returns></returns>
|
||
public static string StrToBase64(string str)
|
||
{
|
||
byte[] b = Encoding.Default.GetBytes(str);
|
||
//byte[] b = Encoding.UTF8.GetBytes(str);
|
||
//转成 Base64 形式的 System.String
|
||
return Convert.ToBase64String(b);
|
||
}
|
||
|
||
/// <summary>
|
||
/// base64还原字符串
|
||
/// </summary>
|
||
/// <param name="str"></param>
|
||
/// <returns></returns>
|
||
public static string Base64ToStr(string str)
|
||
{
|
||
byte[] c = Convert.FromBase64String(str);
|
||
return Encoding.Default.GetString(c);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 参数按照ASCII码从小到大排序(字典序)
|
||
/// </summary>
|
||
/// <param name="paramsMap"></param>
|
||
/// <returns></returns>
|
||
public static string GetParamSrc(Dictionary<string, string> paramsMap)
|
||
{
|
||
var vDic = (from objDic in paramsMap orderby objDic.Key ascending select objDic);
|
||
StringBuilder str = new StringBuilder();
|
||
foreach (KeyValuePair<string, string> kv in vDic)
|
||
{
|
||
string pkey = kv.Key;
|
||
string pvalue = kv.Value;
|
||
str.Append(pkey + "=" + pvalue + "&");
|
||
}
|
||
|
||
var result = str.ToString().Substring(0, str.ToString().Length - 1);
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将查询字符串解析转换为名值集合.
|
||
/// </summary>
|
||
/// <param name="queryString"></param>
|
||
/// <returns></returns>
|
||
public static NameValueCollection GetQueryString(string queryString)
|
||
{
|
||
return GetQueryString(queryString, null, true);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将查询字符串解析转换为名值集合.
|
||
/// </summary>
|
||
/// <param name="queryString"></param>
|
||
/// <param name="encoding"></param>
|
||
/// <param name="isEncoded"></param>
|
||
/// <returns></returns>
|
||
public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
|
||
{
|
||
queryString = queryString.Replace("?", "");
|
||
NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
|
||
if (!string.IsNullOrEmpty(queryString))
|
||
{
|
||
int count = queryString.Length;
|
||
for (int i = 0; i < count; i++)
|
||
{
|
||
int startIndex = i;
|
||
int index = -1;
|
||
while (i < count)
|
||
{
|
||
char item = queryString[i];
|
||
if (item == '=')
|
||
{
|
||
if (index < 0)
|
||
{
|
||
index = i;
|
||
}
|
||
}
|
||
else if (item == '&')
|
||
{
|
||
break;
|
||
}
|
||
i++;
|
||
}
|
||
string key = null;
|
||
string value = null;
|
||
if (index >= 0)
|
||
{
|
||
key = queryString.Substring(startIndex, index - startIndex);
|
||
value = queryString.Substring(index + 1, (i - index) - 1);
|
||
}
|
||
else
|
||
{
|
||
key = queryString.Substring(startIndex, i - startIndex);
|
||
}
|
||
if (isEncoded)
|
||
{
|
||
result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
|
||
}
|
||
else
|
||
{
|
||
result[key] = value;
|
||
}
|
||
if ((i == (count - 1)) && (queryString[i] == '&'))
|
||
{
|
||
result[key] = string.Empty;
|
||
}
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解码URL.
|
||
/// </summary>
|
||
/// <param name="encoding">null为自动选择编码</param>
|
||
/// <param name="str"></param>
|
||
/// <returns></returns>
|
||
public static string MyUrlDeCode(string str, Encoding encoding)
|
||
{
|
||
if (encoding == null)
|
||
{
|
||
Encoding utf8 = Encoding.UTF8;
|
||
//首先用utf-8进行解码
|
||
string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
|
||
//将已经解码的字符再次进行编码.
|
||
string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
|
||
if (str == encode)
|
||
encoding = Encoding.UTF8;
|
||
else
|
||
encoding = Encoding.GetEncoding("gb2312");
|
||
}
|
||
return HttpUtility.UrlDecode(str, encoding);
|
||
}
|
||
}
|
||
} |