在项目开发中公共帮助类是必不可少的,这里记录一些自己摘录或自己编写的帮助类。

64位编码与解码:

 #region URL的64位编码
/// <summary>
/// URL的64位编码
/// </summary>
/// <param name="sourthUrl"></param>
/// <returns></returns>
public static string Base64Encrypt(string sourthUrl)
{
string eurl = HttpUtility.UrlEncode(sourthUrl);
eurl = Convert.ToBase64String(Encoding.Default.GetBytes(eurl));
return eurl;
}
#endregion #region URL的64位解码
/// <summary>
/// URL的64位解码
/// </summary>
/// <param name="eStr"></param>
/// <returns></returns>
public static string Base64Decrypt(string eStr)
{
if (!IsBase64(eStr))
{
return eStr;
}
byte[] buffer = Convert.FromBase64String(eStr);
string sourthUrl = Encoding.Default.GetString(buffer);
sourthUrl = HttpUtility.UrlDecode(sourthUrl);
return sourthUrl;
}
#endregion #region 检查一个字符串是否是Base64字符串
/// <summary>
/// 检查一个字符串是否是Base64字符串
/// </summary>
/// <param name="eStr"></param>
/// <returns></returns>
public static bool IsBase64(string eStr)
{
if ((eStr.Length % ) != )
{
return false;
}
if (!Regex.IsMatch(eStr, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
{
return false;
}
return true;
}
#endregion

字符串过滤:

 #region 检测是否有Sql危险字符
/// <summary>
/// 检测是否有Sql危险字符
/// </summary>
/// <param name="str">要判断字符串</param>
/// <returns>判断结果</returns>
public static bool IsSafeSqlString(string str)
{
return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
} /// <summary>
/// 检查危险字符
/// </summary>
/// <param name="Input"></param>
/// <returns></returns>
public static string Filter(string sInput)
{
if (sInput == null || sInput == "")
return null;
string sInput1 = sInput.ToLower();
string output = sInput;
string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
{
throw new Exception("字符串中含有非法字符!");
}
else
{
output = output.Replace("'", "''");
}
return output;
} /// <summary>
/// 检查过滤设定的危险字符
/// </summary>
/// <param name="InText">要过滤的字符串 </param>
/// <returns>如果参数存在不安全字符,则返回true </returns>
public static bool SqlFilter(string word, string InText)
{
if (InText == null)
return false;
foreach (string i in word.Split('|'))
{
if ((InText.ToLower().IndexOf(i + " ") > -) || (InText.ToLower().IndexOf(" " + i) > -))
{
return true;
}
}
return false;
}
#endregion #region 过滤特殊字符
/// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="Input"></param>
/// <returns></returns>
public static string Htmls(string Input)
{
if (Input != string.Empty && Input != null)
{
string ihtml = Input.ToLower();
ihtml = ihtml.Replace("<script", "&lt;script");
ihtml = ihtml.Replace("script>", "script&gt;");
ihtml = ihtml.Replace("<%", "&lt;%");
ihtml = ihtml.Replace("%>", "%&gt;");
ihtml = ihtml.Replace("<$", "&lt;$");
ihtml = ihtml.Replace("$>", "$&gt;");
return ihtml;
}
else
{
return string.Empty;
}
}
#endregion

字符串与List相互转化:

        #region 把字符串按照分隔符转换成 List
/// <summary>
/// 把字符串按照分隔符转换成 List
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="speater">分隔符</param>
/// <param name="toLower">是否转换为小写</param>
/// <returns></returns>
public static List<string> GetStrArray(string str, char speater, bool toLower)
{
List<string> list = new List<string>();
string[] ss = str.Split(speater);
foreach (string s in ss)
{
if (!string.IsNullOrEmpty(s) && s != speater.ToString())
{
string strVal = s;
if (toLower)
{
strVal = s.ToLower();
}
list.Add(strVal);
}
}
return list;
}
#endregion #region 把 List<string> 按照分隔符组装成 string
/// <summary>
/// 把 List<string> 按照分隔符组装成 string
/// </summary>
/// <param name="list"></param>
/// <param name="speater">分隔符</param>
/// <returns></returns>
public static string GetArrayStr(List<string> list, string speater)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < list.Count; i++)
{
if (i == list.Count - )
{
sb.Append(list[i]);
}
else
{
sb.Append(list[i]);
sb.Append(speater);
}
}
return sb.ToString();
}
#endregion #region 把 List<int> 按照分隔符组装成 string
/// <summary>
/// 把 List<int> 按照分隔符组装成 string
/// </summary>
/// <param name="list"></param>
/// <param name="speater">分隔符</param>
/// <returns></returns>
public static string GetArrayStr(List<int> list, string speater)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < list.Count; i++)
{
if (i == list.Count - )
{
sb.Append(list[i].ToString());
}
else
{
sb.Append(list[i]);
sb.Append(",");
}
}
return sb.ToString();
}
#endregion

HTML转成Text文本:

/// <summary>
/// HTML转行成TEXT
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string HtmlToTxt(string strHtml)
{
string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
@"([\r\n])[\s]+",
@"&(quot|#34);",
@"&(amp|#38);",
@"&(lt|#60);",
@"&(gt|#62);",
@"&(nbsp|#160);",
@"&(iexcl|#161);",
@"&(cent|#162);",
@"&(pound|#163);",
@"&(copy|#169);",
@"&#(\d+);",
@"-->",
@"<!--.*\n"
}; string newReg = aryReg[];
string strOutput = strHtml;
for (int i = ; i < aryReg.Length; i++)
{
Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, string.Empty);
} strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput.Replace("\r\n", ""); return strOutput;
}

DataTable转List<T>:

 /// <summary>
/// DataTable转换成List<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <param name="IsDataField"></param>
/// <returns></returns>
public static List<T> DataTableToList<T>(DataTable dt, bool IsDataField) where T : new()
{
List<T> ts = new List<T>();
Type type = typeof(T);
string tempName = string.Empty;
foreach (DataRow dr in dt.Rows)
{
T myt = new T();
PropertyInfo[] propertys = myt.GetType().GetProperties();
PropertyInfo[] array = propertys;
int i = ;
DataFieldAttribute attribute = null;
PropertyAttribute proAttribute = null;
while (i < array.Length)
{
PropertyInfo pi = array[i];
if (IsDataField)
{
object[] infos = null;
object[] pros = null;
infos = pi.GetCustomAttributes(typeof(DataFieldAttribute), false);
pros = pi.GetCustomAttributes(typeof(PropertyAttribute), false);
if (infos.Length > )
{
attribute = (DataFieldAttribute)(infos[]);
if (pros.Length > )
{
proAttribute = (PropertyAttribute)(pros[]);
if (proAttribute.columnKeyType != ColumnKeyType.Extend)
{
tempName = attribute.FieldName;
}
}
else
tempName = attribute.FieldName;
}
}
else
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (pi.CanWrite)
{
object value = dr[tempName];
//if (value.GetType().Equals(typeof(DateTime)))
// value = System.Convert.ToString(value);
if (value != DBNull.Value)
pi.SetValue(myt, value, null);
}
}
i += ;
continue;
}
ts.Add(myt);
}
return ts;
}

DataTable 转 Object:

/// <summary>
/// DataTable 转 Object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static T DataTableToObject<T>(DataTable dt, bool IsDataField) where T : new()
{
Type type = typeof(T);
string tempName = string.Empty;
T myt = new T();
PropertyInfo[] propertys = myt.GetType().GetProperties();
PropertyInfo[] array = propertys;
int i = ;
DataFieldAttribute attribute = null;
PropertyAttribute proAttribute = null;
while (i < array.Length)
{
PropertyInfo pi = array[i];
if (IsDataField)
{
object[] infos = null;
object[] pros = null;
infos = pi.GetCustomAttributes(typeof(DataFieldAttribute), false);
pros = pi.GetCustomAttributes(typeof(PropertyAttribute), false);
if (infos.Length > )
{
attribute = (DataFieldAttribute)(infos[]);
if (pros.Length>)
{
proAttribute = (PropertyAttribute)(pros[]);
if (proAttribute.columnKeyType != ColumnKeyType.Extend)
{
tempName = attribute.FieldName;
}
}else
tempName = attribute.FieldName;
}
}
else
tempName = pi.Name; if (dt.Columns.Contains(tempName))
{
if (pi.CanWrite)
{
object value = dt.Rows[][tempName];
//if (value.GetType().Equals(typeof(DateTime)))
// value = Convert.ToString(value);
if (value != DBNull.Value)
pi.SetValue(myt, value, null);
}
}
i += ;
continue;
}
return myt;
}

CacheHelper:

/// <summary>
/// 获取数据缓存
/// </summary>
/// <param name="CacheKey">键</param>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject);
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
} /// <summary>
/// 移除指定数据缓存
/// </summary>
public static void RemoveAllCache(string CacheKey)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
_cache.Remove(CacheKey);
} /// <summary>
/// 移除全部缓存
/// </summary>
public static void RemoveAllCache()
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
_cache.Remove(CacheEnum.Key.ToString());
}
}
 

asp.net——公共帮助类的更多相关文章

  1. Util应用程序框架公共操作类(一):数据类型转换公共操作类(介绍篇)

    本系列文章将介绍一些对初学者有帮助的辅助类,这些辅助类本身并没有什么稀奇之处,如何能发现需要封装它们可能更加重要,所谓授之以鱼不如授之以渔,掌握封装公共操作类的技巧才是关键,我会详细说明创建这些类的动 ...

  2. c#.net公共帮助类

    c#.net公共帮助类 比较全面的c#帮助类 比较全面的c#帮助类,日常工作收集,包括前面几家公司用到的,各式各样的几乎都能找到,所有功能性代码都是独立的类,类与类之间没有联系,可以单独引用至项目,分 ...

  3. Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)

    今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...

  4. Util应用程序框架公共操作类(九):Lambda表达式扩展

    上一篇对Lambda表达式公共操作类进行了一些增强,本篇使用扩展方法对Lambda表达式进行扩展. 修改Util项目的Extensions.Expression.cs文件,代码如下. using Sy ...

  5. Util应用程序框架公共操作类(八):Lambda表达式公共操作类(二)

    前面介绍了查询的基础扩展,下面准备给大家介绍一些有用的查询封装手法,比如对日期范围查询,数值范围查询的封装等,为了支持这些功能,需要增强公共操作类. Lambda表达式公共操作类,我在前面已经简单介绍 ...

  6. Util应用程序框架公共操作类(七):Lambda表达式公共操作类

    前一篇扩展了两个常用验证方法,本文将封装两个Lambda表达式操作,用来为下一篇的查询扩展服务. Lambda表达式是一种简洁的匿名函数语法,可以用它将方法作为委托参数传递.在Linq中,大量使用La ...

  7. Util应用程序框架公共操作类(六):验证扩展

    前面介绍了仓储的基本操作,下面准备开始扩展查询,在扩展查询之前,首先要增加两个公共操作类,一个是经常要用到的验证方法,另一个是Lambda表达式的操作类. 很多时候,我们会判断一个对象是否为null, ...

  8. Util应用程序框架公共操作类(五):异常公共操作类

    任何系统都需要处理错误,本文介绍的异常公共操作类,用于对业务上的错误进行简单支持. 对于刚刚接触.Net的新手,碰到错误的时候,一般喜欢通过返回bool值的方式指示是否执行成功. public boo ...

  9. Util应用程序框架公共操作类(四):验证公共操作类

    为了能够验证领域实体,需要一个验证公共操作类来提供支持.由于我将使用企业库(Enterprise Library)的验证组件来完成这项任务,所以本文也将演示对第三方框架的封装要点. .Net提供了一个 ...

随机推荐

  1. 87. Scramble String (String; DP)

    Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrin ...

  2. ios runtime简单实用(添加动态属性)

    #import "Person.h" @interface Person (PersonCategory)   // 添加Person中没有的name属性 @property (n ...

  3. python的paramiko模块简单应用

    用法1,SSHClient 分别可以使用密码和秘钥登陆,然后执行命令,并且获取执行结果 import paramiko #创建一个SSH对象 ssh = paramiko.SSHClient() #允 ...

  4. 过滤输入htmlentities与htmlspecialchars用法

    过滤输入 (即来自所列数据源中的任何数据)是指,转义或删除不安全的字符.在数据到达应用的存储层之前,一定要过滤输入数据.这是第一道防线.假如网站的评论表单接收html,默认情况下 访客可以毫无阻拦地在 ...

  5. MVC加载部分视图Partial

    加载部分视图的方法:Partial() .RenderPartial() . Action() .RenderAction() . RenderPage() partial 与 RenderParti ...

  6. Golang之hello,beego

    学习谢大神的beego记录 过程: 目录结构: 编译命令: go build -o myBeego.exe go_dev/day13/beego_example/main执行myBeego.exe即可 ...

  7. Golang之定义错误(errors)

    基本示例: package main //定义错误 //error 也是个接口 import ( "errors" "fmt" ) var errNotFoun ...

  8. Window 编码 UTF-8 BOM 说明

    UTF-8 不需要 BOM,尽管 Unicode 标准允许在 UTF-8 中使用 BOM.所以不含 BOM 的 UTF-8 才是标准形式,在 UTF-8 文件中放置 BOM 主要是微软的习惯(顺便提一 ...

  9. Ui设计流行趋势,对颜色的探讨

    设计风向转换的趋势越来越短,在设计圈中,流行设计的跟新换代更是快.在设计时间越来越短的今天,在经理领导不断催促的时下,如何准确的把握当下的流行趋势,如何在设计之初就能定好设计的基调.这对于还是刚入设计 ...

  10. UEdit百度富文本编辑器

    1.下载地址:http://ueditor.baidu.com/website/download.html 2.引入js/css/语言包 3.表单id设置 3.js代码