Common公用类

* web.config缓存

1. Web.config中的<appSettings>中添加key ... value

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="keycode" value="1"/>
    <add key="pwd" value="xhx"/>
  </appSettings>

2. 通用类

    public class ConfigHelper
    {
        #region 获取并设置Cache的值
        public static string GetCacheString(string key)
        {
            string cacheKey = "AppSettings_" + key;
            object obj = GetCache(cacheKey); //第二次从Cache中获取数据
            if (obj == null)
            {
                try
                {
                    obj = ConfigurationManager.AppSettings[key]; //第一次直接获取数据
                    if (obj != null)
                        SetCache(cacheKey, obj, DateTime.Now.AddMinutes(180), TimeSpan.Zero); //设置缓存
                    else
                        obj = "";
                }
                catch { }
            }
            return obj.ToString();
        }

        /// <summary>
        /// 设置Cache的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="expiratime"></param>
        /// <param name="s"></param>
        private static void SetCache(string key, object obj, DateTime expiratime, TimeSpan s)
        {
            Cache objCache = HttpRuntime.Cache;
            objCache.Insert(key, obj, null, expiratime, s);
        }

        /// <summary>
        /// 获取指定的Cache
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static Object GetCache(string key)
        {
            Cache objCache = HttpRuntime.Cache;
            return objCache[key];
        }
        #endregion

        #region 调用
        /// <summary>
        /// 事例。
        /// 弊端,针对每个key都要写像这样写,代码冗余。
        /// 调用:var s = ConfigHelper.KeyCode;
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string KeyCode
        {
            get { return GetCacheString(ConstClass.AppSettings_KeyCode); }
        }

        /// <summary>
        /// 通用实例2,通用方法
        /// 调用:var s2 = ConfigHelper.GetValueByKey("keycode");
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValueByKey(string key)
        {
            return GetCacheString(key);
        } 
        #endregion
    }


    #region 常量类
    public class ConstClass
    {
        //这里用const表示常量,默认是string类型
        public const string AppSettings_KeyCode = "keycode";
    } 
    #endregion
从web.config中获取key,设置到cache中

* Json转换

 public class JsonHelper
    {
        #region 基本方法
        public static string ObjectToJSON(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Serialize(obj);  //Json对象转换为Json字符串
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }

        public static T JSONToObject<T>(string jsonText)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //使用C#的动态可以不创建实体类
                var obj = jss.Deserialize<dynamic>(jsonText);
                //调用:obj.Name
                
                return jss.Deserialize<T>(jsonText); //Json字符串转为Json对象
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
            }
        } 
        #endregion


        /// <summary> 
        /// 数据表转键值对集合 
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>哈希表数组</returns> 
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }
        /// <summary> 
        /// 数据集转键值对数组字典 
        /// </summary> 
        /// <param name="dataSet">数据集</param> 
        /// <returns>键值对数组字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();
            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));
            return result;
        }
        /// <summary> 
        /// 数据表转JSON 
        /// </summary> 
        /// <param name="dataTable">数据表</param> 
        /// <returns>JSON字符串</returns> 
        public static string DataTableToJSON(DataTable dt)
        {
            return ObjectToJSON(DataTableToList(dt));
        }

        /// <summary> 
        /// 将JSON文本转换为数据表数据 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据表字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
        }
        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns> 
        public static Dictionary<string, object> DataRowFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, object>>(jsonText);
        }

    }
JsonHelper
   public static class ConvertHelper<T> where T : new()
    {
        /// <summary>
        /// DateTable 转List
        /// </summary>
        /// <param name="dt"></param>
        public static List<T> ConvertToList(DataTable dt)
        {
            List<T> list = new List<T>();

            Type type = typeof(T);

            string tempName = string.Empty;

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();

                //获得公共属性,利用反射获得属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (var it in propertys)
                {
                    tempName = it.Name;

                    //是否包含某一列
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!it.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            //得到列的数据类型
                            string typ = it.GetGetMethod().ReturnType.Name.ToLower();
                            switch (typ)
                            {
                                case "int32":
                                    it.SetValue(t, Convert.ToInt32(value.ToString() == "" ? "0" : value) as object, null);
                                    break;
                                case "double":
                                    it.SetValue(t, Convert.ToDouble(value.ToString() == "" ? "0" : value) as object, null);
                                    break;
                                case "string":
                                    it.SetValue(t, value.ToString() as object, null);
                                    break;
                                case "decimal":
                                    it.SetValue(t, Convert.ToDecimal(value.ToString() == "" ? "0" : value) as object, null);
                                    break;
                                default:
                                    it.SetValue(t, value, null);
                                    break;
                            }
                        }
                    }
                }

                list.Add(t);
            }
            return list;
        }

    }
DataTable转为List

 实例:

//通用:
       public static string JavaScriptSerializer(object obj)
        {
            string jsonstring = "";
            if (obj != null)
            {
                JavaScriptSerializer serial = new JavaScriptSerializer();

                //设置最大序列化长度
                serial.MaxJsonLength = Int32.MaxValue;

                jsonstring = serial.Serialize(obj);

                //日期格式化,包括DateTime.MinValue、DateTime.MaxValue
                jsonstring = Regex.Replace(jsonstring, @"\\/Date[(](.*?)[)]\\/", match =>
                {
                    DateTime dt = new DateTime(1970, 1, 1);
                    dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                    dt = dt.ToLocalTime();
                    return dt.ToString("yyyy-MM-dd HH:mm:ss");
                });
            }
            return jsonstring;
        }


//调用:
        public string GetWeChatStatic()
        {
            GetWeChatSqlWhere();//sql和参数
            BaseJson json = new BaseJson
            {
                text = "{\"isYnYx \":\"" + Base.IsYnYx + "\",\"ltlTotal1\":\"" + GetExtraction() + "\",\"ltlTotal2\":\"" + GetIncome() + "\",\"ltlTotal3\":\"" + GetNewestMoney() + "\"}"
            };
            return JsonHelper.JavaScriptSerializer(json);
        }
View Code

* Url加密解密

前台js中:  

var exchangeName = $("#f_exchangeName option:selected").text();
$("#exchangeName").val(encodeURI(exchangeName));  //加密

后台C#中:

 string exchangeName = HttpUtility.UrlDecode(RequestKit.GetFormValue("exchangeName", "")).Trim(' ');

* XML读写

1、XDocument 读写参见博客:https://www.cnblogs.com/fengxuehuanlin/p/5631664.html

2、XmlDocument读写:

  - 介绍: xml看作由 【文档声明declare、元素Element、属性Attribute、文本Text】等构成的一颗树,最开始的一个叫根节点,每个节点都有自己的子节点,可以通过属性或方法得到节点的值或属性值。

  - 注意:元素和节点可以转换,XmlElement element = (XmlElement)node; 将节点转换为元素,便于得到元素的属性值

  eg:

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
  <!--记录书本的信息-->
  <book Type="必修课" ISBN="7-111-19149-2">
      <title>数据结构</title>
      <author>严蔚敏</author>
      <price>30.00</price>
  </book>
  <book Type="必修课" ISBN="7-111-19149-4">
      <title>计算机硬件技术基础</title>
      <author>李继灿</author>
      <price>25.00</price>
  </book>
</bookstore>
xml
    public class XmlHelper
    {
        #region 使用XMLDocument
        public static void GetXmlDocument()
        {
            XmlDocument doc = new XmlDocument();

            //添加读取xml文件时的约束
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;  //忽略掉注释

            //添加读取文件
            XmlReader reader = XmlReader.Create("../../xml/Book.xml", settings);
            doc.Load(reader);
            //读完后要关闭
            reader.Close(); 

            //得到根节点
            XmlNode root = doc.SelectSingleNode("bookstore");
            //得到根节点的所有子节点
            XmlNodeList childList = root.ChildNodes;

            List<BookMOD> list = new List<BookMOD>();
            //遍历子节点
            foreach(XmlNode node in childList)
            {
                //将节点转换为元素,便于得到元素的属性值
                XmlElement element = (XmlElement)node;

                BookMOD book = new BookMOD();
                //获得子节点的两个属性值
                book.BookISBN = element.GetAttribute("ISBN");  
                book.BookType = element.GetAttribute("Type");

                //得到子节点下的子节点
                XmlNodeList nodeList = element.ChildNodes;
                book.BookName = nodeList.Item(0).InnerText;
                book.BookAuthor = nodeList.Item(1).InnerText;
                book.Price = Convert.ToDouble(nodeList.Item(2).InnerText);

                list.Add(book);
            }

        }
        #endregion
    }
xmlHelper

  完整的参见博客https://blog.csdn.net/tiemufeng1122/article/details/6723764/

 

posted on 2018-07-17 14:48  莫伊筱筱  阅读(266)  评论(0编辑  收藏  举报