| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762 |
- using System;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using BeiJingComService.Core;
- using BeiJingComService.Infrastructure;
- using BeiJingComService.Protocols;
- namespace BeiJingComService.WinForms
- {
- public partial class DiagnosticForm : Form
- {
- private readonly ITransportProtocol[] _protocols;
- private TabControl _tabControl;
- // 调用测试
- private TabPage _tabInvoke;
- private Label _lblStatus;
- private Label _lblFunc;
- private TextBox _txtFunc;
- private Label _lblArgs;
- private TextBox _txtArgs;
- private Label _lblCardInput;
- private TextBox _txtCardInput;
- private Button _btnReadCard, _btnInvoke, _btnRestart, _btnClear;
- private TextBox _txtResult;
- // 运行状态
- private TabPage _tabStatus;
- private ListView _lvStatus;
- private Button _btnRefreshStatus;
- // 配置
- private TabPage _tabConfig;
- private ListView _lvConfig;
- private Button _btnRefreshConfig;
- // 日志
- private TabPage _tabLog;
- private ComboBox _cmbLogFile;
- private TextBox _txtLog;
- private Button _btnRefreshLog, _btnOpenLogDir;
- // 读卡测试
- private TabPage _tabCardCache;
- private TextBox _txtCacheCardInput;
- private ComboBox _cmbCacheCardClass;
- private CheckBox _chkKeepOpen;
- private Button _btnFullRead, _btnCacheRead, _btnCompare, _btnClearResult;
- private TextBox _txtCacheResult;
- public DiagnosticForm(ITransportProtocol[] protocols)
- {
- _protocols = protocols;
- InitializeComponent();
- this.Text = "北京本地 COM 通讯服务 · 诊断面板";
- this.StartPosition = FormStartPosition.CenterScreen;
- this.FormClosing += (s, e) => { e.Cancel = true; this.Hide(); };
- RefreshStatus();
- RefreshConfig();
- LoadLog();
- }
- private void InitializeComponent()
- {
- this.SuspendLayout();
- _tabControl = new TabControl { Dock = DockStyle.Fill };
- // ===== 调用测试 =====
- _tabInvoke = new TabPage { Text = "调用测试", Padding = new Padding(10) };
- _lblStatus = new Label
- {
- Text = "网关状态: 检测中...",
- AutoSize = true,
- Location = new Point(12, 12),
- Font = new Font("Microsoft YaHei", 10, FontStyle.Bold)
- };
- _lblFunc = new Label { Text = "方法(func):", AutoSize = true, Location = new Point(12, 46) };
- _txtFunc = new TextBox
- {
- Location = new Point(110, 43),
- Size = new Size(240, 24),
- Text = "open"
- };
- var lblFuncHint = new Label
- {
- Text = "如 open / close / ReadCardObj / BussniessObj / Trade / TradeAll",
- AutoSize = true,
- ForeColor = Color.Gray,
- Location = new Point(362, 46)
- };
- _lblArgs = new Label { Text = "参数(args,每行一个):", AutoSize = true, Location = new Point(12, 78) };
- _txtArgs = new TextBox
- {
- Location = new Point(12, 102),
- Size = new Size(730, 76),
- Multiline = true,
- ScrollBars = ScrollBars.Both,
- AcceptsReturn = true,
- WordWrap = false,
- Font = new Font("Consolas", 9),
- BackColor = Color.White
- };
- _lblCardInput = new Label { Text = "读卡入参(input,单行 XML):", AutoSize = true, Location = new Point(12, 186) };
- _txtCardInput = new TextBox
- {
- Location = new Point(12, 208),
- Size = new Size(730, 56),
- Multiline = true,
- ScrollBars = ScrollBars.Horizontal,
- AcceptsReturn = false,
- WordWrap = false,
- Font = new Font("Consolas", 9),
- BackColor = Color.White,
- Text = "<multiclass>1</multiclass><QRcode></QRcode><businessType>11</businessType><termId>现场MAC(去横线)</termId><termIp>现场IP</termIp><operatorId>工号</operatorId><operatorName>姓名</operatorName><officeId>科室编码</officeId><officeName>科室名</officeName>"
- };
- _btnReadCard = new Button { Text = "模拟读卡", Location = new Point(12, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
- _btnInvoke = new Button { Text = "调用", Location = new Point(130, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
- _btnRestart = new Button { Text = "重启网关", Location = new Point(248, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
- _btnClear = new Button { Text = "清空结果", Location = new Point(366, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
- _txtResult = new TextBox
- {
- Location = new Point(12, 314),
- Size = new Size(730, 170),
- Multiline = true,
- ReadOnly = true,
- ScrollBars = ScrollBars.Both,
- WordWrap = false,
- BackColor = Color.White,
- Font = new Font("Consolas", 9)
- };
- _btnReadCard.Click += async (s, e) => await OnReadCard();
- _btnInvoke.Click += async (s, e) => await OnInvoke();
- _btnRestart.Click += (s, e) => OnRestart();
- _btnClear.Click += (s, e) => _txtResult.Clear();
- _tabInvoke.Controls.AddRange(new Control[] {
- _lblStatus, _lblFunc, _txtFunc, lblFuncHint, _lblArgs, _txtArgs,
- _lblCardInput, _txtCardInput,
- _btnReadCard, _btnInvoke, _btnRestart, _btnClear, _txtResult
- });
- // ===== 运行状态 =====
- _tabStatus = new TabPage { Text = "运行状态", Padding = new Padding(10) };
- _lvStatus = new ListView
- {
- Location = new Point(12, 12),
- Size = new Size(730, 420),
- View = View.Details,
- FullRowSelect = true,
- GridLines = true,
- HeaderStyle = ColumnHeaderStyle.Nonclickable
- };
- _lvStatus.Columns.Add("项目", 200);
- _lvStatus.Columns.Add("值", 510);
- _btnRefreshStatus = new Button { Text = "刷新", Location = new Point(12, 442), Size = new Size(90, 30), FlatStyle = FlatStyle.System };
- _btnRefreshStatus.Click += (s, e) => RefreshStatus();
- _tabStatus.Controls.AddRange(new Control[] { _lvStatus, _btnRefreshStatus });
- // ===== 配置 =====
- _tabConfig = new TabPage { Text = "配置信息", Padding = new Padding(10) };
- _lvConfig = new ListView
- {
- Location = new Point(12, 12),
- Size = new Size(730, 420),
- View = View.Details,
- FullRowSelect = true,
- GridLines = true,
- HeaderStyle = ColumnHeaderStyle.Nonclickable
- };
- _lvConfig.Columns.Add("配置项", 200);
- _lvConfig.Columns.Add("值", 510);
- _btnRefreshConfig = new Button { Text = "刷新", Location = new Point(12, 442), Size = new Size(90, 30), FlatStyle = FlatStyle.System };
- _btnRefreshConfig.Click += (s, e) => RefreshConfig();
- _tabConfig.Controls.AddRange(new Control[] { _lvConfig, _btnRefreshConfig });
- // ===== 日志 =====
- _tabLog = new TabPage { Text = "日志查看", Padding = new Padding(10) };
- _cmbLogFile = new ComboBox
- {
- Location = new Point(12, 12),
- Size = new Size(260, 24),
- DropDownStyle = ComboBoxStyle.DropDownList
- };
- _cmbLogFile.Items.Add(new LogFileItem("运行日志 _Gateway.log", () => Logger.TodayLogFilePath));
- _cmbLogFile.Items.Add(new LogFileItem("调用原文 _Trade.log", () => TradeLogger.TodayTradeLogFilePath));
- _cmbLogFile.SelectedIndex = 0;
- _cmbLogFile.SelectedIndexChanged += (s, e) => LoadLog();
- _txtLog = new TextBox
- {
- Location = new Point(12, 44),
- Size = new Size(730, 388),
- Multiline = true,
- ReadOnly = true,
- ScrollBars = ScrollBars.Both,
- WordWrap = false,
- BackColor = Color.White,
- Font = new Font("Consolas", 9)
- };
- _btnRefreshLog = new Button { Text = "刷新日志", Location = new Point(12, 442), Size = new Size(100, 30), FlatStyle = FlatStyle.System };
- _btnOpenLogDir = new Button { Text = "打开日志目录", Location = new Point(120, 442), Size = new Size(120, 30), FlatStyle = FlatStyle.System };
- _btnRefreshLog.Click += (s, e) => LoadLog();
- _btnOpenLogDir.Click += (s, e) => OpenLogDir();
- _tabLog.Controls.AddRange(new Control[] { _cmbLogFile, _txtLog, _btnRefreshLog, _btnOpenLogDir });
- // ===== 读卡测试 =====
- _tabCardCache = new TabPage { Text = "读卡测试", Padding = new Padding(10) };
- var lblCacheInput = new Label { Text = "读卡入参(input,单行 XML):", AutoSize = true, Location = new Point(12, 12) };
- _txtCacheCardInput = new TextBox
- {
- Location = new Point(12, 34),
- Size = new Size(730, 56),
- Multiline = true,
- ScrollBars = ScrollBars.Horizontal,
- AcceptsReturn = false,
- WordWrap = false,
- Font = new Font("Consolas", 9),
- BackColor = Color.White,
- Text = "<multiclass>1</multiclass><QRcode></QRcode><businessType>11</businessType><termId>现场MAC(去横线)</termId><termIp>现场IP</termIp><operatorId>工号</operatorId><operatorName>姓名</operatorName><officeId>科室编码</officeId><officeName>科室名</officeName>"
- };
- var lblCacheCardClass = new Label { Text = "card_class(调用方指定):", AutoSize = true, Location = new Point(12, 100) };
- _cmbCacheCardClass = new ComboBox
- {
- Location = new Point(160, 97),
- Size = new Size(120, 24),
- DropDownStyle = ComboBoxStyle.DropDownList
- };
- _cmbCacheCardClass.Items.AddRange(new object[] { "(空,由 COM 判定)", "1 本市", "2 异地" });
- _cmbCacheCardClass.SelectedIndex = 0;
- _chkKeepOpen = new CheckBox
- {
- Text = "keepSession(本次不空闲关会话)",
- AutoSize = true,
- Location = new Point(300, 99)
- };
- _btnFullRead = new Button { Text = "① 完整读卡", Location = new Point(12, 136), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
- _btnCacheRead = new Button { Text = "② 指定类别读卡", Location = new Point(130, 136), Size = new Size(130, 32), FlatStyle = FlatStyle.System };
- _btnCompare = new Button { Text = "③ perRead vs keepOpen", Location = new Point(268, 136), Size = new Size(160, 32), FlatStyle = FlatStyle.System };
- _btnClearResult = new Button { Text = "清空结果", Location = new Point(436, 136), Size = new Size(100, 32), FlatStyle = FlatStyle.System };
- _txtCacheResult = new TextBox
- {
- Location = new Point(12, 178),
- Size = new Size(730, 290),
- Multiline = true,
- ReadOnly = true,
- ScrollBars = ScrollBars.Both,
- WordWrap = false,
- BackColor = Color.White,
- Font = new Font("Consolas", 9)
- };
- _btnFullRead.Click += async (s, e) => await OnCardCacheRead(false);
- _btnCacheRead.Click += async (s, e) => await OnCardCacheRead(true);
- _btnCompare.Click += async (s, e) => await OnCardCacheCompare();
- _btnClearResult.Click += (s, e) => _txtCacheResult.Clear();
- _tabCardCache.Controls.AddRange(new Control[] {
- lblCacheInput, _txtCacheCardInput,
- lblCacheCardClass, _cmbCacheCardClass, _chkKeepOpen,
- _btnFullRead, _btnCacheRead, _btnCompare, _btnClearResult,
- _txtCacheResult
- });
- _tabControl.TabPages.AddRange(new TabPage[] { _tabInvoke, _tabStatus, _tabConfig, _tabLog, _tabCardCache });
- this.Controls.Add(_tabControl);
- this.ClientSize = new Size(770, 540);
- this.MinimumSize = new Size(640, 460);
- this.ResumeLayout(false);
- }
- // ===== 调用测试 =====
- private async Task OnInvoke()
- {
- string func = _txtFunc.Text.Trim();
- if (string.IsNullOrEmpty(func))
- {
- AppendResult("方法(func)为空");
- return;
- }
- string[] args = ParseArgs(_txtArgs.Text);
- _btnInvoke.Enabled = false;
- AppendResult("--- 调用 COM ---");
- try
- {
- ComResult result = await GatewayHost.Instance.ExecuteAsync(func, args);
- AppendResult($"方法: {func}");
- AppendResult($"结果码: {result.Code}");
- AppendResult($"消息: {result.Message}");
- AppendResult($"耗时: {result.ElapsedMs} ms");
- AppendResult("返回内容:");
- AppendResult(string.IsNullOrEmpty(result.Output) ? "(空)" : result.Output);
- RefreshStatus();
- }
- catch (Exception ex)
- {
- AppendResult($"异常: {ex.Message}");
- Logger.Error("诊断面板调用 COM 异常", ex);
- }
- finally
- {
- _btnInvoke.Enabled = true;
- }
- }
- /// <summary>模拟读卡:服务端封装 open→GetPersonClass→GetPersonInfo(Nation),这里一键触发并逐步展示。</summary>
- private async Task OnReadCard()
- {
- string input = _txtCardInput.Text.Trim();
- if (string.IsNullOrEmpty(input))
- {
- AppendResult("读卡入参(input)为空");
- return;
- }
- if (input.IndexOf('\n') >= 0 || input.IndexOf('\r') >= 0)
- {
- AppendResult("读卡入参必须是单行 XML,请勿换行");
- return;
- }
- _btnReadCard.Enabled = false;
- AppendResult("=== 模拟读卡开始 ===");
- try
- {
- string payload = CardReaderFlow.WrapInput(input);
- _txtFunc.Text = CardReaderFlow.FuncPersonClass;
- _txtArgs.Text = payload + "\r\n" + payload;
- CardReadResult result = await CardReaderFlow.ReadAsync(payload);
- var steps = result.Steps ?? new CardReadStep[0];
- foreach (CardReadStep step in steps)
- {
- AppendResult($"--- 步骤: {step.Func} ---");
- AppendResult($"结果码: {step.Code} 耗时: {step.ElapsedMs} ms");
- AppendResult($"消息: {step.Message}");
- AppendResult($"返回: {(string.IsNullOrEmpty(step.Output) ? "(空)" : step.Output)}");
- }
- if (result.FuncName != null)
- {
- _txtFunc.Text = result.FuncName;
- }
- if (result.Code == 0)
- {
- AppendResult($"读卡成功: card_class={result.CardClass},采用方法={result.FuncName},总耗时={result.ElapsedMs} ms");
- }
- else
- {
- AppendResult($"读卡失败: {result.Message}");
- }
- RefreshStatus();
- }
- catch (Exception ex)
- {
- AppendResult("异常: " + ex.Message);
- Logger.Error("诊断面板模拟读卡异常", ex);
- }
- finally
- {
- _btnReadCard.Enabled = true;
- }
- }
- // ===== 读卡测试 =====
- /// <summary>
- /// ① 完整读卡(不传 card_class,由 COM 判定本地/异地);
- /// ② 指定类别读卡(传 card_class,跳过 GetPersonClass_Multimedia,少一笔约 1.4~2.6s)。
- /// Round49:服务端已无本地缓存,两种读法都不依赖历史状态。
- /// </summary>
- private async Task OnCardCacheRead(bool useCardClass)
- {
- string input = _txtCacheCardInput.Text.Trim();
- if (string.IsNullOrEmpty(input))
- {
- AppendCacheResult("读卡入参(input)为空");
- return;
- }
- if (input.IndexOf('\n') >= 0 || input.IndexOf('\r') >= 0)
- {
- AppendCacheResult("读卡入参必须是单行 XML,请勿换行");
- return;
- }
- string cardClass = useCardClass ? GetCardClassValue() : null;
- if (useCardClass && string.IsNullOrEmpty(cardClass))
- {
- AppendCacheResult("指定类别读卡需要先在 card_class 下拉里选「1 本市」或「2 异地」");
- return;
- }
- bool keepSession = _chkKeepOpen.Checked;
- SetCardCacheButtonsEnabled(false);
- AppendCacheResult(useCardClass
- ? "=== ② 指定类别读卡开始(card_class=" + cardClass + ",将跳过人员类别查询)==="
- : "=== ① 完整读卡开始(人员类别由 COM 判定)===");
- try
- {
- string payload = CardReaderFlow.WrapInput(input);
- CardReadResult result = await CardReaderFlow.ReadAsync(payload, cardClass, keepSession);
- AppendCardResult(result, keepSession);
- RefreshStatus();
- }
- catch (Exception ex)
- {
- AppendCacheResult("异常: " + ex.Message);
- Logger.Error("诊断面板读卡测试异常", ex);
- }
- finally
- {
- SetCardCacheButtonsEnabled(true);
- }
- }
- /// <summary>
- /// ③ 会话策略对比:同一笔读卡分别按 perRead / keepSession 各跑一次,给出耗时差。
- /// 用途是量化「重新 open 一次会话」的真实成本(Round49 决策点 3 的依据)。
- /// </summary>
- private async Task OnCardCacheCompare()
- {
- string input = _txtCacheCardInput.Text.Trim();
- if (string.IsNullOrEmpty(input))
- {
- AppendCacheResult("读卡入参(input)为空");
- return;
- }
- if (input.IndexOf('\n') >= 0 || input.IndexOf('\r') >= 0)
- {
- AppendCacheResult("读卡入参必须是单行 XML,请勿换行");
- return;
- }
- // 两轮用同一个 card_class,避免把"跳过一笔"的差异算进会话策略里
- string cardClass = GetCardClassValue();
- if (string.IsNullOrEmpty(cardClass)) cardClass = null;
- SetCardCacheButtonsEnabled(false);
- AppendCacheResult("=== ③ perRead vs keepSession 对比开始 ===");
- try
- {
- string payload = CardReaderFlow.WrapInput(input);
- AppendCacheResult("--- 第 1 轮:perRead(读完空闲即关会话,下一笔要重新 open)---");
- CardReadResult first = await CardReaderFlow.ReadAsync(payload, cardClass, false);
- AppendCardResult(first, false);
- AppendCacheResult("--- 第 2 轮:keepSession(保持会话,复用第 1 轮建立的会话)---");
- CardReadResult second = await CardReaderFlow.ReadAsync(payload, cardClass, true);
- AppendCardResult(second, true);
- AppendCacheResult("--- 对比 ---");
- AppendCacheResult($"perRead 总耗时: {first.ElapsedMs} ms");
- AppendCacheResult($"keepSession 总耗时: {second.ElapsedMs} ms");
- long saved = first.ElapsedMs - second.ElapsedMs;
- AppendCacheResult(first.ElapsedMs > 0
- ? $"差值: {saved} ms({saved * 100.0 / first.ElapsedMs:F1}%)—— 正数表示复用会话省下的时间"
- : $"差值: {saved} ms");
- RefreshStatus();
- }
- catch (Exception ex)
- {
- AppendCacheResult("异常: " + ex.Message);
- Logger.Error("诊断面板读卡会话策略对比异常", ex);
- }
- finally
- {
- // 第 2 轮把「上一条请求要求保活」的标志留成了 true,这里补一笔 close 收尾:
- // 既真的释放读卡器,也把标志复位成默认(false),不给后面的请求留尾巴。
- try
- {
- await GatewayHost.Instance.ExecuteAsync("close", null);
- }
- catch (Exception ex)
- {
- Logger.Error("诊断面板对比收尾 close 失败(忽略)", ex);
- }
- SetCardCacheButtonsEnabled(true);
- }
- }
- /// <summary>card_class 下拉:0=(空)、1=1 本市、2=2 异地。</summary>
- private string GetCardClassValue()
- {
- switch (_cmbCacheCardClass.SelectedIndex)
- {
- case 1: return "1";
- case 2: return "2";
- default: return string.Empty;
- }
- }
- private void SetCardCacheButtonsEnabled(bool enabled)
- {
- _btnFullRead.Enabled = enabled;
- _btnCacheRead.Enabled = enabled;
- _btnCompare.Enabled = enabled;
- }
- private void AppendCardResult(CardReadResult result, bool keepOpen)
- {
- var steps = result.Steps ?? new CardReadStep[0];
- foreach (CardReadStep step in steps)
- {
- AppendCacheResult($"--- 步骤: {step.Func} ---");
- AppendCacheResult($"结果码: {step.Code} 耗时: {step.ElapsedMs} ms");
- AppendCacheResult($"消息: {step.Message}");
- AppendCacheResult($"返回: {(string.IsNullOrEmpty(step.Output) ? "(空)" : step.Output)}");
- }
- AppendCacheResult($"会话模式: {(keepOpen ? "keepSession" : "perRead")}");
- AppendCacheResult($"card_no: {(string.IsNullOrEmpty(result.CardNo) ? "(无)" : result.CardNo)}");
- AppendCacheResult($"采用方法: {result.FuncName}");
- if (result.Code == 0)
- {
- AppendCacheResult($"读卡成功: card_class={result.CardClass},总耗时={result.ElapsedMs} ms");
- }
- else
- {
- AppendCacheResult($"读卡失败({result.Code}): {result.Message}");
- }
- }
- private void AppendCacheResult(string text)
- {
- if (_txtCacheResult.InvokeRequired)
- {
- _txtCacheResult.Invoke(new Action(() => AppendCacheResult(text)));
- return;
- }
- _txtCacheResult.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] {text}\r\n");
- }
- /// <summary>参数框按行拆分,每行一个参数(按顺序对应 COM 方法的各个 byref 参数);空行忽略。</summary>
- private static string[] ParseArgs(string text)
- {
- if (string.IsNullOrEmpty(text)) return null;
- var lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n')
- .Select(line => line.Trim())
- .Where(line => line.Length > 0)
- .ToArray();
- return lines.Length == 0 ? null : lines;
- }
- private void OnRestart()
- {
- try
- {
- GatewayHost.Instance.Reinitialize();
- AppendResult("网关已重建");
- RefreshStatus();
- }
- catch (Exception ex)
- {
- AppendResult($"重建失败: {ex.Message}");
- Logger.Error("诊断面板重建网关失败", ex);
- }
- }
- private void AppendResult(string text)
- {
- if (_txtResult.InvokeRequired)
- {
- _txtResult.Invoke(new Action(() => AppendResult(text)));
- return;
- }
- _txtResult.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] {text}\r\n");
- }
- public void SetInitError(string message)
- {
- if (_lblStatus.InvokeRequired)
- {
- _lblStatus.Invoke(new Action(() => SetInitError(message)));
- return;
- }
- _lblStatus.Text = "网关状态: 初始化失败 - " + message;
- _lblStatus.ForeColor = Color.Red;
- AppendResult("[初始化失败] " + message);
- }
- // ===== 运行状态 =====
- private void RefreshStatus()
- {
- if (_lvStatus.InvokeRequired)
- {
- _lvStatus.Invoke(new Action(RefreshStatus));
- return;
- }
- var host = GatewayHost.Instance;
- _lvStatus.Items.Clear();
- bool initialized = host.IsInitialized;
- AddStatus("网关状态", initialized ? "已初始化" : "未初始化");
- AddStatus("故障标记", host.IsFaulted ? "是(上一笔超时或底层异常)" : "否");
- AddStatus("排队调用数", host.PendingCount.ToString());
- AddStatus("COM ProgID", host.ProgId);
- AddStatus("调用超时", AppConfig.ComTimeoutMs + " ms");
- AddStatus("空闲关会话", AppConfig.ComIdleTimeoutMs + " ms");
- AddStatus("HTTP 端口", AppConfig.HttpPort.ToString());
- AddStatus("HTTP 监听", IsHttpListening() ? "是" : "否");
- AddStatus("累计调用数", host.InvokeCount.ToString());
- AddStatus("最近调用时间", host.LastInvokeTime.HasValue ? host.LastInvokeTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "-");
- AddStatus("最近耗时", host.LastInvokeTime.HasValue ? host.LastElapsedMs + " ms" : "-");
- AddStatus("最后错误", string.IsNullOrEmpty(host.LastError) ? "-" : host.LastError);
- _lblStatus.Text = initialized ? "网关状态: 已初始化" : "网关状态: 未初始化";
- _lblStatus.ForeColor = initialized ? Color.Green : Color.OrangeRed;
- }
- private bool IsHttpListening()
- {
- foreach (var protocol in _protocols)
- {
- var http = protocol as HttpProtocol;
- if (http != null && http.IsListening) return true;
- }
- return false;
- }
- private void AddStatus(string name, string value)
- {
- var item = new ListViewItem(name);
- item.SubItems.Add(value ?? "");
- _lvStatus.Items.Add(item);
- }
- // ===== 配置 =====
- private void RefreshConfig()
- {
- if (_lvConfig.InvokeRequired)
- {
- _lvConfig.Invoke(new Action(RefreshConfig));
- return;
- }
- _lvConfig.Items.Clear();
- AddConfig("HttpPort", AppConfig.HttpPort.ToString());
- AddConfig("MaxRequestSize", AppConfig.MaxRequestSize.ToString());
- AddConfig("AccessToken", string.IsNullOrEmpty(AppConfig.AccessToken) ? "(未设置,不校验)" : "(已设置)");
- AddConfig("CorsAllowOrigin", AppConfig.CorsAllowOrigin);
- AddConfig("ComProgId", AppConfig.ComProgId);
- AddConfig("ComTimeoutMs", AppConfig.ComTimeoutMs.ToString());
- AddConfig("ComIdleTimeoutMs", AppConfig.ComIdleTimeoutMs.ToString());
- AddConfig("ServiceName", AppConfig.ServiceName);
- AddConfig("AutoStart", AppConfig.AutoStart.ToString());
- AddConfig("LogDirectory", AppConfig.LogDirectory);
- AddConfig("LogRetainDays", AppConfig.LogRetainDays.ToString());
- AddConfig("TradeLogEnabled", AppConfig.TradeLogEnabled.ToString());
- AddConfig("TradeLogMaskSensitive", AppConfig.TradeLogMaskSensitive.ToString());
- AddConfig("TradeLogMaxChars", AppConfig.TradeLogMaxChars == 0 ? "0(不截断)" : AppConfig.TradeLogMaxChars.ToString());
- AddConfig("TradeLog文件", AppConfig.TradeLogEnabled
- ? Path.GetFileName(TradeLogger.TodayTradeLogFilePath)
- : "(已关闭)");
- }
- private void AddConfig(string name, string value)
- {
- var item = new ListViewItem(name);
- item.SubItems.Add(value ?? "");
- _lvConfig.Items.Add(item);
- }
- // ===== 日志 =====
- private void LoadLog()
- {
- try
- {
- var item = _cmbLogFile.SelectedItem as LogFileItem;
- string filePath = item != null ? item.Path : Logger.TodayLogFilePath;
- if (!File.Exists(filePath))
- {
- _txtLog.Text = "(日志文件不存在)\r\n" + filePath;
- return;
- }
- var lines = File.ReadLines(filePath, Encoding.UTF8).Reverse().Take(200).Reverse();
- _txtLog.Text = string.Join("\r\n", lines);
- _txtLog.SelectionStart = _txtLog.Text.Length;
- _txtLog.ScrollToCaret();
- }
- catch (Exception ex)
- {
- _txtLog.Text = "读取日志失败: " + ex.Message;
- }
- }
- private void OpenLogDir()
- {
- try
- {
- Directory.CreateDirectory(Logger.LogDirectoryPath);
- Process.Start(Logger.LogDirectoryPath);
- }
- catch (Exception ex)
- {
- MessageBox.Show($"无法打开日志目录: {ex.Message}", "错误",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private sealed class LogFileItem
- {
- private readonly Func<string> _pathProvider;
- public LogFileItem(string displayName, Func<string> pathProvider)
- {
- DisplayName = displayName;
- _pathProvider = pathProvider;
- }
- public string DisplayName { get; private set; }
- /// <summary>动态取路径,跨零点后自动切到当天日志文件。</summary>
- public string Path
- {
- get { return _pathProvider(); }
- }
- public override string ToString()
- {
- return DisplayName;
- }
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (_cmbLogFile != null) _cmbLogFile.Dispose();
- if (_tabControl != null) _tabControl.Dispose();
- }
- base.Dispose(disposing);
- }
- }
- }
|