using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Linq;
using System.Collections.Specialized;
namespace Pcb.Common
{
///
/// 扩展方法
///
public static class Extensions
{
private static readonly JavaScriptSerializer jss = new JavaScriptSerializer();
///
/// 将Object的值根据泛型转换成相应的类型的值
/// 如果转换时发生异常,会抛出异常信息
///
/// 要转换的类型
/// 要转换的值
/// 转换失败的默认值(可以不填)
///
public static T ChangeValue(this object value, T defaultValue = default(T))
{
if (value == null) throw new ArgumentNullException("对象不能为null");
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch (FormatException ex)
{
//异常写入日志中
if (defaultValue == null)
throw ex;
}
return (T)Convert.ChangeType(defaultValue, typeof(T));
}
///
/// 将Object的值根据泛型转换成相应的类型的值
/// 如果转换时发生异常,会返回相应的类型的默认值
///
///
///
///
///
public static T ChangeValueDefault(this object value, T defaultValue = default(T))
{
if (value == null)
return default(T);
try
{
return ChangeValue(value, defaultValue);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
return default(T);
}
///
/// 判断2个字符串是否相等(忽略大小写)
///
///
///
///
public static bool EqualsIgnoreCase(this string value, string param)
{
return string.Equals(value, param, StringComparison.CurrentCultureIgnoreCase);
}
public static string ReplaceStartsWith(this string input, string replace, string to)
{
var retval = input;
if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(replace) && input.StartsWith(replace))
{
retval = to + input.Substring(replace.Length);
}
return retval;
}
public static string Trims(this string val)
{
if (!string.IsNullOrEmpty(val))
{
return val.Trim();
}
return "";
}
///
/// 将一个对象序列化成 JSON 格式字符串
///
///
///
public static string ToJson(this object obj)
{
if (obj == null)
return string.Empty;
return jss.Serialize(obj);
}
///
/// 从JSON字符串中反序列化对象
///
///
///
///
public static T FromJson(this string obj)
{
if (string.IsNullOrEmpty(obj))
return default(T);
return jss.Deserialize(obj);
}
///
/// 编码
///
///
///
public static string Escape(this string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
var sb = new StringBuilder();
foreach (var c in str)
{
sb.Append((char.IsLetterOrDigit(c)
|| c == '-' || c == '_' || c == '\\'
|| c == '/' || c == '.')
? c.ToString()
: Uri.HexEscape(c));
}
return sb.ToString();
}
public static string EscapeZH(this string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
var sb = new StringBuilder();
foreach (var c in str)
{
var temp = string.Empty;
if (char.IsLetterOrDigit(c)
|| c == '-' || c == '_' || c == '\\'
|| c == '/' || c == '.')
temp = c.ToString();
else
{
int charInt = c;
temp = "\\u" + Convert.ToString(charInt, 16);
}
sb.Append(temp);
}
return sb.ToString();
}
///
/// UNICODE 支持汉字
///
///
///
public static string UnEscapeZH(this string str)
{
var outstr = "";
if (!string.IsNullOrEmpty(str) && str.IndexOf('u') > -1)
{
var strlist = str.Replace("%", "").Split('u');
try
{
for (var i = 1; i < strlist.Length; i++)
{
//将unicode字符转为10进制整数,然后转为char中文字符
outstr += (char)int.Parse(strlist[i].Substring(0, 4), NumberStyles.HexNumber);
}
}
catch (FormatException ex)
{
outstr = ex.Message;
}
}
else
{
return str;
}
return outstr;
}
///
///
///
///
public static string UnEscape(this string str)
{
if (str == null)
return string.Empty;
var sb = new StringBuilder();
var len = str.Length;
var i = 0;
while (i != len)
{
if (Uri.IsHexEncoding(str, i))
sb.Append(Uri.HexUnescape(str, ref i));
else
sb.Append(str[i++]);
}
return sb.ToString();
}
///
/// 返回long类型
///
///
///
public static long? ToLong(this string str, long? defaultVal = null)
{
long reOut;
if (long.TryParse(str, out reOut))
return reOut;
return defaultVal;
}
///
/// 对象是否 空
///
///
///
public static bool IsNull(this object val)
{
if (val == null || val == DBNull.Value)
return true;
return false;
}
///
/// 对象是否 空
///
///
///
public static bool IsEmpty(this object val)
{
if (val == null || val == DBNull.Value || val == string.Empty)
return true;
return false;
}
///
/// 对象是否 不为空
///
///
///
public static bool IsNotEmpty(this object val)
{
if (val != null && val != DBNull.Value && val != string.Empty)
return true;
return false;
}
///
/// 返回int类型
///
///
///
public static int? ToInt(this object str, int? defaultVal = null)
{
int reOut;
if (str.IsEmpty())
{
return defaultVal;
}
if (int.TryParse(str.ObjectToString(), out reOut))
return reOut;
var db = str.ToDouble();
if (db.HasValue)
return (int)db;
return defaultVal;
}
public static double? ToDouble(this object str, double? defaultVal = null)
{
double reOut;
if (str.IsEmpty())
{
return defaultVal;
}
if (double.TryParse(str.ObjectToString(), out reOut))
return reOut;
return defaultVal;
}
public static double ToDouble2(this object str, double defaultVal = 0)
{
double reOut;
if (str.IsEmpty())
{
return defaultVal;
}
if (double.TryParse(str.ObjectToString(), out reOut))
return reOut;
return defaultVal;
}
public static int? ToInt(this object obj)
{
return obj.ToInt(null);
}
public static int ToInt2(this object obj)
{
return obj.ToInt(0).Value;
}
public static decimal DoubleToDecimal(this object str, decimal defaultVal = 0)
{
decimal reOut;
if (str.IsEmpty())
{
return 0;
}
if (decimal.TryParse(str.ObjectToString(), out reOut))
return reOut;
return defaultVal;
}
public static short ToShort(this object obj)
{
return Convert.ToInt16(obj);
}
public static bool? ToBoolen(this object str, bool? defaultVal = null)
{
if (str.IsEmpty())
{
return defaultVal;
}
var re = false;
if (bool.TryParse(str.ObjectToString(), out re))
return re;
return defaultVal;
}
public static bool? ToBoolen(this object obj)
{
return obj.ToBoolen(null);
}
public static bool ToBoolen2(this object obj)
{
return obj.ToBoolen(false).Value;
}
public static decimal ToDecimal2(this object obj, decimal def = 0)
{
try
{
if (obj == null) return def;
return obj.ToString().ToDecimal(def);
}
catch
{
return def;
}
}
public static string ToBoolStrCn(this object obj)
{
if (obj != null)
{
return obj.ToBoolen(false).Value ? "是" : "否";
}
return "";
}
public static string ReplaceAll(this string obj, string source, string desc)
{
var arr = obj.Split(new string[] { source }, StringSplitOptions.RemoveEmptyEntries);
var result = obj;
for (var i = 0; i < arr.Length + 2; i++)
{
result = obj.ToString().Replace(source, desc);
}
return result;
}
public static string ToGBK(this string obj)
{
var data = Encoding.GetEncoding("GBK").GetBytes(obj);
//把 GBK 数据 转换为 URL 编码的字符串
var result = HttpUtility.UrlEncode(data);
return result;
}
///
/// 默认保留2位小数
///
/// 默认保留2位小数
///
///
public static decimal ToDecimalByDig(this object dig, int digtal = 2)
{
var dec = dig.ToDecimal2(0);
return Math.Round(dec, digtal, MidpointRounding.AwayFromZero);
}
///
/// 默认保留2位小数
///
/// 默认保留2位小数
///
///
public static float ToFloatByDig(this object dig, int digtal = 2)
{
var dec = dig.ToDecimal2(0);
return Math.Round(dec, digtal, MidpointRounding.AwayFromZero).ToString().ToFloat();
}
///
/// 默认保留2位小数 不四舍五入
///
/// 默认保留2位小数
///
///
public static decimal ToDecimalByDig2(this decimal dig, int digtal = 2)
{
string numToString = dig.ToString();
int index = numToString.IndexOf(".");
int length = numToString.Length;
if (index != -1)
{
return Convert.ToDecimal(string.Format("{0}.{1}",
numToString.Substring(0, index),
numToString.Substring(index + 1, Math.Min(length - index - 1, digtal))));
}
else
{
return dig;
}
}
///
/// 默认保留2位小数
///
/// 默认保留2位小数
///
///
public static float ToFloatCelling2(this object dig)
{
var dec = dig.ToDouble(0).Value;
return Math.Ceiling(dec).ToString().ToFloat();
}
///
/// float进位取整
///
/// 默认保留2位小数
///
///
public static float ToFloatCelling(this object dig)
{
var dec = dig.ToDouble(0).Value;
return Math.Ceiling(dec).ToString().ToFloat();
}
///
/// 返回DateTime类型,精确到秒
///
///
///
public static DateTime? ToDateTime(this object obj)
{
if (obj == null)
return null;
var str = obj.ToString();
DateTime reOut;
if (DateTime.TryParse(str, out reOut))
return reOut;
return null;
}
///
/// 将DateTime?转换成DateTime,如为空则返回1900-01-01 00:00:00
///
///
///
public static DateTime ToDateTime2(this DateTime? dt)
{
if (dt == null)
{
return DateTime.Parse("1900-01-01 00:00:00");
}
else
{
return (DateTime)dt;
}
}
///
/// 将DateTime?转换成DateTime
///
///
///
///
public static DateTime ToDateTime(this DateTime? SrcDateTime, DateTime DefDateTime)
{
if (SrcDateTime.HasValue)
{
return SrcDateTime.Value;
}
else
{
return DefDateTime;
}
}
///
/// 转换时间类型
///
///
///
public static string ToDateString(this object obj)
{
var date = obj.ToDateTime();
if (date == null)
return string.Empty;
return date.Value.ToString("yyyy年MM月dd日");
}
///
/// 短时间
///
///
///
public static string ToShortDateString(this object obj)
{
var date = obj.ToDateTime();
if (date == null)
return string.Empty;
return date.Value.ToString("yyyy-MM-dd");
}
///
/// 显示为分钟时间格式
///
///
///
public static string ToTimeMinuteString(this object obj)
{
var date = obj.ToDateTime();
if (date == null)
return string.Empty;
return date.Value.ToString("yyyy-MM-dd HH:mm");
}
///
/// 显示年份为短年份,只有分钟 如 18-05-30 16:29
///
///
///
public static string ToTimeShortYearString(this object obj)
{
var date = obj.ToDateTime();
if (date == null)
return string.Empty;
return date.Value.ToString("yy-MM-dd HH:mm");
}
///
/// 显示为分钟时间格式
///
///
///
public static string ToTimeSecondString(this object obj)
{
var date = obj.ToDateTime();
if (date == null)
return string.Empty;
return date.Value.ToString("yyyy-MM-dd HH:mm:ss");
}
///
/// 返回Date 类型,精确到天
///
///
///
public static DateTime? ToDate(this string str)
{
DateTime reOut;
if (DateTime.TryParse(str, out reOut))
return reOut.Date;
return null;
}
///
/// 返回Date 类型,精确到天,无法转换用当天值
///
///
///
public static DateTime ToDateWithDefault(this string str)
{
DateTime reOut;
if (DateTime.TryParse(str, out reOut))
return reOut.Date;
return DateTime.Now;
}
public static List ToListInt(this List strList)
{
var list = new List();
foreach (var str in strList)
{
if (str.ToInt().HasValue)
list.Add(str.ToInt().Value);
}
return list;
}
public static List ToListLong(this List strList)
{
var list = new List();
foreach (var str in strList)
{
if (str.ToLong().HasValue)
list.Add(str.ToLong().Value);
}
return list;
}
///
/// 返回 HTML 字符串的编码结果
///
/// 字符串
/// 解码结果
public static string HtmlEncode(this string str)
{
return HttpUtility.HtmlEncode(str);
}
///
/// 返回 HTML 字符串的解码结果
///
/// 字符串
/// 解码结果
public static string HtmlDecode(this string str)
{
return HttpUtility.HtmlDecode(str);
}
///
/// 返回 URL 字符串的编码结果
///
/// 字符串
/// 编码结果
public static string UrlEncode(this string str)
{
return HttpUtility.UrlEncode(str);
}
///
/// 返回 URL 字符串的编码结果
///
/// 字符串
/// 解码结果
public static string UrlDecode(this string str)
{
return HttpUtility.UrlDecode(str);
}
///
/// 转换为字符串,null时转换为string.Empty
///
///
///
public static string ToNullString(this string str)
{
return str == null ? string.Empty : str.Trim();
}
///
/// 转换为字符串,null或空时转换为默认字符串
///
///
///
public static string ToStringWithDefault(this string str, string defaultStr)
{
return string.IsNullOrEmpty(str) ? defaultStr : str;
}
///
/// 返回byte类型
///
///
///
public static byte? ToByte(this string str, byte? defaultVal = null)
{
byte reOut;
if (byte.TryParse(str, out reOut))
return reOut;
return defaultVal;
}
///
/// 全角数字转英文数字
///
///
///
public static string ToNumberString(this string str)
{
var re = string.Empty;
if (!string.IsNullOrEmpty(str))
{
str = str.Replace("0", "0").Replace("1", "1").Replace("2", "2").Replace("3", "3").Replace("4", "4");
str = str.Replace("5", "5").Replace("6", "6").Replace("7", "7").Replace("8", "8").Replace("9", "9");
str = str.Replace(",", ",").Replace("。", ".");
re = str;
}
return re;
}
///
/// 整型变时间
///
///
///
public static DateTime UnixTimeToTime(this string timeStamp)
{
var dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
var lTime = long.Parse(timeStamp + "0000000");
var toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
///
/// 转换为long时间,用于微信支付接口
///
///
///
public static long ToUniversalTimeLong(this DateTime now)
{
return Convert.ToInt64((now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
}
///
/// 取字典返回值
///
///
///
///
public static string GetDictValue(this Dictionary dict, string key)
{
if (dict.ContainsKey(key))
return dict[key];
return null;
}
///
/// 时间变整型
///
///
///
public static int DateTimeToInt(this DateTime time)
{
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
///
/// 转化为字符串,空时改化为string.Empty
///
///
///
public static string ObjectToString(this object obj)
{
if (obj == null)
return string.Empty;
return obj.ToString();
}
///
/// 转为为Decimal数据类型
///
///
///
public static decimal? ToDecimal(this string str, decimal? defaultVal = null)
{
if (str == null)
return defaultVal;
decimal re;
if (decimal.TryParse(str, out re))
{
return re;
}
return defaultVal;
}
///
/// 转为为Decimal数据类型(保留2位小数)
///
///
///
public static decimal? ToDecimalN2(this string str, decimal? defaultVal = null)
{
if (str == null)
return Math.Round(defaultVal.Value, 2); ;
decimal re;
if (decimal.TryParse(str, out re))
{
return Math.Round(re, 2);
}
return Math.Round(defaultVal.Value, 2);
}
public static string FormatDate(this DateTime date)
{
return FormatDate(date, "yyyy-MM-dd");
}
public static string FormatDate(this DateTime date, string formatString)
{
if (date != null)
{
var dNow = DateTime.Now;
var time = dNow - date;
if (time.Days > 28)
{
return date.ToString(formatString);
}
if (time.Days > 0)
{
return time.Days + "天前";
}
if (time.Hours > 0)
{
return time.Hours + "小时前";
}
if (time.Minutes > 0)
{
return time.Minutes + "分钟前";
}
if (time.Seconds > 0)
{
return time.Seconds + "秒前";
}
return "刚刚";
}
return "";
}
///
/// 转货为缩略图地址
///
///
///
public static string ToThumbImageUrl(this string url)
{
if (string.IsNullOrEmpty(url))
return url;
if (url.Length > 3 && url.ToLower().IndexOf("_thumb") == -1)
{
var index = url.LastIndexOf(".");
url = url.Substring(0, index) + "_Thumb" + url.Substring(index, url.Length - index);
return url;
}
return url;
}
///
/// 获取Session值
///
///
///
///
public static T GetSession(this string key)
{
if (!string.IsNullOrEmpty(key) && HttpContext.Current != null && HttpContext.Current.Session != null)
{
return HttpContext.Current.Session[key].ChangeValueDefault();
}
return default(T);
}
///
/// 获取Session值
///
///
///
///
public static void SetSession(this string key, object value)
{
if (!string.IsNullOrEmpty(key) && HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session[key] = value;
}
}
///
/// 转换为绝对地址
///
///
///
public static string ToAbsoluteUrl(this string url)
{
var baseUrl = ConfigurationManager.AppSettings["IhoomeWeiSite.Url"];
if (string.IsNullOrEmpty(url))
baseUrl = "http://wx.ihoome.com";
var re = string.Empty;
if (!string.IsNullOrEmpty(url))
{
if (url.Length > 5)
{
if (url.Substring(0, 5).ToLower().Trim() == "http:")
re = url;
else
re = baseUrl + url;
}
}
return re.ToLower();
}
public static string CodeToName(this object obj, string fm)
{
if (string.IsNullOrEmpty(fm))
throw new Exception("CodeToName(this object obj, string fm) fm参数格式不对!");
var arr = fm.Split(';');
var defaultVal = arr[0].Split(',')[1];
if (obj == null || obj == DBNull.Value)
{
return string.Empty;
}
var str = obj.ToString();
if (string.IsNullOrEmpty(str))
return defaultVal;
try
{
var hash = new Hashtable();
for (var i = 0; i < arr.Length; i++)
{
var key = arr[i].Split(',')[0].ToUpper().Trim();
var val = arr[i].Split(',')[1];
if (!hash.ContainsKey(key))
hash.Add(key, val);
}
return hash[obj.ToString().ToUpper().Trim()].ToString();
}
catch
{
return defaultVal;
}
}
///
/// 取URL后面的参数的键值
///
///
///
///
public static string GetUrlParamByKey(this string url, string key)
{
var dict = new Dictionary();
if (url.Split('?').Length >= 2)
{
var paramsStr = url.Split('?')[1];
var arrayOneParm = paramsStr.Split('&');
foreach (var oneParm in arrayOneParm)
{
var array = oneParm.Split('=');
if (array.Length >= 1)
{
var dictKey = array[0];
var val = array.Length >= 2 ? array[1] : string.Empty;
if (!dict.ContainsKey(dictKey))
dict.Add(dictKey, val);
}
}
}
return dict.ContainsKey(key) ? dict[key] : null;
}
public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)
{
var seenKeys = new HashSet();
foreach (var element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
///
/// 取前一个工作日,例:即周四取周三,周一取前一周周五
///
///
///
public static DateTime GetPreWorkDate(this DateTime date)
{
var dt = date.Date.AddDays(-1);
stardo:
if (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
{
dt = dt.AddDays(-1);
goto stardo;
}
return dt;
}
///
/// 日期转字符串
///
/// 日期对象
/// 字符串格式
/// 字符串
public static string DataTimeToString(this object source, string format = "yyyy-MM-dd HH:mm")
{
return source == null ? string.Empty : Convert.ToDateTime(source).ToString(format);
}
public static string RemoveHtmlEmpty(this string str)
{
return str.ObjectToString().Replace(" ", "").Replace("/r", "").Replace("/n", "").Trim();
}
///
/// 移除最后的字符
///
///
///
///
public static string RemoveEndChar(this string str, string endStr)
{
if (str.Length > endStr.Length)
{
var len = endStr.Length;
var lastStr = str.Substring(str.Length - len, len);
if (lastStr == endStr)
{
return str.Substring(0, str.Length - len);
}
return str;
}
if (str.Length == endStr.Length)
{
return str.Replace(endStr, "");
}
return str;
}
///
/// SQL拼串安全字符检查
///
///
///
public static string SqlSensitivityCheck(this string contents)
{
if (contents.Length > 0)
{
contents = contents.ObjectToString().Replace("'", "");
//convert to lower
var sLowerStr = contents.ToLower();
//RegularExpressions
var sRxStr = @"(\sand\s)|(\sand\s)|(\slike\s)|(select\s)|(insert\s)|
(delete\s)|(update\s[\s\S].*\sset)|(create\s)|(\stable)|(<[iframe|/iframe|script|/script])|
(')|(\sexec)|(\sdeclare)|(\struncate)|(\smaster)|(\sbackup)|(\smid)|(\scount)";
//Match
var bIsMatch = false;
var sRx = new
Regex(sRxStr);
bIsMatch = sRx.IsMatch(sLowerStr, 0);
if (bIsMatch)
return string.Empty;
return contents;
}
return contents;
}
public static void UpdateDictionary(this Dictionary source, string key, string newVal)
{
if (source.ContainsKey(key))
{
source.Remove(key);
source.Add(key, newVal);
}
}
///
/// 时间转时间戳
///
public static long ToTimestamp(this DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return Convert.ToInt64((time - startTime).TotalMilliseconds);
}
///
/// 时间戳转时间 (适合时间戳是毫秒数的情况)
///
///
///
public static DateTime ToDateTime(this long timestamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan toNow = new TimeSpan(timestamp * 10000);
return dtStart.Add(toNow);
}
///
/// HttpUtility Url加密 并转大写
///
public static string ToUrlEncodeUpper(this string str)
{
StringBuilder builder = new StringBuilder();
foreach (char c in str)
{
if (HttpUtility.UrlEncode(c.ToString()).Length > 1)
{
builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
public static string ToUtf8(this string str)
{
UTF8Encoding utf8 = new UTF8Encoding();
Byte[] encodedBytes = utf8.GetBytes(str);
String decodedString = utf8.GetString(encodedBytes);
return decodedString;
}
///
/// 验证数是否在一个范围
///
///
///
///
///
public static bool ToValidRange(this double str, double start, double end)
{
if (str >= start && str <= end)
return true;
return false;
}
///
/// 客编
///
///
///
///
public static string ToMemberNo(this int id, string datafrom = "")
{
return string.Format("J{0}A", id.ToString().PadLeft(5, '0'));
}
///
/// 将数字转化为某数字的倍数 如11整成5的倍数 即15
///
///
///
///
public static int NumToBs(this int num, int bs)
{
return ((num % bs > 0 ? 1 : 0) + num / bs) * bs;
}
///
/// 根据来源获取前缀
///
///
///
public static string ToPreByDataSource(this int source)
{
var preNo = "JP-";
if (EnumDataSource.WebAllPcb.GetHashCode() == source)
{ preNo = "ALL-"; }
else if (EnumDataSource.OutCustomerOrder.GetHashCode() == source)
{ preNo = "OC-"; }
return preNo;
}
///
/// 参数不在指定值时返回错误信息
///
///
///
///
public static string ToParmErrorMsg(this int count, string defmsg)
{
if (count == 0)
{
return defmsg;
}
return "";
}
///
/// 过滤掉特殊字符串
///
///
///
public static string FilterSpecialChar(this string str)
{
if (str == null) return "";
string[] aryReg = { "'", "<", ">", "%", "\"\"", ",", ">=", "=<", "-", "_", ";", "||", "[", "]", "&", "/", "-", "|", " ", };
for (int i = 0; i < aryReg.Length; i++)
{
str = str.ReplaceAll(aryReg[i], "");
}
return str;
}
///
/// 设置为*
///
///
///
///
public static string SetXin(this string str, int cnt, int startcount = 2)
{
var len = str.Length;
var resut = str;
resut = str.Substring(0, len > startcount ? startcount : len);
for (var i = 0; i < cnt; i++)
{
resut += "*";
}
if (len > 3)
resut += str.Substring(len - 2, 1);
return resut;
}
///
/// 设置为*
///
///
///
///
public static string SetXin2(this string str, int cnt, int startcount = 2)
{
var len = str.Length;
var resut = str;
resut = str.Substring(0, len > startcount ? startcount : len);
for (var i = 0; i < cnt; i++)
{
resut += "*";
}
var startLen = startcount + cnt;
if (len > startLen)
{
resut += str.Substring(startLen, len - startLen);
}
return resut;
}
///
/// 保留前面的字符后面跟上cnt个*
///
///
///
///
public static string SetXin3(this string str, int cnt, int startcount = 2)
{
var len = str.Length;
var resut = str;
resut = str.Substring(0, len > startcount ? startcount : len);
for (var i = 0; i < cnt; i++)
{
resut += "*";
}
if (len > 2)
{
resut += str.Substring(len - 1, 1);//取最后一个字
}
return resut;
}
///
/// 保留前面的字符后面跟上cnt个*
///
/// 截取字符串
/// **数
/// 开头的个数
/// 结尾的个数
///
public static string SetXin4(this string str, int cnt, int startcount = 1, int endcount = 1)
{
var len = str.Length;
var resut = str;
resut = str.Substring(0, len > startcount ? startcount : len);
for (var i = 0; i < cnt; i++)
{
resut += "*";
}
if (len >= endcount)
{
resut += str.Substring(len - endcount, endcount);
}
return resut;
}
///
/// 根据状态获取进度百分比
///
///
///
public static string HandleOrderProgress(this object status)
{
var status2 = int.Parse(status.ToString()) / 10 + "";
var result = " '";
switch (status2)
{
case "1":
result = "10%"; break;
case "2":
result = "20%"; break;
case "3":
result = "30%"; break;
case "4":
result = "40%"; break;
case "5":
result = "50%"; break;
case "6":
result = "60%"; break;
case "7":
result = "70%"; break;
case "8":
result = "80%"; break;
case "9":
result = "90%"; break;
default:
result = "100%"; break;
}
return result;
}
/**
* 连接参数
*
*/
public static string Paramjoin(Dictionary urlparams = null)
{
string urlparam = "";
if (urlparams != null && urlparams.Count > 0)
{
List ulist = new List();
foreach (KeyValuePair entry in urlparams)
{
ulist.Add(String.Format("{0}={1}", HttpUtility.UrlEncode(entry.Key), HttpUtility.UrlEncode(entry.Value)));
}
urlparam = String.Join("&", ulist.ToArray());
}
return urlparam;
}
/**
* 生成签名
*/
public static string GenSign(Dictionary param, string apisec)
{
Dictionary dictSort = param.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
string str = apisec;
string separator = "";
foreach (KeyValuePair kv in dictSort)
{
if (kv.Key == "signature")
{
continue;
}
str += separator + kv.Key + "=" + kv.Value;
separator = "&";
}
str += apisec;
byte[] result = Encoding.UTF8.GetBytes(str);
MD5 md5 = new MD5CryptoServiceProvider();
return BitConverter.ToString(md5.ComputeHash(result)).Replace("-", "");
}
///
/// 安全Sql字符串
///
///
///
public static string _ToSqlStr(this string Text)
{
return Text.Trim().Replace("'", "''");
}
///
/// 安全Sql字段名
///
///
///
public static string _ToSqlField(this string Text)
{
return Regex.Replace(Text, @"[^\w_\.]", "");
}
///
/// 金额转换成中文大写金额
///
/// eg:10.74
///
public static string ToMoneyUpper(this string LowerMoney)
{
string functionReturnValue = null;
bool IsNegative = false; // 是否是负数
if (LowerMoney.Trim().Substring(0, 1) == "-")
{
// 是负数则先转为正数
LowerMoney = LowerMoney.Trim().Remove(0, 1);
IsNegative = true;
}
string strLower = null;
string strUpart = null;
string strUpper = null;
int iTemp = 0;
// 保留两位小数 123.489→123.49 123.4→123.4
LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
if (LowerMoney.IndexOf(".") > 0)
{
if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
{
LowerMoney = LowerMoney + "0";
}
}
else
{
LowerMoney = LowerMoney + ".00";
}
strLower = LowerMoney;
iTemp = 1;
strUpper = "";
while (iTemp <= strLower.Length)
{
switch (strLower.Substring(strLower.Length - iTemp, 1))
{
case ".":
strUpart = "圆";
break;
case "0":
strUpart = "零";
break;
case "1":
strUpart = "壹";
break;
case "2":
strUpart = "贰";
break;
case "3":
strUpart = "叁";
break;
case "4":
strUpart = "肆";
break;
case "5":
strUpart = "伍";
break;
case "6":
strUpart = "陆";
break;
case "7":
strUpart = "柒";
break;
case "8":
strUpart = "捌";
break;
case "9":
strUpart = "玖";
break;
}
switch (iTemp)
{
case 1:
strUpart = strUpart + "分";
break;
case 2:
strUpart = strUpart + "角";
break;
case 3:
strUpart = strUpart + "";
break;
case 4:
strUpart = strUpart + "";
break;
case 5:
strUpart = strUpart + "拾";
break;
case 6:
strUpart = strUpart + "佰";
break;
case 7:
strUpart = strUpart + "仟";
break;
case 8:
strUpart = strUpart + "万";
break;
case 9:
strUpart = strUpart + "拾";
break;
case 10:
strUpart = strUpart + "佰";
break;
case 11:
strUpart = strUpart + "仟";
break;
case 12:
strUpart = strUpart + "亿";
break;
case 13:
strUpart = strUpart + "拾";
break;
case 14:
strUpart = strUpart + "佰";
break;
case 15:
strUpart = strUpart + "仟";
break;
case 16:
strUpart = strUpart + "万";
break;
default:
strUpart = strUpart + "";
break;
}
strUpper = strUpart + strUpper;
iTemp = iTemp + 1;
}
strUpper = strUpper.Replace("零拾", "零");
strUpper = strUpper.Replace("零佰", "零");
strUpper = strUpper.Replace("零仟", "零");
strUpper = strUpper.Replace("零零零", "零");
strUpper = strUpper.Replace("零零", "零");
strUpper = strUpper.Replace("零角零分", "整");
strUpper = strUpper.Replace("零分", "整");
strUpper = strUpper.Replace("零角", "零");
strUpper = strUpper.Replace("零亿零万零圆", "亿圆");
strUpper = strUpper.Replace("亿零万零圆", "亿圆");
strUpper = strUpper.Replace("零亿零万", "亿");
strUpper = strUpper.Replace("零万零圆", "万圆");
strUpper = strUpper.Replace("零亿", "亿");
strUpper = strUpper.Replace("零万", "万");
strUpper = strUpper.Replace("零圆", "圆");
strUpper = strUpper.Replace("零零", "零");
// 对壹圆以下的金额的处理
if (strUpper.Substring(0, 1) == "圆")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
}
if (strUpper.Substring(0, 1) == "零")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
}
if (strUpper.Substring(0, 1) == "角")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
}
if (strUpper.Substring(0, 1) == "分")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
}
if (strUpper.Substring(0, 1) == "整")
{
strUpper = "零圆整";
}
functionReturnValue = strUpper;
if (IsNegative == true)
{
return "负" + functionReturnValue;
}
else
{
return functionReturnValue;
}
}
///
/// 是否可发短信
///
///
///
public static bool IsCanSendMobile(this string checkStr)
{
if (string.IsNullOrEmpty(checkStr)) { return false; }
return Regex.IsMatch(checkStr, @"^1\d{10}(\/1\d{10}){0,2}$");
}
/// 判断俩个字符串是否存在交集
///
///
/// 原字符串
/// 对比的字符串
/// 分割符
///
public static bool IsIntersection(this string str, string compareStr, char split2)
{
if (IsNull(str)) return false;
var arr = compareStr.Split(split2).ToList();
var i = 0;
arr.ForEach(x =>
{
if (str.Contains(x))
{
i++;
}
});
return i > 0;
}
///
/// 获取字典值(防止字典为空或键不存在时报错问题,区分大小写)
///
/// 键类型
/// 值类型
/// 字典
/// 键
/// 值
public static TV _GetValue(this Dictionary Dic, TK Key)
{
if (Dic == null) { return default(TV); }
TV val;
if (Dic.TryGetValue(Key, out val))
{
return val;
}
else
{
return default(TV);
}
}
///
/// 获取字典值(防止字典为空或键不存在时报错问题,区分大小写)
///
/// 键类型
/// 值类型
/// 字典
/// 名称
/// 默认值
/// 值
public static TV _GetValue(this Dictionary Dic, TK Key, TV Default)
{
TV txt;
return Dic.TryGetValue(Key, out txt) ? txt : Default;
}
#region 秒转换小时 SecondToHour
///
/// 秒转换小时
///
///
///
public static string SecondToHour(this object time)
{
string str = "";
int hour = 0;
int minute = 0;
int second = 0;
second = Convert.ToInt32(time);
if (second > 60)
{
minute = second / 60;
second = second % 60;
}
if (minute > 60)
{
hour = minute / 60;
minute = minute % 60;
}
return (hour + "小时" + minute + "分钟"
+ second + "秒");
}
#endregion
///
/// 设置Url参数并返回网址
///
/// Http请求类
/// 设置列表
/// 网址字符串
public static string _GetUrlSetValue(this HttpRequestBase Request, params KeyValuePair[] SetList)
{
var query = Request.QueryString._ToUrlQuery(SetList);
return Request.Path + (query.Length == 0 ? string.Empty : "?" + query);
}
///
/// 设置Url参数并返回网址
///
/// Http请求类
/// 设置列表
/// 网址字符串
public static string _GetUrlSetValue(this HttpRequest Request, params KeyValuePair[] SetList)
{
var query = Request.QueryString._ToUrlQuery(SetList);
return Request.Path + (query.Length == 0 ? string.Empty : "?" + query);
}
///
/// 转换名称值列表为Url参数
///
/// 键值列表
/// 设置列表
/// 参数字符串
public static string _ToUrlQuery(this NameValueCollection Lst, params KeyValuePair[] SetList)
{
var dic = new Dictionary();
foreach (var i in Lst)
{
var name = i._ToStr().ToLower();
dic[name] = Lst[name];
}
foreach (var i in SetList)
{
dic[i.Key.ToLower()] = i.Value;
}
return string.Join("&", dic.Select(t => t.Key + "=" + t.Value).ToArray());
}
}
}