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

SyncServiceOperation.cs 18KB

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 个月前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. 
  2. using CnasSynchronousCommon;
  3. using CnasSynchronusClient;
  4. using CnasSynchrousModel;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Timers;
  14. using System.Windows.Forms;
  15. using System.Xml.Serialization;
  16. namespace CNAS_SyncService
  17. {
  18. public class SyncServiceOperation
  19. {
  20. System.Timers.Timer timerSync;
  21. ServiceConfig config = new ServiceConfig();
  22. bool bRunComplete = true;
  23. int WaitCount = 0;
  24. string strNowDate = "";
  25. FileWatcherOperation fileWatcherOperation;
  26. public void Start()
  27. {
  28. AppLog.ServiceInfo("SyncSerivce:服务启动");
  29. //读取全局配置信息
  30. SystemFormatConfig systemFormat = FileOperation.GetSystemFormatConfigData();
  31. GlobalCommonOperation.strStartGeneralVersion = systemFormat.StartGeneralVersion;
  32. GlobalCommonOperation.strStartWebApi = systemFormat.StartWebApi;
  33. GlobalCommonOperation.strWebApiUrl = systemFormat.WebApiUrl;
  34. GlobalCommonOperation.strTargetDbType = systemFormat.TargetDBType;
  35. //读取服务配置信息
  36. config = ReadServiceConfigData();
  37. AppLog.Error("打印日志1" + config.Minutes);
  38. timerSync_Elapsed(null, null);
  39. return;
  40. if (config.Minutes != 0)
  41. {
  42. //启动文件/文件夹监控
  43. if (config.IfStartFileWatcher == "1")
  44. {
  45. fileWatcherOperation = new FileWatcherOperation(ReadSyncInstruments());
  46. fileWatcherOperation.GetFileWatcherItems();
  47. fileWatcherOperation.StartFileWatcher();
  48. }
  49. // 启动定时器
  50. timerSync = new System.Timers.Timer();
  51. timerSync.Interval = config.Minutes * 60 * 1000; //设置计时器事件间隔执行时间
  52. timerSync.Elapsed += new System.Timers.ElapsedEventHandler(timerSync_Elapsed);
  53. timerSync.Enabled = true;
  54. timerSync.AutoReset = true;
  55. }
  56. else
  57. {
  58. //写入日志
  59. AppLog.ServiceInfo("SyncSerivce:未能成功读取定时器时间,本次同步失败。");
  60. }
  61. }
  62. private void timerSync_Elapsed(object sender, ElapsedEventArgs e)
  63. {
  64. AppLog.ServiceInfo("定时器启动");
  65. //如果等待执行次数超出最大数值,则认为当前正在执行出现未知名问题,直接回收当前执行,执行下次
  66. if (WaitCount >= config.MaxWaitCount)
  67. {
  68. //回收垃圾
  69. GC.Collect();
  70. bRunComplete = true;
  71. }
  72. if (bRunComplete)
  73. {
  74. WaitCount = 0; //只要正常执行,等待标识都将恢复为0
  75. bRunComplete = false;
  76. //清理过期日志
  77. if (strNowDate != DateTime.Now.ToString("yyyyMMdd"))
  78. {
  79. AppLog.ServiceInfo("清理过期日志");
  80. strNowDate = DateTime.Now.ToString("yyyyMMdd");
  81. //删除日志文件
  82. string logDays = FileOperation.GetSystemFormatConfigData().ShowLogDays;
  83. int logday;
  84. if (int.TryParse(logDays, out logday))
  85. AppLog.DeleteLog(logday);
  86. }
  87. //执行同步程序
  88. //1.读取配置信息
  89. List<SyncInstrumentItemInfo> lstSyncInstrument = ReadSyncInstruments();
  90. //2 遍历仪器列表,逐个列表进行同步
  91. foreach (var instrumentItem in lstSyncInstrument)
  92. {
  93. //如果是文件,使用FileSystemWatcher查看文件是否发生了变化
  94. if (fileWatcherOperation != null && fileWatcherOperation.LstWatcherItems.Count > 0)
  95. {
  96. var watcherItem = fileWatcherOperation.LstWatcherItems.Where(p => p.SyncItemId == instrumentItem.GUID && p.SyncIfChanged == true).FirstOrDefault();
  97. if (watcherItem != null)
  98. {
  99. RunSyncByInstrument(instrumentItem, watcherItem);
  100. }
  101. else
  102. {
  103. AppLog.ServiceInfo("检测到文件/文件夹没有发生变化,跳过本次同步执行");
  104. }
  105. }
  106. else
  107. {
  108. RunSyncByInstrument(instrumentItem);
  109. }
  110. }
  111. bRunComplete = true;
  112. //回收垃圾
  113. GC.Collect();
  114. }
  115. else
  116. {
  117. WaitCount++;
  118. AppLog.ServiceInfo($"等待标识:{WaitCount}");
  119. }
  120. }
  121. private List<SyncInstrumentItemInfo> ReadSyncInstruments()
  122. {
  123. List<SyncInstrumentItemInfo> lstSyncInstrument = new List<SyncInstrumentItemInfo>();
  124. lstSyncInstrument = FileOperation.GetLocalSyncInStrumentData();
  125. AppLog.ServiceInfo($"读取到本地配置信息行数{lstSyncInstrument.Count}");
  126. return lstSyncInstrument;
  127. }
  128. private void RunSyncByInstrument(SyncInstrumentItemInfo syncInstrumentItem, FileWatcherItem fileWatcherItem = null)
  129. {
  130. //0.读取目标库表数据的最大时间 1.读取来源的数据 2.对读取到的数据进行逻辑处理,整理格式 3.执行同步
  131. AppLog.ServiceInfo("准备根据日期字段查询筛选");
  132. var query = syncInstrumentItem.LstSyncPramas.Where(s => s.IfDateField == true).ToList<SyncParamasInfo>();
  133. if (query.Count == 1)
  134. {
  135. string strCompareTime = "";
  136. string strDateTime = "";
  137. Dictionary<string, string> times = this.ReadSyncTime();
  138. if (true == times?.ContainsKey(syncInstrumentItem.Code))
  139. {
  140. strDateTime = $"{times[syncInstrumentItem.Code]}";
  141. }
  142. //strDateTime = "2016-07-01 00:00:00";
  143. if (strDateTime == "1899-1-1")
  144. {
  145. AppLog.ServiceInfo($"读取上次最晚执行时间失败,请检查原因。");
  146. return;
  147. }
  148. else if (strDateTime == "")
  149. {
  150. strCompareTime = Convert.ToDateTime(config.InitalDT.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
  151. }
  152. else
  153. strCompareTime = Convert.ToDateTime(strDateTime).AddDays(-3).ToString("yyyy-MM-dd HH:mm:ss");
  154. AppLog.ServiceInfo($"读取上次最晚执行时间为{strCompareTime}");
  155. object[] obj = new object[]
  156. {
  157. syncInstrumentItem.LstSyncPramas[0].SourceTable,
  158. query[0].SourceField,
  159. strCompareTime
  160. };
  161. AppLog.ServiceInfo($"准备构建数据源读取工厂");
  162. InstrumentData instrumentData = InstrumentDataFact.CreateInstrumentDataSource(syncInstrumentItem.SyncInstrumentDSInfo, obj);
  163. AppLog.ServiceInfo($"构建数据源读取工厂完成,准备读取数据源");
  164. DataTable dtReadySource = instrumentData.GetInstrumentDataByDate();
  165. AppLog.ServiceInfo($"根据日期读取准备插入的来源数据,共{dtReadySource.Rows.Count}条数据");
  166. string strErrorMsg = "";
  167. RunUpLoad(syncInstrumentItem, dtReadySource, ref strErrorMsg);
  168. if (strErrorMsg != "")
  169. {
  170. //写入日志
  171. AppLog.ServiceInfo(strErrorMsg);
  172. }
  173. else
  174. {
  175. if (fileWatcherItem != null) fileWatcherItem.SyncIfChanged = false;
  176. }
  177. }
  178. else
  179. {
  180. AppLog.ServiceInfo("SyncSerivce:未能成功读取日期字段,可能不存在或存在多个日期字段,本次同步失败。");
  181. }
  182. }
  183. private void RunUpLoad(SyncInstrumentItemInfo syncInstrumentItem, DataTable dtReadySource, ref string strMsg)
  184. {
  185. //根据映射字段获取准备上传的所有数据
  186. if (dtReadySource == null || dtReadySource.Rows.Count <= 0) return;
  187. //构建准备插入的数据
  188. DataTable dtTarget = CnasDataOperationFact.CnasDataOperation().GetCNASTablesStruct(syncInstrumentItem.LstSyncPramas[0].TargetTable, syncInstrumentItem.SyncTargetDBInfo);
  189. AppLog.ServiceInfo("读取目标数据的数据结构");
  190. if (dtTarget.Columns.Count <= 0)
  191. {
  192. strMsg = "未能成功读取CNAS数据库列,请检查数据库配置。";
  193. return;
  194. }
  195. CnasInsertOperation insertOperation = new CnasInsertOperation()
  196. {
  197. syncInstrumentItem = syncInstrumentItem
  198. };
  199. AppLog.ServiceInfo("遍历所有来源数据,构造准备插入的数据");
  200. strMsg = insertOperation.CreateInputData(dtReadySource, ref dtTarget);
  201. if (strMsg != "") return;
  202. if (dtTarget.Rows.Count <= 0)
  203. {
  204. strMsg = "创建准备插入的数据行为空。";
  205. return;
  206. }
  207. AppLog.ServiceInfo("检查准备插入的数据是否合法");
  208. insertOperation.CheckInsertDataFormat(dtTarget, ref strMsg);
  209. if (strMsg != "") return;
  210. //逐行执行插入
  211. List<DataRow> lstError = new List<DataRow>();
  212. int ErrorCount = 0;
  213. int SuccessCount = 0;
  214. int OtherCount = 0;
  215. AppLog.ServiceInfo($"逐行插入目标数据,最终准备插入(更新)数据行{dtTarget.Rows.Count}");
  216. int cols = dtTarget.Columns.Count;
  217. foreach (DataRow dr in dtTarget.Rows)
  218. {
  219. if (cols >= 11 && dr[11].ToString().Length > 1)
  220. {
  221. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[11]}");
  222. dr[11] = kxjsf(dr[11].ToString());
  223. }
  224. if (cols >= 12 && dr[12].ToString().Length > 1)
  225. {
  226. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[12]}");
  227. }
  228. if (cols >= 13 && dr[13].ToString().Length > 1)
  229. {
  230. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[13]}");
  231. }
  232. if (cols >= 14 && dr[14].ToString().Length > 1)
  233. {
  234. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[14]}");
  235. }
  236. if (cols >= 15 && dr[15].ToString().Length > 1)
  237. {
  238. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[15]}");
  239. }
  240. if (cols >= 16 && dr[16].ToString().Length > 1)
  241. {
  242. AppLog.Error($"逐行插入目标数据,最终准备插入(更新)数据行{dr[16]}");
  243. }
  244. dr.AcceptChanges();
  245. int iReturn = CnasDataOperationFact.CnasDataOperation().InsertDataToCNASTable(GlobalCommonOperation.ConvertDataRowToTable(dr), syncInstrumentItem.SyncTargetDBInfo, syncInstrumentItem.LstSyncPramas, syncInstrumentItem.CnasInstrumentColumn, syncInstrumentItem.lstFixedValue);
  246. if (iReturn <= 0) //此时出现问题
  247. {
  248. if (iReturn == -1)
  249. {
  250. AppLog.ServiceInfo("数据库连接中断,终止本次上传。");
  251. break; //此时数据库连接中断,直接跳出循环,结束本次数据同步传输
  252. }
  253. else if (iReturn == -2) //等于-2表示插入准备更新时发现数据一致,不再执行
  254. {
  255. OtherCount++;
  256. }
  257. else
  258. {
  259. ErrorCount++;
  260. //lstError.Add(GlobalCommonOperation.ConvertDataRowToTable(dr).Rows[0]);
  261. }
  262. }
  263. else
  264. {
  265. SuccessCount++;
  266. AppLog.Info("成功插入(更新)1条数据。");
  267. }
  268. }
  269. AppLog.ServiceInfo($"上传操作完成!其中成功{SuccessCount}条,失败{ErrorCount}条,其他{OtherCount}条。............................................................................................................");
  270. WriteSyncTime(DateTime.Now, syncInstrumentItem);
  271. }
  272. private void WriteSyncTime(DateTime time, SyncInstrumentItemInfo syncInstrumentItem)
  273. {
  274. try
  275. {
  276. /* 创建文件夹 */
  277. string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache");
  278. if (!Directory.Exists(logDirectory))
  279. {
  280. Directory.CreateDirectory(logDirectory);
  281. }
  282. /* 更新时间 */
  283. string file = Path.Combine(logDirectory, $"SyncTime.bin");
  284. Dictionary<string, string> times = this.ReadSyncTime() ?? new Dictionary<string, string>();
  285. if (true == times.ContainsKey(syncInstrumentItem.Code))
  286. {
  287. times[syncInstrumentItem.Code] = time.ToString("yyyy-MM-dd HH:mm:ss");
  288. }
  289. else
  290. {
  291. times.Add(syncInstrumentItem.Code, time.ToString("yyyy-MM-dd HH:mm:ss"));
  292. }
  293. /* 写入文件 */
  294. File.WriteAllText(file, JsonConvert.SerializeObject(times, Formatting.Indented));
  295. }
  296. catch (Exception exception)
  297. {
  298. //Invoke(new MethodInvoker(delegate ()
  299. //{
  300. // this.rtxtLog.Text += $"记录同步时间出错!错误信息:{exception.Message} 日期: {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n";
  301. //}));
  302. }
  303. }
  304. private string kxjsf(string sss)
  305. {
  306. double sd = Convert.ToDouble(sss);
  307. //double sd = 123.123456;
  308. string temps2 = "0";
  309. string temps3 = "0";
  310. string temps4 = "0";
  311. int tempi2 = 0;
  312. int tempi3 = 0;
  313. int tempi4 = 0;
  314. if (sss.Contains('.'))
  315. {
  316. string[] s1 = sss.Split('.');
  317. if (s1[1].Length > 2)
  318. {
  319. if (s1[1].Length > 2)
  320. {
  321. temps2 = s1[1].Substring(1, 1);
  322. temps3 = s1[1].Substring(2, 1);
  323. }
  324. tempi2 = int.Parse(temps2);
  325. tempi3 = int.Parse(temps3);
  326. if (s1[1].Length > 3)
  327. {
  328. temps4 = s1[1].Substring(3, 1);
  329. }
  330. tempi4 = int.Parse(temps4);
  331. if (tempi3 > 5 || tempi3 < 5)
  332. {
  333. return sd.ToString("0.00");
  334. }
  335. else
  336. {
  337. if (tempi4 != 0)
  338. {
  339. return sd.ToString("0.00");
  340. }
  341. else
  342. {
  343. if (tempi2 == 0 || tempi2 == 2 || tempi2 == 4 || tempi2 == 6 || tempi2 == 8)
  344. {
  345. return sss.Substring(0, 5);
  346. }
  347. else
  348. {
  349. return sd.ToString("0.00");
  350. }
  351. }
  352. }
  353. }
  354. }
  355. return sss;
  356. }
  357. private ServiceConfig ReadServiceConfigData()
  358. {
  359. ServiceConfig config = new ServiceConfig();
  360. try
  361. {
  362. //读取本地文件中存储的配置信息
  363. XmlSerializer serializer = new XmlSerializer(config.GetType());
  364. FileStream stream = new FileStream(FileHelper.getBasePath() + "/DataConfig/SyncServiceData.xml", FileMode.Open);
  365. config = (ServiceConfig)serializer.Deserialize(stream);
  366. stream.Close();
  367. }
  368. catch (Exception ex)
  369. {
  370. AppLog.ServiceInfo(ex.Message);
  371. }
  372. return config;
  373. }
  374. /// <summary>
  375. ///
  376. /// </summary>
  377. private Dictionary<string, string> ReadSyncTime()
  378. {
  379. Dictionary<string, string> times = null;
  380. if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache", $"SyncTime.bin")))
  381. {
  382. try
  383. {
  384. using (StreamReader reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache", $"SyncTime.bin"), Encoding.UTF8))
  385. {
  386. try
  387. {
  388. string json = reader.ReadToEnd();
  389. times = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  390. }
  391. catch
  392. {
  393. }
  394. finally
  395. {
  396. reader.Close();
  397. reader.Dispose();
  398. }
  399. }
  400. }
  401. catch (Exception exception)
  402. {
  403. Debug.WriteLine(exception.Message);
  404. }
  405. }
  406. return times;
  407. }
  408. }
  409. }