asp.net——公共帮助类
在项目开发中公共帮助类是必不可少的,这里记录一些自己摘录或自己编写的帮助类。
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", "<script");
ihtml = ihtml.Replace("script>", "script>");
ihtml = ihtml.Replace("<%", "<%");
ihtml = ihtml.Replace("%>", "%>");
ihtml = ihtml.Replace("<$", "<$");
ihtml = ihtml.Replace("$>", "$>");
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——公共帮助类的更多相关文章
- Util应用程序框架公共操作类(一):数据类型转换公共操作类(介绍篇)
本系列文章将介绍一些对初学者有帮助的辅助类,这些辅助类本身并没有什么稀奇之处,如何能发现需要封装它们可能更加重要,所谓授之以鱼不如授之以渔,掌握封装公共操作类的技巧才是关键,我会详细说明创建这些类的动 ...
- c#.net公共帮助类
c#.net公共帮助类 比较全面的c#帮助类 比较全面的c#帮助类,日常工作收集,包括前面几家公司用到的,各式各样的几乎都能找到,所有功能性代码都是独立的类,类与类之间没有联系,可以单独引用至项目,分 ...
- Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)
今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...
- Util应用程序框架公共操作类(九):Lambda表达式扩展
上一篇对Lambda表达式公共操作类进行了一些增强,本篇使用扩展方法对Lambda表达式进行扩展. 修改Util项目的Extensions.Expression.cs文件,代码如下. using Sy ...
- Util应用程序框架公共操作类(八):Lambda表达式公共操作类(二)
前面介绍了查询的基础扩展,下面准备给大家介绍一些有用的查询封装手法,比如对日期范围查询,数值范围查询的封装等,为了支持这些功能,需要增强公共操作类. Lambda表达式公共操作类,我在前面已经简单介绍 ...
- Util应用程序框架公共操作类(七):Lambda表达式公共操作类
前一篇扩展了两个常用验证方法,本文将封装两个Lambda表达式操作,用来为下一篇的查询扩展服务. Lambda表达式是一种简洁的匿名函数语法,可以用它将方法作为委托参数传递.在Linq中,大量使用La ...
- Util应用程序框架公共操作类(六):验证扩展
前面介绍了仓储的基本操作,下面准备开始扩展查询,在扩展查询之前,首先要增加两个公共操作类,一个是经常要用到的验证方法,另一个是Lambda表达式的操作类. 很多时候,我们会判断一个对象是否为null, ...
- Util应用程序框架公共操作类(五):异常公共操作类
任何系统都需要处理错误,本文介绍的异常公共操作类,用于对业务上的错误进行简单支持. 对于刚刚接触.Net的新手,碰到错误的时候,一般喜欢通过返回bool值的方式指示是否执行成功. public boo ...
- Util应用程序框架公共操作类(四):验证公共操作类
为了能够验证领域实体,需要一个验证公共操作类来提供支持.由于我将使用企业库(Enterprise Library)的验证组件来完成这项任务,所以本文也将演示对第三方框架的封装要点. .Net提供了一个 ...
随机推荐
- 微信小程序及开发工具介绍
http://mp.weixin.qq.com/wiki 这里下载开发者工具
- tf.unstack\tf.unstack
tf.unstack 原型: unstack( value, num=None, axis=0, name='unstack' ) 官方解释:https://tensorflow.google.cn/ ...
- 122. Best Time to Buy and Sell Stock II (Array;Greedy)
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- 复杂度分析 quick sort&merge sort
空间复杂度看新开了什么数据结构就够了 公式=几个点*每个点执行了多少次 二叉树都是n次 二分法查找:lgn 全部查找:n n:找一个数,但是两边都要找.相当于遍历.类似于rotated sorted ...
- Spring集成Redis使用注解
转载:http://blog.csdn.net/u013725455/article/details/52129283 使用Maven项目,添加jar文件依赖: <project xmlns=& ...
- linux 下 php 安装 pthreads
1.下载pthreads的源码包 https://pecl.php.net/package/pthreads 如:pthreads-3.1.6.tgz 2.解压 > tar zxvf pthre ...
- php5.3 php-fpm 开启 关闭 重启
自php5.3开始,php源码中包含了php-fpm,不需要单独通过补丁的方式安装php-fpm,在源码安装的时候直接 configure 中增加参数 –enable-fpm 即可. 所以启动.关 ...
- resin-pro-4.0.53报错java.lang.Error: java.lang.ClassNotFoundException: com.caucho.loader.SystemClassLoader
最初并未发现,笔者的系统环境变量JAVA_HOME变量设置错误 D:\develop\Java\x64\jdk1.8.0_144 #最初使用了阉割版的JDK 改成完整安装的JDK就可以 D:\deve ...
- lnmp vhost 虚拟目录配置
以前常用Windows 很熟悉,lnmp 配置虚拟目录也很简单. 安装完lnmp环境之后,在nginx的配置文件夹下,我采用的方法是复制default.conf 然后重命名为vhost_a.conf ...
- HTML5 history详解
最近研究vue-router单页转跳而不向服务器请求的原理, 主要是HTML5 history以及hash的应用,支持history时使用history模式 下面详细学习了一下常用的history相关 ...