亮亮大家常用的公共类吧!

七色鸟 2012-07-20 03:06:07

刚到一新衙门,发现老的项目中居然啊公共类都没有的。
什么,替换文本中HTML标签内容,和截取字符串长度(按照字节截取),这些都没的。

大家亮亮自己的吧!
...全文
270 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
种草德鲁伊 2012-07-21
  • 打赏
  • 举报
回复
编译以后有差不多500kB,当然了不是给别人用的。
鸭梨山大帝 2012-07-21
  • 打赏
  • 举报
回复
这就是最悲剧的地方。。。 。。。

[Quote=引用 10 楼 的回复:]

之前做项目,导入了一堆的公共类,然后讲了一通,最后review发现,根本没人用~~~~
好伤心~~~~
[/Quote]
  • 打赏
  • 举报
回复
之前做项目,导入了一堆的公共类,然后讲了一通,最后review发现,根本没人用~~~~
好伤心~~~~
七色鸟 2012-07-20
  • 打赏
  • 举报
回复
另一种,按照字节截取方式。

public static string CutString(this string value, int length)
{
if (string.IsNullOrEmpty(value)) return "";

int dataLength = length * 2; //要截取的字节长度
byte[] bLength = Encoding.GetEncoding("gb2312").GetBytes(value); //原字符串的字节长度

if (bLength.Length <= dataLength)
return value;

string strEndRes = "";
while (true)
{
strEndRes += value.Substring(strEndRes.Length, length);

int size = dataLength - Encoding.GetEncoding("gb2312").GetBytes(strEndRes).Length;
if (size <= 1)
{
if (size == 1 && Encoding.GetEncoding("gb2312").GetBytes(value.Substring(strEndRes.Length, 1)).Length == 1)
{
strEndRes += value.Substring(strEndRes.Length, 1);
}
return strEndRes;
}
length = size / 2;
}
}
七色鸟 2012-07-20
  • 打赏
  • 举报
回复
slyzly,兄弟,你真给力。等会分多给你一点。
事理 2012-07-20
  • 打赏
  • 举报
回复
/// <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;
}
}
事理 2012-07-20
  • 打赏
  • 举报
回复
/// <summary>
/// 消息提示类,简化页面消息提示
/// </summary>
public static class MessageBox
{
const string javaScriptHead = "<script type='text/javascript'>";
const string javaScriptFoot = "</script>";

/// <summary>
/// Page.ClientScript.RegisterStartupScript提示消息
/// 注意:模版页中提示消息不能用此方法;消息中有换行用\\r\\n
/// </summary>
/// <remarks>
/// MessageBox.Show("提示信息!",this);
/// </remarks>
/// <param name="message">提示信息</param>
/// <param name="page">页面对象,一般传入this</param>
public static void Show(string message, Page page)
{
Type pageType = page.GetType();
page.ClientScript.RegisterStartupScript(pageType, pageType.Name, javaScriptHead + "alert('" + message.Replace("'", " ") + "')" + javaScriptFoot);
}

/// <summary>
/// ScriptManager.RegisterStartupScript提示消息
/// </summary>
/// <param name="message">提示信息</param>
/// <param name="updatePanel">UpdatePanel对象</param>
public static void Show(string message, UpdatePanel updatePanel)
{
ScriptManager.RegisterStartupScript(updatePanel, updatePanel.Page.GetType(), updatePanel.ID, "alert('" + message.Replace("'", " ") + "');", true);
}

/// <summary>
/// confirm确认提示消息后,跳转到指定页面,Page.ClientScript.RegisterStartupScript提示消息
/// </summary>
/// <remarks>
/// MessageBox.ShowConfirmAndRedirect("提示消息!","Success.aspx",this);
/// </remarks>
/// <param name="message">提示消息</param>
/// <param name="url">跳转的页面</param>
/// <param name="page">页面对象,一般传入this</param>
public static void ShowConfirmAndRedirect(string message, string url, Page page)
{
string script = "var ok=false;";

if (!string.IsNullOrEmpty(message))
script = "ok=confirm('" + message.Replace("'", " ") + "');";
if (!string.IsNullOrEmpty(url))
script += "if(ok==true)top.location.href='" + url + "'";

script = javaScriptHead + script + javaScriptFoot;

Type pageType = page.GetType();
page.ClientScript.RegisterStartupScript(pageType, pageType.Name, script);
}

/// <summary>
/// 提示消息后刷新指定父页面,Page.ClientScript.RegisterStartupScript提示消息
/// </summary>
/// <param name="message">提示消息</param>
/// <param name="url">父窗口要跳转的页面</param>
/// <param name="page">页面对象,一般传入this</param>
public static void ShowAndRefreshParent(string message, string url, Page page)
{
string script = string.Empty;

if (!string.IsNullOrEmpty(message))
script = "alert('" + message.Replace("'", " ") + "');";
if (!string.IsNullOrEmpty(url))
script += "window.opener.location.href='" + url + "';window.close();";

script = javaScriptHead + script + javaScriptFoot;

Type pageType = page.GetType();
page.ClientScript.RegisterStartupScript(pageType, pageType.Name, script);
}

/// <summary>
/// window.open打开窗口
/// </summary>
/// <param name="url">要打开的页面</param>
/// <param name="width">窗口宽度</param>
/// <param name="height">窗口高度</param>
/// <param name="page">页面对象,一般传入this</param>
public static void OpenWindow(string url, int width, int height, Page page)
{
string script = javaScriptHead + "var newwindow=window.open('" + url + "','_blank','width=" + width + ",height=" + height
+ ",top='+(screen.height-" + height + ")/2+',left='+(screen.width-" + width
+ ")/2+',toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');newwindow.focus();"
+ javaScriptFoot;

Type pageType = page.GetType();
page.ClientScript.RegisterStartupScript(pageType, pageType.Name, script);
}

/// <summary>
/// 弹出居中模态窗口
/// </summary>
/// <param name="url">页面地址</param>
/// <param name="width">模态窗口宽度</param>
/// <param name="height">模态窗口高度</param>
/// <param name="page">页面对象,一般传入this</param>
public static void ShowModalDialog(string url, int width, int height, Page page)
{
string script = javaScriptHead + "window.showModalDialog('" + url + "','','dialogWidth:" + width + "px;dialogHeight:" + height
+ "px;dialogTop:'+(screen.height-" + height + ")/2+'px;dialogLeft:'+(screen.width-" + width
+ ")/2+'px;center:1;scroll:no;status:no;');" + javaScriptFoot;

Type pageType = page.GetType();
page.ClientScript.RegisterStartupScript(pageType, pageType.Name, script);
}

#region Response.Write 提示消息

/// <summary>
/// Response提示消息后跳转到指定页面
/// window.location.href
/// </summary>
/// <param name="message">提示信息</param>
/// <param name="url">跳转的页面</param>
public static void ResponseMsgAndRedirect(string message, string url)
{
string script = string.Empty;

if (!string.IsNullOrEmpty(message))
script = "alert('" + message.Replace("'", " ") + "');";
if (!string.IsNullOrEmpty(url))
script += "window.location.href='" + url + "'";

script = javaScriptHead + script + javaScriptFoot;

System.Web.HttpContext.Current.Response.Write(script);
}

/// <summary>
/// Response提示消息后,子页面触发父页面跳转,适用于iframe
/// parent.location.href
/// </summary>
/// <param name="message">提示信息</param>
/// <param name="url">要跳转页面</param>
public static void ResponseMsgAndParentRedirect(string message, string url)
{
string script = string.Empty;

if (!string.IsNullOrEmpty(message))
script = "alert('" + message.Replace("'", " ") + "');";
if (!string.IsNullOrEmpty(url))
script += "parent.location.href='" + url + "'";

script = javaScriptHead + script + javaScriptFoot;

System.Web.HttpContext.Current.Response.Write(script);
}

/// <summary>
/// Response提示消息后,最顶层的页面跳转,适用于iframe中子页面触发顶层页面跳转
/// top.location.href
/// </summary>
/// <param name="message">提示信息</param>
/// <param name="url">要跳转的页面</param>
public static void ResponseMsgAndTopRedirect(string message, string url)
{
string script = string.Empty;

if (!string.IsNullOrEmpty(message))
script = "alert('" + message.Replace("'", " ") + "');";
if (!string.IsNullOrEmpty(url))
script += "top.location.href='" + url + "'";

script = javaScriptHead + script + javaScriptFoot;

System.Web.HttpContext.Current.Response.Write(script);
}

/// <summary>
/// Response提示消息后返回指定页面
/// </summary>
/// <param name="message">提示信息</param>
/// <param name="historyCount">history.go(historyCount)</param>
public static void ResponseMsgAndHistoryBack(string message, int historyCount)
{
string script = string.Empty;

if (!string.IsNullOrEmpty(message))
script = "alert('" + message.Replace("'", " ") + "');";

script = javaScriptHead + script + "history.go(" + historyCount + ")" + javaScriptFoot;

System.Web.HttpContext.Current.Response.Write(script);
}
#endregion
}
事理 2012-07-20
  • 打赏
  • 举报
回复
贴几个我项目中用到的。

/// <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
暗尘掩月 2012-07-20
  • 打赏
  • 举报
回复
http://blog.csdn.net/anchenyanyue
叶黑 2012-07-20
  • 打赏
  • 举报
回复
sqlDALHelper 别人写的
天下在我心 2012-07-20
  • 打赏
  • 举报
回复
自己写一个吧,很简单的。

62,243

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧