// 过滤器 public bool IsFilterOK(LogInfo info) { if (info.Category == "ResetLogMirror") { return true; } if (((int)info.LogType & _logType ) == 0) { return false; } if (_lstLogCategory.Count != 0) { bool bFind = false; _lstLogCategory.ForEach((m) => { if (null == info || info.Category == null) { return; } if (info.Category.StartsWith(m)) { bFind = true; } }); return bFind; } return true; }
public void Log(LogInfo logInfo) { if(!String.IsNullOrEmpty(logInfo.Channel) && !Channels.Contains(logInfo.Channel)) { Channels.Add(logInfo.Channel); } ProcessOnStartClear(); LogInfo.Add(logInfo); if(logInfo.Severity==LogSeverity.Error) { NoErrors++; } else if(logInfo.Severity==LogSeverity.Warning) { NoWarnings++; } else { NoMessages++; } if(logInfo.Severity==LogSeverity.Error && PauseOnError) { UnityEngine.Debug.Break(); } }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; //string _scheduleType = this.GetType().DeclaringType.FullName; try { _log.Info("Scheduler Start: (RefreshCache)", logInfo); Config.Cache.RefreshCache(); RelationLeagueTeam.Cache.RefreshCache(); RelationGroupTeam.Cache.RefreshCache(); League.Cache.RefreshCache(); Match.Cache.RefreshCache(); Player.Cache.RefreshCache(); Team.Cache.RefreshCache(); Video.Cache.RefreshCache(); _log.Info("Scheduler End: (RefreshCache)", logInfo); } catch (Exception ex) { _log.Warn(ex, logInfo); } }
/// <summary> /// 更新数据 /// </summary> /// <param name="mod">LogInfo</param> /// <returns>受影响行数</returns> public int Update(LogInfo mod) { using (DbConnection conn = db.CreateConnection()) { conn.Open(); using (DbTransaction tran = conn.BeginTransaction()) { try { using (DbCommand cmd = db.GetStoredProcCommand("SP_Log_Update")) { db.AddInParameter(cmd, "@LogID", DbType.Int32, mod.LogID); db.AddInParameter(cmd, "@Title", DbType.String, mod.Title); db.AddInParameter(cmd, "@Remark", DbType.String, mod.Remark); db.AddInParameter(cmd, "@LogTime", DbType.DateTime, mod.LogTime); db.AddInParameter(cmd, "@State", DbType.Int32, mod.State); db.AddInParameter(cmd, "@IsDeleted", DbType.Int32, mod.IsDeleted); db.AddInParameter(cmd, "@Sort", DbType.Int32, mod.Sort); tran.Commit(); return db.ExecuteNonQuery(cmd); } } catch (Exception e) { tran.Rollback(); throw e; } finally { conn.Close(); } } } }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; try { log.Info("Scheduler Start: (AutoUpdateActiveCasinoItemEarning)", logInfo); IRepository repo = new Repository(); var list = repo.All<CasinoItem>().FindAll(x => x.ItemType.Equals(CasinoType.SingleChoice) && x.Earning.HasValue); foreach (var c in list) { c.Statistics(); } log.Info("Scheduler End: (AutoUpdateActiveCasinoItemEarning)", logInfo); } catch (Exception ex) { log.Warn(ex, logInfo); } }
/// <summary>Retrieve the summary row builder for the Log object.</summary> /// <param name="log">The logable item that provides the data.</param> /// <param name="info">The metadata used to build the row.</param> /// <returns></returns> public static IRowBuilder GetSummaryBuilder(ILogable log, LogInfo info) { // TODO Try to find a better way to do this. return (info.OutputData.Type == OutputType.CONSOLE || info.OutputData.Type == OutputType.EMAIL) ? new ConsoleLogRowBuilder(log, info) : GetRowBuilder(log, info); }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; try { _log.Info("Scheduler Start: (AutoUpdateActiveBankerCash)", logInfo); IRepository repo = new Repository(); var list = repo.All<Banker>().FindAll(x => x.IsActive); foreach (var b in list) { b.Statistic(); } _log.Info("Scheduler End: (AutoUpdateActiveBankerCash)", logInfo); } catch (Exception ex) { _log.Warn(ex, logInfo); } }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; try { _log.Info("Scheduler Start: (AutoUpdateUserInfo)", logInfo); // 同步所有未取得实名信息的用户资料 SyncUserMemberName(); // 同步所有微信用户信息 SyncUserWeChatInfo(); _log.Info("Scheduler End: (AutoUpdateUserInfo)", logInfo); } catch (Exception ex) { _log.Warn(ex, logInfo); } }
public Log_Form() { this.page = 20; this.pageIndex = 1; this.model = new Model(); this.db = new DBHelper(); this.log = new LogInfo(); this.InitializeComponent(); }
private void SerializeInternal(LogInfo model, IDictionary<string, object> result) { result.Add("logid", model.LogID); result.Add("title", model.Title); result.Add("remark", model.Remark); result.Add("logtime", model.LogTime); result.Add("state", model.State); result.Add("isdeleted", model.IsDeleted); result.Add("sort", model.Sort); }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; try { _log.Info("Scheduler Start: (AutoUpdateMonthlyRank)", logInfo); IRepository repo = new Repository(); var iDay = DateTime.Today; var firstBetDate = repo.Single<Bet>(1).BetTime; while (!(iDay.Year <= firstBetDate.Year && iDay.Month < firstBetDate.Month)) { var winner = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Winner); var loser = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Loser); var rper = GamblerDW.GetTopGamblerMonthly(iDay, RankType.RP); if (winner != null && loser != null) { var day = iDay; var rank = repo.Query<Rank>(x => x.RankYear == day.Year && x.RankMonth == day.Month).FirstOrDefault(); if (rank != null) { //update rank.Init(winner, loser, rper); repo.Update(rank); } else { //insert var instance = new Rank { RankYear = day.Year, RankMonth = day.Month }; instance.Init(winner, loser, rper); repo.Insert(instance); } } iDay = iDay.AddMonths(-1); } _log.Info("Scheduler End: (AutoUpdateMonthlyRank)", logInfo); } catch (Exception ex) { _log.Warn(ex, logInfo); } }
public void Debug(string message, LogInfo para = null) { if (para != null) { Logging(GetType().Name, DateTime.Now, LogLevel.Debug, message, string.Empty, para.UserClient); } else { Logging(GetType().Name, DateTime.Now, LogLevel.Debug, message, string.Empty); } }
public void Debug(string message, LogInfo para = null) { if (para != null) { Logging(GetType().Name, DateTime.Now, LogLevel.Debug, message, string.Empty, para.ThreadInstance, para.MethodInstance); } else { Logging(GetType().Name, DateTime.Now, LogLevel.Debug, message, string.Empty); } }
public void Fatal(Exception ex, LogInfo para = null) { Contract.Requires(ex != null); if (para != null) { Logging(GetType().Name, DateTime.Now, LogLevel.Fatal, ex.Message, ex.StackTrace, para.UserClient); } else { Logging(GetType().Name, DateTime.Now, LogLevel.Fatal, ex.Message, ex.StackTrace); } }
public void Error(Exception ex, LogInfo para = null) { Contract.Requires(ex != null); if (para != null) { Logging(GetType().Name, DateTime.Now, LogLevel.Error, ex.Message, ex.StackTrace, para.ThreadInstance, para.MethodInstance); } else { Logging(GetType().Name, DateTime.Now, LogLevel.Error, ex.Message, ex.StackTrace); } }
public void Log(LogInfo logInfo) { lock(this) { LogFileWriter.WriteLine(logInfo.Message); if(IncludeCallStacks && logInfo.Callstack.Count>0) { foreach(var frame in logInfo.Callstack) { LogFileWriter.WriteLine(frame.GetFormattedMethodName()); } LogFileWriter.WriteLine(); } } }
/// <summary> /// Serialize given log info and convert it to buffer /// </summary> /// <param name="logInfo">Log info that must serialize</param> /// <returns>Bufeer that contain serialized log info</returns> public byte[] SerializeLogInfoBuffer(LogInfo logInfo) { try { using (var tempStream = new MemoryStream()) { BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(tempStream, new List<LogInfo> { logInfo }); return tempStream.ToArray(); } } catch (Exception ex) { return null; } }
public SimpleContainer(GenericsAutoCloser genericsAutoCloser, ConfigurationRegistry configurationRegistry, TypesList typesList, LogError errorLogger, LogInfo infoLogger, Dictionary<Type, Func<object, string>> valueFormatters) { Configuration = configurationRegistry; implementationSelectors = configurationRegistry.GetImplementationSelectors(); this.genericsAutoCloser = genericsAutoCloser; this.typesList = typesList; dependenciesInjector = new DependenciesInjector(this); this.errorLogger = errorLogger; containerContext = new ContainerContext { infoLogger = infoLogger, typesList = typesList, valueFormatters = valueFormatters }; }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; //string _scheduleType = this.GetType().DeclaringType.FullName; try { log.Info("Scheduler Start: (RefreshCache)", logInfo); Config.UpdateAssemblyInfo(Assembly.GetExecutingAssembly(), ConfigSystem.Arsenal); ConfigGlobal_Arsenal.Refresh(); RelationLeagueTeam.Clean(); RelationLeagueTeam.Cache.RefreshCache(); RelationGroupTeam.Clean(); RelationLeagueTeam.Cache.RefreshCache(); League.Cache.RefreshCache(); Match.Cache.RefreshCache(); Player.Cache.RefreshCache(); Team.Cache.RefreshCache(); Video.Cache.RefreshCache(); //AcnCasino CasinoItem.Clean(); ChoiceOption.Clean(); Bet.Clean(); BetDetail.Clean(); // Clean Log Log.Clean(); log.Info("Scheduler End: (RefreshCache)", logInfo); } catch (Exception ex) { log.Warn(ex, logInfo); } }
public static string Process(Context ctx, LogInfo info, LogWarn war, LogErr err) { try { string startobf = "Starting "; ModuleDefMD module = ModuleDefMD.Load(ctx.FileName); module.GlobalType.FindOrCreateStaticConstructor(); foreach (TaskID task in ctx.TasksList) { switch (task) { case AntiDebugTask.ID: { info(startobf + "Anti-Debug Task..."); AntiDebugTask.Execute(module); } break; case StringEncodingTask.ID: { info(startobf + "String encoding Task..."); StringEncodingTask.Execute(module); } break; case ControlFlowTask.ID: { info(startobf + "Control Flow Task..."); ControlFlowTask.Execute(module); } break; case InvalidMDTask.ID: { info(startobf + "Invalid Metadata Task..."); InvalidMDTask.Execute(module); } break; case RenameTask.ID: RenameTask.IsObfuscationActive = true; break; } } info(startobf + "Rename Task..." + Environment.NewLine); RenameTask.Execute(module); module.Write(ctx.NewPath, new ModuleWriterOptions() { Listener = NETUtils.listener }); return ctx.NewPath; } catch (Exception ex) { err(ex.Message); return ""; } }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; try { _log.Info("Scheduler Start: (AutoUpdateOrderType)", logInfo); IRepository repo = new Repository(); var oList = repo.All<Order>(); var oiList = repo.All<OrderItem>().FindAll(x => Product.Cache.Load(x.ProductGuid) != null); if (oList.Count > 0 && oiList.Count > 0) { // Don't place LINQ to Foreach, first ToList(), then use list.FindAll to improve performance foreach (var o in oList) { var list = oiList.FindAll(x => x.OrderID.Equals(o.ID)); // Refresh the OrderType of instance if (list.Count > 0) { var type = Order.GetOrderTypeByOrderItems(list); if (!o.OrderType.Equals(type)) { o.OrderType = type; repo.Update(o); } } } } _log.Info("Scheduler End: (AutoUpdateOrderType)", logInfo); } catch (Exception ex) { _log.Warn(ex, logInfo); } }
public ExplorerHeader(Microsoft.WindowsAPICodePack.Controls.WindowsForms.ExplorerBrowser explorerBrowser) { // Initialize our logging delegates logInfo += delegate(string message) { }; logError += delegate(string message) { }; this.explorerBrowser = explorerBrowser; this.Paint += ExplorerHeader_Paint; InitializeComponent(); this.height = this.Size.Height; // Optimize Painting. SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); // initialize known folder combo box List<string> knownFolderList = new List<string>(); foreach (IKnownFolder folder in Microsoft.WindowsAPICodePack.Shell.KnownFolders.All) { knownFolderList.Add(folder.CanonicalName); } knownFolderList.Sort(); KnownFolders = knownFolderList.ToArray(); this.pathEdit.Items.AddRange(KnownFolders); // setup explorerBrowser navigation events this.explorerBrowser.NavigationFailed += new EventHandler<NavigationFailedEventArgs>(this.explorerBrowser_NavigationFailed); this.explorerBrowser.NavigationComplete += new EventHandler<NavigationCompleteEventArgs>(this.explorerBrowser_NavigationComplete); // set up Navigation log event and button state this.explorerBrowser.NavigationLog.NavigationLogChanged += new EventHandler<NavigationLogEventArgs>(this.NavigationLog_NavigationLogChanged); this.explorerNavigationButtons1.HasLeftHistroy = false; this.explorerNavigationButtons1.HasRightHistroy = false; this.explorerNavigationButtons1.LeftButtonClick += LeftButtonClick; this.explorerNavigationButtons1.RightButtonClick += RightButtonClick; this.explorerNavigationButtons1.DropDownClick += DropDownClick; this.pathEdit.Click += navigateButton_Click; picDeleteHistory.BackgroundImage = Resources.DeleteHistory; }
public void Log(LogInfo logInfo) { LogInfo.Add(logInfo); if(logInfo.Severity==LogSeverity.Error) { NoErrors++; } else if(logInfo.Severity==LogSeverity.Warning) { NoWarnings++; } else { NoMessages++; } if(logInfo.Severity==LogSeverity.Error && PauseOnError) { UnityEngine.Debug.Break(); } }
protected void btnDelete_Click(object sender, EventArgs e) { resvh.deleteReservation(int.Parse(Request["id"])); //---write log ---- string msg = "職員:" + LogOnUserName + "刪除了"+ Request["id"] + "號預約 客戶:" + txtSharePersonEngName.Text + " 電話:" + txtMobile.Text ; msg += " 預約師傅:" + ddlEmployee.SelectedItem.Text; msg += " 時間:" + dtEventDate.DateValue.ToString() + " " + eventStart.TimeValue.Value.ToShortTimeString() + " 至" + eventEnd.TimeValue.Value.ToShortTimeString(); msg += " 服務:" + txtServiceName.Text ; msg += " 修改時間:" + DateTime.Now.ToString(); LogInfo log = new LogInfo(); log.op = LogOnUserName; log.opDate = DateTime.Now; log.eventDate = (DateTime)dtEventDate.DateValue; log.client = txtSharePersonEngName.Text.Replace("'", "''"); log.tel = txtMobile.Text.Replace("'","''"); log.employee = ddlEmployee.SelectedItem.Text; log.logInfo = msg; resvh.WriteLog(log); Page.ClientScript.RegisterStartupScript(typeof(string), "cls", "<script>window.close();window.opener.document.getElementById('btnRefresh').click();</script>"); }
public void Execute(object state) { var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; //string _scheduleType = this.GetType().DeclaringType.FullName; try { _log.Info("Scheduler Start: (RefreshCache)", logInfo); Config.UpdateAssemblyInfo(Assembly.GetExecutingAssembly(), ConfigSystem.iArsenal); ConfigGlobal.Refresh(); Arsenal_Match.Cache.RefreshCache(); Arsenal_Player.Cache.RefreshCache(); Arsenal_Team.Cache.RefreshCache(); MatchTicket.Cache.RefreshCache(); Member.Cache.RefreshCache(); Product.Cache.RefreshCache(); Showcase.Cache.RefreshCache(); // Clean Log Log.Clean(); // Clean QrCode Files CleanQrCodeFiles(); _log.Info("Scheduler End: (RefreshCache)", logInfo); } catch (Exception ex) { _log.Warn(ex, logInfo); } }
public override void OnActionExecuted(ActionExecutedContext filterContext) { Type controllerType = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType; Logger logger = Logger.GetLogger(controllerType); string methodName = string.Format("{0}.{1}", controllerType.FullName, filterContext.ActionDescriptor.ActionName); LogInfo log = new LogInfo(methodName) { LogType = LogType.Admin }; //参数信息 ParameterDescriptor[] parameters = filterContext.ActionDescriptor.GetParameters(); IEnumerable<string> paramInfos = parameters.Select(parameter => parameter.ParameterName) .Select(name => string.Format("{0}={1}", name, _actionParameters[name])); string paramsInfo = paramInfos.ExpandAndToString(";"); object customMessage = filterContext.Controller.TempData[SiteStaticStrings.LogCustomeMessage]; object operationResult = filterContext.Controller.TempData[SiteStaticStrings.LogOperationResult]; log.Message = customMessage == null ? null : (string)customMessage; if (operationResult != null) { OperationResult result = (OperationResult)operationResult; log.ResultType = result.ResultType; log.Message = log.Message ?? result.LogMessage ?? (result.Message ?? result.ResultType.ToDescription()); } }
protected void gvSchedule_SelectedIndexChanged(object sender, EventArgs e) { ILog log = new AppLog(); var logInfo = new LogInfo { MethodInstance = MethodBase.GetCurrentMethod(), ThreadInstance = Thread.CurrentThread }; try { if (gvSchedule.SelectedIndex != -1) { var key = gvSchedule.DataKeys[gvSchedule.SelectedIndex].Value.ToString(); var s = Schedule.Single(key); var instance = s.IScheduleInstance; ManagedThreadPool.QueueUserWorkItem(instance.Execute); s.LastCompletedTime = DateTime.Now; s.Update(); log.Info($"ISchedule Manually: {s.ScheduleType}", logInfo); //this.ClientScript.RegisterClientScriptBlock(typeof(string), "success", string.Format("任务:{0}执行成功');", s.ScheduleType), true); } } catch (Exception ex) { log.Error(ex, logInfo); //this.ClientScript.RegisterClientScriptBlock(typeof(string), "failed", string.Format("alert('{0}');", ex.Message.ToString()), true); } finally { //BindData(); } }
public MainForm() { InitializeComponent(); modelRecord = new Model(); this.logInfo = new LogInfo(); this.address = new AddressList(); this.userName = new UserNameList(); this.mailInfo = new List<string>(); Control.CheckForIllegalCrossThreadCalls = false; skinGalleryHelper = new RibbonDemos.SkinGalleryHelper(ribbonGallerySkins); ((DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit)ReceiveNameEdit.Edit).ButtonClick+=new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(ImportNameButton_Click); ((DevExpress.XtraEditors.Repository.RepositoryItemRadioGroup)MailCollectionType.Edit).SelectedIndexChanged += new EventHandler(CollectionRadioGroup_SelectIndexChanged); ((DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit)AddCommuRecord.Edit).CheckedChanged += new EventHandler(AutoAddCommuRecord_CheckedChanged); ((DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit)AddSendMailLog.Edit).CheckedChanged += new EventHandler(AutoAddSendMailLog_CheckedChanged); ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)FliterUsersComboBox.Edit).SelectedIndexChanged+=new EventHandler(FliterUsers_SelectedIndexChanged); this.CookieMailPanel.Visible = true; //this.PopMailPanel.Visible = false; // this.MailEditorPanel.Visible = true; }
public static void AddInfoToLog(LogInfo time, string msg) { string fName = "DiskAnalysis.log"; lock (tt) { try { StreamWriter writer; if (!File.Exists(fName)) writer = File.CreateText(fName); else writer = File.AppendText(fName); using (writer) { writer.WriteLine(string.Format("{0} {1} {2}", DateTime.Now, time, msg)); writer.Close(); } } catch { } } }
public static void Main() { try { TTransport transport = new TSocket("localhost", 9090); TProtocol protocol = new TBinaryProtocol(transport); SendLog.Client client = new SendLog.Client(protocol); transport.Open(); try { Random ran = new Random(); string strContent = ""; List<LogInfo> lstLogInfo = new List<LogInfo>(); for (int i = 0; i < 1000; i++ ) { LogInfo info = new LogInfo(); info.Content = strContent; strContent += i; info.DeviceName = i.ToString(); info.Time = (int)DateTime.UtcNow.Ticks; info.Category = "category" + i; lstLogInfo.Add(info); } client.send_log(lstLogInfo); } finally { transport.Close(); } } catch (TApplicationException x) { Console.WriteLine(x.StackTrace); } }
public static List <LogInfo> ExtractAllFiles(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_ExtractAllFiles info = cmd.Info.Cast <CodeInfo_ExtractAllFiles>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string destDir = StringEscaper.Preprocess(s, info.DestDir); Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check if encoded file exist if (!EncodedFile.ContainsFolder(sc, dirName)) { return(LogInfo.LogErrorMessage(logs, $"Encoded folder [{dirName}] not found in script [{sc.RealPath}].")); } // Filter dest path if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string[] dirs = sc.Sections[ScriptSection.Names.EncodedFolders].Lines; if (!dirs.Any(d => d.Equals(dirName, StringComparison.OrdinalIgnoreCase))) { return(LogInfo.LogErrorMessage(logs, $"Directory [{dirName}] not exists in [{scriptFile}]")); } if (!Directory.Exists(destDir)) { if (File.Exists(destDir)) { return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] is not a directory")); } Directory.CreateDirectory(destDir); } string[] lines = sc.Sections[dirName].Lines; Dictionary <string, string> fileDict = IniReadWriter.ParseIniLinesIniStyle(lines); int fileCount = fileDict.Count; s.MainViewModel.SetBuildCommandProgress("ExtractAndRun Progress", fileCount); try { int i = 0; foreach (string file in fileDict.Keys) { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressText = $"Decompressing \"{file}\"\r\n({(x + i) * 100 / fileCount:0.0}%)"; s.MainViewModel.BuildCommandProgressValue = x + i; } }); using (FileStream fs = new FileStream(Path.Combine(destDir, file), FileMode.Create, FileAccess.Write)) { EncodedFile.ExtractFile(sc, dirName, file, fs, progress); } i += 1; } } finally { s.MainViewModel.ResetBuildCommandProgress(); } logs.Add(new LogInfo(LogState.Success, $"Encoded folder [{dirName}] was extracted to [{destDir}]")); return(logs); }
public static AnalyticsEngineConfiguration GetConfig() { var config = new AnalyticsEngineConfiguration { AnalyticsEngines = new AnalyticsEngineCollection() }; FileStream fileReader = null; string filePath = null; try { config = (AnalyticsEngineConfiguration)DataCache.GetCache("AnalyticsEngineConfig"); if ((config == null)) { filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.SiteAnalytics); //Create a FileStream for the Config file fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); var doc = new XPathDocument(fileReader); config = new AnalyticsEngineConfiguration { AnalyticsEngines = new AnalyticsEngineCollection() }; foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsEngineConfig/Engines/AnalyticsEngine")) { var analyticsEngine = new AnalyticsEngine { EngineType = nav.SelectSingleNode("EngineType").Value, ElementId = nav.SelectSingleNode("ElementId").Value, InjectTop = Convert.ToBoolean(nav.SelectSingleNode("InjectTop").Value), ScriptTemplate = nav.SelectSingleNode("ScriptTemplate").Value }; config.AnalyticsEngines.Add(analyticsEngine); } if (File.Exists(filePath)) { //Set back into Cache DataCache.SetCache("AnalyticsEngineConfig", config, new DNNCacheDependency(filePath)); } } } catch (Exception ex) { //log it var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsEngineConfiguration", "GetConfig Failed"); if (!string.IsNullOrEmpty(filePath)) { log.AddProperty("FilePath", filePath); } log.AddProperty("ExceptionMessage", ex.Message); LogController.Instance.AddLog(log); Logger.Error(log); } finally { if (fileReader != null) { //Close the Reader fileReader.Close(); } } return(config); }
/// <summary> /// logs an exception related to a module provider once per cache-lifetime /// </summary> /// <param name="ex"></param> /// <param name="status"></param> /// <param name="result"></param> /// <param name="messages"></param> /// <param name="provider"></param> public static void LogModuleProviderExceptionInRequest(Exception ex, string status, ExtensionUrlProvider provider, UrlAction result, List <string> messages) { if (ex != null) { string moduleProviderName = "Unknown Provider"; string moduleProviderVersion = "Unknown Version"; if (provider != null) { moduleProviderName = provider.ProviderConfig.ProviderName; moduleProviderVersion = provider.GetType().Assembly.GetName(false).Version.ToString(); } //this logic prevents a site logging an exception for every request made. Instead //the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. //create a cache key for this exception type string cacheKey = ex.GetType().ToString(); //see if there is an existing object logged for this exception type object existingEx = DataCache.GetCache(cacheKey); if (existingEx == null) { //if there was no existing object logged for this exception type, this is a new exception DateTime expire = DateTime.Now.AddHours(1); DataCache.SetCache(cacheKey, cacheKey, expire); //just store the cache key - it doesn't really matter //create a log event string productVer = Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); var elc = new EventLogController(); var logEntry = new LogInfo { LogTypeKey = "GENERAL_EXCEPTION" }; logEntry.AddProperty("Url Rewriting Extension Url Provider Exception", "Exception in Url Rewriting Process"); logEntry.AddProperty("Provider Name", moduleProviderName); logEntry.AddProperty("Provider Version", moduleProviderVersion); logEntry.AddProperty("Http Status", status); logEntry.AddProperty("Product Version", productVer); if (result != null) { logEntry.AddProperty("Original Path", result.OriginalPath ?? "null"); logEntry.AddProperty("Raw Url", result.RawUrl ?? "null"); logEntry.AddProperty("Final Url", result.FinalUrl ?? "null"); logEntry.AddProperty("Rewrite Result", !string.IsNullOrEmpty(result.RewritePath) ? result.RewritePath : "[no rewrite]"); logEntry.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) ? "[no redirect]" : result.FinalUrl); logEntry.AddProperty("Action", result.Action.ToString()); logEntry.AddProperty("Reason", result.Reason.ToString()); logEntry.AddProperty("Portal Id", result.PortalId.ToString()); logEntry.AddProperty("Tab Id", result.TabId.ToString()); logEntry.AddProperty("Http Alias", result.PortalAlias != null ? result.PortalAlias.HTTPAlias : "Null"); if (result.DebugMessages != null) { int i = 1; foreach (string debugMessage in result.DebugMessages) { string msg = debugMessage; if (debugMessage == null) { msg = "[message was null]"; } logEntry.AddProperty("Debug Message[result] " + i.ToString(), msg); i++; } } } else { logEntry.AddProperty("Result", "Result value null"); } if (messages != null) { int i = 1; foreach (string msg in messages) { logEntry.AddProperty("Debug Message[raw] " + i.ToString(), msg); i++; } } logEntry.AddProperty("Exception Type", ex.GetType().ToString()); logEntry.AddProperty("Message", ex.Message); logEntry.AddProperty("Stack Trace", ex.StackTrace); if (ex.InnerException != null) { logEntry.AddProperty("Inner Exception Message", ex.InnerException.Message); logEntry.AddProperty("Inner Exception Stacktrace", ex.InnerException.StackTrace); } logEntry.BypassBuffering = true; elc.AddLog(logEntry); } } }
/* * WB082 Behavior * ExtractFile : DestDir must be Directory, create if not exists. * Ex) (...),README.txt,%BaseDir%\Temp\Hello * -> No Hello : Create directory "Hello" and extract files into new directory. * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. * * ExtractAllFiles * Ex) (...),Fonts,%BaseDir%\Temp\Hello * -> No Hello : Failure * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. * * PEBakery Behavior * ExtractFile/ExtractAllFiles : DestDir must be Directory, create if not exists. * Ex) (...),README.txt,%BaseDir%\Temp\Hello * -> No Hello : Create directory "Hello" and extract files into new directory. * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. */ public static List <LogInfo> ExtractFile(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_ExtractFile info = cmd.Info.Cast <CodeInfo_ExtractFile>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string fileName = StringEscaper.Preprocess(s, info.FileName); string destDir = StringEscaper.Preprocess(s, info.DestDir); // Should be directory name Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check if encoded file exist if (!EncodedFile.ContainsFile(sc, dirName, fileName)) { return(LogInfo.LogErrorMessage(logs, $"Encoded file [{dirName}\\{fileName}] not found in script [{sc.RealPath}].")); } // Filter dest path if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } if (!Directory.Exists(destDir)) // DestDir already exists { if (File.Exists(destDir)) // Error, cannot proceed { return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] is not a directory.")); } Directory.CreateDirectory(destDir); } s.MainViewModel.SetBuildCommandProgress("ExtractFile Progress", 1); try { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressValue = x; if (x < EncodedFile.Base64ReportFactor) { // [Stage 1] Base64 s.MainViewModel.BuildCommandProgressText = $"Reading \"{fileName}\" from script\r\n({x * 100:0.0}%)"; } else { // [Stage 2] Decompress s.MainViewModel.BuildCommandProgressText = $"Decompressing \"{fileName}\"\r\n({x * 100:0.0}%)"; } } }); string destPath = Path.Combine(destDir, fileName); using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write)) { EncodedFile.ExtractFile(sc, dirName, fileName, fs, progress); } } finally { s.MainViewModel.ResetBuildCommandProgress(); } logs.Add(new LogInfo(LogState.Success, $"Encoded file [{fileName}] was extracted to [{destDir}]")); return(logs); }
/// <summary> /// Selects a tab within module HISTOROM /// </summary> /// <param name="tabIndex"> /// Index of the tab the caller wants to select /// </param> /// <returns> /// true: if tab has been selected successfully /// false: if something went wrong /// </returns> public bool Run(int tabIndex) { try { switch (tabIndex) { case 0: if (new TabContainer().SelectTabTable()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Table successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Table!"); return(false); case 1: if (new TabContainer().SelectTabGraphic()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Graphic successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Graphic!"); return(false); case 2: if (new TabContainer().SelectTabStatistic()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Statistic successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Statistic!"); return(false); case 3: if (new TabContainer().SelectTabSettings()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Settings successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Settings!"); return(false); default: EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Wrong index used!Use 0 for table, 1 for graphic , 2 for statistic and 3 for settings"); return(false); } } catch (Exception exception) { EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message); return(false); } }
/// <summary> /// Gets the message body by change request. /// </summary> /// <param name="CustomerID">The change request identifier.</param> /// <returns></returns> public async Task <ProfileMQ> GetProfileUpdateMessageBody(int CustomerID) { try { DataSet ds = new DataSet(); SqlParameter[] parameters = { new SqlParameter("@CustomerID", SqlDbType.Int), }; parameters[0].Value = CustomerID; _DataHelper = new DataAccessHelper("Customers_GetProfileMessageQueue", parameters, _configuration); var result = await _DataHelper.RunAsync(ds); var msgBody = new ProfileMQ(); if (ds.Tables.Count > 0) { msgBody = (from model in ds.Tables[0].AsEnumerable() select new ProfileMQ() { accountID = model.Field <int>("accountID"), customerID = model.Field <int>("customerID"), subscriberID = model.Field <int?>("subscriberID"), mobilenumber = model.Field <string>("mobilenumber"), MaskedCardNumber = model.Field <string>("MaskedCardNumber"), Token = model.Field <string>("Token"), CardType = model.Field <string>("CardType"), IsDefault = model.Field <int?>("IsDefault"), CardHolderName = model.Field <string>("CardHolderName"), ExpiryMonth = model.Field <int?>("ExpiryMonth"), ExpiryYear = model.Field <int?>("ExpiryYear"), CardFundMethod = model.Field <string>("CardFundMethod"), CardBrand = model.Field <string>("CardBrand"), CardIssuer = model.Field <string>("CardIssuer"), billingUnit = model.Field <string>("billingUnit"), billingFloor = model.Field <string>("billingFloor"), billingBuildingNumber = model.Field <string>("billingBuildingNumber"), billingBuildingName = model.Field <string>("billingBuildingName"), billingStreetName = model.Field <string>("billingStreetName"), billingPostCode = model.Field <string>("billingPostCode"), billingContactNumber = model.Field <string>("billingContactNumber"), email = model.Field <string>("email"), displayname = model.Field <string>("displayname"), paymentmode = model.Field <string>("paymentmode"), amountpaid = model.Field <double?>("amountpaid"), MPGSOrderID = model.Field <string>("MPGSOrderID"), invoicelist = model.Field <string>("invoicelist"), invoiceamounts = model.Field <string>("invoiceamounts") }).FirstOrDefault(); } return(msgBody); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw; } finally { _DataHelper.Dispose(); } }
/// <summary> /// Checks if module (online) is ready /// </summary> /// <param name="element"> /// Element to check /// </param> /// <returns> /// <br>True: if module is ready</br> /// <br>False: if module is not ready</br> /// </returns> public bool IsModuleOnlineReady(Element element) { Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Entered"); return(element != null && element.Enabled); }
public static List<LogInfo> Set(EngineState s, CodeCommand cmd) { CodeInfo_Set info = cmd.Info.Cast<CodeInfo_Set>(); Variables.VarKeyType varType = Variables.DetectType(info.VarKey); if (varType == Variables.VarKeyType.None) { // Check Macro if (Regex.Match(info.VarKey, Macro.MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success) // Macro Name Validation { string macroCommand = StringEscaper.Preprocess(s, info.VarValue); if (macroCommand.Equals("NIL", StringComparison.OrdinalIgnoreCase)) macroCommand = null; LogInfo log = s.Macro.SetMacro(info.VarKey, macroCommand, cmd.Section, info.Permanent, false); return new List<LogInfo>(1) { log }; } } // [WB082 Behavior] -> Enabled if s.CompatAllowSetModifyInterface == true // If PERMANENT was used but the key exists in interface command, the value will not be written to script.project but in interface. // Need to investigate where the logs are saved in this case. switch (info.Permanent) { case true: { // Check if interface contains VarKey List<LogInfo> logs = new List<LogInfo>(); if (Variables.DetectType(info.VarKey) != Variables.VarKeyType.Variable) goto case false; #region Set interface control's value (Compat) if (s.CompatAllowSetModifyInterface) { string varKey = Variables.TrimPercentMark(info.VarKey); string finalValue = StringEscaper.Preprocess(s, info.VarValue); Script sc = cmd.Section.Script; ScriptSection iface = sc.GetInterfaceSection(out _); if (iface == null) goto case false; (List<UIControl> uiCtrls, _) = UIParser.ParseStatements(iface.Lines, iface); UIControl uiCtrl = uiCtrls.Find(x => x.Key.Equals(varKey, StringComparison.OrdinalIgnoreCase)); if (uiCtrl == null) goto case false; bool valid = uiCtrl.SetValue(finalValue, false, out List<LogInfo> varLogs); logs.AddRange(varLogs); if (valid) { // Update uiCtrl into file uiCtrl.Update(); // Also update local variables logs.AddRange(Variables.SetVariable(s, info.VarKey, info.VarValue, false, false)); return logs; } } goto case false; #endregion } case false: default: return Variables.SetVariable(s, info.VarKey, info.VarValue, info.Global, info.Permanent); } }
public override void Insert(SqlDataReader reader, SqlConnection sqlCon, InfoDto info, LogInfo logInfo) { if (reader == null) { return; } if (reader.HasRows) { SqlCommand cmd = new SqlCommand(GetSqlInsert( $@"[{nc01}],[{nc07}],[{nc08}]", $@"@{nc01},@{nc07},@{nc08}" ), sqlCon); AddDefaultParameters(cmd); cmd.Parameters.Add($"@{nc01}", SqlDbType.NVarChar, 50); cmd.Parameters.Add($"@{nc07}", SqlDbType.SmallInt); cmd.Parameters.Add($"@{nc08}", SqlDbType.Int); cmd.Parameters.Add($"@{ncId}", SqlDbType.UniqueIdentifier); CopyRows(reader, cmd, info, logInfo); } }
public void AddPlatformOperationLog(LogInfo model) { model.ShopId = 0; context.LogInfo.Add(model); context.SaveChanges(); }
void OnGUIEx() { GUI.skin.box.alignment = TextAnchor.MiddleLeft; GUI.skin.button.fontSize = mBtWidget / 7; GUI.skin.label.fontSize = mBtWidget / 6; GUI.skin.box.fontSize = mBtWidget / 7; //GUILayout.Label() GUI.Box(new Rect(Screen.width - mBtWidget - 10, 10, mBtWidget, mBtRealHight), mGuiFPSTex); GUI.Box(new Rect(Screen.width - mBtWidget - 10, 10 + mBtHight, mBtWidget, mBtRealHight), mGuiCPUTex); GUI.Box(new Rect(Screen.width - mBtWidget - 10, 10 + mBtHight * 2, mBtWidget, mBtRealHight), mGuiMoTex); if (mIsScale) { if (GUI.Button(new Rect(10, 10, mBtWidget, mBtRealHight), "展开(↓↓)")) { mIsScale = false; } return; } if (GUI.Button(new Rect(10, 10 + mBtHight * 3, mBtWidget, mBtRealHight), "收起(↑↑)")) { mIsScale = true; } GUI.contentColor = Color.white; for (int i = 0; i < mLogBufs.Count; i++) { LogUnit lu = mLogBufs[i]; GUI.contentColor = lu.color; if (GUI.Button(lu.mRect, lu.keyName + "(" + lu.mLogInfos.Count + ")")) { mSelectLogUnity = lu; mhSbarValue = 0; mhSbarSize = 0; mDetailInfo = null; mPauseLogInfo = null; mScrollPosition = Vector2.zero; } } if (mDetailInfo != null) { GUI.Box(new Rect(mBtWidget + 20, 10 + mBtHight, (int)(mBtWidget * 4.5 * mButtonDp), mBtHight * 10), ""); GUILayout.BeginArea(new Rect(mBtWidget + 20, 10 + mBtHight, (int)(mBtWidget * 4.5 * mButtonDp), mBtHight * 10)); mScrollPosition = GUILayout.BeginScrollView(mScrollPosition, GUILayout.Width((int)(mBtWidget * 4.5 * mButtonDp)), GUILayout.Height(mBtHight * 10)); GUI.contentColor = GetColor(mDetailInfo.logType); GUILayout.Label("打印信息: \n" + mDetailInfo.logName + "\n\n堆栈信息:\n" + mDetailInfo.logStack); GUILayout.EndScrollView(); GUILayout.EndArea(); GUI.contentColor = GetColor(mDetailInfo.logType); if (GUI.Button(new Rect(mBtWidget + 20, 10, (int)(mBtWidget * 4.5 * mButtonDp), mBtRealHight), mDetailInfo.logName)) { mDetailInfo = null; } } else if (mSelectLogUnity != null) { List <LogInfo> infos = mPauseLogInfo != null ? mPauseLogInfo : mSelectLogUnity.mLogInfos; int logCout = infos.Count; int curYe = 0; if (logCout > 10) { float bb = mhSbarValue / (1 - mhSbarSize);; mhSbarSize = 10 / (float)logCout; curYe = (int)((logCout - 10) / (1 - mhSbarSize) * mhSbarValue); mhSbarValue = (1 - mhSbarSize) * bb; mhSbarValue = GUI.VerticalScrollbar(new Rect((int)(mBtWidget * 5.5 * mButtonDp) + 35, 10 + mBtHight, mBtWidget / 4, mBtHight * 10 - (mBtHight - mBtRealHight)), mhSbarValue, mhSbarSize, 0.0f, 1.0f); } int index = 0; for (int i = curYe; i < infos.Count && i < curYe + 10; i++) { LogInfo li = infos[i]; GUI.contentColor = GetColor(li.logType); if (GUI.Button(new Rect(mBtWidget + 20, 10 + mBtHight + mBtHight * index++, (int)(mBtWidget * 4.5 * mButtonDp), mBtRealHight), li.logName)) { mDetailInfo = li; } } GUI.contentColor = Color.white; if (mPauseLogInfo != null) { GUI.contentColor = Color.blue; if (GUI.Button(new Rect(mBtWidget + 20, 10, mBtWidget * 2 * mButtonDp, mBtRealHight), "开启日志")) { mPauseLogInfo = null; } } else if (GUI.Button(new Rect(mBtWidget + 20, 10, mBtWidget * 2 * mButtonDp, mBtRealHight), "暂停日志")) { mPauseLogInfo = new List <LogInfo>(mSelectLogUnity.mLogInfos.ToArray()); } GUI.contentColor = Color.red; if (GUI.Button(new Rect(mBtWidget * 2 * mButtonDp + mBtWidget + 40, 10, mBtWidget * 2 * mButtonDp, mBtRealHight), "清空日志")) { mSelectLogUnity.mLogInfos.Clear(); mPauseLogInfo = null; } } }
void DoGMWindow(int windowID) { int RealHight = mBtRealHight; GUI.contentColor = Color.white; GUI.DragWindow(new Rect(0, 0, mBtWidget, RealHight * 1)); GUI.skin.box.alignment = TextAnchor.MiddleLeft; GUI.skin.button.fontSize = mBtWidget / 7; GUI.skin.label.fontSize = mBtWidget / 7; GUI.skin.box.fontSize = mBtWidget / 7; GUI.skin.textField.fontSize = mBtWidget / 7; GUI.skin.textField.alignment = TextAnchor.MiddleLeft; //GUI.Box(new Rect(5, 20, mBtWidget, RealHight), mGuiFPSTex); GUI.Label(new Rect(5, mBtHight * 0.4f, (int)(mBtWidget), RealHight), "输入指令:"); //输入框 if (mLastGMText == "") { GUI.Label(new Rect(5, mBtHight, (int)(mBtWidget), RealHight), "examples:gm"); } else { if (GUI.Button(new Rect(5, mBtHight, mBtWidget, RealHight), mLastGMText)) { GM.ResetGM("gm/" + mInputeText); } } mInputeText = GUI.TextField(new Rect(5, mBtHight * 2, (int)(mBtWidget), RealHight), mInputeText); if (GUI.Button(new Rect(5 + mBtWidget / 2 / 2.7f, mBtHight * 3.0f, mBtWidget / 1.5f, RealHight), "确定")) { if (mInputeText != "") { if (GM.ResetGM("gm/" + mInputeText) == GM.GMResult.GM_Success) { mLastGMText = mInputeText; mInputeText = ""; } else { string gm = mInputeText.ToLower(); if (gm == "gm") { if (mGMShowText == "") { var gmshwo = GM.GetShow(); mGMShowText = "GM指令大全:\nlog/版本号\n"; foreach (var k in gmshwo) { mGMShowText += k.Key + ":" + k.Value + "\n"; } } else { mGMShowText = ""; mInputeText = ""; } } else if (gm.Contains("log")) { if (gm.Length <= 3) { AllLog.Clear(); WarningLog.Clear(); ErrorLog.Clear(); LogVersion ver = new LogVersion(); ver.ReadFile(); for (int i = ver.version; i > 0; i--) { LogFile log = new LogFile(); if (log.ReadFile(_GetLogPath(i))) { if (log.firstError.Count > 0) { LogInfo logInfo = new LogInfo(); logInfo.logType = LogType.Error; logInfo.logName = "version:" + log.version.ToString() + "报错:" + log.time; logInfo.logStack = log.firstError[0].logStack; ErrorLog.Add(logInfo); } } } LogFile lf = new LogFile(); lf.time = "版本日志"; lf.version = ver.version; mIsShowLogVersion = lf; ShowListLog(2); } else { string subGm = gm.Substring("log/".Length); int vs = 0; int.TryParse(subGm, out vs); if (vs == 0) { LogVersion ver = new LogVersion(); ver.ReadFile(); vs = ver.version; } LogFile log = new LogFile(); if (log.ReadFile(_GetLogPath(vs))) { AllLog.Clear(); WarningLog.Clear(); ErrorLog.Clear(); AllLog.AddRange(log.mAllLog); ErrorLog.AddRange(log.firstError); } mIsShowLogVersion = log; } } } } } }
// 2013-06-28 EC - Added in addition to function above /// <summary> /// Checks if module (online) is ready /// </summary> /// <param name="adapter"> /// Element to check /// </param> /// <returns> /// <br>True: if module is ready</br> /// <br>False: if module is not ready</br> /// </returns> public bool IsModuleOnlineReady(Adapter adapter) { Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Entered"); return(adapter != null && adapter.Enabled); }
/// <summary> /// Runs the specified item identifier. /// </summary> /// <param name="itemId">The item identifier.</param> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <returns><c>true</c> if executed, <c>false</c> otherwise.</returns> public bool Run(string itemId, string source, string destination) { Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Not available with standard Parameterization. Use HMI instead."); return(false); }
/// <summary> /// Read single curve and check if curve data are updated. /// </summary> /// <param name="waitUntilFinished"> /// The wait Until Finished. /// </param> /// <returns> /// <br>True: If call worked fine</br> /// <br>False: If an error occurred</br> /// </returns> public bool RunViaMenu(bool waitUntilFinished) { try { // 2013-06-26 - EC - Changed Type Text to Element Element text = (new DiagramElements()).CurveDataNumber; if (new IsDTMConnected().Run()) { if ((new RunReadCurve()).ViaMenu()) { // Report info that reading has started EH.PCPS.TestAutomation.Common.Tools.Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Single reading started"); // If should be wait until reading is finished if (waitUntilFinished) { // Check availability of curve number if (text != null) { var watch = new Stopwatch(); watch.Start(); const string Separator = "/"; // 2013-06-26 - EC - Code replaces code below string curvesIni = text.GetAttributeValueText("WindowText"); // curvesIni = text.TextValue; // 2013-06-26 - EC - Code replaces code below string curvesNew = text.GetAttributeValueText("WindowText"); // curvesNew = text.TextValue; int separatorPositionIni = curvesIni.IndexOf(Separator, StringComparison.Ordinal); int separatorPositionNew = curvesNew.IndexOf(Separator, StringComparison.Ordinal); curvesIni = curvesIni.Substring(0, separatorPositionIni); curvesNew = curvesNew.Substring(0, separatorPositionNew); int curvesIniCount = Convert.ToInt16(curvesIni); // ReSharper disable RedundantAssignment int curvesNewCount = Convert.ToInt16(curvesNew); // ReSharper restore RedundantAssignment bool isCurveNumberUpdated = false; bool isReadingFinished = false; bool isReading = true; while (isReading) { if (watch.ElapsedMilliseconds < DefaultValues.GeneralTimeout) { // 2013-06-26 - EC - Code replaces code below curvesNew = text.GetAttributeValueText("WindowText"); // curvesNew = text.TextValue; separatorPositionNew = curvesNew.IndexOf(Separator, StringComparison.Ordinal); curvesNew = curvesNew.Substring(0, separatorPositionNew); curvesNewCount = Convert.ToInt16(curvesNew); // Prüfe Kurvenzahl if (curvesNewCount < (curvesIniCount + 1)) { isCurveNumberUpdated = false; } else { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Curve number updated"); isCurveNumberUpdated = true; } if ((new ReadAndWrite()).IsReading()) { isReadingFinished = false; } else { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Progressbar disabled"); isReadingFinished = true; } // Auswertung des bisherigen Ergebnisses if (isCurveNumberUpdated && isReadingFinished) { isReading = false; EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Single reading finished"); } } else { isReading = false; EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Single reading unfinished after timeout"); } } watch.Stop(); if (isCurveNumberUpdated == false && isReadingFinished) { EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Single reading did not finish within " + DefaultValues.GeneralTimeout + " milliseconds"); return(false); } if (isCurveNumberUpdated && isReadingFinished == false) { EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Unfinished curve reading after timeout."); return(false); } if (isCurveNumberUpdated) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Single reading finished after " + watch.ElapsedMilliseconds + " milliseconds. (Timeout: " + DefaultValues.GeneralTimeout + " milliseconds)"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Unknown problem."); return(false); } EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Textfield is not accessable."); return(false); } EH.PCPS.TestAutomation.Common.Tools.Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Single reading started"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Function [RunReadSingleCurve.ViaMenu] was not Executiond."); return(false); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Module is not online."); return(false); } catch (Exception exception) { EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message); return(false); } }
/// <summary> /// Selects a tab within module HISTOROM /// </summary> /// <param name="tabName"> /// Name of the tab the caller wants to have selected /// </param> /// <returns> /// true: if tab has been selected successfully /// false: if something went wrong /// </returns> public bool Run(string tabName) { try { switch (tabName) { case "Data overview": if (new TabContainer().SelectTabTable()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Table successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Table!"); return(false); case "Diagram data": if (new TabContainer().SelectTabGraphic()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Graphic successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Graphic!"); return(false); case "Statistic results": if (new TabContainer().SelectTabStatistic()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Statistic successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Statistic!"); return(false); case "Settings": if (new TabContainer().SelectTabSettings()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Opened Tab Settings successfully!"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Could not open Tab Settings!"); return(false); default: EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Wrong tab name!"); return(false); } } catch (Exception exception) { EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message); return(false); } }
public void Add(LogInfo logInfo) { DBHelper.ExecuteProc("PR_Accessories_Log_Add", GetParameters(logInfo)); }
/// <summary> /// 根据文档ID修改文档信息 /// </summary> /// <param name="DocM">文档信息</param> /// <returns>bool值</returns> public static bool UpdateDoc(DocModel DocM) { UserInfoUtil userInfo = (UserInfoUtil)SessionUtil.Session["UserInfo"]; LogInfoModel logModel = new LogInfoModel(); //操作日志 bool isSucc = false; //定义返回变量 #region 设置操作日志内容 //设置公司代码 logModel.CompanyCD = userInfo.CompanyCD; //设置登陆用户ID logModel.UserID = userInfo.UserID; //设置模块ID 模块ID在ConstUtil中定义,以便维护 logModel.ModuleID = ConstUtil.MODULE_ID_DOC_LIST; //操作单据编号 编号 logModel.ObjectID = DocM.DocumentNo; //操作对象 操作的表信息 logModel.ObjectName = ConstUtil.TABLE_NAME_DOC; //涉及关键元素 涉及其他业务、表关系 logModel.Element = ConstUtil.LOG_PROCESS_UPDATE; //备注 操作类型 logModel.Remark = ConstUtil.LOG_PROCESS_UPDATE; #endregion try { isSucc = DocDBHelper.UpdateDoc(DocM); } catch (System.Exception ex) { #region 操作失败时记录日志到文件 //定义变量 LogInfo logSys = new LogInfo(); //设置日志类型 需要指定为系统日志 logSys.Type = LogInfo.LogType.SYSTEM; //指定系统日志类型 出错信息 logSys.SystemKind = LogInfo.SystemLogKind.SYSTEM_ERROR; //指定登陆用户信息 logSys.UserInfo = userInfo; //设定模块ID logSys.ModuleID = ConstUtil.MODULE_ID_DOC_LIST; //描述 logSys.Description = ex.ToString(); //输出日志 LogUtil.WriteLog(logSys); #endregion } if (isSucc)//操作成功 { logModel.Remark += "成功"; } else//操作失败 { logModel.Remark += "失败"; } //记录日志 LogDBHelper.InsertLog(logModel); return(isSucc); }
public static TransactionInfoCapsule BuildInstance(TransactionCapsule transaction, BlockCapsule block, TransactionTrace trace) { TransactionInfo result = new TransactionInfo(); ReceiptCapsule receipt = trace.Receipt; result.Result = TransactionInfo.Types.code.Sucess; if (trace.RuntimeError.IsNotNullOrEmpty() || trace.Result.Exception != null) { result.Result = TransactionInfo.Types.code.Failed; result.ResMessage = ByteString.CopyFromUtf8(trace.RuntimeError); } result.Id = ByteString.CopyFrom(transaction.Id.Hash); ProgramResult program_result = trace.Result; long fee = program_result.TransactionResult.Fee + receipt.EnergyFee + receipt.NetFee + receipt.MultiSignFee; result.Fee = fee; result.ContractResult.Add(ByteString.CopyFrom(program_result.HReturn)); result.ContractAddress = ByteString.CopyFrom(program_result.ContractAddress); result.UnfreezeAmount = program_result.TransactionResult.UnfreezeAmount; result.AssetIssueID = program_result.TransactionResult.AssetIssueID; result.ExchangeId = program_result.TransactionResult.ExchangeId; result.WithdrawAmount = program_result.TransactionResult.WithdrawAmount; result.ExchangeReceivedAmount = program_result.TransactionResult.ExchangeReceivedAmount; result.ExchangeInjectAnotherAmount = program_result.TransactionResult.ExchangeInjectAnotherAmount; result.ExchangeWithdrawAnotherAmount = program_result.TransactionResult.ExchangeWithdrawAnotherAmount; List <TransactionInfo.Types.Log> logs = new List <TransactionInfo.Types.Log>(); program_result.LogInfos.ForEach(info => logs.Add(LogInfo.BuildLog(info))); result.Log.AddRange(logs); if (block != null) { result.BlockNumber = block.Instance.BlockHeader.RawData.Number; result.BlockTimeStamp = block.Instance.BlockHeader.RawData.Timestamp; } result.Receipt = receipt.Receipt; if (Args.Instance.VM.SaveInternalTx == true && program_result.InternalTransactions != null) { foreach (var tx in program_result.InternalTransactions) { Protocol.InternalTransaction internal_transaction = new Protocol.InternalTransaction(); internal_transaction.Hash = ByteString.CopyFrom(tx.Hash); internal_transaction.CallerAddress = ByteString.CopyFrom(tx.SendAddress); internal_transaction.TransferToAddress = ByteString.CopyFrom(tx.TransferToAddress); CallValueInfo call_value_info = new CallValueInfo(); call_value_info.CallValue = tx.Value; internal_transaction.CallValueInfo.Add(call_value_info); foreach (var token_info in tx.TokenInfo) { call_value_info = new CallValueInfo(); call_value_info.TokenId = token_info.Key; call_value_info.CallValue = token_info.Value; internal_transaction.CallValueInfo.Add(call_value_info); } internal_transaction.Note = ByteString.CopyFrom(Encoding.UTF8.GetBytes(tx.Note)); internal_transaction.Rejected = tx.IsReject; result.InternalTransactions.Add(internal_transaction); } } return(new TransactionInfoCapsule(result)); }
public static List <LogInfo> Encode(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_Encode info = cmd.Info.Cast <CodeInfo_Encode>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string filePath = StringEscaper.Preprocess(s, info.FilePath); EncodedFile.EncodeMode mode = EncodedFile.EncodeMode.ZLib; if (info.Compression != null) { string encodeModeStr = StringEscaper.Preprocess(s, info.Compression); if (encodeModeStr.Equals("None", StringComparison.OrdinalIgnoreCase)) { mode = EncodedFile.EncodeMode.Raw; } else if (encodeModeStr.Equals("Deflate", StringComparison.OrdinalIgnoreCase)) { mode = EncodedFile.EncodeMode.ZLib; } else if (encodeModeStr.Equals("LZMA2", StringComparison.OrdinalIgnoreCase)) { mode = EncodedFile.EncodeMode.XZ; } else { return(LogInfo.LogErrorMessage(logs, $"[{encodeModeStr}] is invalid compression")); } } Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check srcFileName contains wildcard if (filePath.IndexOfAny(new char[] { '*', '?' }) == -1) { // No Wildcard s.MainViewModel.SetBuildCommandProgress("Encode Progress", 1); try { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressValue = x; if (x < EncodedFile.CompReportFactor) // [Stage 1] Compress { s.MainViewModel.BuildCommandProgressText = $"Compressing \"{filePath}\"\r\n({x * 100:0.0}%)"; } else // [Stage 2] Base64 { s.MainViewModel.BuildCommandProgressText = $"Writing \"{filePath}\" to script\r\n({x * 100:0.0}%)"; } } }); EncodedFile.AttachFile(sc, dirName, Path.GetFileName(filePath), filePath, mode, progress); logs.Add(new LogInfo(LogState.Success, $"[{filePath}] was encoded into [{sc.RealPath}]", cmd)); } finally { s.MainViewModel.ResetBuildCommandProgress(); } } else { // With Wildcard // Use FileHelper.GetDirNameEx to prevent ArgumentException of Directory.GetFiles string srcDirToFind = FileHelper.GetDirNameEx(filePath); string[] files = Directory.GetFiles(srcDirToFind, Path.GetFileName(filePath)); // No file will be compressed if (files.Length == 0) { logs.Add(new LogInfo(LogState.Warning, $"Files matching wildcard [{filePath}] were not found", cmd)); return(logs); } s.MainViewModel.SetBuildCommandProgress("Encode Progress", files.Length); try { int i = 0; object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressText = $"Attaching {filePath}...\r\n({(x + i) * 100:0.0}%)"; s.MainViewModel.BuildCommandProgressValue = x + i; } }); // One or more file will be copied logs.Add(new LogInfo(LogState.Success, $"[{filePath}] will be encoded into [{sc.RealPath}]", cmd)); foreach (string f in files) { EncodedFile.AttachFile(sc, dirName, Path.GetFileName(f), f, mode, progress); logs.Add(new LogInfo(LogState.Success, $"[{f}] encoded ({i + 1}/{files.Length})", cmd)); i += 1; } logs.Add(new LogInfo(LogState.Success, $"[{files.Length}] files copied", cmd)); } finally { s.MainViewModel.ResetBuildCommandProgress(); } } return(logs); }
/// <summary> /// LogEnd logs the Application Start Event. /// </summary> public static void LogEnd() { try { ApplicationShutdownReason shutdownReason = HostingEnvironment.ShutdownReason; string shutdownDetail; switch (shutdownReason) { case ApplicationShutdownReason.BinDirChangeOrDirectoryRename: shutdownDetail = "The AppDomain shut down because of a change to the Bin folder or files contained in it."; break; case ApplicationShutdownReason.BrowsersDirChangeOrDirectoryRename: shutdownDetail = "The AppDomain shut down because of a change to the App_Browsers folder or files contained in it."; break; case ApplicationShutdownReason.ChangeInGlobalAsax: shutdownDetail = "The AppDomain shut down because of a change to Global.asax."; break; case ApplicationShutdownReason.ChangeInSecurityPolicyFile: shutdownDetail = "The AppDomain shut down because of a change in the code access security policy file."; break; case ApplicationShutdownReason.CodeDirChangeOrDirectoryRename: shutdownDetail = "The AppDomain shut down because of a change to the App_Code folder or files contained in it."; break; case ApplicationShutdownReason.ConfigurationChange: shutdownDetail = "The AppDomain shut down because of a change to the application level configuration."; break; case ApplicationShutdownReason.HostingEnvironment: shutdownDetail = "The AppDomain shut down because of the hosting environment."; break; case ApplicationShutdownReason.HttpRuntimeClose: shutdownDetail = "The AppDomain shut down because of a call to Close."; break; case ApplicationShutdownReason.IdleTimeout: shutdownDetail = "The AppDomain shut down because of the maximum allowed idle time limit."; break; case ApplicationShutdownReason.InitializationError: shutdownDetail = "The AppDomain shut down because of an AppDomain initialization error."; break; case ApplicationShutdownReason.MaxRecompilationsReached: shutdownDetail = "The AppDomain shut down because of the maximum number of dynamic recompiles of resources limit."; break; case ApplicationShutdownReason.PhysicalApplicationPathChanged: shutdownDetail = "The AppDomain shut down because of a change to the physical path for the application."; break; case ApplicationShutdownReason.ResourcesDirChangeOrDirectoryRename: shutdownDetail = "The AppDomain shut down because of a change to the App_GlobalResources folder or files contained in it."; break; case ApplicationShutdownReason.UnloadAppDomainCalled: shutdownDetail = "The AppDomain shut down because of a call to UnloadAppDomain."; break; default: shutdownDetail = "Shutdown reason: " + shutdownReason; break; } var log = new LogInfo { BypassBuffering = true, LogTypeKey = EventLogType.APPLICATION_SHUTTING_DOWN.ToString(), }; log.AddProperty("Shutdown Details", shutdownDetail); LogController.Instance.AddLog(log); // enhanced shutdown logging var runtime = typeof(HttpRuntime).InvokeMember( "_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null) as HttpRuntime; if (runtime == null) { Logger.InfoFormat("Application shutting down. Reason: {0}", shutdownDetail); } else { var shutDownMessage = runtime.GetType().InvokeMember( "_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) as string; var shutDownStack = runtime.GetType().InvokeMember( "_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) as string; Logger.Info("Application shutting down. Reason: " + shutdownDetail + Environment.NewLine + "ASP.NET Shutdown Info: " + shutDownMessage + Environment.NewLine + shutDownStack); } } catch (Exception exc) { Exceptions.LogException(exc); } var status = Globals.DependencyProvider.GetRequiredService <IApplicationStatusInfo>().Status; if (status != UpgradeStatus.Install) { // purge log buffer LoggingProvider.Instance().PurgeLogBuffer(); } }
/// <summary> /// Save curve(s) with given filename. /// </summary> /// <param name="fileName"> /// Filename to save file as /// </param> /// <param name="overwriteData"> /// True allows file overwriting /// </param> /// <param name="appendData"> /// True allows appending data to existing file /// </param> /// <returns> /// <br>True: If call worked fine</br> /// <br>False: If an error occurred</br> /// </returns> public bool RunViaMenu(string fileName, bool overwriteData, bool appendData) { try { string pathForWatcher = Path.GetDirectoryName(fileName); // if save as dialog was not opened if ((new OpenSaveCurveAs()).ViaMenu() == false) { // failed to open save as dialog Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Failed to open save as file browser dialog"); return(false); } // if no user specific fileName exists if (fileName == string.Empty) { // get system-proposed filename fileName = Execution.SaveAsFileBrowser.ProposedFileName; // set default path fileName = SystemInformation.GetApplicationDataPath + @"\" + fileName; pathForWatcher = Path.GetDirectoryName(fileName); } var watcher = new FileWatcher(pathForWatcher, "*.curves"); watcher.StartFileWatcher(); if (Execution.SaveAsFileBrowser.SaveAs(fileName) == false) { // failed to save file Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Failed to save file or overwrite = false"); watcher.StopFileWatcher(); return(false); } Button confirmOverwrite = (new ReplaceFileElements()).BtnNo; // if no overwrite message box came up if (confirmOverwrite == null) { return(true); } // if file is already available // if file should be overwritten if (overwriteData) { confirmOverwrite.Click(DefaultValues.locDefaultLocation); } else if (appendData) { Button confirmAppend = (new ReplaceFileElements()).BtnYes; if (confirmAppend != null && confirmAppend.Enabled) { confirmAppend.Click(DefaultValues.locDefaultLocation); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Data were appended to existing file: " + fileName); } else { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Button to confirm append is not accessible."); return(false); } } else { // cancel overwrite and append message Button cancelAction = (new ReplaceFileElements()).BtnCancel; if (cancelAction != null && cancelAction.Enabled) { cancelAction.Click(DefaultValues.locDefaultLocation); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Saving has been canceled. Data remain available."); watcher.StopFileWatcher(); return(true); } Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Button to cancel saving is not accessable."); watcher.StopFileWatcher(); return(false); } // Check for changed or created file if (!watcher.WaitUntilEventFired(DefaultValues.GeneralTimeout)) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "FileSystemWatcher did not recognize a file operation, saving failed"); watcher.StopFileWatcher(); return(false); } // saving was succesfull Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Saved file successfully"); watcher.StopFileWatcher(); return(true); } catch (Exception exception) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message); return(false); } }
/// <summary> /// 根据文档ID删除文档信息 /// </summary> /// <param name="DocID">文档ID</param> /// <returns>操作记录数</returns> public static int DelDocDoc(string[] DocID) { UserInfoUtil userInfo = (UserInfoUtil)SessionUtil.Session["UserInfo"]; LogInfoModel logModel = new LogInfoModel(); //操作日志 int isSucc = 0; //定义返回变量 #region 设置操作日志内容 //设置公司代码 logModel.CompanyCD = userInfo.CompanyCD; //设置登陆用户ID logModel.UserID = userInfo.UserID; //设置模块ID 模块ID在ConstUtil中定义,以便维护 logModel.ModuleID = ConstUtil.MODULE_ID_DOC_LIST; System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < DocID.Length; i++) { sb.Append(DocID[i] + ";"); } //操作单据编号 logModel.ObjectID = "文档ID:" + sb.ToString(); //操作对象 操作的表信息 logModel.ObjectName = ConstUtil.TABLE_NAME_DOC; //涉及关键元素 涉及其他业务、表关系 logModel.Element = ConstUtil.LOG_PROCESS_DELETE; //备注 操作类型 logModel.Remark = ConstUtil.LOG_PROCESS_DELETE; #endregion try { isSucc = LinkManDBHelper.DelLinkInfo(DocID, ConstUtil.TABLE_NAME_DOC); } catch (System.Exception ex) { #region 操作失败时记录日志到文件 //定义变量 LogInfo logSys = new LogInfo(); //设置日志类型 需要指定为系统日志 logSys.Type = LogInfo.LogType.SYSTEM; //指定系统日志类型 出错信息 logSys.SystemKind = LogInfo.SystemLogKind.SYSTEM_ERROR; //指定登陆用户信息 logSys.UserInfo = userInfo; //设定模块ID logSys.ModuleID = ConstUtil.MODULE_ID_DOC_LIST; //描述 logSys.Description = ex.ToString(); //输出日志 LogUtil.WriteLog(logSys); #endregion } if (isSucc > 0)//操作成功 { logModel.Remark += "成功"; } else//操作失败 { logModel.Remark += "失败"; } //记录日志 LogDBHelper.InsertLog(logModel); return(isSucc); }
/// <summary> /// Starts compare, then cancels it after a specified time /// </summary> /// <param name="timeToWaitUntilCancelInMilliseconds"> /// The time to wait until the comparison is canceled in milliseconds. /// </param> /// <returns> /// <c>true</c> if compare is canceled successfully, <c>false</c> otherwise. /// </returns> public bool Run(int timeToWaitUntilCancelInMilliseconds) { bool result = true; var watch = new Stopwatch(); // Try to start the comparison if ((new Action()).StartCompare() == false) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Compare could not be started."); result = false; } else { watch.Start(); while (watch.ElapsedMilliseconds < timeToWaitUntilCancelInMilliseconds) { if ((new ComparisonProgress()).IsComparing() == false) { result = false; } } watch.Stop(); if (result == false) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Comparison finished. The time to wait until canceling is too long"); } else { if (new Action().CancelCompare() == false) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Compare could not be canceled."); result = false; } else { Button compareButton = new GUI.ApplicationArea.MainView.ActionElements().ButtonCompare; Button cancelButton = new GUI.ApplicationArea.MainView.ActionElements().ButtonCancel; Element modeSelection = new GUI.ApplicationArea.MainView.SelectionElements().ElementModeSelection; if (compareButton == null || cancelButton == null || modeSelection == null) { result = false; Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Button Compare, Cancel or ModeSelection is null"); } else { string mode = modeSelection.GetAttributeValueText("Text"); if (mode != string.Empty || cancelButton.Enabled || compareButton.Enabled) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Compare was canceled but did not abort."); result = false; } else { Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Compare was canceled successfully."); } } } } } return(result); }
private void DrawLogsList() { GUILayout.BeginVertical(GUI.skin.box); { if (IsLock_) { ScrollPosition_.y = float.MaxValue; } ScrollPosition_ = GUILayout.BeginScrollView(ScrollPosition_); { var IsSelected = false; InfoCount_ = 0; WarningCount_ = 0; ErrorCount_ = 0; foreach (var Log in Logs_) { switch (Log.Type) { case LogType.Log: InfoCount_++; if (!IsShowInfo_) { continue; } break; case LogType.Warning: WarningCount_++; if (!IsShowWarning_) { continue; } break; case LogType.Error: ErrorCount_++; if (!IsShowError_) { continue; } break; default: break; } if (GUILayout.Toggle(TraceNode_ == Log, GetLogMsg(Log))) { IsSelected = true; if (TraceNode_ != Log) { TraceNode_ = Log; TraceScrollPosition_ = Vector2.zero; } } } if (!IsSelected) { TraceNode_ = null; } } GUILayout.EndScrollView(); } GUILayout.EndVertical(); GUILayout.BeginVertical(GUI.skin.box); { TraceScrollPosition_ = GUILayout.BeginScrollView(TraceScrollPosition_, GUILayout.Height(100f)); { if (TraceNode_ != null) { GUILayout.BeginHorizontal(); GUILayout.Label($"<b>{GetLogMsg(TraceNode_)}</b>"); if (GUILayout.Button("Copy", GUILayout.Width(60f), GUILayout.Height(30f))) { TextEditor_.text = $"{TraceNode_.Message}{Environment.NewLine}{TraceNode_.StackTrace}{Environment.NewLine}"; TextEditor_.OnFocus(); TextEditor_.Copy(); TextEditor_.text = null; } GUILayout.EndHorizontal(); GUILayout.Label(TraceNode_.StackTrace); } } GUILayout.EndScrollView(); } GUILayout.EndVertical(); }
private void OnPageLoad(object sender, EventArgs e) { try { AnalyticsEngineCollection analyticsEngines = AnalyticsEngineConfiguration.GetConfig().AnalyticsEngines; if (analyticsEngines == null || analyticsEngines.Count == 0) { return; } var page = (Page)sender; if ((page == null)) { return; } foreach (AnalyticsEngine engine in analyticsEngines) { if ((!String.IsNullOrEmpty(engine.ElementId))) { AnalyticsEngineBase objEngine = null; if ((!String.IsNullOrEmpty(engine.EngineType))) { Type engineType = Type.GetType(engine.EngineType); if (engineType == null) { objEngine = new GenericAnalyticsEngine(); } else { objEngine = (AnalyticsEngineBase)Activator.CreateInstance(engineType); } } else { objEngine = new GenericAnalyticsEngine(); } if (objEngine != null) { string script = engine.ScriptTemplate; if ((!String.IsNullOrEmpty(script))) { script = objEngine.RenderScript(script); if ((!String.IsNullOrEmpty(script))) { var element = (HtmlContainerControl)page.FindControl(engine.ElementId); if (element != null) { var scriptControl = new LiteralControl(); scriptControl.Text = script; if (engine.InjectTop) { element.Controls.AddAt(0, scriptControl); } else { element.Controls.Add(scriptControl); } } } } } } } } catch (Exception ex) { var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsModule", "OnPageLoad"); log.AddProperty("ExceptionMessage", ex.Message); LogController.Instance.AddLog(log); Logger.Error(ex); } }
public static List <LogInfo> IniReadOp(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_IniReadOp infoOp = cmd.Info.Cast <CodeInfo_IniReadOp>(); string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName); Debug.Assert(fileName != null, $"{nameof(fileName)} != null"); if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } IniKey[] keys = new IniKey[infoOp.Cmds.Count]; for (int i = 0; i < keys.Length; i++) { CodeInfo_IniRead info = infoOp.Infos[i]; string sectionName = StringEscaper.Preprocess(s, info.Section); string key = StringEscaper.Preprocess(s, info.Key); if (sectionName.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty")); } if (key.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty")); } keys[i] = new IniKey(sectionName, key); } keys = IniReadWriter.ReadKeys(fileName, keys); int successCount = 0; for (int i = 0; i < keys.Length; i++) { IniKey kv = keys[i]; CodeCommand subCmd = infoOp.Cmds[i]; if (kv.Value != null) { logs.Add(new LogInfo(LogState.Success, $"Key [{kv.Key}] and it's value [{kv.Value}] successfully read", subCmd)); string escapedValue = StringEscaper.Escape(kv.Value, false, true); List <LogInfo> varLogs = Variables.SetVariable(s, infoOp.Infos[i].DestVar, escapedValue, false, false, false); LogInfo.AddCommand(varLogs, subCmd); logs.AddRange(varLogs); successCount += 1; } else { if (infoOp.Infos[i].DefaultValue != null) { logs.Add(new LogInfo(LogState.Ignore, $"Key [{kv.Key}] does not exist. Assigning default value [{infoOp.Infos[i].DefaultValue}]")); List <LogInfo> varLogs = Variables.SetVariable(s, infoOp.Infos[i].DestVar, infoOp.Infos[i].DefaultValue, false, false, false); logs.AddRange(varLogs); } else { logs.Add(new LogInfo(LogState.Ignore, $"Key [{kv.Key}] does not exist", subCmd)); List <LogInfo> varLogs = Variables.SetVariable(s, infoOp.Infos[i].DestVar, string.Empty, false, false, false); logs.AddRange(varLogs); } } } logs.Add(new LogInfo(LogState.Success, $"Read [{successCount}] values from [{fileName}]", cmd)); return(logs); }
/// <summary> /// Run cyclic curve reading /// </summary> /// <param name="numberOfCurves">Number of curves to read</param> /// <param name="waitUntilFinished">Configure if should be waited until a curve is read or not</param> /// <returns>true: if execution worked, false: if an error occurred</returns> public bool RunViaMenu(int numberOfCurves, bool waitUntilFinished) { try { // 2013-06-26 - EC - Changed Type Text to Element Element text = (new DiagramElements()).CurveDataNumber; if (new IsDTMConnected().Run()) { if ((new RunCyclicRead()).ViaMenu()) { EH.PCPS.TestAutomation.Common.Tools.Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Cyclic reading started"); if (text != null) { const string Separator = "/"; // 2013-06-26 - EC - Code replaces code below string curvesIni = text.GetAttributeValueText("WindowText"); // curvesIni = text.TextValue; // 2013-06-26 - EC - Code replaces code below string curvesNew = text.GetAttributeValueText("WindowText"); // curvesNew = text.TextValue; int separatorPositionIni = curvesIni.IndexOf(Separator, StringComparison.Ordinal); int separatorPositionNew = curvesNew.IndexOf(Separator, StringComparison.Ordinal); curvesIni = curvesIni.Substring(0, separatorPositionIni); curvesNew = curvesNew.Substring(0, separatorPositionNew); int curvesIniCount = Convert.ToInt16(curvesIni); int curvesNewCount = Convert.ToInt16(curvesNew); while (curvesNewCount < (curvesIniCount + numberOfCurves)) { // 2013-06-26 - EC - Code replaces code below curvesNew = text.GetAttributeValueText("WindowText"); // curvesNew = text.TextValue; separatorPositionNew = curvesNew.IndexOf(Separator, StringComparison.Ordinal); curvesNew = curvesNew.Substring(0, separatorPositionNew); curvesNewCount = Convert.ToInt16(curvesNew); } if (waitUntilFinished) { if ((new RunEndReadWrite()).ViaMenu()) { var watch = new Stopwatch(); watch.Start(); while ((new ReadAndWrite()).IsReading()) { if (watch.ElapsedMilliseconds <= DefaultValues.GeneralTimeout) { continue; } EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Cyclic reading did not finish within " + DefaultValues.GeneralTimeout + " milliseconds"); watch.Stop(); return(false); } watch.Stop(); EH.PCPS.TestAutomation.Common.Tools.Log.Info( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Cyclic reading finished after " + watch.ElapsedMilliseconds + " milliseconds. (Timeout: " + DefaultValues.GeneralTimeout + " milliseconds)"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Function [RunEndReadWrite.ViaMenu] was not Executiond."); return(false); } EH.PCPS.TestAutomation.Common.Tools.Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Cyclic reading started"); return(true); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Textfield is not accessable."); return(false); } EH.PCPS.TestAutomation.Common.Tools.Log.Error( LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Function [RunCyclicReading.ViaMenu] was not Executiond."); return(false); } EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Module is not online."); return(false); } catch (Exception exception) { EH.PCPS.TestAutomation.Common.Tools.Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message); return(false); } }
/// <summary> /// Configures the parameter of the tab 'Fluid Properties'. /// </summary> /// <param name="dynamicViscosityUnit">The dynamic viscosity unit. Use string.empty if you want to skip this parameter.</param> /// <param name="temperatureUnit">The temperature unit. Use string.empty if you want to skip this parameter.</param> /// <param name="referenceTemperature">The reference temperature. Use string.empty if you want to skip this parameter.</param> /// <param name="firstColumn">The first column. Use string.empty if you want to skip this parameter.</param> /// <param name="secondColumn">The second column. Use string.empty if you want to skip this parameter.</param> /// <returns><c>true</c> if all parameter are configured successfully, <c>false</c> otherwise.</returns> public bool Run(string dynamicViscosityUnit, string temperatureUnit, string referenceTemperature, string firstColumn, string secondColumn) { bool result = DeviceFunctionLoader.CoDIA.Viscosity.Functions.ApplicationArea.MainView.Execution.SelectTab.Run(0); if (this.IsValid(dynamicViscosityUnit)) { new TabFluidProperties().ComboBoxViscosityUnit = dynamicViscosityUnit; if (dynamicViscosityUnit != new TabFluidProperties().ComboBoxViscosityUnit) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Configuring failed at setting dynamic viscosity unit. Value doesn't match expectation."); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), dynamicViscosityUnit + " != " + new TabFluidProperties().ComboBoxViscosityUnit); result = false; } } if (this.IsValid(temperatureUnit)) { new TabFluidProperties().ComboBoxReferenceTemperatureUnit = temperatureUnit; if (temperatureUnit != new TabFluidProperties().ComboBoxReferenceTemperatureUnit) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Configuring failed at setting temperature unit. Value doesn't match expectation."); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), temperatureUnit + " != " + new TabFluidProperties().ComboBoxReferenceTemperatureUnit); result = false; } } if (this.IsValid(referenceTemperature)) { new TabFluidProperties().NumericTextBoxReferenceTemperature = referenceTemperature; if (referenceTemperature != new TabFluidProperties().NumericTextBoxReferenceTemperature) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Configuring failed at setting reference temperature. Value doesn't match expectation."); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), referenceTemperature + " != " + new TabFluidProperties().NumericTextBoxReferenceTemperature); result = false; } } if (this.IsValid(firstColumn)) { new TabFluidProperties().ComboBoxAssignmentColumn1 = firstColumn; if (firstColumn != new TabFluidProperties().ComboBoxAssignmentColumn1) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Configuring failed at setting first column. Value doesn't match expectation."); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), firstColumn + " != " + new TabFluidProperties().ComboBoxAssignmentColumn1); result = false; } } if (this.IsValid(secondColumn)) { new TabFluidProperties().ComboBoxAssignmentColumn2 = secondColumn; if (secondColumn != new TabFluidProperties().ComboBoxAssignmentColumn2) { Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Configuring failed at setting second column. Value doesn't match expectation."); Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), secondColumn + " != " + new TabFluidProperties().ComboBoxAssignmentColumn2); result = false; } } return result; }
public static List <LogInfo> ExtractAndRun(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_ExtractAndRun info = cmd.Info.Cast <CodeInfo_ExtractAndRun>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string fileName = StringEscaper.Preprocess(s, info.FileName); Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check if encoded file exist if (!EncodedFile.ContainsFile(sc, dirName, fileName)) { return(LogInfo.LogErrorMessage(logs, $"Encoded file [{dirName}\\{fileName}] not found in script [{sc.RealPath}].")); } string tempDir = FileHelper.GetTempDir(); string tempPath = Path.Combine(tempDir, fileName); s.MainViewModel.SetBuildCommandProgress("ExtractAndRun Progress", 1); try { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressValue = x; if (x < EncodedFile.Base64ReportFactor) { // [Stage 1] Base64 s.MainViewModel.BuildCommandProgressText = $"Reading \"{fileName}\" from script\r\n({x * 100:0.0}%)"; } else { // [Stage 2] Decompress s.MainViewModel.BuildCommandProgressText = $"Decompressing \"{fileName}\"\r\n({x * 100:0.0}%)"; } } }); using (FileStream fs = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) { EncodedFile.ExtractFile(sc, dirName, info.FileName, fs, progress); } } finally { s.MainViewModel.ResetBuildCommandProgress(); } Process proc = new Process { EnableRaisingEvents = true, StartInfo = new ProcessStartInfo { FileName = tempPath, UseShellExecute = true, } }; string _params = null; if (!string.IsNullOrEmpty(info.Params)) { _params = StringEscaper.Preprocess(s, info.Params); proc.StartInfo.Arguments = _params; } proc.Exited += (object sender, EventArgs e) => { if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } // ReSharper disable once AccessToDisposedClosure proc.Dispose(); }; try { proc.Start(); } catch (Exception) { proc.Dispose(); throw; } if (_params == null) { logs.Add(new LogInfo(LogState.Success, $"Extracted and executed [{fileName}]")); } else { logs.Add(new LogInfo(LogState.Success, $"Extracted and executed [{fileName} {_params}]")); } return(logs); }