CNAS取数仪器端升级
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

367 líneas
15KB

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