protected SyncData(OracleDbOperation targetDb, OracleDbOperation localDb, string targetCode, string localCode, FtpHelper targetFtp, FtpHelper localFtp, StringBuilder sbLog) { this.targetDb = targetDb; this.localDb = localDb; this.targetCode = targetCode; this.localCode = localCode; this.targetFtp = targetFtp; this.localFtp = localFtp; this.sbLog = sbLog; dtOperation = new DataTableOperation(); deleteAction = () => { LogOperation.Append(sbLog, "删除成功"); }; totalAction = (tableName, count) => { LogOperation.Append(sbLog, "统计:" + tableName + "表共同步了" + count + "条数据"); }; deleteFileAction = (itemCode, fileName) => { LogOperation.Append(sbLog, string.Format("项目编号:{0}, 删除文件:{1}", itemCode, fileName)); }; ftpCopyAction = (itemCode, fileCount) => { LogOperation.Append(sbLog, string.Format("项目编号:{0}, 拷贝文件数:{1}", itemCode, fileCount.ToString())); }; }
public IActionResult Index() { try { Coin coinResult = new Coin(); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44310/api/"); //HTTP GET var responseTask = client.GetAsync("coin/2/50"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync <Coin>(); readTask.Wait(); coinResult = readTask.Result; } else { LogOperation.InsertLog(new StackTrace().GetFrame(1).GetMethod().Name, string.Concat("Coinbase servisinden response hatalı döndü", result.ReasonPhrase), DateTime.Now); ModelState.AddModelError(string.Empty, "Coinbase Server error. Please contact administrator."); } } return(View(coinResult)); } catch (Exception ex) { LogOperation.InsertLog(new StackTrace().GetFrame(1).GetMethod().Name, string.Concat("Coinbase servisi çağrılırken hata oluştu", ex.Message), DateTime.Now); return(RedirectToAction("Error", "Home")); } }
public void Error(LogTarget target, IntPtr objectId, LogOperation operation) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Error) { return; } Log(LogSeverity.Error, target, objectId, operation); }
public void Error(LogTarget target, IntPtr objectId, LogOperation operation, string format, params object[] args) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Error) { return; } Log(LogSeverity.Error, target, objectId, operation, string.Format(format, args)); }
public void Warn(LogTarget target, IntPtr objectId, LogOperation operation, string message) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Warn) { return; } Log(LogSeverity.Warn, target, objectId, operation, message); }
public void Log(LogSeverity severity, LogTarget target, IntPtr objectId, LogOperation operation) { if (this.targets[(int)target] == false || this.severity > severity) { return; } Write(severity, target, objectId, operation, null); }
public static void SaveLog(LogOperation log) { _queuedLogs.Enqueue(log); if (log.Urgent || _queuedLogs.Count >= MaxQueueSize) { FlushQueuedLogs(); } }
public unsafe void Fatal(LogTarget target, void *objectId, LogOperation operation, string message) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Fatal) { return; } Log(LogSeverity.Fatal, target, objectId, operation, message); }
public unsafe void Fatal(LogTarget target, void *objectId, LogOperation operation, string format, params object[] args) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Fatal) { return; } Log(LogSeverity.Fatal, target, objectId, operation, string.Format(format, args)); }
public unsafe void Fatal(LogTarget target, void *objectId, LogOperation operation) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Fatal) { return; } Log(LogSeverity.Fatal, target, (IntPtr)objectId, operation); }
public Log() { InitializeComponent(); logOperation = new LogOperation(); var operation = new List <LogOperation>(); logOperation.GetLog(operation); dgvLog.DataSource = operation; }
[HttpGet("{fiattype}/{maxsize}/{symbol}")]// GET /api/coin public IActionResult GetCoinBySymbol(string symbol) { try { return(Ok(_coinData.GetCoinList(FiatType.USD).Datas.Where(x => x.Symbol == symbol))); } catch (Exception ex) { LogOperation.InsertLog("Coin/GetCoinBySymbol", string.Concat("Coinbase servisi çağrılırken hata oluştu", ex.Message), DateTime.Now); return(NotFound(ex.Message)); } }
[HttpGet("{fiattype}/{maxsize}")]// GET /api/coin public IActionResult GetCoinList(FiatType fiatType, int maxSize) { try { return(Ok(_coinData.GetCoinList(fiatType, maxSize))); } catch (Exception ex) { LogOperation.InsertLog("Coin/GetCoinList", string.Concat("Coinbase servisi çağrılırken hata oluştu", ex.Message), DateTime.Now); return(NotFound(ex.Message)); } }
protected LogOperation GetLogException(EnumOperation operation) { LogOperation logOperation = new LogOperation() { Date = DateTime.Now, Controller = this.ControllerContext.RouteData.Values["controller"].ToString(), Description = this.ControllerContext.RouteData.Values["action"].ToString(), Operation = operation.ToString() }; return(logOperation); }
/// <summary> /// 同步。 /// </summary> /// <param name="setting">同步配置。</param> /// <param name="log">日志信息。</param> /// <returns>同步是否成功。</returns> public bool Sync(SyncConfig syncConfig, SyncConfigTarget targetConfig, SyncConfigLocal localConfig, ref StringBuilder sbLog) { bool result = false; LogOperation.Append(sbLog, string.Format("开始同步数据:{0}({1}) 开始时间:{2}", targetConfig.Name, targetConfig.Code, DateTime.Now)); OracleDbOperation localDb = new OracleDbOperation(localConfig.DbConfig.ConnStr); FtpHelper localFtp = new FtpHelper(localConfig.FtpConfig.Ip, localConfig.FtpConfig.Port, localConfig.FtpConfig.Username, localConfig.FtpConfig.Password); OracleDbOperation targetDb = new OracleDbOperation(targetConfig.DbConfig.ConnStr); FtpHelper targetFtp = new FtpHelper(targetConfig.FtpConfig.Ip, targetConfig.FtpConfig.Port, targetConfig.FtpConfig.Username, targetConfig.FtpConfig.Password); try { targetDb.BeginTransaction(); localDb.BeginTransaction(); List <SyncData> syncDataList = new List <SyncData>(); ////系统数据 syncDataList.Add(new SyncDataSystemInfo(targetDb, localDb, targetConfig.Code, localConfig.Code, targetFtp, localFtp, sbLog)); ////项目数据 syncDataList.Add(new SyncDataItem(syncConfig, targetDb, localDb, targetConfig.Code, localConfig.Code, targetFtp, localFtp, sbLog)); ////流程数据 syncDataList.Add(new SyncDataWorkflow(targetDb, localDb, targetConfig.Code, localConfig.Code, targetFtp, localFtp, sbLog)); ////Syncs.Add(new SyncXtxx(targetDbOperation, localDbOperation, targetSetting.Code, localSetting.Code, targetFtpOperation, localFtpOperation, sbLog)); foreach (var syncData in syncDataList) { syncData.Sync(); } targetDb.Commit(); localDb.Commit(); result = true; } catch (Exception e) { targetDb.Rollback(); localDb.Rollback(); LogOperation.WriteExceptionLog(sbLog, e); } sbLog.AppendLine(); sbLog.AppendLine("结束时间:" + DateTime.Now); return(result); }
protected LogOperation GetLogOperation(EnumOperation operation, RouteData routeData, int userId) { LogOperation logOperation = new LogOperation() { Date = DateTime.Now, Controller = routeData.Values["controller"].ToString(), Description = routeData.Values["action"].ToString(), Operation = operation.ToString(), UserId = userId }; if (userId == 0) { logOperation.Description += " Login: "******"Login"].ToString(); } return(logOperation); }
public static void InsertLog(LogOperation logOp, string title, string description, string pageUrl) { NTSDBContext db = new NTSDBContext(); int UserID = Functions.CurrentUserID(); string operation = getOperationType(logOp); //ActivityLog log = new ActivityLog(); //log.ActionType = operation; //log.Title = title; //log.Description = description; //log.UserID = UserID; //log.AddedOn = DateTime.Now; //log.PageUrl = pageUrl; //log.RemoteAddress = HttpContext.Current.Request.UserHostAddress; //db.ActivityLog.Add(log); //db.SaveChanges(); }
public static string getOperationType(LogOperation logOp) { if (logOp == LogOperation.Add) { return("Add"); } else if (logOp == LogOperation.Update) { return("Update"); } else if (logOp == LogOperation.Delete) { return("Delete"); } else if (logOp == LogOperation.Search) { return("Search"); } else if (logOp == LogOperation.View) { return("View"); } else if (logOp == LogOperation.Active) { return("Active"); } else if (logOp == LogOperation.InActive) { return("InActive"); } else if (logOp == LogOperation.Publish) { return("Publish"); } else if (logOp == LogOperation.UnPublish) { return("UnPublish"); } else { return(""); } }
public override void ExecuteCommand(LogSession session, StringRequestInfo requestInfo) { try { string[] contents = requestInfo.Body.Split(','); int pageNumber = 0; int.TryParse(contents[0], out pageNumber); int rowsPerPage = 0; int.TryParse(contents[1], out rowsPerPage); AlarmLogRepository repo = new AlarmLogRepository(); List <AlarmLog> alarmLogList = repo.GetListPaged(pageNumber, rowsPerPage, null, "OperationTime desc"); session.TrySend("GetAlarmLog " + JsonConvert.SerializeObject(alarmLogList) + "\r\n"); } catch (Exception ex) { LogOperation.AddErrLog(LogOperation.ErrLogType.InnerErr, ex); } }
public static void assignLogPath(string __logpath, LogState _logstate, LogOperation _logoperation) { _logPath = (_logoperation.Equals(LogOperation.BackupOperation)) ? $"{__logpath}\\Backup_ErrorLog_{DateTime.Now.ToString("yyyy_MM_dd")}.csv" : $"{__logpath}\\Restore_ErrorLog_{DateTime.Now.ToString("yyyy_MM_dd")}.csv"; if (_logstate.Equals(LogState.Overwrite)) { if (File.Exists(_logPath)) { try { File.Delete(_logPath); } catch (Exception) { throw; } } } }
/// <summary> /// 日志检查线程 /// </summary> private static void AutoLogCheckThread(object o) { ABCDManager autoLogCheck = o as ABCDManager; LogOperation logOperation = new LogOperation(); while (autoLogCheck.IBoolIsThreadLogCheckWorking) { try { logOperation.LogCompressionAndDelete(); Thread.Sleep(100); } catch (Exception e) { FileLog.WriteError("AutoLogCheckThread() ", e.Message); Thread.Sleep(5 * 60 * 1000); } } }
public override void Sync() { LogOperation.WriteTitle(sbLog, "-------------------------------------同步流程信息开始-------------------------------------"); string companyCodeConditionString = "ccode = '" + targetCode + "'"; List <string> workflowId = new List <string>(); LogOperation.WriteSyncTableTitle(sbLog, "wf_workflow", SyncType.AddAfterDelete, companyCodeConditionString); SyncByAddAfterDelete("wf_workflow", companyCodeConditionString, deleteAction, (dr) => { LogOperation.Append(sbLog, "流程ID:" + dr["FLOWID"] + "。"); workflowId.Add("'" + dr["FLOWID"] + "'"); }, totalAction); string workflowConditionString = "flowid in (" + string.Join(",", workflowId.ToArray()) + ")"; LogOperation.WriteSyncTableTitle(sbLog, "wf_node", SyncType.AddAfterDelete, workflowConditionString); SyncByAddAfterDelete("wf_node", workflowConditionString, deleteAction, (dr) => { LogOperation.Append(sbLog, "流程ID:" + dr["FLOWID"] + "," + "环节ID" + dr["NODEID"] + "。"); }, totalAction); LogOperation.WriteSyncTableTitle(sbLog, "wf_file", SyncType.Comparer, string.Empty); SyncByComparer("wf_file", string.Empty, new List <string>() { "FILECODE" }, false, (dr) => { LogOperation.Append(sbLog, "添加 文档编码:" + dr["FILECODE"]); }, (dr) => { LogOperation.Append(sbLog, "删除 文档编码:" + dr["FILECODE"]); }, (drTarget, drLocal) => { LogOperation.Append(sbLog, "更新 文档编码:" + drTarget["FILECODE"]); }); LogOperation.WriteTitle(sbLog, "-------------------------------------同步流程信息结束-------------------------------------"); }
public IActionResult Authenticate(User model) { string response = string.Empty; try { response = _userService.Authenticate(model); if (string.IsNullOrEmpty(response)) { LogOperation.InsertLog("User/Authenticate", string.Format("Hatalı login işlemi : Username - {0} - Password - {1}", model.UserName, model.Password), DateTime.Now); return(BadRequest(new { message = "Username or password is incorrect" })); } } catch (Exception ex) { LogOperation.InsertLog("User/Authenticate", string.Format("Authenticate metodunda hata alındı : {0}", ex.Message), DateTime.Now); } return(Ok(response)); }
public IActionResult UploadBase64(string fileBase64, string fileName) { try { byte[] bytes = Convert.FromBase64String(fileBase64); var fileExtension = Path.GetExtension(fileName); var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); var strRan = Convert.ToString(new Random().Next(100, 999)); var saveName = strDateTime + strRan + fileExtension; var savePath = @"H:\Wangtiantian\资料\.NET Core\Web.NET Core.Demo\Web.NETCoreAPI\UploadFile\File\" + saveName; FileStream fs = new FileStream(savePath, FileMode.CreateNew); fs.Write(bytes, 0, bytes.Length); fs.Close(); return(Ok(savePath)); } catch (Exception ex) { LogOperation.WriteLog(ex.ToString()); return(Ok("上传失败!")); } }
public override void Sync() { MessageManage messageManage = new MessageManage(); Action <DataRow> actionAddLocalMessageFile = new Action <DataRow>((dr) => { string xxbh = dr["xxbh"].ToString(); string messageFtpPath = CommonManage.GetFtpMessagePath(); LogOperation.Append(sbLog, "从" + targetCode + "到" + localCode + "同步系统消息(" + xxbh + ")的文件。"); targetFtp.CopyDirectory(messageFtpPath, xxbh, localFtp, messageFtpPath, xxbh, null); }); Action <DataRow> actionAddTargetMessageFile = new Action <DataRow>((dr) => { string xxbh = dr["xxbh"].ToString(); string messageFtpPath = CommonManage.GetFtpMessagePath(); LogOperation.Append(sbLog, "从" + localCode + "到" + targetCode + "同步系统消息(" + xxbh + ")的文件。"); localFtp.CopyDirectory(messageFtpPath, xxbh, targetFtp, messageFtpPath, xxbh, null); }); Action <DataRow> actionDeleteLocalMessageFile = new Action <DataRow>((dr) => { string xxbh = dr["xxbh"].ToString(); LogOperation.Append(sbLog, "删除" + localCode + "的系统消息(" + xxbh + ")的文件。"); localFtp.DeleteDirectory(CommonManage.GetFtpMessagePath(xxbh)); }); Action <DataRow> actionDeleteTargetMessageFile = new Action <DataRow>((dr) => { string xxbh = dr["xxbh"].ToString(); LogOperation.Append(sbLog, "删除" + targetCode + "的系统消息(" + xxbh + ")的文件。"); targetFtp.DeleteDirectory(CommonManage.GetFtpMessagePath(xxbh)); }); LogOperation.WriteTitle(sbLog, "同步系统消息开始(从" + targetCode + "到" + localCode + ")。"); SyncXxbh(targetDb, localDb, localCode, actionAddLocalMessageFile, actionDeleteTargetMessageFile, actionDeleteLocalMessageFile); LogOperation.WriteTitle(sbLog, "同步系统消息结束(从" + targetCode + "到" + localCode + ")。"); LogOperation.WriteTitle(sbLog, "同步系统消息开始(从" + localCode + "到" + targetCode + ")。"); SyncXxbh(localDb, targetDb, targetCode, actionAddTargetMessageFile, actionDeleteLocalMessageFile, actionDeleteTargetMessageFile); LogOperation.WriteTitle(sbLog, "同步系统消息结束(从" + localCode + "到" + targetCode + ")。"); }
public ActionResult Search(string symbol) { List <Data> coinResult = new List <Data>(); try { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44310/api/"); var responseTask = client.GetAsync("coin/2/5000/" + symbol.ToUpper()); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync <List <Data> >(); readTask.Wait(); coinResult = readTask.Result; if (coinResult != null) { coinResult.ForEach(s => s.last_updated = DateTime.Now.ToString()); } } else { LogOperation.InsertLog(new StackTrace().GetFrame(1).GetMethod().Name, string.Concat("Coinbase servisinden response hatalı döndü", result.ReasonPhrase), DateTime.Now); ModelState.AddModelError(string.Empty, "Coinbase Server error. Please contact administrator."); } } return(View("CoinInfo", coinResult)); } catch (Exception ex) { LogOperation.InsertLog(new StackTrace().GetFrame(1).GetMethod().Name, string.Concat("Coinbase servisi çağrılırken hata oluştu", ex.Message), DateTime.Now); return(RedirectToAction("Error", "Home")); } }
public ActionResult Autherize(User user) { try { string jToken = string.Empty; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44310/user/authenticate"); //HTTP POST var postTask = client.PostAsJsonAsync <User>("authenticate", user); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsStringAsync(); readTask.Wait(); jToken = readTask.Result; } if (string.IsNullOrEmpty(jToken)) { ModelState.AddModelError("LogOnError", "The user name or password provided is incorrect."); return(View()); } else { return(RedirectToAction("CoinInfo", "Home")); } } } catch (Exception ex) { LogOperation.InsertLog("Login/Autherize", string.Concat("Coinbase servisi çağrılırken hata oluştu", ex.Message), DateTime.Now); return(RedirectToAction("Error", "Home")); } }
public unsafe void Warn(LogTarget target, void* objectId, LogOperation operation, string format, params object[] args) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Warn) return; Log(LogSeverity.Warn, target, objectId, operation, string.Format(format, args)); }
public async Task RestorePartialParallelAsync(Regions regions, string TargetPath, string _user, LogOptions _logOptions, LogState _logstate, LogOperation _logoperation, CancellationToken token) { Logger.assignLogPath(TargetPath, _logstate, _logoperation); RestoreCopyHandler objrestorehandler = new RestoreCopyHandler(); objrestorehandler.OnAtomicCurrent += DataBackup_OnAtomicCurrent; var model = FileOperations.Read(TargetPath); if (model.CustomPaths != null) { regions.SetPaths(model.CustomPaths); } OnDataRestoreStart?.Invoke(this, new StringEventArgs("Data Restore Started")); var BackupDirectoriesInfo = (new DirectoryInfo(TargetPath)).GetDirectories(); foreach (var path in regions.GetPaths(_user)) { PathValidator validator = new PathValidator(); if (validator.Validate(path)) { var _path = new DirectoryInfo(path); foreach (var item in BackupDirectoriesInfo.Where(x => x.Name.Equals(_path.Name))) { if (!(new DirectoryInfo(path)).Name.Equals(item.Name)) { OnCalculationStart?.Invoke(this, true); //EnumData countModel = new EnumData(); //CountModel counts = await countModel.GetCountAsync(new DirectoryInfo(item.FullName)); //OnAtomicTotalCounts?.Invoke(this, (counts.FileCount + counts.DirCount)); int counts = await SafeNativeMethods.FilesAndDirectoryListCountAsync(item.FullName); OnAtomicTotalCounts?.Invoke(this, counts); new DirectoryInfo($@"{path}\{item.Name}").Create(); await objrestorehandler.CopyPartialParallelAsync(item, new DirectoryInfo($@"{path}\{item.Name}"), _logOptions, token); } else { OnCalculationStart?.Invoke(this, true); //EnumData countModel = new EnumData(); //CountModel counts = await countModel.GetCountAsync(new DirectoryInfo(item.FullName)); //OnAtomicTotalCounts?.Invoke(this, (counts.FileCount + counts.DirCount)); int counts = await SafeNativeMethods.FilesAndDirectoryListCountAsync(item.FullName); OnAtomicTotalCounts?.Invoke(this, counts); await objrestorehandler.CopyPartialParallelAsync(item, new DirectoryInfo(path), _logOptions, token); } } } else { Logger.log(path, "path not found", _logOptions); } } OnDataRestoreComplete?.Invoke(this, new StringEventArgs("Data Restore Completed")); }
public void Log(LogSeverity severity, LogTarget target, IntPtr objectId, LogOperation operation, string message) { if (this.targets[(int)target] == false || this.severity > severity) return; Write(severity, target, objectId, operation, message); }
public unsafe void Debug(LogTarget target, void* objectId, LogOperation operation, string message) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Debug) return; Log(LogSeverity.Debug, target, objectId, operation, message); }
public void Debug(LogTarget target, IntPtr objectId, LogOperation operation, string format, params object[] args) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Debug) return; Log(LogSeverity.Debug, target, objectId, operation, string.Format(format, args)); }
public void Warn(LogTarget target, IntPtr objectId, LogOperation operation, string message) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Warn) return; Log(LogSeverity.Warn, target, objectId, operation, message); }
public void Trace(LogTarget target, IntPtr objectId, LogOperation operation) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Trace) return; Log(LogSeverity.Trace, target, objectId, operation); }
public unsafe void Log(LogSeverity severity, LogTarget target, void* objectId, LogOperation operation) { if (this.targets[(int)target] == false || this.severity > severity) return; Write(severity, target, (IntPtr)objectId, operation, null); }
public unsafe void Log(LogSeverity severity, LogTarget target, void* objectId, LogOperation operation, string format, params object[] args) { if (this.targets[(int)target] == false || this.severity > severity) return; Write(severity, target, (IntPtr)objectId, operation, string.Format(format, args)); }
public unsafe void Warn(LogTarget target, void* objectId, LogOperation operation) { if (this.targets[(int)target] == false || this.severity > LogSeverity.Warn) return; Log(LogSeverity.Warn, target, (IntPtr)objectId, operation); }
private void Write(LogSeverity severity, LogTarget target, IntPtr objectId, LogOperation operation, string message) { var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); lock (this) { if (this.writer != null) { try { this.writer.Flush(); } catch (ObjectDisposedException) { this.writer = null; } } if (this.writer == null) Open(); if (this.disabled) return; this.writer.Write(now); this.writer.Write('|'); this.writer.Write("{0:X8}|", (uint)(Process.GetCurrentProcess().Id)); var threadId = Thread.CurrentThread.ManagedThreadId; this.writer.Write(threadId.ToString().PadLeft(2)); this.writer.Write('|'); this.writer.Write("{0:X8}", GetCurrentThreadId()); this.writer.Write('|'); if (Cef.CurrentlyOn(CefThreadId.UI)) { this.writer.Write("CefUI "); } else if (Cef.CurrentlyOn(CefThreadId.IO)) { this.writer.Write("CefIO "); } else if (Cef.CurrentlyOn(CefThreadId.File)) { this.writer.Write("CefFile"); } else if (threadId == gcFinalizerThreadId) { this.writer.Write("GC "); } else { var threadName = Thread.CurrentThread.Name; if (string.IsNullOrEmpty(threadName)) { this.writer.Write(" "); } else { if (threadName.Length > 7) threadName = threadName.Substring(0, 7); this.writer.Write(threadName.PadRight(7)); } } this.writer.Write('|'); this.writer.Write(severityNames[(int)severity]); this.writer.Write('|'); this.writer.Write(targetNames[(int)target]); this.writer.Write('|'); if (objectId == IntPtr.Zero) { this.writer.Write(" "); } else { this.writer.Write("{0:X8}", (uint)objectId); } this.writer.Write('|'); if (operation != LogOperation.None) { this.writer.Write(operationNames[(int)operation]); if (message != null) this.writer.Write(": "); } this.writer.WriteLine(message ?? string.Empty); if (this.autoFlush) writer.Flush(); } }
private void SyncXxbh(OracleDbOperation sourceDbOperation, OracleDbOperation targetDbOperation, string targetCode, Action <DataRow> actionAddTargetMessageFile, Action <DataRow> actionDeleteSourceMessageFile, Action <DataRow> actionDeleteTargetMessageFile) { string sql; List <OracleParameter> parameters = new List <OracleParameter>(); DataTable dt; //用指定的行政区代码去系统信息接收表中查询所有与接收人行政区代码相等的记录,即需要同步的信息编号。 sql = "select distinct(jsxxbh) from xtxxjs where jsrxzdm = :jsrxzdm"; parameters.Clear(); parameters.Add(new OracleParameter("jsrxzdm", targetCode)); dt = sourceDbOperation.ExecuteDataTable(sql, "temp", parameters); var xxbhs = (from DataRow dr in dt.Rows select "'" + dr[0] + "'").ToArray(); if (xxbhs.Length > 0) { //分别取源系统和目标系统取出需要同步的信息接收数据。 string xxbhsCondition = string.Join(",", xxbhs); sql = "select * from xtxxjs where jsxxbh in (" + xxbhsCondition + ")"; DataTable dtSourceXtxxjs = sourceDbOperation.ExecuteDataTable(sql, "xtxxjs", null); DataTable dtTargetXtxxjs = targetDbOperation.ExecuteDataTable(sql, "xtxxjs", null); string xtxxCondition = "xxbh in (" + xxbhsCondition + ")"; //进行比对同步。 LogOperation.WriteSyncTableTitle(sbLog, "xtxx", SyncType.Comparer, xtxxCondition); SyncByComparer(sourceDbOperation, targetDbOperation, "xtxx", xtxxCondition, new List <string>() { "xxbh" }, true, (dr) => { string xxbh = dr["xxbh"].ToString(); LogOperation.Append(sbLog, "添加目标系统信息!信息编号:" + xxbh); foreach (var needAddXtxxjs in dtSourceXtxxjs.Select("jsxxbh = '" + xxbh + "' and jsrxzdm = '" + targetCode + "'")) { DataRow newXtxxjs = dtTargetXtxxjs.NewRow(); Copy(needAddXtxxjs, newXtxxjs); dtTargetXtxxjs.Rows.Add(newXtxxjs); } if (actionAddTargetMessageFile != null) { actionAddTargetMessageFile(dr); } }, (dr) => { LogOperation.Append(sbLog, "删除垃圾系统信息!信息编号:" + dr["XXBH"]); }, (drSource, drTarget) => { string xxbh = drSource["XXBH"].ToString(); LogOperation.Append(sbLog, "更新系统信息!信息编号:" + xxbh); if (actionAddTargetMessageFile != null) { actionAddTargetMessageFile(drSource); } //判断是否需要删除邮件。 if (drSource["FSRSC"].ToString() == "1") { var querySource = from DataRow dr in dtSourceXtxxjs.Rows where dr["JSXXBH"].ToString() == xxbh select dr; var queryTarget = from DataRow dr in dtTargetXtxxjs.Rows where dr["JSXXBH"].ToString() == xxbh select dr; bool needDelete = true; foreach (var itemSource in querySource) { string jsr = itemSource["JSR"].ToString(); var queryTargetJsr = (from dr in queryTarget where dr["JSR"].ToString() == jsr select dr).FirstOrDefault(); if (queryTargetJsr == null) { if (itemSource["JSRSC"].ToString() == "0") { needDelete = false; break; } } else { if (queryTargetJsr["JSRSC"].ToString() == "0") { needDelete = false; break; } } } //删除邮件。 if (needDelete) { dtOperation.DeleteDbDataRow(drSource, (dr) => { dtOperation.DeleteDbDataRows(querySource, null); LogOperation.Append(sbLog, "删除源系统信息,因为收发双方都已删除此信息!信息编号:" + xxbh); actionDeleteSourceMessageFile(drSource); }); dtOperation.DeleteDbDataRow(drTarget, (dr) => { dtOperation.DeleteDbDataRows(queryTarget, null); LogOperation.Append(sbLog, "删除目标系统信息,因为收发双方都已删除此信息!信息编号:" + xxbh); actionDeleteSourceMessageFile(drTarget); }); } } }); //保存信息接收信息。 sourceDbOperation.UpdateDataTable(dtSourceXtxxjs); targetDbOperation.UpdateDataTable(dtTargetXtxxjs); } }
public LogEntry(string key, LogOperation op) { this.Key = key; this.Op = op; }
/// <summary> /// Register audit information /// </summary> /// <param name="context">The current context</param> /// <param name="entry">DbContext entry to audit</param> /// <param name="logOperation">Audit operation</param> private static void ApplyAuditLog(DbContext context, DbEntityEntry entry, LogOperation logOperation) { var currentPrincipal = Thread.CurrentPrincipal; var user = currentPrincipal != null? (currentPrincipal.Identity).Name:string.Empty; var includedProperties = new List <string>(); var entityKey = context.GetEntityKey(entry.Entity).GetEntityString(); var entityType = entry.Entity.GetType(); if (entry.IsAttr <AuditableAttribute>()) { var props = entityType.GetProperties().Where(pi => !pi.IsAttr <NotAuditableAttribute>()); includedProperties.AddRange(props.Select(pi => pi.Name)); } else { var props = entityType.GetProperties() .Where(p => p.IsAttr <AuditableAttribute>() && !p.IsAttr <NotAuditableAttribute>()); includedProperties.AddRange(props.Select(pi => pi.Name)); } if (entry.State == EntityState.Modified) { var originalValues = context.Entry(entry.Entity).GetDatabaseValues(); var changedProperties = (from propertyName in originalValues.PropertyNames let propertyEntry = entry.Property(propertyName) let currentValue = propertyEntry.CurrentValue let originalValue = originalValues[propertyName] where (!Equals(currentValue, originalValue) && includedProperties.Contains(propertyName)) select new ChangedProperty { Name = propertyName, CurrentValue = currentValue, OriginalValue = originalValue }).ToArray(); if (changedProperties.Any()) { foreach (var log in changedProperties.Select(changedProperty => new AuditLog { Created = DateTime.Now, EntityFullName = entry.Entity.GetType().FullName, Entity = Utils.Serialize(entry.Entity), EntityId = entityKey, Operation = logOperation, User = user, OldValue = Convert.ToString(changedProperty.OriginalValue), NewValue = Convert.ToString(changedProperty.CurrentValue), PropertyName = changedProperty.Name })) { // ReSharper disable once SuspiciousTypeConversion.Global ((IAuditDbContext)context).AuditLogs.Add(log); } } } else if (includedProperties.Any()) { var log = new AuditLog { Created = DateTime.Now, EntityFullName = entry.Entity.GetType().FullName, Entity = Utils.Serialize(entry.Entity), EntityId = entityKey, Operation = logOperation, User = user }; // ReSharper disable once SuspiciousTypeConversion.Global ((IAuditDbContext)context).AuditLogs.Add(log); } }
public void ApplyAuditLog(DbContext workingContext, DbEntityEntry entry, LogOperation logOperation) { var includedProperties = new List<string>(); var entityKey = workingContext.GetEntityKey(entry.Entity); var entityType = entry.Entity.GetType(); if (entry.IsAttr<AuditableAttribute>()) { var props = entityType.GetProperties().Where(pi => !pi.IsAttr<NotAuditableAttrubute>()); includedProperties.AddRange(props.Select(pi => pi.Name)); } else { var props = entityType.GetProperties() .Where(p => p.IsAttr<AuditableAttribute>() && !p.IsAttr<NotAuditableAttrubute>()); includedProperties.AddRange(props.Select(pi => pi.Name)); } if (entry.State == EntityState.Modified) { var originalValues = workingContext.Entry(entry.Entity).GetDatabaseValues(); var changedProperties = (from propertyName in originalValues.PropertyNames let propertyEntry = entry.Property(propertyName) let currentValue = propertyEntry.CurrentValue let originalValue = originalValues[propertyName] where (!Equals(currentValue, originalValue) && includedProperties.Contains(propertyName)) select new ChangedProperty { Name = propertyName, CurrentValue = currentValue, OriginalValue = originalValue }).ToArray(); if (changedProperties.Any()) { foreach (var log in changedProperties.Select(changedProperty => new AuditLog { Created = DateTime.Now, EntityFullName = entry.Entity.GetType().FullName, Entity = Utils.Serialize(entry.Entity), EntityIdBytes = Utils.Serialize(entry.Entity), Operation = logOperation, OldValue = changedProperty.OriginalValue.ToString(), NewValue = changedProperty.CurrentValue.ToString(), PropertyName = changedProperty.Name })) { AuditLogs.Add(log); } SaveChanges(); } } else { var log = new AuditLog { Created = DateTime.Now, EntityFullName = entry.Entity.GetType().FullName, Entity = Utils.Serialize(entry.Entity), EntityIdBytes = Utils.Serialize(entityKey), Operation = logOperation, }; AuditLogs.Add(log); SaveChanges(); } }