CNAS取数仪器端升级
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

916 rindas
35KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using CnasSynchronusClient;
  10. using CnasSynchrousModel;
  11. using CnasSynchronousCommon;
  12. using log4net.Repository.Hierarchy;
  13. using System.Threading;
  14. using System.IO;
  15. using Newtonsoft.Json;
  16. using System.Diagnostics;
  17. namespace CNAS_RunSync
  18. {
  19. public partial class ucSynchrousMain : UserControl
  20. {
  21. private string delayDays = FileOperation.GetSystemFormatConfigData().ShowDelayDays;
  22. private SyncInstrumentItemInfo syncInstrumentItem = new SyncInstrumentItemInfo();
  23. //private Dictionary<string, DataTable> dictSourceTables = new Dictionary<string, DataTable>();
  24. private DataTable dtSource = new DataTable(); //当前显示数据源
  25. private Dictionary<string, DataRow> dictSource = new Dictionary<string, DataRow>();
  26. private Dictionary<string, Type> DictComboBox = new Dictionary<string, Type>(); //ComboBox数据源
  27. private List<string> lstIntOrDouble = new List<string>() { "等于", "不等于", "大于", "小于", "不大于", "不小于" };
  28. private List<string> lstText = new List<string>() { "等于", "不等于", "包含", "不包含" };
  29. private Color FinedBackColor = Color.LightCyan; //查询后选中项
  30. Dictionary<string, string> DictField = new Dictionary<string, string>();
  31. public ucSynchrousMain()
  32. {
  33. InitializeComponent();
  34. }
  35. //需要存在一个仪器才能正常显示数据
  36. public ucSynchrousMain(SyncInstrumentItemInfo syncInstrumentItem)
  37. {
  38. InitializeComponent();
  39. dgvSyncData.AutoGenerateColumns = false;
  40. dgvSyncData.RowHeadersVisible = false;
  41. //dgvSyncData.RowsDefaultCellStyle.BackColor = Color.Bisque;
  42. dgvSyncData.AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke;
  43. this.syncInstrumentItem = syncInstrumentItem;
  44. }
  45. /// <summary>
  46. /// 控件加载时发生
  47. /// </summary>
  48. /// <param name="sender"></param>
  49. /// <param name="e"></param>
  50. private void ucSynchrousMain_Load(object sender, EventArgs e)
  51. {
  52. BindData();
  53. }
  54. /// <summary>
  55. /// 绑定数据
  56. /// </summary>
  57. public void BindData()
  58. {
  59. if (this.syncInstrumentItem == null) return;
  60. this.lblTitle.Text = string.Format("当前仪器:【{0}】", syncInstrumentItem.Code);
  61. if (syncInstrumentItem.LstSyncPramas == null) return;
  62. if (syncInstrumentItem.SyncInstrumentDSInfo == null) return;
  63. //if (syncInstrumentItem.SyncInstrumentDSInfo.Path == null) return;
  64. if (syncInstrumentItem.SyncInstrumentDSInfo.InstrumentDataSourceType == DataSourceType.None) return;
  65. this.lblTitleMsg.Text= string.Format("类型:{0} 路径:{1}", syncInstrumentItem.SyncInstrumentDSInfo.InstrumentDataSourceType.ToString(),syncInstrumentItem.SyncInstrumentDSInfo.Path);
  66. //获取目标表最近上传时间
  67. Dictionary<string, string> times = this.ReadSyncTime();
  68. if (true == times?.ContainsKey(this.syncInstrumentItem.Code))
  69. {
  70. this.lblTitleLastUpdateTime.Text = $"最近上传时间:{times[this.syncInstrumentItem.Code]}";
  71. }
  72. //获取配置
  73. SystemFormatConfig systemConfig = FileOperation.GetSystemFormatConfigData(this.syncInstrumentItem.Code);
  74. if (null != systemConfig)
  75. {
  76. this.delayDays = systemConfig.ShowDelayDays;
  77. }
  78. //清空现有绑定
  79. DictComboBox.Clear();
  80. dictSource.Clear();
  81. //加载相关数据
  82. //1.1根据仪器类型加载本地存储的中英文字段说明映射
  83. //if (syncInstrumentItem.LstSyncPramas.Count > 0)
  84. //{
  85. //InstrumentDescribeZH describeZH = new InstrumentDescribeZH(syncInstrumentItem.InstruType, syncInstrumentItem.LstSyncPramas[0].SourceTable);
  86. //describeZH.GetFieldDescribe();
  87. //DictField = describeZH.DictField;
  88. //}
  89. //2.datagridview中绑定数据(绑定的是从数据源中读取的数据)
  90. //2.1 根据映射表,创建datagridviewcolumn/和绑定数据列
  91. if (syncInstrumentItem.LstSyncPramas.Count <= 0) return;
  92. //创建选择列
  93. AddCheckBoxColumn(dgvSyncData, "selectedColumn", "", 80, true);
  94. //创建数据列
  95. foreach (var item in syncInstrumentItem.LstSyncPramas)
  96. {
  97. string strColumnName = item.SourceField;
  98. if (DictField.ContainsKey(strColumnName))
  99. strColumnName = DictField[strColumnName];
  100. AddDatagridColumn(dgvSyncData, item.SourceField, strColumnName, 150, bSort: item.IfDateField);
  101. }
  102. //创建GUID列
  103. AddDatagridColumn(dgvSyncData, "GridGuid", "GridGuid", 50, false);
  104. //2.2获取数据源数据
  105. try
  106. {
  107. this.RefreshData();
  108. }
  109. catch (Exception exception)
  110. {
  111. MessageBox.Show($"查询数据时发生异常:{exception.Message}");
  112. }
  113. //3.初始化查询相关内容
  114. //3.1 绑定Combobox数据源
  115. if (0 < dtSource?.Columns?.Count)
  116. {
  117. foreach (DataColumn dc in dtSource.Columns)
  118. {
  119. if (syncInstrumentItem.LstSyncPramas.Where(s => s.SourceField.ToUpper() == dc.ColumnName.ToUpper()).LongCount<SyncParamasInfo>() > 0)
  120. {
  121. string strColumnName = dc.ColumnName;
  122. if (DictField.ContainsKey(strColumnName))
  123. strColumnName = DictField[strColumnName];
  124. DictComboBox.Add(strColumnName, dc.DataType);
  125. }
  126. }
  127. if (DictComboBox.Count > 0)
  128. {
  129. BindingSource bsComboBox = new BindingSource
  130. {
  131. DataSource = DictComboBox
  132. };
  133. cmbColumns.DataSource = bsComboBox;
  134. cmbColumns.ValueMember = "Key";
  135. cmbColumns.DisplayMember = "Key";
  136. }
  137. }
  138. }
  139. /// <summary>
  140. ///
  141. /// </summary>
  142. private void RefreshData()
  143. {
  144. //清空现有绑定
  145. dictSource?.Clear();
  146. dtSource?.Clear();
  147. dtSource?.Dispose();
  148. dtSource = null;
  149. dgvSyncData?.Rows?.Clear();
  150. //2.2 获取数据源数据,构建datagridviewcell
  151. //2.2.1 获取数据源数据
  152. var query = syncInstrumentItem.LstSyncPramas.Where(s => s.IfDateField == true).ToList<SyncParamasInfo>();
  153. if (query.Count == 1)
  154. {
  155. object[] obj = new object[]
  156. {
  157. syncInstrumentItem.LstSyncPramas[0].SourceTable,
  158. query[0].SourceField,
  159. DateTime.Now.AddDays(Convert.ToInt32(delayDays)).ToString("yyyy-MM-dd HH:mm:ss")
  160. };
  161. InstrumentData instrumentData = InstrumentDataFact.CreateInstrumentDataSource(syncInstrumentItem.SyncInstrumentDSInfo, obj);
  162. dtSource = instrumentData.GetInstrumentDataByDate();
  163. DataView dv = dtSource.DefaultView;
  164. try
  165. {
  166. dv.Sort = $"{query[0].SourceField} DESC";
  167. }
  168. catch
  169. {
  170. }
  171. dtSource = dv.ToTable();
  172. }
  173. //2.2.2 构建datagridviewcell
  174. foreach (DataRow dr in dtSource.Rows)
  175. {
  176. DataGridViewRow dataGridViewRow = new DataGridViewRow();
  177. foreach (DataGridViewColumn dataGridViewColumn in dgvSyncData.Columns)
  178. {
  179. if (dataGridViewColumn.Index == 0)
  180. {
  181. dataGridViewRow.Cells.Add(new DataGridViewCheckBoxCell());
  182. }
  183. if (dtSource.Columns.Contains(dataGridViewColumn.Name))
  184. AddDataTextCell(dataGridViewRow, dataGridViewColumn, dr);
  185. }
  186. //添加GUID值
  187. string strGuid = Guid.NewGuid().ToString();
  188. DataGridViewTextBoxCell txtCell = new DataGridViewTextBoxCell
  189. {
  190. Value = strGuid
  191. };
  192. dataGridViewRow.Cells.Add(txtCell);
  193. dgvSyncData.Rows.Add(dataGridViewRow);
  194. dictSource.Add(strGuid, dr);
  195. }
  196. }
  197. /// <summary>
  198. /// 添加datagridview的列
  199. /// </summary>
  200. /// <param name="dgvShow"></param>
  201. /// <param name="strColumnName"></param>
  202. /// <param name="strColumnHeaderText"></param>
  203. /// <param name="Width"></param>
  204. /// <param name="bVisible"></param>
  205. private void AddDatagridColumn(DataGridView dgvShow, string strColumnName, string strColumnHeaderText, int Width, bool bVisible = true, bool bSort = false)
  206. {
  207. DataGridViewColumn Column = new DataGridViewColumn()
  208. {
  209. Name = strColumnName,
  210. HeaderText = strColumnHeaderText,
  211. Width = Width,
  212. Visible = bVisible,
  213. CellTemplate = new DataGridViewTextBoxCell(),
  214. ReadOnly = true,
  215. SortMode = bSort ? DataGridViewColumnSortMode.Automatic : DataGridViewColumnSortMode.NotSortable
  216. };
  217. //设置文本对齐方式
  218. Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  219. Column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
  220. //设置该列背景颜色
  221. dgvShow.Columns.Add(Column);
  222. }
  223. private void AddCheckBoxColumn(DataGridView dgvShow, string strColumnName, string strColumnHeaderText, int Width, bool bVisible = true)
  224. {
  225. DataGridViewCheckBoxColumn selectedColumn = new DataGridViewCheckBoxColumn()
  226. {
  227. HeaderText = strColumnHeaderText,
  228. Name = strColumnName,
  229. Visible = bVisible,
  230. Width = Width,
  231. ReadOnly = false,
  232. TrueValue = true,
  233. FalseValue = false
  234. };
  235. //设置文本对齐方式
  236. selectedColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  237. selectedColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
  238. //设置该列背景颜色
  239. dgvShow.Columns.Add(selectedColumn);
  240. // 添加列头复选框
  241. Rectangle rect = dgvShow.GetCellDisplayRectangle(0, -1, true);
  242. rect.X = rect.Location.X + (rect.Width - 14) / 2 + 0;
  243. rect.Y = rect.Location.Y + (rect.Height - 14) / 2 + 9;
  244. this.cbHeader = new CheckBox
  245. {
  246. Name = "checkboxHeader",
  247. Size = new Size(14, 14),
  248. Location = rect.Location
  249. };
  250. cbHeader.CheckedChanged += new EventHandler(cbHeader_CheckedChanged);
  251. dgvShow.Controls.Add(cbHeader);
  252. }
  253. private CheckBox cbHeader = new CheckBox();
  254. private void cbHeader_CheckedChanged(object sender, EventArgs e)
  255. {
  256. dgvSyncData.EndEdit();
  257. if (sender is CheckBox self)
  258. {
  259. for (int index = 0; index < dgvSyncData.Rows.Count; ++index)
  260. {
  261. DataGridViewRow row = dgvSyncData.Rows[index];
  262. if (CheckState.Checked == self.CheckState)
  263. {
  264. row.Cells["selectedColumn"].Value = true;
  265. }
  266. else if (CheckState.Unchecked == self.CheckState)
  267. {
  268. row.Cells["selectedColumn"].Value = false;
  269. }
  270. }
  271. }
  272. }
  273. private void dgvSyncData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
  274. {
  275. //只有第一列“选择列”时触发
  276. if (e.ColumnIndex == 0)
  277. {
  278. if (dgvSyncData.Rows[e.RowIndex].Cells[0].Value.ToString() == "True")
  279. dgvSyncData.Rows[e.RowIndex].DefaultCellStyle.BackColor = FinedBackColor;
  280. else
  281. {
  282. if (e.RowIndex % 2 == 1)
  283. {
  284. dgvSyncData.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.WhiteSmoke;
  285. }
  286. else
  287. {
  288. dgvSyncData.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
  289. }
  290. }
  291. }
  292. }
  293. /// <summary>
  294. /// 添加datagridview的单元格
  295. /// </summary>
  296. /// <param name="dataGridViewRow"></param>
  297. /// <param name="dataGridViewColumn"></param>
  298. /// <param name="dr"></param>
  299. private void AddDataTextCell(DataGridViewRow dataGridViewRow, DataGridViewColumn dataGridViewColumn, DataRow dr)
  300. {
  301. DataGridViewTextBoxCell txtCell = new DataGridViewTextBoxCell();
  302. txtCell.Value = Convert.ToString(dr[dataGridViewColumn.Name]);
  303. dataGridViewRow.Cells.Add(txtCell);
  304. }
  305. private void btnRunData_Click(object sender, EventArgs e)
  306. {
  307. //组织上传数据
  308. if (dgvSyncData.Columns.Count <= 0) return;
  309. DataTable dtReadySource = dtSource.Clone();
  310. GetUpLoadData(ref dtReadySource);
  311. if (dtReadySource.Rows.Count <= 0)
  312. {
  313. string strMsg = "未能获得上传数据,请查询筛选后重试!";
  314. MessageBox.Show(strMsg);
  315. WriteMsgToRichTextBox(strMsg);
  316. }
  317. //执行上传
  318. RunUpLoad(dtReadySource);
  319. }
  320. /// <summary>
  321. /// 获取上传数据
  322. /// </summary>
  323. /// <param name="dtReadySource">准备上传的数据</param>
  324. private void GetUpLoadData(ref DataTable dtReadySource)
  325. {
  326. foreach (DataGridViewRow dgvRow in dgvSyncData.Rows)
  327. {
  328. if (dgvRow.DefaultCellStyle.BackColor == FinedBackColor)
  329. {
  330. string strGuid = dgvRow.Cells["GridGuid"].Value.ToString();
  331. if (!dictSource.ContainsKey(strGuid)) continue;
  332. DataRow dr = dictSource[strGuid];
  333. DataRow drReady = dtReadySource.NewRow();
  334. foreach (DataColumn dc in dtReadySource.Columns)
  335. {
  336. if (dr.Table.Columns.Contains(dc.ColumnName))
  337. drReady[dc.ColumnName] = dr[dc.ColumnName];
  338. }
  339. dtReadySource.Rows.Add(drReady);
  340. }
  341. }
  342. }
  343. private void RunUpLoad(DataTable dtReadySource)
  344. {
  345. //根据映射字段获取准备上传的所有数据
  346. if (dtReadySource == null || dtReadySource.Rows.Count <= 0) return;
  347. //构建准备插入的数据
  348. DataTable dtTarget = CnasDataOperationFact.CnasDataOperation().GetCNASTablesStruct(syncInstrumentItem.LstSyncPramas[0].TargetTable, syncInstrumentItem.SyncTargetDBInfo);
  349. if (dtTarget.Columns.Count <= 0)
  350. {
  351. MessageBox.Show("未能成功读取CNAS数据库列,请检查数据库配置。");
  352. WriteMsgToRichTextBox("未能成功读取CNAS数据库列,请检查数据库配置。");
  353. return;
  354. }
  355. //创建插入操作类
  356. CnasInsertOperation insertOperation = new CnasInsertOperation { syncInstrumentItem = syncInstrumentItem };
  357. //逐行插入数据到内存表
  358. string strErrorMsg = insertOperation.CreateInputData(dtReadySource, ref dtTarget);
  359. if (strErrorMsg != "")
  360. {
  361. MessageBox.Show(strErrorMsg);
  362. return;
  363. }
  364. if (dtTarget.Rows.Count <= 0)
  365. {
  366. MessageBox.Show("未能获取到符合要求的数据,请检查配置或联系管理员。");
  367. WriteMsgToRichTextBox("未能获取到符合要求的数据,请检查配置或联系管理员。");
  368. return;
  369. }
  370. //检查数据合法性
  371. insertOperation.CheckInsertDataFormat(dtTarget, ref strErrorMsg);
  372. if (strErrorMsg != "")
  373. {
  374. MessageBox.Show(strErrorMsg);
  375. return;
  376. }
  377. //逐行执行插入内存表数据到数据库中
  378. int ErrorCount = 0;
  379. int SuccessCount = 0;
  380. int OtherCount = 0;
  381. List<DataRow> lstError = new List<DataRow>();
  382. int cols = dtTarget.Columns.Count;
  383. foreach (DataRow dr in dtTarget.Rows)
  384. {
  385. if (cols >= 11 && dr[11].ToString().Length > 1)
  386. {
  387. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[11]}");
  388. dr[11] = kxjsf(dr[11].ToString());
  389. }
  390. if (cols >= 12 && dr[12].ToString().Length > 1)
  391. {
  392. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[12]}");
  393. }
  394. if (cols >= 13 && dr[13].ToString().Length > 1)
  395. {
  396. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[13]}");
  397. }
  398. if (cols >= 14 && dr[14].ToString().Length > 1)
  399. {
  400. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[14]}");
  401. }
  402. if (cols >= 15 && dr[15].ToString().Length > 1)
  403. {
  404. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[15]}");
  405. }
  406. if (cols >= 16 && dr[16].ToString().Length > 1)
  407. {
  408. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[16]}");
  409. }
  410. dr.AcceptChanges();
  411. int iReturn = CnasDataOperationFact.CnasDataOperation().InsertDataToCNASTable(GlobalCommonOperation.ConvertDataRowToTable(dr), syncInstrumentItem.SyncTargetDBInfo, syncInstrumentItem.LstSyncPramas, syncInstrumentItem.CnasInstrumentColumn, syncInstrumentItem.lstFixedValue);
  412. if (iReturn <= 0) //此时出现问题
  413. {
  414. if (iReturn == -1)
  415. {
  416. AppLog.ServiceInfo("数据库连接中断,终止本次上传。");
  417. WriteMsgToRichTextBox("数据库连接中断,终止本次上传。");
  418. break; //此时数据库连接中断,直接跳出循环,结束本次数据同步传输
  419. }
  420. else if (iReturn == -2) //等于-2表示插入准备更新时发现数据一致,不再执行
  421. {
  422. OtherCount++;
  423. }
  424. else
  425. {
  426. ErrorCount++;
  427. /*需要转换一下,否则会将整个dt全部写入日志*/
  428. lstError.Add(GlobalCommonOperation.ConvertDataRowToTable(dr).Rows[0]);
  429. }
  430. }
  431. else
  432. {
  433. SuccessCount++;
  434. }
  435. }
  436. ////判断返回结果
  437. //if (lstError.Count <= 0)
  438. //{
  439. // MessageBox.Show("上传完成!");
  440. //}
  441. //else
  442. //{
  443. // AppLog.Error($"未成功上传的数据如下:{TransConvert.ListToString(lstError)}");
  444. // MessageBox.Show("上传过程中发生异常,存在部分数据未成功上传,请联系管理员!");
  445. //}
  446. MessageBox.Show($"上传操作完成!其中成功{SuccessCount}条,失败{ErrorCount}条,其他{OtherCount}条。");
  447. WriteMsgToRichTextBox($"上传操作完成!其中成功{SuccessCount}条,失败{ErrorCount}条,其他{OtherCount}条。");
  448. if (lstError.Count > 0)
  449. {
  450. AppLog.Error($"未成功上传的数据如下:{TransConvert.ListToString(lstError)}");
  451. WriteMsgToRichTextBox($"未成功上传的数据如下:{TransConvert.ListToString(lstError)}");
  452. }
  453. // 记录上传时间
  454. if (0 < SuccessCount)
  455. {
  456. DateTime time = DateTime.Now;
  457. this.lblTitleLastUpdateTime.Text = $"最近上传时间:{time.ToString("yyyy-MM-dd HH:mm:ss")}";
  458. this.WriteSyncTime(time);
  459. }
  460. }
  461. private string kxjsf(string sss)
  462. {
  463. double sd = Convert.ToDouble(sss);
  464. //double sd = 123.123456;
  465. string temps2 = "0";
  466. string temps3 = "0";
  467. string temps4 = "0";
  468. int tempi2 = 0;
  469. int tempi3 = 0;
  470. int tempi4 = 0;
  471. if (sss.Contains('.'))
  472. {
  473. string[] s1 = sss.Split('.');
  474. if (s1[1].Length > 2)
  475. {
  476. if (s1[1].Length > 2)
  477. {
  478. temps2 = s1[1].Substring(1, 1);
  479. temps3 = s1[1].Substring(2, 1);
  480. }
  481. tempi2 = int.Parse(temps2);
  482. tempi3 = int.Parse(temps3);
  483. if (s1[1].Length > 3)
  484. {
  485. temps4 = s1[1].Substring(3, 1);
  486. }
  487. tempi4 = int.Parse(temps4);
  488. if (tempi3 > 5 || tempi3 < 5)
  489. {
  490. return sd.ToString("0.00");
  491. }
  492. else
  493. {
  494. if (tempi4 != 0)
  495. {
  496. return sd.ToString("0.00");
  497. }
  498. else
  499. {
  500. if (tempi2 == 0 || tempi2 == 2 || tempi2 == 4 || tempi2 == 6 || tempi2 == 8)
  501. {
  502. return sss.Substring(0, 5);
  503. }
  504. else
  505. {
  506. return sd.ToString("0.00");
  507. }
  508. }
  509. }
  510. }
  511. }
  512. return sss;
  513. }
  514. private void cmbColumns_SelectedIndexChanged(object sender, EventArgs e)
  515. {
  516. if (cmbColumns.SelectedItem == null) return;
  517. KeyValuePair<string, Type> obj = (KeyValuePair<string, Type>)cmbColumns.SelectedItem;
  518. if (DictComboBox.ContainsKey(obj.Key))
  519. {
  520. Type selectType = DictComboBox[obj.Key];
  521. switch (selectType.ToString())
  522. {
  523. case "System.DateTime":
  524. UseDateTimeControl();
  525. break;
  526. case "System.Double":
  527. case "System.Int64":
  528. case "System.Int32":
  529. UseNormalControl();
  530. //绑定条件ComboBox
  531. combCondition.DataSource = lstIntOrDouble;
  532. break;
  533. case "System.Byte[]":
  534. case "System.String":
  535. default:
  536. UseNormalControl();
  537. //绑定条件ComboBox
  538. combCondition.DataSource = lstText;
  539. break;
  540. }
  541. }
  542. }
  543. /// <summary>
  544. /// 使用时间类型专用的查询控件组
  545. /// </summary>
  546. private void UseDateTimeControl()
  547. {
  548. if (pnlCheck.Controls.Contains(pnlText))
  549. pnlCheck.Controls.Remove(pnlText);
  550. if (!pnlCheck.Controls.Contains(pnlDate))
  551. {
  552. pnlCheck.Controls.Add(pnlDate);
  553. pnlDate.Visible = true;
  554. pnlDate.Dock = DockStyle.Fill;
  555. }
  556. }
  557. /// <summary>
  558. /// 使用标准的查询控件组
  559. /// </summary>
  560. private void UseNormalControl()
  561. {
  562. if (pnlCheck.Controls.Contains(pnlDate))
  563. pnlCheck.Controls.Remove(pnlDate);
  564. if (!pnlCheck.Controls.Contains(pnlText))
  565. {
  566. pnlCheck.Controls.Add(pnlText);
  567. pnlText.Visible = true;
  568. pnlText.Dock = DockStyle.Fill;
  569. }
  570. }
  571. private void btnFind_Click(object sender, EventArgs e)
  572. {
  573. if (cmbColumns.SelectedValue == null)
  574. {
  575. return;
  576. }
  577. //0.获取数据源数据
  578. try
  579. {
  580. this.RefreshData();
  581. }
  582. catch (Exception exception)
  583. {
  584. MessageBox.Show($"查询数据时发生异常:{exception.Message}");
  585. return;
  586. }
  587. //1.合法性检测
  588. if (DictComboBox[cmbColumns.SelectedValue.ToString()].ToString().Equals("System.DateTime"))
  589. {
  590. if (dtpTarget.Value < dtpSource.Value)
  591. {
  592. MessageBox.Show("查询时间需要一个有效的时间范围!");
  593. return;
  594. }
  595. }
  596. else
  597. {
  598. if (this.txtFind.Text.Trim() == "") //为空 认为是取消查询
  599. {
  600. btnCancelFind_Click(sender, e);
  601. return;
  602. }
  603. }
  604. //2.将datagridview中满足条件的项修改背景色
  605. //2.1 判断当前显示的datagridview是否含有旧的查询数据
  606. //2.2 将满足条件的项背景色改为特殊颜色
  607. for (int index = dgvSyncData.Rows.Count - 1; 0 <= index; --index)
  608. {
  609. DataGridViewRow row = dgvSyncData.Rows[index];
  610. //查询列的当前值
  611. string strGuid = row.Cells["GridGuid"].Value.ToString();
  612. if (DictField.Count > 0)
  613. {
  614. var query = DictField.Where(s => s.Value == cmbColumns.SelectedValue.ToString());
  615. if (query.Count() == 1)
  616. {
  617. string strValue = row.Cells[query.ElementAtOrDefault(0).Key].Value.ToString();
  618. //判断是否满足条件
  619. if (false == CheckMatchCondition(strValue))
  620. {
  621. dgvSyncData.Rows.RemoveAt(index);
  622. }
  623. }
  624. }
  625. else
  626. {
  627. string strValue = row.Cells[cmbColumns.SelectedValue.ToString()].Value.ToString();
  628. //判断是否满足条件
  629. if (false == CheckMatchCondition(strValue))
  630. {
  631. dgvSyncData.Rows.RemoveAt(index);
  632. }
  633. }
  634. }
  635. }
  636. private bool CheckMatchCondition(string strValue)
  637. {
  638. if (DictComboBox[cmbColumns.SelectedValue.ToString()].ToString().Equals("System.DateTime"))
  639. {
  640. DateTime dt = DateTime.Now;
  641. if (!DateTime.TryParse(strValue, out dt)) return false;
  642. DateTime dtSource = dtpSource.Value;
  643. DateTime dtTarget = dtpTarget.Value;
  644. DateTime dtValue = dt;
  645. if (dt >= dtSource && dt <= dtTarget)
  646. return true;
  647. else
  648. return false;
  649. }
  650. else
  651. {
  652. string strFindText = this.txtFind.Text.ToString();
  653. bool bReturn = false;
  654. try
  655. {
  656. switch (combCondition.SelectedValue.ToString())
  657. {
  658. case "等于":
  659. bReturn = strValue == strFindText ? true : false;
  660. break;
  661. case "不等于":
  662. bReturn = strValue != strFindText ? true : false;
  663. break;
  664. case "包含":
  665. bReturn = strValue.Contains(strFindText) ? true : false;
  666. break;
  667. case "不包含":
  668. bReturn = !strValue.Contains(strFindText) ? true : false;
  669. break;
  670. case "大于":
  671. bReturn = Convert.ToDouble(strValue) > Convert.ToDouble(strFindText) ? true : false;
  672. break;
  673. case "不小于":
  674. bReturn = Convert.ToDouble(strValue) >= Convert.ToDouble(strFindText) ? true : false;
  675. break;
  676. case "小于":
  677. bReturn = Convert.ToDouble(strValue) < Convert.ToDouble(strFindText) ? true : false;
  678. break;
  679. case "不大于":
  680. bReturn = Convert.ToDouble(strValue) <= Convert.ToDouble(strFindText) ? true : false;
  681. break;
  682. }
  683. }
  684. catch (Exception ex)
  685. {
  686. AppLog.Error(ex.Message);
  687. bReturn = false;
  688. }
  689. return bReturn;
  690. }
  691. }
  692. /// <summary>
  693. /// 获得查询语句(非日期类型)
  694. /// </summary>
  695. /// <param name="strColumnName"></param>
  696. /// <param name="strColumnType"></param>
  697. /// <param name="strCondition"></param>
  698. /// <param name="strValue"></param>
  699. /// <returns></returns>
  700. private string GetSelectString(string strColumnName, string strCondition, string strValue)
  701. {
  702. string strCondi = "";
  703. switch (strCondition)
  704. {
  705. case "等于":
  706. strCondi = "=";
  707. break;
  708. case "不等于":
  709. strCondi = "<>";
  710. break;
  711. case "包含":
  712. strCondi = "like";
  713. break;
  714. case "不包含":
  715. strCondi = "not like";
  716. break;
  717. case "大于":
  718. strCondi = ">";
  719. break;
  720. case "不小于":
  721. strCondi = ">=";
  722. break;
  723. case "小于":
  724. strCondi = "<";
  725. break;
  726. case "不大于":
  727. strCondi = "<=";
  728. break;
  729. }
  730. if (strCondi == "like" || strCondi == "not like")
  731. return string.Format("{0} {1} '%{2}%'", strColumnName, strCondi, strValue);
  732. else
  733. return string.Format("{0} {1} '{2}'", strColumnName, strCondi, strValue);
  734. }
  735. private void btnCancelFind_Click(object sender, EventArgs e)
  736. {
  737. this.txtFind.Text = string.Empty;
  738. foreach (DataGridViewRow dgvrow in dgvSyncData.Rows)
  739. {
  740. if (dgvrow.Cells[0].Value != null && dgvrow.Cells[0].Value.ToString() == "True")
  741. dgvrow.Cells[0].Value = false;
  742. if (dgvrow.Index % 2 == 1)
  743. {
  744. dgvrow.DefaultCellStyle.BackColor = Color.WhiteSmoke;
  745. }
  746. else
  747. {
  748. dgvrow.DefaultCellStyle.BackColor = Color.White;
  749. }
  750. }
  751. }
  752. public void WriteMsgToRichTextBox(string strMsg)
  753. {
  754. Invoke(new MethodInvoker(delegate ()
  755. {
  756. this.rtxtLog.Text += string.Format("{0} 日期: {1}\n", strMsg,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  757. }));
  758. }
  759. /// <summary>
  760. ///
  761. /// </summary>
  762. /// <param name="message"></param>
  763. private void WriteSyncTime(DateTime time)
  764. {
  765. try
  766. {
  767. /* 创建文件夹 */
  768. string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache");
  769. if (!Directory.Exists(logDirectory))
  770. {
  771. Directory.CreateDirectory(logDirectory);
  772. }
  773. /* 更新时间 */
  774. string file = Path.Combine(logDirectory, $"SyncTime.bin");
  775. Dictionary<string, string> times = this.ReadSyncTime() ?? new Dictionary<string, string>();
  776. if (true == times.ContainsKey(this.syncInstrumentItem.Code))
  777. {
  778. times[this.syncInstrumentItem.Code] = time.ToString("yyyy-MM-dd HH:mm:ss");
  779. }
  780. else
  781. {
  782. times.Add(this.syncInstrumentItem.Code, time.ToString("yyyy-MM-dd HH:mm:ss"));
  783. }
  784. /* 写入文件 */
  785. File.WriteAllText(file, JsonConvert.SerializeObject(times, Formatting.Indented));
  786. }
  787. catch (Exception exception)
  788. {
  789. Invoke(new MethodInvoker(delegate ()
  790. {
  791. this.rtxtLog.Text += $"记录同步时间出错!错误信息:{exception.Message} 日期: {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n";
  792. }));
  793. }
  794. }
  795. /// <summary>
  796. ///
  797. /// </summary>
  798. private Dictionary<string, string> ReadSyncTime()
  799. {
  800. Dictionary<string, string> times = null;
  801. if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache", $"SyncTime.bin")))
  802. {
  803. try
  804. {
  805. using (StreamReader reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache", $"SyncTime.bin"), Encoding.UTF8))
  806. {
  807. try
  808. {
  809. string json = reader.ReadToEnd();
  810. times = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  811. }
  812. catch
  813. {
  814. }
  815. finally
  816. {
  817. reader.Close();
  818. reader.Dispose();
  819. }
  820. }
  821. }
  822. catch (Exception exception)
  823. {
  824. Debug.WriteLine(exception.Message);
  825. }
  826. }
  827. return times;
  828. }
  829. }
  830. }