private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { string exceptionInfo = TraceHelper.GetExceptionInfo(e.ExceptionObject as Exception); EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , exceptionInfo , Utility.Category , EventLogEntryType.Error ); Console.WriteLine(exceptionInfo); WriteInformationToConsole("\r\n{0}", exceptionInfo); Console.ReadLine(); }
public void Start() { if (threadforwork == null) { threadforwork = new Thread(Work); } threadforwork.IsBackground = true; threadforwork.Start(); EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , StartMessage , Utility.Category , EventLogEntryType.Information ); }
static void Main() { EventLoggerHelper.TryCreateEventLogSource("AGNTSynchronousServiceLog", Utility.EventSource); EventLoggerHelper.EnabledMaxEventLogEntryTypeLevel = EventLogEntryType.Information; AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); HostFactory.Run(x => { x.Service <SystemService>(s => { s.ConstructUsing(name => new SystemService()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription(ConfigurationManager.AppSettings["ServiceDescription"]); x.SetDisplayName(ConfigurationManager.AppSettings["DisplayName"]); x.SetServiceName(ConfigurationManager.AppSettings["ServiceName"]); }); }
public void Execute(IJobExecutionContext context) { lock (LockObj) { try { EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , StartSync , Utility.Category , EventLogEntryType.Information ); var config = AppConfig.ConfigList[GetType().Name]; var service = new SyncAgntService(); service.Process(config); EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , EndSync , Utility.Category , EventLogEntryType.Information ); } catch (Exception ex) { EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , ex.ToString() , Utility.Category , EventLogEntryType.Error ); } } }
private void UploadFiles(IList <string> uploadFiles) { foreach (var f in uploadFiles) { try { _Adapter.Send( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _Config.LocalUploadDirectory), _Config.RemoteUploadDirectory, $"{f}.TMP", $"{f}.TMP" ); _Adapter.RenameFile(_Config.RemoteUploadDirectory, $"{f}.TMP", $"{f}.DAT"); EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"上传文件[{f}.DAT]成功." , Utility.Category , EventLogEntryType.Information ); //File.Delete(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _Config.LocalUploadDirectory), $"{f}.TMP")); } catch (Exception ex) { //记录错误日志,不抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"上传文件[{f}.TMP]出错:{ ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } } #endregion }
private void Work() { try { systemScheduler = SystemScheduler.CreateInstance(); foreach (var key in AppConfig.ConfigList.Keys) { systemScheduler.InitScheduler(AppConfig.ConfigList[key], key); } systemScheduler.StartScheduler(); } catch (Exception ex) { EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , ex.ToString() , Utility.Category , EventLogEntryType.Error ); } }
public void Stop() { if (systemScheduler != null) { systemScheduler.StopScheduler(); } if (threadforwork != null) { if (threadforwork.ThreadState == System.Threading.ThreadState.Running) { threadforwork.Abort(); } } EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , StopMessage , Utility.Category , EventLogEntryType.Warning ); }
public void ProcessForSynch() { var downloadSuccessFiles = new List <string>(); #region 先FTP下载以前处理的结果文件,扩展名为RET,到本地临时文件目录,然后删除已下载的远程文件,ERR错误文件可以保留 var downLoadFiles = _Adapter.ListDirectory(_Config.RemoteDownloadDirectory); foreach (var file in downLoadFiles) { try { _Adapter.Receive(_Config.RemoteDownloadDirectory, _Config.TempFilesDirectory, file, file); EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"下载文件[{file}]成功." , Utility.Category , EventLogEntryType.Information ); //只处理扩展名为RET的文件 if (file.EndsWith(FileStag.RET.ToString())) { downloadSuccessFiles.Add(file); } else { try { //扩展名不为RET的文件,下载完成后,直接删除FTP Server上的文件 _Adapter.DeleteFile(_Config.RemoteDownloadDirectory, file); } catch (Exception ex) { //记录错误日志,不用抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"删除远程文件[{file}]出错:{ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } } } catch (Exception ex) { //记录错误日志,不用抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"下传文件出错:{ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } } #endregion #region .处理每一个RET文件 var handlerSuccessFiles = new List <string>(); foreach (var df in downloadSuccessFiles) { try { var fileType = df.Substring(3, 4); if (!_Components.Any(c => c.Key.ID == fileType)) { throw new Exception($"无法找到此文件对应的处理组件.{df}"); } var currentComponent = _Components.FirstOrDefault(c => c.Key.ID == fileType); var currentDataSettings = _Config.DataPathSettings.FirstOrDefault(d => d.Key == fileType); if (currentDataSettings.Key == null) { throw new Exception($"无法找到处理此文件对应的数据库连接字符串信息.{df}"); } Type unitType = Type.GetType(_Config.UnitList.FirstOrDefault(u => u.Key == fileType).Value); IUnit currentUnit = Activator.CreateInstance(unitType) as IUnit; var idList = currentUnit.ProcessDownloadFile(currentComponent, _Config.TempFilesDirectory, df); //对于一个文件,所有的记录一起处理,如果出错,那么本省全部出错, //一块处理的目的是一个信息出错了,那么认为这个文件处理就出错了,需要分析错误原因 if (!string.IsNullOrEmpty(idList)) { currentUnit.UpdateDataToDatabase(currentDataSettings.Value, idList); } EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"处理下传文件[{df}]成功." , Utility.Category , EventLogEntryType.Information ); handlerSuccessFiles.Add(df); } catch (Exception ex) { //记录错误日志,并不抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"处理下传文件出错:{ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } } #endregion #region 把处理成功的文件move到Success目录下,处理错误的文件继续放在临时目录下,用于以后定位排查问题 foreach (var f in handlerSuccessFiles) { var sourceFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(_Config.TempFilesDirectory, f)); var targetFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(Path.Combine(_Config.TempFilesDirectory, "Success"), f)); try { File.Move(sourceFile, targetFile); //处理成功后才删除FTP服务器上的文件,没有成功就继续获取下次再处理 _Adapter.DeleteFile(_Config.RemoteDownloadDirectory, f); } catch (Exception ex) { //记录错误日志,不抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"移动文件[{sourceFile}]到[{targetFile}]目录出错:{ ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } } #endregion #region 然后从数据中查询IsProcessed = 0的记录,按照每一个省行号生成一个扩展名为TMP的文件(格式按照XX.AGNT.xml定义) foreach (var f in _Config.FileSettings) { Type unitType = Type.GetType(_Config.UnitList.FirstOrDefault(u => u.Key == f.Key).Value); IUnit currentUnit = Activator.CreateInstance(unitType) as IUnit; var currentDataSettings = _Config.DataPathSettings.FirstOrDefault(d => d.Key == f.Key); if (currentDataSettings.Key == null) { throw new Exception($"无法找到处理此类文件对应的数据库连接字符串信息.{f.Key}"); } var dataTable = new Dictionary <string, IList <Hashtable> >(); try { currentUnit.GetDataFromDatabase(currentDataSettings.Value, dataTable); EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"从数据库中获取数据[{f.Key}]成功." , Utility.Category , EventLogEntryType.Information ); } catch (Exception ex) { //记录错误日志,不抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"从数据库中获取[{f.Key}]数据出错:{ ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } AssembleFiles(f, dataTable, currentUnit); } #endregion }
public IList <string> AssembleFiles(KeyValuePair <string, Tuple <string, string, string> > fileSetting, KeyValuePair <Message, AssemblerBase> component, Dictionary <string, IList <Hashtable> > dataTable, string localUploadDirectory) { var currentAssembly = component.Value; var uploadFiles = new List <string>(); foreach (var province in dataTable.Keys)//分省 { var fileName = string.Empty; try { //分省的消息集合 var messages = new List <Message>(); var headerMessage = component.Key.Clone(); messages.Add(headerMessage); var hashTableList = dataTable[province]; var totalNumber = hashTableList.Count(); decimal totalMoney = 0; var realDate = DateTime.Now.AddDays(int.Parse(ConfigurationManager.AppSettings["AddDays"])); fileName = $"{fileSetting.Value.Item3}.{fileSetting.Key}.{province.PadLeft(5, '0')}.{string.Empty.PadRight(10, '0')}.001.E{realDate.ToString("MMdd")}"; int seqNum = 1; foreach (var rows in hashTableList) { totalMoney += decimal.Parse(rows["Amount"].ToString()); var message = component.Key.Clone(); message.Body.FirstOrDefault(b => b.ID == "SeqNum").Value = (++seqNum).ToString(); message.Body.FirstOrDefault(b => b.ID == "BranchNum").Value = rows["BranchNo"].ToString(); message.Body.FirstOrDefault(b => b.ID == "CustNum").Value = rows["CustNum"].ToString(); message.Body.FirstOrDefault(b => b.ID == "OutCardNum").Value = rows["CardNum"].ToString(); message.Body.FirstOrDefault(b => b.ID == "Amount").Value = rows["Amount"].ToString(); //优化:以后把收费类型/摘要做成可配置的参数放到数据库或者配置文件中 var chargeType = rows["ChargeType"].ToString() == "01" ? "al" : "bh"; message.Body.FirstOrDefault(b => b.ID == "PromoCode").Value = chargeType; message.Body.FirstOrDefault(b => b.ID == "IDType").Value = rows["IDType"].ToString(); message.Body.FirstOrDefault(b => b.ID == "IDCard").Value = rows["IDNum"].ToString(); message.Body.FirstOrDefault(b => b.ID == "CustName").Value = rows["CustName"].ToString(); var summary = chargeType == "al" ? "卡工本费|智能柜台" : "认证工具|智能柜台"; message.Body.FirstOrDefault(b => b.ID == "Summary").Value = summary; message.Body.FirstOrDefault(b => b.ID == "ID").Value = rows["ID"].ToString(); currentAssembly.Assemble(message); messages.Add(message); } headerMessage.Head.FirstOrDefault(b => b.ID == "FileName").Value = $"{fileName}.DAT"; headerMessage.Head.FirstOrDefault(b => b.ID == "BranchNum").Value = province; headerMessage.Head.FirstOrDefault(b => b.ID == "TotalNumber").Value = totalNumber.ToString(); headerMessage.Head.FirstOrDefault(b => b.ID == "TotalMoney").Value = totalMoney.ToString(); headerMessage.Head.FirstOrDefault(b => b.ID == "EffectTime").Value = realDate.ToString("yyyyMMdd"); currentAssembly.Assemble(headerMessage, true); //生成文件 string tempFileName = $"{fileName}.TMP"; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, localUploadDirectory); using (FileStream fs = new FileStream(Path.Combine(path, tempFileName), FileMode.Create)) { bool isFirst = true; foreach (var mes in messages) { var fileValue = new StringBuilder(); if (isFirst) { foreach (var mh in mes.Head) { fileValue.Append(mh.Value); } isFirst = false; } else { foreach (var mb in mes.Body) { fileValue.Append(mb.Value); } } byte[] data = Encoding.GetEncoding("gb2312").GetBytes(fileValue.ToString()); fs.Write(data, 0, data.Length); fs.WriteByte(13); fs.WriteByte(10); } fs.Flush(); fs.Close(); } EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"生成文件[{tempFileName}]成功." , Utility.Category , EventLogEntryType.Information ); uploadFiles.Add(fileName); } catch (Exception ex) { //记录错误日志,不抛出 EventLoggerHelper.WriteEventLogEntry ( Utility.EventSource , Utility.EventID , $"写入文件[{ fileName}.TMP]出错:{ ex.ToString()}" , Utility.Category , EventLogEntryType.Error ); } } return(uploadFiles); }