using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Data;
using System.Web;
namespace JiepeiWMS.Extends
{
public static class Extension
{
///
/// 安全输出字符串(页面内容)
///
///
///
public static string _ToSafe(this string s)
{
return System.Web.HttpUtility.HtmlEncode(s);
}
///
/// 返回字符并编码
///
///
///
public static string _ToStringSafe(this string s)
{
if (string.IsNullOrEmpty(s))
{
return "";
}
return _ToSafe(s);
}
///
/// 去除空格并编码
///
///
///
public static string _TrimSafe(this string s)
{
if (string.IsNullOrEmpty(s))
{
return "";
}
return _ToSafe(s.Trim());
}
///
/// 转换INT类型
///
///
///
///
public static int _ToInt32(this string s, int defautValue)
{
int result = defautValue;
if (string.IsNullOrWhiteSpace(s))
{
return result;
}
if (int.TryParse(s, out result))
{
return result;
}
return defautValue;
}
///
/// 转换INT类型
///
///
///
public static int _ToInt32(this string s)
{
return _ToInt32(s, 0);
}
///
/// 转换INT类型
///
///
///
///
public static long _ToInt64(this string s, long defautValue)
{
long result = defautValue;
if (string.IsNullOrWhiteSpace(s))
{
return result;
}
if (long.TryParse(s, out result))
{
return result;
}
return defautValue;
}
///
/// 转换INT类型
///
///
///
public static long _ToInt64(this string s)
{
return _ToInt64(s, 0);
}
///
/// 转换成FLOAT类型
///
///
///
///
public static float _ToFloat(this string s, float defautValue)
{
float result = defautValue;
float.TryParse(s, out result);
return result;
}
///
/// 转换成FLOAT类型
///
///
///
public static float _ToFloat(this string s)
{
return _ToFloat(s, 0);
}
///
/// 转换成Double类型
///
///
///
///
public static double _ToDouble(this string s, double defaultValue)
{
double result = 0;
if (double.TryParse(s, out result))
{
return result;
}
return defaultValue;
}
///
/// 转换成Double类型
///
///
///
///
public static double? _ToDouble(this object s, double defaultValue)
{
double result = 0;
if (double.TryParse(s.ToString(), out result))
{
return result;
}
return defaultValue;
}
///
/// 转换成Double类型
///
///
///
public static double _ToDouble(this string s)
{
return _ToDouble(s, 0);
}
public static decimal _ToDecimal(this string Txt, decimal defaultValue)
{
decimal result = 0;
if (decimal.TryParse(Txt, out result))
{
return result;
}
return defaultValue;
}
public static decimal _ToDecimal(this string s)
{
return _ToDecimal(s, 0);
}
public static byte _ToByte(this string s)
{
byte b = 0;
byte.TryParse(s, out b);
return b;
}
///
/// 转换日期格式
///
///
/// ,
public static DateTime _ToDateTime(this string s)
{
DateTime time;
if (DateTime.TryParse(s, out time))
{
return time;
}
else
{
return _InitDateTime();
}
}
public static DateTime _InitDateTime()
{
return DateTime.Parse("1900-01-01");
}
///
/// 过滤字符串s中左尖括号和右尖括号之间的内容
/// add by sunyichao 2015-09-14
///
/// 待处理字符串
/// 过滤字符串,为HTML标签的元素名,eg:过滤div,则传值div
///
public static string _ToFilterHTMLElement(this string s, string filerExtension)
{
if (string.IsNullOrEmpty(s))
{
return "";
}
else
{
if (s.Contains("<"))
{
s = new Regex(@"<" + filerExtension + "[^>]*>(.+?)" + filerExtension + ">").Replace(s, "");
}
return s;
}
}
public static string _ReplaceHtmlTag(this string html, int length = 0)
{
string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
if (length > 0 && strText.Length > length)
return strText.Substring(0, length);
return strText;
}
public static string _ToUrlDecode(this string s)
{
if (string.IsNullOrEmpty(s))
{
return "";
}
return System.Web.HttpUtility.UrlDecode(s.Trim());
}
///
/// 例 : "3,2,3,1"字符串 返回 整数型List
///
///
///
///
public static List _ToIntList(this string str, char split)
{
string[] arr = str.Split(split);
List list = new List();
foreach (string item in arr)
{
if (_ToInt32(item) > 0 && list.IndexOf(_ToInt32(item)) == -1)
{
list.Add(_ToInt32(item));
}
}
return list;
}
public static bool _ToBool(this string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
s = s.ToLower();
if (s == "true" || s == "1")
{
return true;
}
return false;
}
public static bool _IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}
public static string _FormatWith(this string s, params object[] args)
{
return string.Format(s, args);
}
///
/// 数字转中文
///
/// eg: 22
///
public static string _NumberToChinese(this int number)
{
string res = string.Empty;
string str = number.ToString();
string schar = str.Substring(0, 1);
switch (schar)
{
case "1":
res = "一";
break;
case "2":
res = "二";
break;
case "3":
res = "三";
break;
case "4":
res = "四";
break;
case "5":
res = "五";
break;
case "6":
res = "六";
break;
case "7":
res = "七";
break;
case "8":
res = "八";
break;
case "9":
res = "九";
break;
default:
res = "零";
break;
}
if (str.Length > 1)
{
switch (str.Length)
{
case 2:
case 6:
res += "十";
break;
case 3:
case 7:
res += "百";
break;
case 4:
res += "千";
break;
case 5:
res += "万";
break;
default:
res += "";
break;
}
res += _NumberToChinese(int.Parse(str.Substring(1, str.Length - 1)));
}
return res;
}
///
/// 随机打乱列表
///
///
///
public static List _ToListRandom(this List myList)
{
Random ran = new Random();
List newList = new List();
int index = 0;
string temp = "";
for (int i = 0; i < myList.Count; i++)
{
index = ran.Next(0, myList.Count);
if (index != i)
{
temp = myList[i];
myList[i] = myList[index];
myList[index] = temp;
}
}
return myList;
}
#region 戴雁冰扩展
///
/// 提取文件目录(\结尾)
///
/// 包含绝对路径完整文件名
/// 文件目录
public static string _FthPath(this string AbsFullFileName)
{
string filename;
return _FthPath(AbsFullFileName, out filename);
}
///
/// 提取文件目录(\结尾)
///
/// 包含绝对路径完整文件名
/// 文件名(无路径无扩展名)
/// 文件目录
public static string _FthPath(this string AbsFullFileName, out string FileName)
{
string extname;
return _FthPath(AbsFullFileName, out FileName, out extname);
}
///
/// 提取文件目录(\结尾)
///
/// 包含绝对路径完整文件名
/// 文件名(无路径无扩展名)
/// 扩展名
/// 文件目录
public static string _FthPath(this string AbsFullFileName, out string FileName, out string ExtName)
{
//输出空
if (string.IsNullOrEmpty(AbsFullFileName))
{
FileName = ExtName = ""; return "";
}
//找最后一级名称
int nidx = AbsFullFileName.LastIndexOf("\\");
if (nidx < 0) { nidx = AbsFullFileName.LastIndexOf("/"); }
if (nidx < 0) { FileName = AbsFullFileName; }
else { FileName = AbsFullFileName.Substring(nidx + 1); }
//是否为路径
int at = FileName.LastIndexOf(".");
if (at < 0)
{
FileName = ExtName = ""; return AbsFullFileName.Substring(0, nidx + 1);
}
ExtName = FileName.Substring(at + 1);
FileName = FileName.Substring(0, at);
//输出文件名及路径
return AbsFullFileName.Substring(0, nidx + 1);
}
///
/// 清除Html标签
///
/// Html代码
///
public static string _ClrHtmlTags(this string Html)
{
return Regex.Replace(Html, @"\<[\/]?([^\s]+?)(?:[^""'>]*?([""'])[^""']+\2)*[^\>]*?>", string.Empty);
}
///
/// 复制当前字符串Num次并连接在一起
///
/// 文本
/// 复制次数
/// 文本
public static string _CopyAndJoin(this string Text, int Num)
{
StringBuilder sb = new StringBuilder();
for (var i = 0; i < Num; i++)
{
sb.Append(Text);
}
return sb.ToString();
}
///
/// 转换成整型数组
///
/// 整型列表字符串
/// 分隔符
/// 是否移除转换错误的值
/// 错误时的默认值(只有IsClearError=false时有效)
/// 整型列表
public static List _ToIntList(this string Src, char SeparatorChar = ',', bool IsClearError = true, int ErrorDefValue = 0)
{
List l = new List();
Action fn;
if (IsClearError) { fn = t => { }; }
else { fn = t => l.Add(t); }
foreach (string i in Src.Split(SeparatorChar))
{
int t = 0;
if (int.TryParse(i, out t)) { l.Add(t); }
else { fn(ErrorDefValue); }
}
return l;
}
///
/// 设置网址参数
///
/// 网址字符串
///
///
/// 网址字符串
public static string _SetUrlParam(this string UrlStr, string Name, string Value)
{
var sp = UrlStr.Split('?');
if (sp.Length > 1)
{
var query = Regex.Replace("&" + sp[1], "[?&]" + Name + "=[^&]*", "", RegexOptions.IgnoreCase);
query = (query + "&" + Name + "=" + Value).TrimStart('&');
return sp[0] + "?" + query;
}
else
{
return UrlStr + "?" + Name + "=" + Value;
}
}
///
/// 转换成参数字典
///
/// 完整或相对网址
/// 返回字典
public static Dictionary _ToUrlParams(this string Url)
{
var dic = new Dictionary();
Regex.Replace(Url, @"[&?]([^?&=]*)(?:=([^]*)|$)", m =>
{
dic[m.Groups[1].Value.ToLower()] = m.Groups[2].Value;
return string.Empty;
}, RegexOptions.Multiline);
return dic;
}
///
/// 过滤字符串中的数字并转换成数值
///
/// 文本
/// 默认值
///
public static decimal _ToDecimalByFltNum(this string Txt, decimal DefaultNum = 0)
{
var str = Regex.Replace(Txt, @"[^\d]+", "");
decimal val;
if (decimal.TryParse(str, out val))
{
return val;
}
return DefaultNum;
}
///
/// 转换成数字(含小数点)列表(单个或多个非数字会转成一个",")
///
/// 带数字的字符串
///
public static string _ToNumListStr(this string NumStr)
{
return Regex.Replace(NumStr, @"[^\d\.\-\+]+", ",").Trim(',');
}
///
/// 转换成数值列表
///
/// 数字列表,如:13,23.3,23,45
///
public static List _ToDecimalList(this string NumListStr)
{
return NumListStr.Split(',').Select(t => _ToDecimal(t)).ToList();
}
///
/// 时间转时间戳
///
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);
}
///
/// MD5加密
///
///
///
public static string _EcdMD5(this string Value, bool IsLower = true)
{
var str = string.Empty;
using (var md5 = MD5.Create())
{
var result = md5.ComputeHash(Encoding.UTF8.GetBytes(Value));
str = BitConverter.ToString(result);
str = str.Replace("-", "");
}
return IsLower ? str.ToLower() : str;
}
///
/// MD5加密
///
///
///
public static List _Select(this DataRowCollection Rows, Func FnSelect)
{
var lst = new List();
foreach (DataRow row in Rows)
{
lst.Add(FnSelect(row));
}
return lst;
}
/**
* 生成签名
*/
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("-", "");
}
/**
* 连接参数
*
*/
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 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 string ToUtf8(this string str)
{
UTF8Encoding utf8 = new UTF8Encoding();
Byte[] encodedBytes = utf8.GetBytes(str);
String decodedString = utf8.GetString(encodedBytes);
return decodedString;
}
#endregion
}
}