遗忘海岸

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

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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

复制代码
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   遗忘海岸  阅读(234)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示