CNAS取数仪器端升级
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ucSynchrousMain.cs 34KB

4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. };
  233. //设置文本对齐方式
  234. selectedColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  235. selectedColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
  236. //设置该列背景颜色
  237. dgvShow.Columns.Add(selectedColumn);
  238. }
  239. /// <summary>
  240. /// 添加datagridview的单元格
  241. /// </summary>
  242. /// <param name="dataGridViewRow"></param>
  243. /// <param name="dataGridViewColumn"></param>
  244. /// <param name="dr"></param>
  245. private void AddDataTextCell(DataGridViewRow dataGridViewRow, DataGridViewColumn dataGridViewColumn, DataRow dr)
  246. {
  247. DataGridViewTextBoxCell txtCell = new DataGridViewTextBoxCell();
  248. txtCell.Value = Convert.ToString(dr[dataGridViewColumn.Name]);
  249. dataGridViewRow.Cells.Add(txtCell);
  250. }
  251. private void btnRunData_Click(object sender, EventArgs e)
  252. {
  253. //组织上传数据
  254. if (dgvSyncData.Columns.Count <= 0) return;
  255. DataTable dtReadySource = dtSource.Clone();
  256. GetUpLoadData(ref dtReadySource);
  257. if (dtReadySource.Rows.Count <= 0)
  258. {
  259. string strMsg = "未能获得上传数据,请查询筛选后重试!";
  260. MessageBox.Show(strMsg);
  261. WriteMsgToRichTextBox(strMsg);
  262. }
  263. //执行上传
  264. RunUpLoad(dtReadySource);
  265. }
  266. /// <summary>
  267. /// 获取上传数据
  268. /// </summary>
  269. /// <param name="dtReadySource">准备上传的数据</param>
  270. private void GetUpLoadData(ref DataTable dtReadySource)
  271. {
  272. foreach (DataGridViewRow dgvRow in dgvSyncData.Rows)
  273. {
  274. if (dgvRow.DefaultCellStyle.BackColor == FinedBackColor)
  275. {
  276. string strGuid = dgvRow.Cells["GridGuid"].Value.ToString();
  277. if (!dictSource.ContainsKey(strGuid)) continue;
  278. DataRow dr = dictSource[strGuid];
  279. DataRow drReady = dtReadySource.NewRow();
  280. foreach (DataColumn dc in dtReadySource.Columns)
  281. {
  282. if (dr.Table.Columns.Contains(dc.ColumnName))
  283. drReady[dc.ColumnName] = dr[dc.ColumnName];
  284. }
  285. dtReadySource.Rows.Add(drReady);
  286. }
  287. }
  288. }
  289. private void RunUpLoad(DataTable dtReadySource)
  290. {
  291. //根据映射字段获取准备上传的所有数据
  292. if (dtReadySource == null || dtReadySource.Rows.Count <= 0) return;
  293. //构建准备插入的数据
  294. DataTable dtTarget = CnasDataOperationFact.CnasDataOperation().GetCNASTablesStruct(syncInstrumentItem.LstSyncPramas[0].TargetTable, syncInstrumentItem.SyncTargetDBInfo);
  295. if (dtTarget.Columns.Count <= 0)
  296. {
  297. MessageBox.Show("未能成功读取CNAS数据库列,请检查数据库配置。");
  298. WriteMsgToRichTextBox("未能成功读取CNAS数据库列,请检查数据库配置。");
  299. return;
  300. }
  301. //创建插入操作类
  302. CnasInsertOperation insertOperation = new CnasInsertOperation { syncInstrumentItem = syncInstrumentItem };
  303. //逐行插入数据到内存表
  304. string strErrorMsg = insertOperation.CreateInputData(dtReadySource, ref dtTarget);
  305. if (strErrorMsg != "")
  306. {
  307. MessageBox.Show(strErrorMsg);
  308. return;
  309. }
  310. if (dtTarget.Rows.Count <= 0)
  311. {
  312. MessageBox.Show("未能获取到符合要求的数据,请检查配置或联系管理员。");
  313. WriteMsgToRichTextBox("未能获取到符合要求的数据,请检查配置或联系管理员。");
  314. return;
  315. }
  316. //检查数据合法性
  317. insertOperation.CheckInsertDataFormat(dtTarget, ref strErrorMsg);
  318. if (strErrorMsg != "")
  319. {
  320. MessageBox.Show(strErrorMsg);
  321. return;
  322. }
  323. //逐行执行插入内存表数据到数据库中
  324. int ErrorCount = 0;
  325. int SuccessCount = 0;
  326. int OtherCount = 0;
  327. List<DataRow> lstError = new List<DataRow>();
  328. int cols = dtTarget.Columns.Count;
  329. foreach (DataRow dr in dtTarget.Rows)
  330. {
  331. if (cols >= 11 && dr[11].ToString().Length > 1)
  332. {
  333. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[11]}");
  334. dr[11] = kxjsf(dr[11].ToString());
  335. }
  336. if (cols >= 12 && dr[12].ToString().Length > 1)
  337. {
  338. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[12]}");
  339. }
  340. if (cols >= 13 && dr[13].ToString().Length > 1)
  341. {
  342. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[13]}");
  343. }
  344. if (cols >= 14 && dr[14].ToString().Length > 1)
  345. {
  346. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[14]}");
  347. }
  348. if (cols >= 15 && dr[15].ToString().Length > 1)
  349. {
  350. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[15]}");
  351. }
  352. if (cols >= 16 && dr[16].ToString().Length > 1)
  353. {
  354. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[16]}");
  355. }
  356. dr.AcceptChanges();
  357. int iReturn = CnasDataOperationFact.CnasDataOperation().InsertDataToCNASTable(GlobalCommonOperation.ConvertDataRowToTable(dr), syncInstrumentItem.SyncTargetDBInfo, syncInstrumentItem.LstSyncPramas, syncInstrumentItem.CnasInstrumentColumn, syncInstrumentItem.lstFixedValue);
  358. if (iReturn <= 0) //此时出现问题
  359. {
  360. if (iReturn == -1)
  361. {
  362. AppLog.ServiceInfo("数据库连接中断,终止本次上传。");
  363. WriteMsgToRichTextBox("数据库连接中断,终止本次上传。");
  364. break; //此时数据库连接中断,直接跳出循环,结束本次数据同步传输
  365. }
  366. else if (iReturn == -2) //等于-2表示插入准备更新时发现数据一致,不再执行
  367. {
  368. OtherCount++;
  369. }
  370. else
  371. {
  372. ErrorCount++;
  373. /*需要转换一下,否则会将整个dt全部写入日志*/
  374. lstError.Add(GlobalCommonOperation.ConvertDataRowToTable(dr).Rows[0]);
  375. }
  376. }
  377. else
  378. {
  379. SuccessCount++;
  380. }
  381. }
  382. ////判断返回结果
  383. //if (lstError.Count <= 0)
  384. //{
  385. // MessageBox.Show("上传完成!");
  386. //}
  387. //else
  388. //{
  389. // AppLog.Error($"未成功上传的数据如下:{TransConvert.ListToString(lstError)}");
  390. // MessageBox.Show("上传过程中发生异常,存在部分数据未成功上传,请联系管理员!");
  391. //}
  392. MessageBox.Show($"上传操作完成!其中成功{SuccessCount}条,失败{ErrorCount}条,其他{OtherCount}条。");
  393. WriteMsgToRichTextBox($"上传操作完成!其中成功{SuccessCount}条,失败{ErrorCount}条,其他{OtherCount}条。");
  394. if (lstError.Count > 0)
  395. {
  396. AppLog.Error($"未成功上传的数据如下:{TransConvert.ListToString(lstError)}");
  397. WriteMsgToRichTextBox($"未成功上传的数据如下:{TransConvert.ListToString(lstError)}");
  398. }
  399. // 记录上传时间
  400. if (0 < SuccessCount)
  401. {
  402. DateTime time = DateTime.Now;
  403. this.lblTitleLastUpdateTime.Text = $"最近上传时间:{time.ToString("yyyy-MM-dd HH:mm:ss")}";
  404. this.WriteSyncTime(time);
  405. }
  406. }
  407. private string kxjsf(string sss)
  408. {
  409. double sd = Convert.ToDouble(sss);
  410. //double sd = 123.123456;
  411. string temps2 = "0";
  412. string temps3 = "0";
  413. string temps4 = "0";
  414. int tempi2 = 0;
  415. int tempi3 = 0;
  416. int tempi4 = 0;
  417. if (sss.Contains('.'))
  418. {
  419. string[] s1 = sss.Split('.');
  420. if (s1[1].Length > 2)
  421. {
  422. if (s1[1].Length > 2)
  423. {
  424. temps2 = s1[1].Substring(1, 1);
  425. temps3 = s1[1].Substring(2, 1);
  426. }
  427. tempi2 = int.Parse(temps2);
  428. tempi3 = int.Parse(temps3);
  429. if (s1[1].Length > 3)
  430. {
  431. temps4 = s1[1].Substring(3, 1);
  432. }
  433. tempi4 = int.Parse(temps4);
  434. if (tempi3 > 5 || tempi3 < 5)
  435. {
  436. return sd.ToString("0.00");
  437. }
  438. else
  439. {
  440. if (tempi4 != 0)
  441. {
  442. return sd.ToString("0.00");
  443. }
  444. else
  445. {
  446. if (tempi2 == 0 || tempi2 == 2 || tempi2 == 4 || tempi2 == 6 || tempi2 == 8)
  447. {
  448. return sss.Substring(0, 5);
  449. }
  450. else
  451. {
  452. return sd.ToString("0.00");
  453. }
  454. }
  455. }
  456. }
  457. }
  458. return sss;
  459. }
  460. private void cmbColumns_SelectedIndexChanged(object sender, EventArgs e)
  461. {
  462. if (cmbColumns.SelectedItem == null) return;
  463. KeyValuePair<string, Type> obj = (KeyValuePair<string, Type>)cmbColumns.SelectedItem;
  464. if (DictComboBox.ContainsKey(obj.Key))
  465. {
  466. Type selectType = DictComboBox[obj.Key];
  467. switch (selectType.ToString())
  468. {
  469. case "System.DateTime":
  470. UseDateTimeControl();
  471. break;
  472. case "System.Double":
  473. case "System.Int64":
  474. case "System.Int32":
  475. UseNormalControl();
  476. //绑定条件ComboBox
  477. combCondition.DataSource = lstIntOrDouble;
  478. break;
  479. case "System.Byte[]":
  480. case "System.String":
  481. default:
  482. UseNormalControl();
  483. //绑定条件ComboBox
  484. combCondition.DataSource = lstText;
  485. break;
  486. }
  487. }
  488. }
  489. /// <summary>
  490. /// 使用时间类型专用的查询控件组
  491. /// </summary>
  492. private void UseDateTimeControl()
  493. {
  494. if (pnlCheck.Controls.Contains(pnlText))
  495. pnlCheck.Controls.Remove(pnlText);
  496. if (!pnlCheck.Controls.Contains(pnlDate))
  497. {
  498. pnlCheck.Controls.Add(pnlDate);
  499. pnlDate.Visible = true;
  500. pnlDate.Dock = DockStyle.Fill;
  501. }
  502. }
  503. /// <summary>
  504. /// 使用标准的查询控件组
  505. /// </summary>
  506. private void UseNormalControl()
  507. {
  508. if (pnlCheck.Controls.Contains(pnlDate))
  509. pnlCheck.Controls.Remove(pnlDate);
  510. if (!pnlCheck.Controls.Contains(pnlText))
  511. {
  512. pnlCheck.Controls.Add(pnlText);
  513. pnlText.Visible = true;
  514. pnlText.Dock = DockStyle.Fill;
  515. }
  516. }
  517. private void btnFind_Click(object sender, EventArgs e)
  518. {
  519. if (cmbColumns.SelectedValue == null)
  520. {
  521. return;
  522. }
  523. //0.获取数据源数据
  524. try
  525. {
  526. this.RefreshData();
  527. }
  528. catch (Exception exception)
  529. {
  530. MessageBox.Show($"查询数据时发生异常:{exception.Message}");
  531. return;
  532. }
  533. //1.合法性检测
  534. if (DictComboBox[cmbColumns.SelectedValue.ToString()].ToString().Equals("System.DateTime"))
  535. {
  536. if (dtpTarget.Value < dtpSource.Value)
  537. {
  538. MessageBox.Show("查询时间需要一个有效的时间范围!");
  539. return;
  540. }
  541. }
  542. else
  543. {
  544. if (this.txtFind.Text.Trim() == "") //为空 认为是取消查询
  545. {
  546. btnCancelFind_Click(sender, e);
  547. return;
  548. }
  549. }
  550. //2.将datagridview中满足条件的项修改背景色
  551. //2.1 判断当前显示的datagridview是否含有旧的查询数据
  552. //2.2 将满足条件的项背景色改为特殊颜色
  553. for (int index = dgvSyncData.Rows.Count - 1; 0 <= index; --index)
  554. {
  555. DataGridViewRow row = dgvSyncData.Rows[index];
  556. //查询列的当前值
  557. string strGuid = row.Cells["GridGuid"].Value.ToString();
  558. if (DictField.Count > 0)
  559. {
  560. var query = DictField.Where(s => s.Value == cmbColumns.SelectedValue.ToString());
  561. if (query.Count() == 1)
  562. {
  563. string strValue = row.Cells[query.ElementAtOrDefault(0).Key].Value.ToString();
  564. //判断是否满足条件
  565. if (false == CheckMatchCondition(strValue))
  566. {
  567. dgvSyncData.Rows.RemoveAt(index);
  568. }
  569. }
  570. }
  571. else
  572. {
  573. string strValue = row.Cells[cmbColumns.SelectedValue.ToString()].Value.ToString();
  574. //判断是否满足条件
  575. if (false == CheckMatchCondition(strValue))
  576. {
  577. dgvSyncData.Rows.RemoveAt(index);
  578. }
  579. }
  580. }
  581. }
  582. private bool CheckMatchCondition(string strValue)
  583. {
  584. if (DictComboBox[cmbColumns.SelectedValue.ToString()].ToString().Equals("System.DateTime"))
  585. {
  586. DateTime dt = DateTime.Now;
  587. if (!DateTime.TryParse(strValue, out dt)) return false;
  588. DateTime dtSource = dtpSource.Value;
  589. DateTime dtTarget = dtpTarget.Value;
  590. DateTime dtValue = dt;
  591. if (dt >= dtSource && dt <= dtTarget)
  592. return true;
  593. else
  594. return false;
  595. }
  596. else
  597. {
  598. string strFindText = this.txtFind.Text.ToString();
  599. bool bReturn = false;
  600. try
  601. {
  602. switch (combCondition.SelectedValue.ToString())
  603. {
  604. case "等于":
  605. bReturn = strValue == strFindText ? true : false;
  606. break;
  607. case "不等于":
  608. bReturn = strValue != strFindText ? true : false;
  609. break;
  610. case "包含":
  611. bReturn = strValue.Contains(strFindText) ? true : false;
  612. break;
  613. case "不包含":
  614. bReturn = !strValue.Contains(strFindText) ? true : false;
  615. break;
  616. case "大于":
  617. bReturn = Convert.ToDouble(strValue) > Convert.ToDouble(strFindText) ? true : false;
  618. break;
  619. case "不小于":
  620. bReturn = Convert.ToDouble(strValue) >= Convert.ToDouble(strFindText) ? true : false;
  621. break;
  622. case "小于":
  623. bReturn = Convert.ToDouble(strValue) < Convert.ToDouble(strFindText) ? true : false;
  624. break;
  625. case "不大于":
  626. bReturn = Convert.ToDouble(strValue) <= Convert.ToDouble(strFindText) ? true : false;
  627. break;
  628. }
  629. }
  630. catch (Exception ex)
  631. {
  632. AppLog.Error(ex.Message);
  633. bReturn = false;
  634. }
  635. return bReturn;
  636. }
  637. }
  638. /// <summary>
  639. /// 获得查询语句(非日期类型)
  640. /// </summary>
  641. /// <param name="strColumnName"></param>
  642. /// <param name="strColumnType"></param>
  643. /// <param name="strCondition"></param>
  644. /// <param name="strValue"></param>
  645. /// <returns></returns>
  646. private string GetSelectString(string strColumnName, string strCondition, string strValue)
  647. {
  648. string strCondi = "";
  649. switch (strCondition)
  650. {
  651. case "等于":
  652. strCondi = "=";
  653. break;
  654. case "不等于":
  655. strCondi = "<>";
  656. break;
  657. case "包含":
  658. strCondi = "like";
  659. break;
  660. case "不包含":
  661. strCondi = "not like";
  662. break;
  663. case "大于":
  664. strCondi = ">";
  665. break;
  666. case "不小于":
  667. strCondi = ">=";
  668. break;
  669. case "小于":
  670. strCondi = "<";
  671. break;
  672. case "不大于":
  673. strCondi = "<=";
  674. break;
  675. }
  676. if (strCondi == "like" || strCondi == "not like")
  677. return string.Format("{0} {1} '%{2}%'", strColumnName, strCondi, strValue);
  678. else
  679. return string.Format("{0} {1} '{2}'", strColumnName, strCondi, strValue);
  680. }
  681. private void btnCancelFind_Click(object sender, EventArgs e)
  682. {
  683. this.txtFind.Text = string.Empty;
  684. foreach (DataGridViewRow dgvrow in dgvSyncData.Rows)
  685. {
  686. if (dgvrow.Cells[0].Value != null && dgvrow.Cells[0].Value.ToString() == "True")
  687. dgvrow.Cells[0].Value = false;
  688. if (dgvrow.Index % 2 == 1)
  689. {
  690. dgvrow.DefaultCellStyle.BackColor = Color.WhiteSmoke;
  691. }
  692. else
  693. {
  694. dgvrow.DefaultCellStyle.BackColor = Color.White;
  695. }
  696. }
  697. }
  698. private void dgvSyncData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
  699. {
  700. //只有第一列“选择列”时触发
  701. if (e.ColumnIndex == 0)
  702. {
  703. if (dgvSyncData.Rows[e.RowIndex].Cells[0].Value.ToString() == "True")
  704. dgvSyncData.Rows[e.RowIndex].DefaultCellStyle.BackColor = FinedBackColor;
  705. else
  706. {
  707. if (e.RowIndex % 2 == 1)
  708. {
  709. dgvSyncData.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.WhiteSmoke;
  710. }
  711. else
  712. {
  713. dgvSyncData.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
  714. }
  715. }
  716. }
  717. }
  718. public void WriteMsgToRichTextBox(string strMsg)
  719. {
  720. Invoke(new MethodInvoker(delegate ()
  721. {
  722. this.rtxtLog.Text += string.Format("{0} 日期: {1}\n", strMsg,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  723. }));
  724. }
  725. /// <summary>
  726. ///
  727. /// </summary>
  728. /// <param name="message"></param>
  729. private void WriteSyncTime(DateTime time)
  730. {
  731. try
  732. {
  733. /* 创建文件夹 */
  734. string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache");
  735. if (!Directory.Exists(logDirectory))
  736. {
  737. Directory.CreateDirectory(logDirectory);
  738. }
  739. /* 更新时间 */
  740. string file = Path.Combine(logDirectory, $"SyncTime.bin");
  741. Dictionary<string, string> times = this.ReadSyncTime() ?? new Dictionary<string, string>();
  742. if (true == times.ContainsKey(this.syncInstrumentItem.Code))
  743. {
  744. times[this.syncInstrumentItem.Code] = time.ToString("yyyy-MM-dd HH:mm:ss");
  745. }
  746. else
  747. {
  748. times.Add(this.syncInstrumentItem.Code, time.ToString("yyyy-MM-dd HH:mm:ss"));
  749. }
  750. /* 写入文件 */
  751. File.WriteAllText(file, JsonConvert.SerializeObject(times, Formatting.Indented));
  752. }
  753. catch (Exception exception)
  754. {
  755. Invoke(new MethodInvoker(delegate ()
  756. {
  757. this.rtxtLog.Text += $"记录同步时间出错!错误信息:{exception.Message} 日期: {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n";
  758. }));
  759. }
  760. }
  761. /// <summary>
  762. ///
  763. /// </summary>
  764. private Dictionary<string, string> ReadSyncTime()
  765. {
  766. Dictionary<string, string> times = null;
  767. if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache", $"SyncTime.bin")))
  768. {
  769. try
  770. {
  771. using (StreamReader reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache", $"SyncTime.bin"), Encoding.UTF8))
  772. {
  773. try
  774. {
  775. string json = reader.ReadToEnd();
  776. times = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  777. }
  778. catch
  779. {
  780. }
  781. finally
  782. {
  783. reader.Close();
  784. reader.Dispose();
  785. }
  786. }
  787. }
  788. catch (Exception exception)
  789. {
  790. Debug.WriteLine(exception.Message);
  791. }
  792. }
  793. return times;
  794. }
  795. }
  796. }