亮亮大家常用的公共类吧!
刚到一新衙门,发现老的项目中居然啊公共类都没有的。
什么,替换文本中HTML标签内容,和截取字符串长度(按照字节截取),这些都没的。
大家亮亮自己的吧!
[解决办法]
http://topic.csdn.net/u/20090815/08/1AA82791-A7A2-4640-80B4-907F5771D676.html
[解决办法]
http://blog.csdn.net/anchenyanyue
[解决办法]
贴几个我项目中用到的。
- C# code
/// <summary> /// 截取指定长度中英文字符串(宽度一样) /// </summary> /// <param name="str">要截取的字符串</param> /// <param name="length">截取长度,中文字符长度</param> /// <returns>截取后的字符串</returns> public static string CutStr(object str, int length) { if (str == null) return string.Empty; Encoding encoding = Encoding.GetEncoding("gb2312"); int len = length * 2; int j = 0, k = 0; string cutStr = str.ToString(); for (int i = 0; i < cutStr.Length; i++) { byte[] bytes = encoding.GetBytes(cutStr.Substring(i, 1)); if (bytes.Length == 2)//不是英文 j += 2; else j++; if (j <= len) k += 1; if (j >= len) return cutStr.Substring(0, k) + "..."; } return cutStr; } /// <summary> /// 下载指定路径文件 /// </summary> /// <param name="path">文件绝对路径</param> public static void DownLoadFile(string path) { System.IO.FileInfo fi = new System.IO.FileInfo(path); if (fi.Exists) { //判断文件是否正在使用 try { using (System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None)) { } } catch (Exception ex) { throw; } System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(path.Substring(path.LastIndexOf("\\") + 1), System.Text.Encoding.UTF8)); System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString()); System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gb2321"; System.Web.HttpContext.Current.Response.WriteFile(fi.FullName); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.Close(); } else { System.Web.HttpContext.Current.Response.Write("<script>alert('源文件不存在!');</script>"); } } /// <summary> /// 获取枚举的描述信息 /// </summary> /// <param name="en">枚举</param> /// <returns></returns> public static string GetEnumDescription(this Enum en) { Type type = en.GetType(); System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) return ((System.ComponentModel.DescriptionAttribute)attrs[0]).Description; } return en.ToString(); }/// <summary>/// 通用应用程序缓存辅助类/// </summary>public static class CacheHelper{ public delegate T GetDataMethod<T>();//获取数据的方法 /// <summary> /// 通用应用程序缓存方法,缓存数据10分钟 /// </summary> /// <typeparam name="T">缓存数据的类型,一般是集合,如IList<UsersData></typeparam> /// <param name="key">键</param> /// <param name="getDataMethod">获取数据的方法</param> /// <returns>数据列表</returns> public static T GetCache<T>(string key, GetDataMethod<T> getDataMethod) { //T dataList = getDataMethod(); //return dataList; if (HttpRuntime.Cache[key] == null) { T dataList = getDataMethod(); HttpRuntime.Cache.Add(key, dataList, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null); return dataList; } return (T)HttpRuntime.Cache[key]; } /// <summary> /// 移除应用程序缓存 /// </summary> /// <param name="key">键</param> public static void RemoveCacheByKey(string key) { HttpRuntime.Cache.Remove(key); }} /// <summary> /// 获取用户IP地址 /// </summary> public static string IPAddress { get { //string ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; //HTTP_X_FORWARDED_FOR获取的用户真实ip可能存在欺骗,所以忽略通过代理的访问的用户真实ip地址,记录代理ip string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (string.IsNullOrEmpty(ipAddress)) ipAddress = HttpContext.Current.Request.UserHostAddress; if (ipAddress.Length > 15) //是ipv6格式ip,转换为ipv4 { //取得客户端主机 IPv4 位址(通过DNS反查) string ipv4 = string.Empty; foreach (System.Net.IPAddress ip in System.Net.Dns.GetHostAddresses(ipAddress)) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ipv4 = ip.ToString(); break; } } if (ipv4.Length == 0) { foreach (System.Net.IPAddress ip2 in System.Net.Dns.GetHostEntry(ipAddress).AddressList) { if (ip2.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ipv4 = ip2.ToString(); break; } } } return ipv4.Length > 0 ? ipv4 : string.Empty; } return ipAddress; } } #region Cookie操作 /// <summary> /// 设置指定Cookie名称的值 /// </summary> /// <param name="cookieName">cookie名称</param> /// <param name="cookieValue">值</param> /// <param name="expires">过期时间,DateTime.MinValue表示默认过期时间</param> public static void AddCookie(string cookieName, string cookieValue, DateTime expires) { HttpContext.Current.Response.Cookies[cookieName].Value = string.Empty; HttpContext.Current.Response.Cookies[cookieName].Value = cookieValue; if (expires != DateTime.MinValue) HttpContext.Current.Response.Cookies[cookieName].Expires = expires; } /// <summary> /// 读取指定cookie名称的值 /// </summary> /// <param name="cookieName">cookie名称</param> /// <returns>值</returns> public static string GetCookie(string cookieName) { string cookieValue = string.Empty; try { cookieValue = HttpContext.Current.Request.Cookies[cookieName].Value; } catch { } return cookieValue; } /// <summary> /// 删除指定名称cookie /// </summary> /// <param name="cookieName">cookie名称</param> public static void RemoveCookie(string cookieName) { HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.MinValue; } #endregion
[解决办法]
/// <summary>
/// 过滤xss攻击脚本
/// </summary>
public static class XSSFilter
{
/// <summary>
/// 过滤xss攻击脚本
/// </summary>
/// <param name="html">传入字符串</param>
/// <returns>过滤后的字符串</returns>
public static string Filter(string html)
{
if (string.IsNullOrEmpty(html)) return string.Empty;
// CR(0a) ,LF(0b) ,TAB(9) 除外,过滤掉所有的不打印出来字符.
// 目的防止这样形式的入侵 <java\0script>
// 注意:\n, \r, \t 可能需要单独处理,因为可能会要用到
string ret = System.Text.RegularExpressions.Regex.Replace(html, "([\x00-\x08][\x0b-\x0c][\x0e-\x20])", string.Empty);
//替换所有可能的16进制构建的恶意代码
//<IMG SRC=@avascript:a&_#X6Cert('XSS')>
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()~`;:?+/={}[]-_|'\"\\";
for (int i = 0; i < chars.Length; i++)
{
ret = System.Text.RegularExpressions.Regex.Replace(ret, string.Concat("(&#[x|X]0{0,}", Convert.ToString((int)chars[i], 16).ToLower(), ";?)"),
chars[i].ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
}
//过滤\t, \n, \r构建的恶意代码
string[] keywords = {"javascript", "vbscript", "expression", "applet", "meta", "xml", "blink",
"link", "style", "script","object", "iframe", "frame", // "embed",
"frameset", "ilayer", "layer", "bgsound", "title", "base" ,"onabort",
"onactivate", "onafterprint", "onafterupdate", "onbeforeactivate",
"onbeforecopy", "onbeforecut", "onbeforedeactivate",
"onbeforeeditfocus", "onbeforepaste", "onbeforeprint", "onbeforeunload",
"onbeforeupdate", "onblur", "onbounce", "oncellchange", "onchange",
"onclick", "oncontextmenu", "oncontrolselect", "oncopy", "oncut",
"ondataavailable", "ondatasetchanged", "ondatasetcomplete", "ondblclick",
"ondeactivate", "ondrag", "ondragend", "ondragenter", "ondragleave",
"ondragover", "ondragstart", "ondrop", "onerror", "onerrorupdate",
"onfilterchange", "onfinish", "onfocus", "onfocusin", "onfocusout",
"onhelp", "onkeydown", "onkeypress", "onkeyup", "onlayoutcomplete",
"onload", "onlosecapture", "onmousedown", "onmouseenter", "onmouseleave",
"onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel",
"onmove", "onmoveend", "onmovestart", "onpaste", "onpropertychange",
"onreadystatechange", "onreset", "onresize", "onresizeend", "onresizestart",
"onrowenter", "onrowexit", "onrowsdelete", "onrowsinserted", "onscroll",
"onselect", "onselectionchange", "onselectstart", "onstart", "onstop",
"onsubmit", "onunload"};
bool found = true;
while (found)
{
var retBefore = ret;
StringBuilder pattern = new StringBuilder(1000);
StringBuilder pattern2 = new StringBuilder(1000);
for (int i = 0; i < keywords.Length; i++)
{
pattern.Remove(0, pattern.Length);
pattern.Append("<");
pattern2.Remove(0, pattern2.Length);
pattern2.Append("/");
for (int j = 0; j < keywords[i].Length; j++)
{
if (j > 0)
{
pattern.Append("((&#[x|X]0{0,8}([9][a][b]);?)?|(�{0,8}([9][10][13]);?)?)?");
pattern2.Append("((&#[x|X]0{0,8}([9][a][b]);?)?|(�{0,8}([9][10][13]);?)?)?");
}
pattern.Append(keywords[i][j]);
pattern2.Append(keywords[i][j]);
}
string replacement = string.Concat(keywords[i].Substring(0, 2), "<x>", keywords[i].Substring(2));
ret = System.Text.RegularExpressions.Regex.Replace(ret, pattern.ToString(), replacement, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
ret = System.Text.RegularExpressions.Regex.Replace(ret, pattern2.ToString(), replacement, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (ret == retBefore)
found = false;
}
}
return ret;
}
}
[解决办法]
之前做项目,导入了一堆的公共类,然后讲了一通,最后review发现,根本没人用~~~~
好伤心~~~~
[解决办法]
这就是最悲剧的地方。。。 。。。
[解决办法]
编译以后有差不多500kB,当然了不是给别人用的。