遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

一个错误记录类&一个序列化配置文件读取类

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);


        }

    }
    /// <summary>
    /// 参数
    /// </summary>
    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
{
    /// <summary>
    /// 管理对象序列化配置文件
    /// 对配置文件进行文件监视缓存
    /// 需要再根目录下存在/data/xml目录
    /// 使用类的FullName来保持
    /// 泛型类,使用最内部的类名表示
    /// 所以List~T
    /// 跟Stack~T 会对应同样的文件名
    /// 需要进行区分
    /// 如果你要要很多Name-value这样的数据要用List~T类型
    /// 建议将T加个TypeId,这样放到同个文件中,读出来后按Type,进行过滤
    /// 2013-07-08加入了目录检测
    /// </summary>
    public class XmlDataCfgMgr<T> 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<XmlDataCfgMgr<T>> _Lazy = new Lazy<XmlDataCfgMgr<T>>(() => 
        {
            return new XmlDataCfgMgr<T>();
        }, 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<DirectoryInfo> needCreatedDirs = new Stack<DirectoryInfo>();
            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;
        }

 

 

 

 

 

posted on 2013-05-16 14:55  遗忘海岸  阅读(233)  评论(0编辑  收藏  举报