Common公用类

* web.config缓存

1. Web.config中的中添加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();
        }

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

        /// 
        /// 获取指定的Cache
        /// 
        /// 
        /// 
        private static Object GetCache(string key)
        {
            Cache objCache = HttpRuntime.Cache;
            return objCache[key];
        }
        #endregion

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

        /// 
        /// 通用实例2,通用方法
        /// 调用:var s2 = ConfigHelper.GetValueByKey("keycode");
        /// 
        /// 
        /// 
        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(string jsonText)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //使用C#的动态可以不创建实体类
                var obj = jss.Deserialize<dynamic>(jsonText);
                //调用:obj.Name
                
                return jss.Deserialize(jsonText); //Json字符串转为Json对象
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
            }
        } 
        #endregion


        ///  
        /// 数据表转键值对集合 
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        ///  
        /// 数据表 
        /// 哈希表数组 
        public static Liststring, object>> DataTableToList(DataTable dt)
        {
            Liststring, object>> list = new Liststring, 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;
        }
        ///  
        /// 数据集转键值对数组字典 
        ///  
        /// 数据集 
        /// 键值对数组字典 
        public static Dictionary<string, Liststring, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, Liststring, object>>> result = new Dictionary<string, Liststring, object>>>();
            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));
            return result;
        }
        ///  
        /// 数据表转JSON 
        ///  
        /// 数据表 
        /// JSON字符串 
        public static string DataTableToJSON(DataTable dt)
        {
            return ObjectToJSON(DataTableToList(dt));
        }

        ///  
        /// 将JSON文本转换为数据表数据 
        ///  
        /// JSON文本 
        /// 数据表字典 
        public static Dictionary<string, Liststring, object>>> TablesDataFromJSON(string jsonText)
        {
            return JSONToObjectstring, Liststring, object>>>>(jsonText);
        }
        ///  
        /// 将JSON文本转换成数据行 
        ///  
        /// JSON文本 
        /// 数据行的字典 
        public static Dictionary<string, object> DataRowFromJSON(string jsonText)
        {
            return JSONToObjectstring, object>>(jsonText);
        }

    }
JsonHelper
   public static class ConvertHelper where T : new()
    {
        /// 
        /// DateTable 转List
        /// 
        /// 
        public static List ConvertToList(DataTable dt)
        {
            List list = new List();

            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.00price>
  book>
  <book Type="必修课" ISBN="7-111-19149-4">
      <title>计算机硬件技术基础title>
      <author>李继灿author>
      <price>25.00price>
  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 list = new List();
            //遍历子节点
            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/

 

转载于:https://www.cnblogs.com/SmileSunday/p/9323314.html

你可能感兴趣的:(Common公用类)