using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SQLite; using System.IO; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using NLog; using NPoco; using POSV.Entity; using POSV.Utils; using System.Drawing.Printing; using POSV.Bean; using System.Windows.Forms; using System.Text; using POSV.HttpApi; using System.Runtime.InteropServices; using System.IO.Ports; using POSV.MsgCenter; using System.Configuration; using System.Drawing.Text; using System.Drawing; using System.ComponentModel; namespace POSV { public class Global { private static Logger logger = NLog.LogManager.GetCurrentClassLogger(); private static object _lock = new object(); private Dictionary _globalConfig = null; public List _productList = null; public List _productTypeList = null; public List _productSpecList = null; public List _kdsPlanList = null; public List _kitPlanList = null; private static Global _product = null; private static Global _productType = null; private static Global _productSpec = null; private static Global _KdsPlan = null; private static Global _KitPlan = null; private static Global _storeInfo = null; public StoreInfo StoreInfoMessage = null; private static Global _instance = null; /// /// 是否有要上传的销售数据 /// public static bool isHaveUpLoadTicket = true; /// /// 是否有要上传的耗料数据 /// public static bool isHaveBurdenTicket = true; /// /// 是否有要上传的交班数据 /// public static bool isHaveUpLoadShift = true; /// /// 是否有要上传的熟客数据 /// public static bool isHaveUpLoadVisitor = true; /// /// 是否有要上传的操作日志 /// public static bool isHaveUpLoadBusLog = true; /// /// 是否有要上传的非营业数据 /// public static bool isHaveUpLoadFyy = true; /// /// 是否有要同步到服务中心的销售数据 /// public static bool isHaveCenterTicket = true; /// /// 是否正在交班,交班过程中不接单 /// public static bool isHandOver = false; #region 20240309 subin 沽清同步至云平台 /// /// 是否通过沽清至云平台 /// public static bool isSale2Web = false; #endregion public static Global Product { get { if (_product == null) { lock (_lock) { _product = new Global(); //加载菜品 _product.InitProductExt(); logger.Info("加载菜品资料......"); } } return _product; } } public static Global ProductType { get { if (_productType == null) { lock (_lock) { _productType = new Global(); //加载菜品 _productType.InitProductTypeExt(); logger.Info("加载菜品资料......"); } } return _productType; } } public static Global KdsPlan { get { if (_KdsPlan == null) { lock (_lock) { _KdsPlan = new Global(); //加载厨显 _KdsPlan.InitKdsPlanExt(); logger.Info("加载厨显方案......"); } } return _KdsPlan; } } public static Global KitPlan { get { if (_KitPlan == null) { lock (_lock) { _KitPlan = new Global(); //加载菜品 _KitPlan.InitKitPlanExt(); logger.Info("加载厨打方案......"); } } return _KitPlan; } } public static Global ProductSpec { get { if (_productSpec == null) { lock (_lock) { _productSpec = new Global(); //加载菜品 _productSpec.InitProductSpec(); logger.Info("加载菜品资料......"); } } return _productSpec; } } public static Global StoreInfo { get { if (_storeInfo == null) { lock (_lock) { _storeInfo = new Global(); //加载门店信息 _storeInfo.InitStoreInfo(); logger.Info("加载菜品资料......"); } } return _storeInfo; } } public static Global Instance { get { if (_instance == null) { lock (_lock) { _instance = new Global(); _instance.InitConfig(); _instance.InitAuthc(); //加载菜品 //_instance.InitProductExt(); //加载商品规格 //_instance.InitProductSpec(); //加载门店信息 //_instance.InitStoreInfo(); //启动消息仓库 MsgDepot.Start(); logger.Info("加载全局配置参数......"); } } return _instance; } } private bool CheckFontExisting(string fontName = "微软雅黑") { Font font; try { font = new Font(fontName, 10); if (font.Name != fontName) { return false; } logger.Debug("加载系统字体<" + fontName + ">"); } catch (Exception ex) { logger.Error(ex, "无法加载系统字体<" + fontName + ">"); return false; } return true; } private void InitFont() { try { if (!this.CheckFontExisting()) { string fontPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"fonts/"); if (!Directory.Exists(fontPath)) { Directory.CreateDirectory(fontPath); } var fileNames = Directory.GetFiles(fontPath, "*.ttf").Where(t => t.ToLower().EndsWith(".ttf")).ToList(); foreach (var fileName in fileNames) { installFontIfNeeded(fileName); } } } catch { } } private void installFontIfNeeded(string fileName) { InstalledFontCollection fontsCollection = new InstalledFontCollection(); FontFamily[] fontFamilies = fontsCollection.Families; List fonts = new List(); //Install the font. int result = WindowsAPI.AddFontResource(fileName); int error = Marshal.GetLastWin32Error(); if (error != 0) { logger.Error(new Win32Exception(error).Message); } else { logger.Info((result == 0) ? "Font is already installed." : "Font installed successfully."); } } private void InitStoreInfo() { try { using (var db = Instance.OpenDataBase) { this.StoreInfoMessage = db.FirstOrDefault("where id = @0", Global.Instance.Authc.StoreId); } } catch (Exception ex) { logger.Error(ex, "加载门店信息失败"); } } private void InitProductTypeExt() { try { using (var db = Instance.OpenDataBase) { this._productTypeList = db.Fetch("select * from pos_product_type"); } if (this._productTypeList != null) { logger.Debug("获取菜品分类成功"); } else { this._productTypeList = new List(); } } catch (Exception ex) { logger.Error(ex, "加载菜品分类失败"); } } private void InitKdsPlanExt() { try { using (var db = Instance.OpenDataBase) { this._kdsPlanList = db.Fetch("select * from pos_kds_plan"); } if (this._kdsPlanList != null) { logger.Debug("获取厨显方案成功"); } else { this._kdsPlanList = new List(); } } catch (Exception ex) { logger.Error(ex, "获取厨显方案成功"); } } private void InitKitPlanExt() { try { using (var db = Instance.OpenDataBase) { this._kitPlanList = db.Fetch("select * from pos_kit_plan"); } } catch (Exception ex) { logger.Error(ex, "获取厨打方案发生异常"); } finally { if (this._kitPlanList == null) { this._kitPlanList = new List(); } } } private void InitProductExt() { try { using (var db = Instance.OpenDataBase) { //获取菜品排序方式 var productOrder = Global.Instance.GlobalConfigStringValue(ConfigConstant.CASHIER_PRODUCTORDER, "不排序"); var productOrderType = ProductOrderType.不排序; Enum.TryParse(productOrder, out productOrderType); switch (productOrderType) { case ProductOrderType.不排序: { this._productList = db.Fetch(SqlConstant.ProductExtAll); } break; case ProductOrderType.按编号: { this._productList = db.Fetch(SqlConstant.ProductExtAll + " order by p.no"); } break; case ProductOrderType.按价格: { this._productList = db.Fetch(SqlConstant.ProductExtAll + " order by p.price"); } break; case ProductOrderType.按名称: { this._productList = db.Fetch(SqlConstant.ProductExtAll + " order by p.name"); } break; } } if (this._productList != null) { logger.Debug("获取菜品成功"); } else { this._productList = new List(); } } catch (Exception ex) { logger.Error(ex, "加载菜品失败"); } } private void InitProductSpec() { try { using (var db = Instance.OpenDataBase) { this._productSpecList = db.Query().ToList(); } if (this._productSpecList != null) { logger.Debug("获取菜品成功"); } else { this._productSpecList = new List(); } } catch (Exception ex) { logger.Error(ex, "加载菜品失败"); } } private void InitAuthc() { Authc authc = null; lock (Instance.SyncLock) { using (var db = _instance.OpenDataBase) { var lists = db.Query().ToList(); if (lists != null && lists.Count > 0) { authc = lists.First(); } } } _instance.Authc = authc; } /// /// 餐饮的版本标识 /// public string AppSign { get { return "cy2"; } } /// /// 重启程序标识 /// 需要配合 /// Application.ExitThread(); /// public bool Restart { get; set; } = false; /// /// 来电猫工作端口 /// public List Cats { get; set; } public Database OpenDataBase { get { return new PosDatabase(Instance.SQLiteConnectionString, DatabaseType.SQLite, SQLiteFactory.Instance); } } /// /// 构建Sqlite连接字符串 /// public string SQLiteConnectionString { get { SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder(); builder.DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"data\posv2.s3db"); //builder.Password = "passwd"; builder.Version = 3; builder.CacheSize = 4000; builder.DefaultTimeout = 5000; //builder.PageSize = 4096; builder.FailIfMissing = false; builder.Pooling = true; builder.SyncMode = SynchronizationModes.Normal; builder.JournalMode = SQLiteJournalModeEnum.Wal; return builder.ToString(); } } /// /// 商品信息附加符号前缀和后缀 /// public Tuple Additional { get { var result = new Tuple("[", "]"); var additional = Global.Instance.GlobalConfigStringValue(ConfigConstant.CASHIER_ADDITIONAL, "方括号"); var additionalType = AdditionalType.方括号; Enum.TryParse(additional, out additionalType); switch (additionalType) { case AdditionalType.不填充: { result = new Tuple("", ""); } break; case AdditionalType.方括号: { result = new Tuple("[", "]"); } break; case AdditionalType.圆括号: { result = new Tuple("(", ")"); } break; case AdditionalType.花括号: { result = new Tuple("{", "}"); } break; case AdditionalType.六角括号: { result = new Tuple("〔", "〕"); } break; case AdditionalType.方头括号: { result = new Tuple("【", "】"); } break; } return result; } } private void InitConfig() { try { using (var db = Instance.OpenDataBase) { this._globalConfig = db.Dictionary(SqlConstant.ConfigQueryAllToDictionary); } if (this._globalConfig != null) { logger.Debug("获取系统默认参数成功..."); } else { this._globalConfig = new Dictionary(); } } catch (Exception ex) { logger.Error(ex, "加载系统全局配置异常"); } } /// /// 全部重载 /// public void ReloadConfig() { this.InitConfig(); } public void ReloadConfig(string group) { lock (Instance.SyncLock) { try { using (var db = Instance.OpenDataBase) { string sql = string.Format(SqlConstant.ConfigQueryByGroupToDictionary, group); var config = db.Dictionary(sql); if (config != null) { foreach (var c in config) { this._globalConfig[c.Key] = c.Value; if (logger.IsDebugEnabled) { logger.Debug(c.Key + "=" + c.Value); } } logger.Debug("获取<" + group + ">参数成功..."); } } } catch (Exception ex) { logger.Error(ex, "加载系统<" + group + ">组配置异常"); } } } public string AliPayServerUrl { get; set; } = "https://openapi.alipay.com/gateway.do"; /// /// 通用操作锁 /// public object SyncLock = new object(); /// /// 缓存操作锁 /// public object CacheLock = new object(); /// /// 来电猫数据接收锁 /// public object CatLock = new object(); /// /// POS机本地认证信息 /// public Authc Authc { get; set; } /// /// 收银员登录信息 /// public Worker Worker { get; set; } /// /// 当前班次信息 /// public BusinessPlanLog BusinessPlanLog { get; set; } /// /// 门店营业方案 /// public BusinessPlan BusinessPlan { get; set; } /// /// 判读是否有权限 /// /// /// public bool HasPermission(string moduleNo) { if (string.IsNullOrEmpty(moduleNo)) { return true; } return this.Worker != null && Global.Instance.Worker.Permission != null && Global.Instance.Worker.Permission.Contains(moduleNo); } /// /// 当前是否为练习模式 /// /// public bool IsStudyMode() { return GlobalConfigBoolValue(ConfigConstant.CONFIG_CASHIER_ENABLESTUDYMODE, false); } public Tuple EnableServiceCenter { get { bool enabled = Instance.GlobalConfigBoolValue(ConfigConstant.DEVICE_SERVICECENTER_ENABLE, false); if (enabled) { string host = Instance.GlobalConfigStringValue(ConfigConstant.DEVICE_SERVICECENTER_IP, string.Empty); int port = Instance.GlobalConfigIntValue(ConfigConstant.DEVICE_SERVICECENTER_PORT, 0); if (string.IsNullOrEmpty(host) || port == 0) { return new Tuple(false, "消息中心参数配置不正确!", string.Empty, 0); } else { return new Tuple(true, "消息中心参数配置正确!", host, port); } } else { return new Tuple(false, "消息中心尚未启用", string.Empty, 0); } } } /// /// 是否联机 /// public bool Online { get; set; } /// /// 是否WiFi网络 /// public bool IsWiFi { get; set; } /// /// 是否登录成功 /// public bool IsLogin { get; set; } = false; /// /// 是否到期 /// public bool AuthLogin { get; set; } = true; /// /// 是否连接消息中心 /// public Tuple MessageCenterOnline { get; set; } /// /// 是否允许上传数据 /// public bool AllowUpload { get; set; } = true; /// /// 是否启用副屏 /// public bool EnableVice { get; set; } = false; /// /// 加载配置参数,返回Bool类型 /// /// /// public bool GlobalConfigBoolValue(string keys) { string value = GlobalConfigStringValue(keys, string.Empty); return "1".Equals(value); } public bool GlobalConfigBoolValue(string keys, bool defaultValue) { if (this._globalConfig.ContainsKey(keys)) { string value = this._globalConfig[keys]; return "1".Equals(value); } else { return defaultValue; } } /// /// 加载配置参数,返回String类型 /// /// /// public string GlobalConfigStringValue(string keys) { return GlobalConfigStringValue(keys, string.Empty); } public string GlobalConfigStringValue(string keys, string defaultValue) { if (this._globalConfig.ContainsKey(keys)) { return this._globalConfig[keys]; } else { return defaultValue; } } /// /// 加载配置参数,返回Int类型 /// /// /// public int GlobalConfigIntValue(string keys) { return GlobalConfigIntValue(keys, 0); } public int GlobalConfigIntValue(string keys, int defaultValue) { if (this._globalConfig.ContainsKey(keys)) { int result = defaultValue; int.TryParse(this._globalConfig[keys], out result); return result; } else { return defaultValue; } } public List AvailablePrinters { get { List printers = new List(); try { var document = new PrintDocument(); string defaultPrinter = document.PrinterSettings.PrinterName; if (!string.IsNullOrEmpty(defaultPrinter)) { printers.Add(defaultPrinter); //默认打印机始终出现在列表的第一项 } foreach (string printerName in PrinterSettings.InstalledPrinters) { if (!printers.Contains(printerName)) { printers.Add(printerName); } } if (printers.Count > 0) { printers.Add("None"); } } catch { } return printers; } } public static string GetValueFromConfig(string key) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //获取AppSettings的节点 AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings"); return appsection.Settings[key].Value; } catch { return "公版"; } } public bool IsRegisted() { //先比较Mac地址 var localMacAddress = new List(); localMacAddress.AddRange(DeviceUtils.Instance.MacAddress.Split(',')); //数据库存住的特征值 var dbMacAddress = new List(); if (Global.Instance.Authc != null && !string.IsNullOrEmpty(Global.Instance.Authc.MacAddress)) { dbMacAddress.AddRange(Global.Instance.Authc.MacAddress.Split(',')); } //Mac地址匹配至少1项,视为一个数量的硬件匹配 var flag = localMacAddress.Intersect(dbMacAddress).Count() > 0 ? 1 : 0; //取本地计算机的特征值 var local = new List(); local.AddRange(DeviceUtils.Instance.ComputerName.Split(',')); local.AddRange(DeviceUtils.Instance.CpuID.Split(',')); local.AddRange(DeviceUtils.Instance.DiskID.Split(',')); var db = new List(); if (Global.Instance.Authc != null) { if (!string.IsNullOrEmpty(Global.Instance.Authc.CompterName)) { db.AddRange(Global.Instance.Authc.CompterName.Split(',')); } if (!string.IsNullOrEmpty(Global.Instance.Authc.CpuSerialNumber)) { db.AddRange(Global.Instance.Authc.CpuSerialNumber.Split(',')); } if (!string.IsNullOrEmpty(Global.Instance.Authc.DiskSerialNumber)) { db.AddRange(Global.Instance.Authc.DiskSerialNumber.Split(',')); } } return (local.Intersect(db).Count() + flag) >= 3; } /// /// 打印机参数初始默认值 /// /// public PrinterItem GetDefaultPrinterItem() { var printer = new PrinterItem(); printer.Id = "None"; printer.Name = "None"; printer.Port = "None"; var data = new Dictionary(); data.Add(Constant.COM_PORT_NAME, "COM1"); data.Add(Constant.COM_PORT_BAUD, "19200"); data.Add(Constant.LPT_NAME, "LPT1"); data.Add(Constant.USB_PID, "0"); data.Add(Constant.USB_VID, "0"); data.Add(Constant.NET_IP_ADDRESS, "127.0.0.1"); data.Add(Constant.DRIVE_NAME, "None"); printer.Data = data; printer.DynamicLibrary = "通用打印模式"; printer.Type = 1; printer.InitCommand = "27,64"; printer.NormalCommand = "27,33,0,28,33,0"; printer.DoubleHeightCommand = "27,33,16,28,33,8"; printer.DoubleWidthCommand = "27,33,32,28,33,4"; printer.DoubleWidthHeightCommand = "27,33,48,28,33,12"; printer.CutPageCommand = "29,86,66"; printer.CashboxCommand = "27,112,0,100,100"; printer.UserDefined = 0; printer.PageWidth = 58; printer.AlignCenterCommand = "27,97,49"; printer.AlignLeftCommand = "27,97,48"; printer.AlignRightCommand = "27,97,50"; return printer; } /// /// 标签打印机参数初始默认值 /// /// public PrinterItem GetDefaultLabelPrinterItem() { var printer = new PrinterItem(); printer.Id = "None"; printer.Name = "None"; printer.Port = "None"; var data = new Dictionary(); data.Add(Constant.COM_PORT_NAME, "COM1"); data.Add(Constant.COM_PORT_BAUD, "19200"); data.Add(Constant.LPT_NAME, "LPT1"); data.Add(Constant.USB_PID, "0"); data.Add(Constant.USB_VID, "0"); data.Add(Constant.NET_IP_ADDRESS, "127.0.0.1"); data.Add(Constant.DRIVE_NAME, "None"); printer.Data = data; printer.AlignCenterCommand = "27,97,49"; printer.AlignLeftCommand = "27,97,48"; printer.AlignRightCommand = "27,97,50"; printer.DynamicLibrary = "通用打印模式"; printer.Type = 1; printer.Dpi = 203; printer.UserDefined = 0; return printer; } /// /// 通用标签打印机参数初始默认值 /// /// public PrinterItem GetNormalDefaultLabelPrinterItem() { var printer = new PrinterItem(); printer.Id = "None"; printer.Name = "通用标签打印机"; printer.Port = "None"; var data = new Dictionary(); data.Add(Constant.COM_PORT_NAME, "COM1"); data.Add(Constant.COM_PORT_BAUD, "19200"); data.Add(Constant.LPT_NAME, "LPT1"); data.Add(Constant.USB_PID, "0"); data.Add(Constant.USB_VID, "0"); data.Add(Constant.NET_IP_ADDRESS, "127.0.0.1"); data.Add(Constant.DRIVE_NAME, "None"); printer.Data = data; printer.AlignCenterCommand = "27,97,49"; printer.AlignLeftCommand = "27,97,48"; printer.AlignRightCommand = "27,97,50"; printer.DynamicLibrary = "通用打印模式"; printer.Type = 1; printer.Dpi = 203; printer.UserDefined = 0; return printer; } /// /// 获取客显默认设置 /// /// public GuestShowItem GetDefaultGuestShowItem() { var showItem = new GuestShowItem(); showItem.Name = "None"; showItem.Port = "None"; var param = new GuestShowParameter(); param.InitCmd = "27,64"; param.R1DisplayCmd = "27,81,65,d,13"; showItem.Parameter = param; return showItem; } /// /// 打印机参数初始默认值 /// /// public KitchenPrinterItem GetDefaultKitchenPrinterItem() { var printer = new KitchenPrinterItem(); printer.KitId = "None"; printer.KitType = 0; printer.PrinterItem = GetDefaultPrinterItem(); return printer; } /// /// 厨显默认值 /// /// public KitchenDisplayItem GetDefaultKitchenDisplayItem() { var display = new KitchenDisplayItem(); display.PlanId = "None"; display.KdsNo = "None"; return display; } public string GetKitchenTypeName(string typeNo) { string typeName = "一菜一单"; switch (typeNo) { case "1": { typeName = "一小类一单"; } break; case "2": { typeName = "一桌一单"; } break; case "0": default: { typeName = "一菜一单"; } break; } return typeName; } public void BugReport(Exception e) { BugReport(e, "自动收集错误"); } public void BugReport(Exception e, string title) { if(string.Compare(Application.ProductVersion,"1.0.1") > 0) { return; } string errorLog = GetExceptionInfo(e, title); logger.Error(errorLog); if (!Global.Instance.Online) { return; } try { string tenantId = Global.Instance.Authc.TenantId; string branchNo = Global.Instance.Authc.StoreNo; string posNo = Global.Instance.Authc.PosNo; //调用业务系统开放平台 var api = OpenApiUtils.Instance.NextApi(ApiType.Business); //构建请求参数 SortedList parameters = new SortedList(); parameters.Add("type", "poserrorlog"); parameters.Add("terminalType", Constant.TERMINAL_TYPE); parameters.Add("appSign", Constant.APP_SIGN); parameters.Add("versionType", "1"); parameters.Add("versionNum", Application.ProductVersion); parameters.Add("tenantId", Global.Instance.Authc.TenantId); parameters.Add("storeNo", Global.Instance.Authc.StoreNo); parameters.Add("osName", DeviceUtils.GetSystemType()); parameters.Add("posNo", Global.Instance.Authc.PosNo); parameters.Add("info", title); parameters.Add("errorLog", errorLog); HttpClientUtils.PostAsync(api, api.Open, parameters); } catch (Exception ex) { logger.Error(ex, "异常上报错误"); } } static string GetExceptionInfo(Exception e, string title) { string ExceptionName = e.GetType().Name; StringBuilder sb = new StringBuilder(); sb.Append("---------------------Header-----------------"); sb.Append(Environment.NewLine); sb.Append("" + title + "\n"); sb.Append(Environment.NewLine); sb.Append("<" + ExceptionName + ">\n"); sb.Append(Environment.NewLine); sb.Append("" + DateTime.Now.ToString() + "\n"); sb.Append(Environment.NewLine); sb.Append("" + System.Net.WebUtility.HtmlEncode(e.Message) + "\n"); sb.Append(Environment.NewLine); if (e.Source != null) { sb.Append("" + e.Source + "\n"); sb.Append(Environment.NewLine); } if (e.StackTrace != null) { sb.Append("" + e.StackTrace + "\n"); sb.Append(Environment.NewLine); } if (e.InnerException != null) { sb.Append("" + System.Net.WebUtility.HtmlEncode(e.InnerException.ToString()) + "\n"); sb.Append(Environment.NewLine); } sb.Append("" + e.TargetSite + "\n"); sb.Append(Environment.NewLine); sb.Append("\n"); sb.Append(Environment.NewLine); sb.Append("---------------------Footer-----------------"); sb.Append(Environment.NewLine); return sb.ToString(); } [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); /// /// 释放内存 /// public static void ClearMemory() { try { GC.Collect(); GC.WaitForPendingFinalizers(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1); } logger.Info("清理内存......"); } catch (Exception ex) { logger.Error(ex, "清理内存异常"); } } #region subin 2023-07-24 add 分账信息 /// /// 是否有要上传的销售分账数据 /// public static bool isHaveUpLoadSplitPay = true; #endregion } public class NewtonsoftJsonColumnSerializer : IColumnSerializer { public JsonSerializerSettings SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat, DateFormatString = "yyyy-MM-dd HH:mm:ss", NullValueHandling = NullValueHandling.Ignore }; public string Serialize(object value) { return JsonConvert.SerializeObject(value, SerializerSettings); } public object Deserialize(string value, Type targetType) { return JsonConvert.DeserializeObject(value, targetType, SerializerSettings); } } public class PosDatabase : Database { private static Logger logger = NLog.LogManager.GetCurrentClassLogger(); public PosDatabase(string connectionString, DatabaseType dbType, DbProviderFactory provider) : base(connectionString, dbType, provider) { DatabaseFactory.ColumnSerializer = new NewtonsoftJsonColumnSerializer(); } protected override void OnExecutedCommand(DbCommand cmd) { base.OnExecutedCommand(cmd); } protected override void OnExecutingCommand(DbCommand cmd) { base.OnExecutingCommand(cmd); logger.Trace(FormatCommand(cmd)); } protected override bool OnInserting(InsertContext insertContext) { var entity = insertContext.Poco as BaseEntity; if (entity != null) { if (string.IsNullOrEmpty(entity.Id)) { entity.Id = IdWorkerUtils.Instance.NextId(); } entity.CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); entity.CreateUser = Constant.DEFAULT_SYNC_USER; } return base.OnInserting(insertContext); } protected override bool OnUpdating(UpdateContext updateContext) { var entity = updateContext.Poco as BaseEntity; if (entity != null) { entity.ModifyDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); entity.ModifyUser = Constant.DEFAULT_SYNC_USER; } return base.OnUpdating(updateContext); } } }