You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1364 lines
41 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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<string, string> _globalConfig = null;
public List<ProductExt> _productList = null;
public List<ProductType> _productTypeList = null;
public List<ProductSpec> _productSpecList = null;
public List<KdsPlan> _kdsPlanList = null;
public List<KitPlan> _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;
/// <summary>
/// 是否有要上传的销售数据
/// </summary>
public static bool isHaveUpLoadTicket = true;
/// <summary>
/// 是否有要上传的耗料数据
/// </summary>
public static bool isHaveBurdenTicket = true;
/// <summary>
/// 是否有要上传的交班数据
/// </summary>
public static bool isHaveUpLoadShift = true;
/// <summary>
/// 是否有要上传的熟客数据
/// </summary>
public static bool isHaveUpLoadVisitor = true;
/// <summary>
/// 是否有要上传的操作日志
/// </summary>
public static bool isHaveUpLoadBusLog = true;
/// <summary>
/// 是否有要上传的非营业数据
/// </summary>
public static bool isHaveUpLoadFyy = true;
/// <summary>
/// 是否有要同步到服务中心的销售数据
/// </summary>
public static bool isHaveCenterTicket = true;
/// <summary>
/// 是否正在交班,交班过程中不接单
/// </summary>
public static bool isHandOver = false;
#region 20240309 subin 沽清同步至云平台
/// <summary>
/// 是否通过沽清至云平台
/// </summary>
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<string> fonts = new List<string>();
//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<StoreInfo>("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<ProductType>("select * from pos_product_type");
}
if (this._productTypeList != null)
{
logger.Debug("获取菜品分类成功");
}
else
{
this._productTypeList = new List<ProductType>();
}
}
catch (Exception ex)
{
logger.Error(ex, "加载菜品分类失败");
}
}
private void InitKdsPlanExt()
{
try
{
using (var db = Instance.OpenDataBase)
{
this._kdsPlanList = db.Fetch<KdsPlan>("select * from pos_kds_plan");
}
if (this._kdsPlanList != null)
{
logger.Debug("获取厨显方案成功");
}
else
{
this._kdsPlanList = new List<KdsPlan>();
}
}
catch (Exception ex)
{
logger.Error(ex, "获取厨显方案成功");
}
}
private void InitKitPlanExt()
{
try
{
using (var db = Instance.OpenDataBase)
{
this._kitPlanList = db.Fetch<KitPlan>("select * from pos_kit_plan");
}
}
catch (Exception ex)
{
logger.Error(ex, "获取厨打方案发生异常");
}
finally
{
if (this._kitPlanList == null)
{
this._kitPlanList = new List<KitPlan>();
}
}
}
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<ProductExt>(SqlConstant.ProductExtAll);
}
break;
case ProductOrderType.:
{
this._productList = db.Fetch<ProductExt>(SqlConstant.ProductExtAll + " order by p.no");
}
break;
case ProductOrderType.:
{
this._productList = db.Fetch<ProductExt>(SqlConstant.ProductExtAll + " order by p.price");
}
break;
case ProductOrderType.:
{
this._productList = db.Fetch<ProductExt>(SqlConstant.ProductExtAll + " order by p.name");
}
break;
}
}
if (this._productList != null)
{
logger.Debug("获取菜品成功");
}
else
{
this._productList = new List<ProductExt>();
}
}
catch (Exception ex)
{
logger.Error(ex, "加载菜品失败");
}
}
private void InitProductSpec()
{
try
{
using (var db = Instance.OpenDataBase)
{
this._productSpecList = db.Query<ProductSpec>().ToList();
}
if (this._productSpecList != null)
{
logger.Debug("获取菜品成功");
}
else
{
this._productSpecList = new List<ProductSpec>();
}
}
catch (Exception ex)
{
logger.Error(ex, "加载菜品失败");
}
}
private void InitAuthc()
{
Authc authc = null;
lock (Instance.SyncLock)
{
using (var db = _instance.OpenDataBase)
{
var lists = db.Query<Authc>().ToList();
if (lists != null && lists.Count > 0)
{
authc = lists.First();
}
}
}
_instance.Authc = authc;
}
/// <summary>
/// 餐饮的版本标识
/// </summary>
public string AppSign { get { return "cy2"; } }
/// <summary>
/// 重启程序标识
/// 需要配合
/// Application.ExitThread();
/// </summary>
public bool Restart { get; set; } = false;
/// <summary>
/// 来电猫工作端口
/// </summary>
public List<SerialPort> Cats { get; set; }
public Database OpenDataBase
{
get
{
return new PosDatabase(Instance.SQLiteConnectionString, DatabaseType.SQLite, SQLiteFactory.Instance);
}
}
/// <summary>
/// 构建Sqlite连接字符串
/// </summary>
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();
}
}
/// <summary>
/// 商品信息附加符号前缀和后缀
/// </summary>
public Tuple<string, string> Additional
{
get
{
var result = new Tuple<string, string>("[", "]");
var additional = Global.Instance.GlobalConfigStringValue(ConfigConstant.CASHIER_ADDITIONAL, "方括号");
var additionalType = AdditionalType.;
Enum.TryParse(additional, out additionalType);
switch (additionalType)
{
case AdditionalType.:
{
result = new Tuple<string, string>("", "");
}
break;
case AdditionalType.:
{
result = new Tuple<string, string>("[", "]");
}
break;
case AdditionalType.:
{
result = new Tuple<string, string>("(", ")");
}
break;
case AdditionalType.:
{
result = new Tuple<string, string>("{", "}");
}
break;
case AdditionalType.:
{
result = new Tuple<string, string>("", "");
}
break;
case AdditionalType.:
{
result = new Tuple<string, string>("【", "】");
}
break;
}
return result;
}
}
private void InitConfig()
{
try
{
using (var db = Instance.OpenDataBase)
{
this._globalConfig = db.Dictionary<string, string>(SqlConstant.ConfigQueryAllToDictionary);
}
if (this._globalConfig != null)
{
logger.Debug("获取系统默认参数成功...");
}
else
{
this._globalConfig = new Dictionary<string, string>();
}
}
catch (Exception ex)
{
logger.Error(ex, "加载系统全局配置异常");
}
}
/// <summary>
/// 全部重载
/// </summary>
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<string, string>(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";
/// <summary>
/// 通用操作锁
/// </summary>
public object SyncLock = new object();
/// <summary>
/// 缓存操作锁
/// </summary>
public object CacheLock = new object();
/// <summary>
/// 来电猫数据接收锁
/// </summary>
public object CatLock = new object();
/// <summary>
/// POS机本地认证信息
/// </summary>
public Authc Authc { get; set; }
/// <summary>
/// 收银员登录信息
/// </summary>
public Worker Worker { get; set; }
/// <summary>
/// 当前班次信息
/// </summary>
public BusinessPlanLog BusinessPlanLog { get; set; }
/// <summary>
/// 门店营业方案
/// </summary>
public BusinessPlan BusinessPlan { get; set; }
/// <summary>
/// 判读是否有权限
/// </summary>
/// <param name="moduleNo"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 当前是否为练习模式
/// </summary>
/// <returns></returns>
public bool IsStudyMode()
{
return GlobalConfigBoolValue(ConfigConstant.CONFIG_CASHIER_ENABLESTUDYMODE, false);
}
public Tuple<bool, string, string, int> 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<bool, string, string, int>(false, "消息中心参数配置不正确!", string.Empty, 0);
}
else
{
return new Tuple<bool, string, string, int>(true, "消息中心参数配置正确!", host, port);
}
}
else
{
return new Tuple<bool, string, string, int>(false, "消息中心尚未启用", string.Empty, 0);
}
}
}
/// <summary>
/// 是否联机
/// </summary>
public bool Online { get; set; }
/// <summary>
/// 是否WiFi网络
/// </summary>
public bool IsWiFi { get; set; }
/// <summary>
/// 是否登录成功
/// </summary>
public bool IsLogin { get; set; } = false;
/// <summary>
/// 是否到期
/// </summary>
public bool AuthLogin { get; set; } = true;
/// <summary>
/// 是否连接消息中心
/// </summary>
public Tuple<bool, bool> MessageCenterOnline { get; set; }
/// <summary>
/// 是否允许上传数据
/// </summary>
public bool AllowUpload { get; set; } = true;
/// <summary>
/// 是否启用副屏
/// </summary>
public bool EnableVice { get; set; } = false;
/// <summary>
/// 加载配置参数返回Bool类型
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 加载配置参数返回String类型
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 加载配置参数返回Int类型
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
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<string> AvailablePrinters
{
get
{
List<string> printers = new List<string>();
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<string>();
localMacAddress.AddRange(DeviceUtils.Instance.MacAddress.Split(','));
//数据库存住的特征值
var dbMacAddress = new List<string>();
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<string>();
local.AddRange(DeviceUtils.Instance.ComputerName.Split(','));
local.AddRange(DeviceUtils.Instance.CpuID.Split(','));
local.AddRange(DeviceUtils.Instance.DiskID.Split(','));
var db = new List<string>();
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;
}
/// <summary>
/// 打印机参数初始默认值
/// </summary>
/// <returns></returns>
public PrinterItem GetDefaultPrinterItem()
{
var printer = new PrinterItem();
printer.Id = "None";
printer.Name = "None";
printer.Port = "None";
var data = new Dictionary<string, string>();
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;
}
/// <summary>
/// 标签打印机参数初始默认值
/// </summary>
/// <returns></returns>
public PrinterItem GetDefaultLabelPrinterItem()
{
var printer = new PrinterItem();
printer.Id = "None";
printer.Name = "None";
printer.Port = "None";
var data = new Dictionary<string, string>();
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;
}
/// <summary>
/// 通用标签打印机参数初始默认值
/// </summary>
/// <returns></returns>
public PrinterItem GetNormalDefaultLabelPrinterItem()
{
var printer = new PrinterItem();
printer.Id = "None";
printer.Name = "通用标签打印机";
printer.Port = "None";
var data = new Dictionary<string, string>();
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;
}
/// <summary>
/// 获取客显默认设置
/// </summary>
/// <returns></returns>
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;
}
/// <summary>
/// 打印机参数初始默认值
/// </summary>
/// <returns></returns>
public KitchenPrinterItem GetDefaultKitchenPrinterItem()
{
var printer = new KitchenPrinterItem();
printer.KitId = "None";
printer.KitType = 0;
printer.PrinterItem = GetDefaultPrinterItem();
return printer;
}
/// <summary>
/// 厨显默认值
/// </summary>
/// <returns></returns>
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<string, string> parameters = new SortedList<string, string>();
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>" + title + "</Title>\n");
sb.Append(Environment.NewLine);
sb.Append("<" + ExceptionName + ">\n");
sb.Append(Environment.NewLine);
sb.Append("<LogDateTime>" + DateTime.Now.ToString() + "</LogDateTime>\n");
sb.Append(Environment.NewLine);
sb.Append("<Message>" + System.Net.WebUtility.HtmlEncode(e.Message) + "</Message>\n");
sb.Append(Environment.NewLine);
if (e.Source != null)
{
sb.Append("<Source>" + e.Source + "</Source>\n");
sb.Append(Environment.NewLine);
}
if (e.StackTrace != null)
{
sb.Append("<StackTrace>" + e.StackTrace + "</StackTrace>\n");
sb.Append(Environment.NewLine);
}
if (e.InnerException != null)
{
sb.Append("<InnerException>" + System.Net.WebUtility.HtmlEncode(e.InnerException.ToString()) + "</InnerException>\n");
sb.Append(Environment.NewLine);
}
sb.Append("<TargetSite>" + e.TargetSite + "</TargetSite>\n");
sb.Append(Environment.NewLine);
sb.Append("</" + ExceptionName + ">\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);
/// <summary>
/// 释放内存
/// </summary>
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 分账信息
/// <summary>
/// 是否有要上传的销售分账数据
/// </summary>
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);
}
}
}