博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个错误记录类&一个序列化配置文件读取类
阅读量:6367 次
发布时间:2019-06-23

本文共 6198 字,大约阅读时间需要 20 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace PDAJob.PDAService.Service{    using EFModel;    using System.Xml.Serialization;    using System.Text;    using System.IO;    using System.Diagnostics;    public class ErrLogMgr    {        public static void Log(string msg, params CallParam[] args)        {            StackFrame sf = new StackFrame(1);            var methodInfo = sf.GetMethod();            var fname = methodInfo.DeclaringType.FullName +"->" + methodInfo.Name;            Action act = () =>            {                using (var ctx = DBCtx.NewCtx())                {                    try                    {                           string argsStr = "";                        if (args.Length > 0)                        {                            argsStr = args.Aggregate("", (total, ent) => total +=ent +",").TrimEnd(",".ToCharArray());                        }                        var logEntry = new KB_Lable_Log();                        logEntry.LogType = 44;                        logEntry.AddTime = DateTime.Now;                        logEntry.Msg = string.Format("Func:{2},Err:{0},Params:{1}", msg, argsStr,fname);                        ctx.KB_Lable_Log.AddObject(logEntry);                        ctx.SaveChanges();                    }                    catch { }                }            };            act.BeginInvoke(null, null);        }    }    ///     /// 参数    ///     public class CallParam    {        public CallParam() { }        public CallParam(string name, object value)        {            this.Name = name;            this.Value = value;        }        public string Name { get; set; }        public object Value { get; set; }        public override string ToString()        {            return   string.Format("n$:{0}->v$:{1}", this.Name, ConverToStr(this.Value));        }        private static string ConverToStr(object obj)        {            if (obj == null) return string.Empty;            if (obj.GetType().IsPrimitive || obj is string)            {                return obj.ToString();            }            if (IsNullable(obj.GetType()))            {                return obj.ToString();            }            //执行xml序列化            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());            StringBuilder sb = new StringBuilder();            using (var sw = new StringWriter(sb))            {                xmlSerializer.Serialize(sw, obj);            }            return sb.ToString();        }        private static bool IsNullable(Type t)        {            return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>);        }    }}
View Code

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Xml.Serialization;using System.Text;using System.IO;using System.Web.Caching;namespace F.Studio.Common.Cfg{    ///     /// 管理对象序列化配置文件    /// 对配置文件进行文件监视缓存    /// 需要再根目录下存在/data/xml目录    /// 使用类的FullName来保持    /// 泛型类,使用最内部的类名表示    /// 所以List~T    /// 跟Stack~T 会对应同样的文件名    /// 需要进行区分    /// 如果你要要很多Name-value这样的数据要用List~T类型    /// 建议将T加个TypeId,这样放到同个文件中,读出来后按Type,进行过滤    /// 2013-07-08加入了目录检测    ///     public class XmlDataCfgMgr
where T:class { private static readonly string _Dir=@"data/xml/"; private static readonly string _CacheKey = "XmlDataCfgCacheKey"; public string CacheKey { get { return _CacheKey + FileName; } } public string FileName { get { var t = typeof(T); while (t.IsGenericType) { var a = t.GetGenericArguments(); if (a.Length > 0) t = a[0]; } //这里,_Dir清明不要有/或\ return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _Dir + t.FullName + ".xml"); } } private XmlDataCfgMgr() { } private static Lazy
> _Lazy = new Lazy
>(() => { return new XmlDataCfgMgr
(); }, true); public static T GetV(T def) { return _Lazy.Value.Get(def); } public static string SaveV(T obj) { return _Lazy.Value.Save(obj); } public T Get(T def) { var item = HttpRuntime.Cache[CacheKey] as T; if (item == null) { lock (this) { item = HttpRuntime.Cache[CacheKey] as T; if (item == null) { item = Deserializer(); var monitorFilename = FileName; try { var fileCacheDep = new CacheDependency(monitorFilename); System.Web.HttpRuntime.Cache.Add(CacheKey, item, fileCacheDep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null); } catch (Exception) { }; } } //Console.WriteLine("读取文件!"); } if (item == null) return def; return item; } private T Deserializer() { T obj = null; try { var xml = LoadContent().Trim(); if (string.IsNullOrEmpty(xml)) return null; XmlSerializer serializer = new XmlSerializer(typeof(T)); using (var sr = new StringReader(xml)) { obj = serializer.Deserialize(new StringReader(xml)) as T; } } catch { } return obj; } private string LoadContent() { if (!File.Exists(FileName)) { return string.Empty; } try { var content = File.ReadAllText(FileName); return content; } catch (Exception) { return string.Empty; } } public string Save(T obj) { //执行xml序列化 var type = typeof(T); XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); StringBuilder sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { xmlSerializer.Serialize(sw, obj); } #region 确保目录存在 DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(FileName)); var dir = dirInfo; Stack
needCreatedDirs = new Stack
(); while (!dir.Exists) { needCreatedDirs.Push(dir); dir = dir.Parent; } while (needCreatedDirs.Count > 0) { needCreatedDirs.Pop().Create(); } #endregion File.WriteAllText(FileName, sb.ToString()); return sb.ToString(); } }}
View Code

//=========可空类型的泛型参数==============        

protected object getV<T>(Nullable<T> v) where T : struct

        {
            if (v.HasValue) return v;
            return DBNull.Value;
        }

 

 

 

 

 

转载地址:http://erema.baihongyu.com/

你可能感兴趣的文章
kpvalidate开辟验证组件,通用Java Web请求服务器端数据验证组件
查看>>
用Chart控件绘制动态图表
查看>>
数字信号处理之低通滤波器设计
查看>>
Learning Cocos2d-x for WP8(3)——文字篇
查看>>
转 AngularJS 2.0将面向移动应用并放弃旧浏览器
查看>>
Leetcode: Swap Nodes in Pairs
查看>>
学习《Hardware-Efficient Bilateral Filtering for Stereo Matching》一文笔记。
查看>>
webservice2
查看>>
求最大公约数和小于n的所有质数
查看>>
Length of Last Word
查看>>
NFS(Network File System)服务配置和使用
查看>>
开源的PaaS方案:在OpenStack上部署CloudFoundry (五)常见问题
查看>>
java 字符串格式化
查看>>
支付宝申请到编码流程
查看>>
ZOJ 3872--解题报告
查看>>
为什么整个互联网行业都缺前端工程师?
查看>>
《GK101任意波发生器》升级固件发布(版本:1.0.2build851)
查看>>
Centos6.4下安装protobuf及简单使用
查看>>
android代码签名和混乱的包装
查看>>
JS插件之——ztree
查看>>