常用代码

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace ESales.Common
{
    /// <summary>
    /// 应用帮助类
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// 判断DataSet是否为空
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static bool IsEmptyDataSet(DataSet ds)
        {
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #region 字符串操作
        /// <summary>
        /// 转换为Int数组
        /// </summary>
        /// <param name="strArray"></param>
        /// <returns></returns>
        public static int[] ToIntArray(string[] strArray)
        {
            if (strArray != null)
            {
                int[] intAry = new int[strArray.Length];
                for (int i = 0; i < intAry.Length; i++)
                {
                    intAry[i] = int.Parse(strArray[i]);
                }
                return intAry;
            }
            else
            {
                return new int[] { };
            }
        }


        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="text">要截取的源字符串</param>
        /// <param name="maxLength">允许的最大字符串长度</param>
        /// <param name="replace">要在结尾附加的字符串</param>
        /// <param name="onDiffCharSet">是否开启中/英文字符集区分(开启时一个中文字符算两位,一个英文字符只算一位)</param>
        /// <returns>返回截取后的字符串</returns>
        public static string SubString(string text, int maxLength, string replace, bool onDiffCharSet)
        {
            string outString = string.Empty;

            if (string.IsNullOrEmpty(replace))
            {
                replace = string.Empty;
            }

            if (!string.IsNullOrEmpty(text))
            {
                if (onDiffCharSet)
                {
                    if (GetStringLength(text) <= maxLength)
                    {
                        outString = text;
                    }
                    else
                    {
                        string strTemp = text;
                        for (int i = text.Length; i >= 0; i--)
                        {
                            strTemp = strTemp.Substring(0, i);
                            if (GetStringLength(strTemp) <= maxLength)
                            {
                                outString = strTemp + replace;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (text.Length > maxLength)
                    {
                        outString = text.Substring(0, maxLength) + replace;
                    }
                }
            }
            else
            {
                outString = replace;
            }

            return outString;
        }

        /// <summary>
        /// 获取字符串的长度(中文字符算两位,英文字符算一位)
        /// </summary>
        /// <param name="text">要计算的源字符串</param>
        /// <returns>返回整型的字符串的长度值</returns>
        public static int GetStringLength(string text)
        {
            int length = 0;
            if (!string.IsNullOrEmpty(text))
            {
                // 备注:使用 [\u4e00-\u9fa5] 替换时,只会替换中文字符,对于其它双
                // 字节字符处理无效(中文标点也会忽略掉)
                length = Regex.Replace(text, "[^\x00-\xff]", "zz", RegexOptions.IgnoreCase).Length;
            }
            return length;
        }
        #endregion


        #region HTML编码转换
        /// <summary>
        /// 对HTML字符进行编码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string HtmlEncode(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else
            {
                return HttpUtility.HtmlEncode(text);
            }
        }

        /// <summary>
        /// 对HTML字符进行解码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string HtmlDecode(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else
            {
                return HttpUtility.HtmlDecode(text);
            }
        }

        /// <summary>
        /// 将文本格式转化为HTML格式, 如:\r\n 转换为 <br/>
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Text2Html(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else
            {
                StringBuilder strBuilder = new StringBuilder(text);
                strBuilder.Replace("  ", " &nbsp;");
                strBuilder.Replace(" ", " &nbsp;");//全角中文空格
                strBuilder.Replace("\r\n", "<br/>");
                strBuilder.Replace("\r", "<br/>");
                strBuilder.Replace("\n", "<br/>");

                return strBuilder.ToString();
            }
        }

        /// <summary>
        /// 将HTML格式转化为文本格式, 如:<br/> 转换为 \r\n
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string Html2Text(string html)
        {
            if (string.IsNullOrEmpty(html))
            {
                return string.Empty;
            }
            else
            {
                StringBuilder strBuilder = new StringBuilder(html);
                strBuilder.Replace(" &nbsp;", "  ");
                strBuilder.Replace(" &nbsp;", " ");//全角中文空格
                strBuilder.Replace("<br/>", "\r\n");
                strBuilder.Replace("<br/>", "\r");
                strBuilder.Replace("<br/>", "\n");

                return strBuilder.ToString();
            }
        }
        #endregion


        #region Request & Session & Cookie & Web.Config 强类型值读取
        public static T GetRequest<T>(string key, T defaultValue)
        {
            string value = HttpContext.Current.Request[key];

            if (string.IsNullOrEmpty(value))
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    return defaultValue;
                }
            }
        }

        public static T GetSession<T>(string key, T defaultValue)
        {
            object value = HttpContext.Current.Session[key];

            if (value == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    return defaultValue;
                }
            }
        }

        public static T GetAppConfig<T>(string key, T defaultValue)
        {
            string value = ConfigurationManager.AppSettings[key];

            if (string.IsNullOrEmpty(value))
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        #endregion


        #region 页面帮助脚本
        /// <summary>
        /// 通过Script脚本在页面上显示提示信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="message">提示信息</param>
        public static void Alert(string message)
        {
            HttpContext.Current.Response.Write(string.Format(
                "<script language=\"javascript\">alert(\"{0}\");</script>", message));
            //page.ClientScript.RegisterClientScriptBlock(page.GetType(), page.UniqueID,
            //    string.Format("alert(\"{0}\");", message), true);
        }

        /// <summary>
        /// 通过Script脚本在页面上显示提示信息, 并跳转到新的地址
        /// </summary>
        /// <param name="message">提示信息</param>
        /// <param name="gotoUrl">要跳转的页</param>
        public static void Alert(string message, string gotoUrl)
        {
            //page.ClientScript.RegisterClientScriptBlock(page.GetType(), page.UniqueID,
            //    string.Format("alert(\"{0}\");location.href=\"{1}\";", message, gotoUrl), true);

            HttpContext.Current.Response.Write(string.Format(
                "<script language=\"javascript\">alert(\"{0}\");location.href=\"{1}\";</script>", message, gotoUrl));
        }
        #endregion


        #region 其他帮助方法
        /// <summary>
        /// 获取ASP.NET控件相应的HTML字符串表示
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string RenderHtmlOfControl(System.Web.UI.Control c)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringWriter writer = new System.IO.StringWriter(sb);
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(writer);
            c.RenderControl(htw);
            return sb.ToString();
        }

        /// <summary>
        /// 使用MD5加密字符串
        /// </summary>
        /// <param name="text">要加密的字符串</param>
        /// <returns>加密后的字符串(32位大写字符)</returns>
        public static string MD5(string text)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "md5");
        }

  /// <summary>
        /// 使用BASE64对文本进行编码
        /// </summary>
        /// <param name="text">要编码的字符串</param>
        /// <returns></returns>
        public static string Base64Encode(string text)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(text);
            //转成 Base64 形式的 System.String
            string outStr = Convert.ToBase64String(b);
            return outStr;
        }

        /// <summary>
        /// 使用BASE64对文本进行解码
        /// </summary>
        /// <param name="text">要解码的字符串</param>
        /// <returns></returns>
        public static string Base64Decode(string text)
        {
            byte[] c = Convert.FromBase64String(text);
            string outStr = System.Text.Encoding.Default.GetString(c);
            return outStr;
        }

        /// <summary>
        /// 设置一个选择项, 其他被选中的项会取消选中状态
        /// </summary>
        /// <param name="list">要进行查找的LIST</param>
        /// <param name="val">同List.Item[i].Value进行对比的值</param>
        public static void SelecteItem(ListControl list, string val)
        {
            for (int i = 0; i < list.Items.Count; i++)
            {
                list.Items[i].Selected = false;
            }
            for (int i = 0; i < list.Items.Count; i++)
            {
                if (list.Items[i].Value == val)
                {
                    list.Items[i].Selected = true;
                    return;
                }
            }
        }

        /// <summary>
        /// 设置一个的选择项(可用于选择多个项)
        /// </summary>
        /// <param name="list">要进行查找的LIST</param>
        /// <param name="val">同List.Item[i].Value进行对比的值</param>
        /// <param name="cancel">是否取消已选中的项</param>
        public static void SelectItem(ListControl list, string val, bool cancel)
        {
            for (int i = 0; i < list.Items.Count; i++)
            {
                if (list.Items[i].Value == val)
                {
                    list.Items[i].Selected = true;
                }
                else
                {
                    if (cancel)
                    {
                        list.Items[i].Selected = false;
                    }
                }
            }
        }
        #endregion

    }//class Utils
}

posted @ 2008-10-20 16:11  蛤蟆  阅读(157)  评论(0)    收藏  举报