diff --git a/src/ColumnizerLib/Column.cs b/src/ColumnizerLib/Column.cs index 03fb37b6..7cabf065 100644 --- a/src/ColumnizerLib/Column.cs +++ b/src/ColumnizerLib/Column.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace LogExpert; @@ -7,8 +7,8 @@ public class Column : IColumn { #region Fields - private static readonly int _maxLength = 4678 - 3; - private static readonly string _replacement = "..."; + private const int MAXLENGTH = 4678 - 3; + private const string REPLACEMENT = "..."; private static readonly IEnumerable> _replacements; @@ -18,42 +18,35 @@ public class Column : IColumn #region cTor - static Column() + static Column () { var replacements = new List>( - new Func[] - { + [ //replace tab with 3 spaces, from old coding. Needed??? - input => input.Replace("\t", " "), + input => input.Replace("\t", " ", StringComparison.Ordinal), //shorten string if it exceeds maxLength - input => - { - if (input.Length > _maxLength) - { - return input.Substring(0, _maxLength) + _replacement; - } - - return input; - } - }); + input => input.Length > MAXLENGTH + ? string.Concat(input.AsSpan(0, MAXLENGTH), REPLACEMENT) + : input + ]); if (Environment.Version >= Version.Parse("6.2")) { //Win8 or newer support full UTF8 chars with the preinstalled fonts. - //Replace null char with UTF8 Symbol U+2400 (␀) - replacements.Add(input => input.Replace("\0", "␀")); + //Replace null char with UTF8 Symbol U+2400 (␀) + replacements.Add(input => input.Replace("\0", "␀", StringComparison.Ordinal)); } else { //Everything below Win8 the installed fonts seems to not to support reliabel //Replace null char with space - replacements.Add(input => input.Replace("\0", " ")); + replacements.Add(input => input.Replace("\0", " ", StringComparison.Ordinal)); } _replacements = replacements; - EmptyColumn = new Column {FullValue = string.Empty}; + EmptyColumn = new Column { FullValue = string.Empty }; } #endregion @@ -90,24 +83,24 @@ public string FullValue #region Public methods - public static Column[] CreateColumns(int count, IColumnizedLogLine parent) + public static Column[] CreateColumns (int count, IColumnizedLogLine parent) { return CreateColumns(count, parent, string.Empty); } - public static Column[] CreateColumns(int count, IColumnizedLogLine parent, string defaultValue) + public static Column[] CreateColumns (int count, IColumnizedLogLine parent, string defaultValue) { var output = new Column[count]; for (var i = 0; i < count; i++) { - output[i] = new Column {FullValue = defaultValue, Parent = parent}; + output[i] = new Column { FullValue = defaultValue, Parent = parent }; } return output; } - public override string ToString() + public override string ToString () { return DisplayValue ?? string.Empty; } diff --git a/src/ColumnizerLib/LineEntry.cs b/src/ColumnizerLib/LineEntry.cs index bcbb4699..3869767c 100644 --- a/src/ColumnizerLib/LineEntry.cs +++ b/src/ColumnizerLib/LineEntry.cs @@ -10,10 +10,10 @@ public struct LineEntry /// /// The content of the line. /// - public ILogLine logLine; + public ILogLine LogLine { get; set; } /// /// The line number. See for an explanation of the line number. /// - public int lineNum; + public int LineNum { get; set; } } \ No newline at end of file diff --git a/src/CsvColumnizer/CsvColumnizer.cs b/src/CsvColumnizer/CsvColumnizer.cs index 8d6bffe5..9254c4ca 100644 --- a/src/CsvColumnizer/CsvColumnizer.cs +++ b/src/CsvColumnizer/CsvColumnizer.cs @@ -1,9 +1,3 @@ -using CsvHelper; - -using LogExpert; - -using Newtonsoft.Json; - using System; using System.Collections.Generic; using System.IO; @@ -12,6 +6,12 @@ using System.Runtime.Versioning; using System.Windows.Forms; +using CsvHelper; + +using LogExpert; + +using Newtonsoft.Json; + [assembly: SupportedOSPlatform("windows")] namespace CsvColumnizer; @@ -24,7 +24,7 @@ public class CsvColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerCon { #region Fields - private static readonly string _configFileName = "csvcolumnizer.json"; + private const string CONFIGFILENAME = "csvcolumnizer.json"; private readonly IList _columnList = []; private CsvColumnizerConfig _config; @@ -38,7 +38,7 @@ public class CsvColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerCon #region Public methods - public string PreProcessLine(string logLine, int lineNum, int realLineNum) + public string PreProcessLine (string logLine, int lineNum, int realLineNum) { if (realLineNum == 0) { @@ -72,22 +72,22 @@ public string PreProcessLine(string logLine, int lineNum, int realLineNum) return logLine; } - public string GetName() + public string GetName () { return "CSV Columnizer"; } - public string GetDescription() + public string GetDescription () { return "Splits CSV files into columns.\r\n\r\nCredits:\r\nThis Columnizer uses the CsvHelper. https://github.com/JoshClose/CsvHelper. \r\n"; } - public int GetColumnCount() + public int GetColumnCount () { return _isValidCsv ? _columnList.Count : 1; } - public string[] GetColumnNames() + public string[] GetColumnNames () { var names = new string[GetColumnCount()]; if (_isValidCsv) @@ -106,7 +106,7 @@ public string[] GetColumnNames() return names; } - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) { if (_isValidCsv) { @@ -116,7 +116,7 @@ public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLin return CreateColumnizedLogLine(line); } - private static ColumnizedLogLine CreateColumnizedLogLine(ILogLine line) + private static ColumnizedLogLine CreateColumnizedLogLine (ILogLine line) { ColumnizedLogLine cLogLine = new() { @@ -126,32 +126,32 @@ private static ColumnizedLogLine CreateColumnizedLogLine(ILogLine line) return cLogLine; } - public bool IsTimeshiftImplemented() + public bool IsTimeshiftImplemented () { return false; } - public void SetTimeOffset(int msecOffset) + public void SetTimeOffset (int msecOffset) { throw new NotImplementedException(); } - public int GetTimeOffset() + public int GetTimeOffset () { throw new NotImplementedException(); } - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { throw new NotImplementedException(); } - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) { throw new NotImplementedException(); } - public void Selected(ILogLineColumnizerCallback callback) + public void Selected (ILogLineColumnizerCallback callback) { if (_isValidCsv) // see PreProcessLine() { @@ -186,14 +186,14 @@ public void Selected(ILogLineColumnizerCallback callback) } } - public void DeSelected(ILogLineColumnizerCallback callback) + public void DeSelected (ILogLineColumnizerCallback callback) { // nothing to do } - public void Configure(ILogLineColumnizerCallback callback, string configDir) + public void Configure (ILogLineColumnizerCallback callback, string configDir) { - var configPath = configDir + "\\" + _configFileName; + var configPath = configDir + "\\" + CONFIGFILENAME; FileInfo fileInfo = new(configPath); CsvColumnizerConfigDlg dlg = new(_config); @@ -214,9 +214,9 @@ public void Configure(ILogLineColumnizerCallback callback, string configDir) } } - public void LoadConfig(string configDir) + public void LoadConfig (string configDir) { - var configPath = Path.Combine(configDir, _configFileName); + var configPath = Path.Combine(configDir, CONFIGFILENAME); if (!File.Exists(configPath)) { @@ -239,7 +239,7 @@ public void LoadConfig(string configDir) } } - public Priority GetPriority(string fileName, IEnumerable samples) + public Priority GetPriority (string fileName, IEnumerable samples) { Priority result = Priority.NotSupport; @@ -255,7 +255,7 @@ public Priority GetPriority(string fileName, IEnumerable samples) #region Private Methods - private IColumnizedLogLine SplitCsvLine(ILogLine line) + private IColumnizedLogLine SplitCsvLine (ILogLine line) { ColumnizedLogLine cLogLine = new() { diff --git a/src/DefaultPlugins/ProcessLauncher.cs b/src/DefaultPlugins/ProcessLauncher.cs index 8e381867..de439ddf 100644 --- a/src/DefaultPlugins/ProcessLauncher.cs +++ b/src/DefaultPlugins/ProcessLauncher.cs @@ -1,3 +1,4 @@ +using System; using System.Diagnostics; namespace LogExpert; @@ -26,7 +27,7 @@ public void Execute (string keyword, string param, ILogExpertCallback callback, } else { - end = param.IndexOf(' '); + end = param.IndexOf(' ', StringComparison.Ordinal); } if (end == -1) @@ -39,14 +40,14 @@ public void Execute (string keyword, string param, ILogExpertCallback callback, lock (_callbackLock) { var parameters = param[end..].Trim(); - parameters = parameters.Replace("%F", callback.GetFileName()); - parameters = parameters.Replace("%K", keyword); + parameters = parameters.Replace("%F", callback.GetFileName(), StringComparison.Ordinal); + parameters = parameters.Replace("%K", keyword, StringComparison.Ordinal); var lineNumber = callback.GetLineNum(); //Line Numbers start at 0, but are displayed (+1) var logline = callback.GetLogLine(lineNumber).FullLine; - parameters = parameters.Replace("%L", string.Empty + lineNumber); - parameters = parameters.Replace("%T", callback.GetTabTitle()); - parameters = parameters.Replace("%C", logline); + parameters = parameters.Replace("%L", string.Empty + lineNumber, System.StringComparison.Ordinal); + parameters = parameters.Replace("%T", callback.GetTabTitle(), StringComparison.Ordinal); + parameters = parameters.Replace("%C", logline, StringComparison.Ordinal); Process explorer = new(); explorer.StartInfo.FileName = procName; diff --git a/src/JsonColumnizer/JsonColumnizer.cs b/src/JsonColumnizer/JsonColumnizer.cs index 04c6f071..48dacfea 100644 --- a/src/JsonColumnizer/JsonColumnizer.cs +++ b/src/JsonColumnizer/JsonColumnizer.cs @@ -1,12 +1,12 @@ -using LogExpert; - -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - using System; using System.Collections.Generic; using System.Linq; +using LogExpert; + +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + namespace JsonColumnizer; /// @@ -14,36 +14,28 @@ namespace JsonColumnizer; /// public class JsonColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerPriority { - #region Fields - - private static readonly JsonColumn _initialColumn = new JsonColumn("Text"); - - private readonly IList _columnList = new List([InitialColumn]); - - #endregion - #region Properties public HashSet ColumnSet { get; set; } = []; - protected IList ColumnList => _columnList; + protected IList ColumnList { get; } = new List([InitialColumn]); - protected static JsonColumn InitialColumn => _initialColumn; + protected static JsonColumn InitialColumn { get; } = new JsonColumn("Text"); #endregion #region Public methods - public virtual void Selected(ILogLineColumnizerCallback callback) + public virtual void Selected (ILogLineColumnizerCallback callback) { ColumnList.Clear(); ColumnSet.Clear(); - var line = callback.GetLogLine(0); + ILogLine line = callback.GetLogLine(0); if (line != null) { - var json = ParseJson(line); + JObject json = ParseJson(line); if (json != null) { var fieldCount = json.Properties().Count(); @@ -51,52 +43,51 @@ public virtual void Selected(ILogLineColumnizerCallback callback) for (var i = 0; i < fieldCount; ++i) { var columeName = json.Properties().ToArray()[i].Name; - if (!ColumnSet.Contains(columeName)) + if (ColumnSet.Add(columeName)) { - ColumnSet.Add(columeName); ColumnList.Add(new JsonColumn(columeName)); } } } else { - ColumnSet.Add("Text"); + _ = ColumnSet.Add("Text"); ColumnList.Add(InitialColumn); } } - if (ColumnList.Count() == 0) + if (ColumnList.Count == 0) { - ColumnSet.Add("Text"); + _ = ColumnSet.Add("Text"); ColumnList.Add(InitialColumn); } } - public virtual void DeSelected(ILogLineColumnizerCallback callback) + public virtual void DeSelected (ILogLineColumnizerCallback callback) { // nothing to do } - public virtual string GetName() + public virtual string GetName () { return "JSON Columnizer"; } - public virtual string GetDescription() + public virtual string GetDescription () { return "Splits JSON files into columns.\r\n\r\nCredits:\r\nThis Columnizer uses the Newtonsoft json package.\r\n\r\nFirst line must be valid or else only one column will be displayed and the other values dropped!"; } - public virtual int GetColumnCount() + public virtual int GetColumnCount () { return ColumnList.Count; } - public virtual string[] GetColumnNames() + public virtual string[] GetColumnNames () { var names = new string[GetColumnCount()]; var i = 0; - foreach (var column in ColumnList) + foreach (JsonColumn column in ColumnList) { names[i++] = column.Name; } @@ -104,7 +95,7 @@ public virtual string[] GetColumnNames() return names; } - public virtual IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + public virtual IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) { JObject json = ParseJson(line); @@ -115,7 +106,7 @@ public virtual IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, var cLogLine = new ColumnizedLogLine { LogLine = line }; - var columns = Column.CreateColumns(ColumnList.Count, cLogLine); + Column[] columns = Column.CreateColumns(ColumnList.Count, cLogLine); columns.Last().FullValue = line.FullLine; @@ -124,32 +115,32 @@ public virtual IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, return cLogLine; } - public virtual bool IsTimeshiftImplemented() + public virtual bool IsTimeshiftImplemented () { return false; } - public virtual void SetTimeOffset(int msecOffset) + public virtual void SetTimeOffset (int msecOffset) { throw new NotImplementedException(); } - public virtual int GetTimeOffset() + public virtual int GetTimeOffset () { throw new NotImplementedException(); } - public virtual DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + public virtual DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { throw new NotImplementedException(); } - public virtual void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + public virtual void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) { throw new NotImplementedException(); } - public virtual Priority GetPriority(string fileName, IEnumerable samples) + public virtual Priority GetPriority (string fileName, IEnumerable samples) { Priority result = Priority.NotSupport; if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) @@ -164,7 +155,7 @@ public virtual Priority GetPriority(string fileName, IEnumerable sampl #region Private Methods - protected static JObject ParseJson(ILogLine line) + protected static JObject ParseJson (ILogLine line) { return JsonConvert.DeserializeObject(line.FullLine, new JsonSerializerSettings() { @@ -182,13 +173,13 @@ public class ColumnWithName : Column // {"time":"2019-02-13T02:55:35.5186240Z","message":"Hosting starting"} // {"time":"2019-02-13T02:55:35.5186240Z","level":"warning", "message":"invalid host."} // - protected virtual IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) + protected virtual IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json) { var cLogLine = new ColumnizedLogLine { LogLine = line }; var columns = json.Properties().Select(property => new ColumnWithName { FullValue = property.Value.ToString(), ColumnName = property.Name.ToString(), Parent = cLogLine }).ToList(); - foreach (var jsonColumn in columns) + foreach (ColumnWithName jsonColumn in columns) { // When find new column in a log line, add a new column in the end of the list. if (!ColumnSet.Contains(jsonColumn.ColumnName)) @@ -198,7 +189,7 @@ protected virtual IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) ColumnList.Clear(); } - ColumnSet.Add(jsonColumn.ColumnName); + _ = ColumnSet.Add(jsonColumn.ColumnName); ColumnList.Add(new JsonColumn(jsonColumn.ColumnName)); } } @@ -208,9 +199,9 @@ protected virtual IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) // This will make sure the log line displayed correct even the order of json fields changed. // List returnColumns = []; - foreach (var column in ColumnList) + foreach (JsonColumn column in ColumnList) { - var existingColumn = columns.Find(x => x.ColumnName == column.Name); + ColumnWithName existingColumn = columns.Find(x => x.ColumnName == column.Name); if (existingColumn != null) { returnColumns.Add(new Column() { FullValue = existingColumn.FullValue, Parent = cLogLine }); diff --git a/src/JsonCompactColumnizer/JsonCompactColumnizer.cs b/src/JsonCompactColumnizer/JsonCompactColumnizer.cs index d286ac88..5cc3b33d 100644 --- a/src/JsonCompactColumnizer/JsonCompactColumnizer.cs +++ b/src/JsonCompactColumnizer/JsonCompactColumnizer.cs @@ -1,11 +1,11 @@ -using LogExpert; - -using Newtonsoft.Json.Linq; - using System; using System.Collections.Generic; using System.Linq; +using LogExpert; + +using Newtonsoft.Json.Linq; + namespace JsonColumnizer; /// @@ -15,28 +15,28 @@ public class JsonCompactColumnizer : JsonColumnizer, IColumnizerPriority { #region Public methods - public override string GetName() + public override string GetName () { return "JSON Compact Columnizer"; } - public override string GetDescription() + public override string GetDescription () { return "A JSON columnier for Serilog.Formatting.Compact format."; } - public override void Selected(ILogLineColumnizerCallback callback) + public override void Selected (ILogLineColumnizerCallback callback) { ColumnList.Clear(); // Create column header with cached column list. - foreach (var col in _tagDict.Keys) + foreach (var col in TagDict.Keys) { - ColumnList.Add(new JsonColumn(_tagDict[col])); + ColumnList.Add(new JsonColumn(TagDict[col])); } } - public override Priority GetPriority(string fileName, IEnumerable samples) + public override Priority GetPriority (string fileName, IEnumerable samples) { Priority result = Priority.NotSupport; if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) @@ -72,7 +72,7 @@ public override Priority GetPriority(string fileName, IEnumerable samp #region Private Methods - protected Dictionary _tagDict = new() + protected Dictionary TagDict { get; set; } = new() { {"@t", "Timestamp"}, {"@l", "Level"}, @@ -83,7 +83,7 @@ public override Priority GetPriority(string fileName, IEnumerable samp {"@mt", "Message Template"}, }; - protected override IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) + protected override IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json) { List returnColumns = []; var cLogLine = new ColumnizedLogLine { LogLine = line }; @@ -94,11 +94,11 @@ protected override IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) // Always rearrage the order of all json fields within a line to follow the sequence of columnNameList. // This will make sure the log line displayed correct even the order of json fields changed. // - foreach (var column in _tagDict.Keys) + foreach (var column in TagDict.Keys) { if (column.StartsWith('@')) { - var existingColumn = columns.Find(x => x.ColumnName == column); + ColumnWithName existingColumn = columns.Find(x => x.ColumnName == column); if (existingColumn != null) { diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs index 012bd06b..0d8833a3 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs @@ -1,7 +1,3 @@ -using LogExpert; - -using Newtonsoft.Json; - using System; using System.Collections.Generic; using System.Globalization; @@ -11,6 +7,10 @@ using System.Runtime.Versioning; using System.Windows.Forms; +using LogExpert; + +using Newtonsoft.Json; + [assembly: SupportedOSPlatform("windows")] namespace Log4jXmlColumnizer; @@ -22,17 +22,17 @@ public class Log4jXmlColumnizer : ILogLineXmlColumnizer, IColumnizerConfigurator protected const string DATETIME_FORMAT = "dd.MM.yyyy HH:mm:ss.fff"; private static readonly XmlConfig xmlConfig = new(); - private readonly char separatorChar = '\xFFFD'; + private const char separatorChar = '\xFFFD'; private readonly char[] trimChars = ['\xFFFD']; private Log4jXmlColumnizerConfig _config; - protected CultureInfo cultureInfo = new("de-DE"); - protected int timeOffset; + private readonly CultureInfo _cultureInfo = new("de-DE"); + private int _timeOffset; #endregion #region cTor - public Log4jXmlColumnizer() + public Log4jXmlColumnizer () { _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); } @@ -41,12 +41,12 @@ public Log4jXmlColumnizer() #region Public methods - public IXmlLogConfiguration GetXmlLogConfiguration() + public IXmlLogConfiguration GetXmlLogConfiguration () { return xmlConfig; } - public ILogLine GetLineTextForClipboard(ILogLine logLine, ILogLineColumnizerCallback callback) + public ILogLine GetLineTextForClipboard (ILogLine logLine, ILogLineColumnizerCallback callback) { Log4JLogLine line = new() { @@ -57,27 +57,27 @@ public ILogLine GetLineTextForClipboard(ILogLine logLine, ILogLineColumnizerCall return line; } - public string GetName() + public string GetName () { return "Log4j XML"; } - public string GetDescription() + public string GetDescription () { return "Reads and formats XML log files written with log4j."; } - public int GetColumnCount() + public int GetColumnCount () { return _config.ActiveColumnCount; } - public string[] GetColumnNames() + public string[] GetColumnNames () { return _config.ActiveColumnNames; } - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) { ColumnizedLogLine clogLine = new(); clogLine.LogLine = line; @@ -146,22 +146,22 @@ public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLin } - public bool IsTimeshiftImplemented() + public bool IsTimeshiftImplemented () { return true; } - public void SetTimeOffset(int msecOffset) + public void SetTimeOffset (int msecOffset) { - timeOffset = msecOffset; + _timeOffset = msecOffset; } - public int GetTimeOffset() + public int GetTimeOffset () { - return timeOffset; + return _timeOffset; } - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { if (line.FullLine.Length < 15) { @@ -185,11 +185,11 @@ public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) DateTime dateTime = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddMilliseconds(timestamp); - if (_config.localTimestamps) + if (_config.LocalTimestamps) { dateTime = dateTime.ToLocalTime(); } - return dateTime.AddMilliseconds(timeOffset); + return dateTime.AddMilliseconds(_timeOffset); } else { @@ -202,17 +202,17 @@ public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) } } - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) { if (column == 0) { try { - var newDateTime = DateTime.ParseExact(value, DATETIME_FORMAT, cultureInfo); - var oldDateTime = DateTime.ParseExact(oldValue, DATETIME_FORMAT, cultureInfo); + var newDateTime = DateTime.ParseExact(value, DATETIME_FORMAT, _cultureInfo); + var oldDateTime = DateTime.ParseExact(oldValue, DATETIME_FORMAT, _cultureInfo); var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - timeOffset = (int)(mSecsNew - mSecsOld); + _timeOffset = (int)(mSecsNew - mSecsOld); } catch (FormatException) { @@ -220,7 +220,7 @@ public void PushValue(ILogLineColumnizerCallback callback, int column, string va } } - public void Configure(ILogLineColumnizerCallback callback, string configDir) + public void Configure (ILogLineColumnizerCallback callback, string configDir) { FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"); @@ -234,7 +234,7 @@ public void Configure(ILogLineColumnizerCallback callback, string configDir) } } - public void LoadConfig(string configDir) + public void LoadConfig (string configDir) { var configPath = configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"; @@ -249,7 +249,7 @@ public void LoadConfig(string configDir) try { _config = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); - if (_config.columnList.Count < COLUMN_COUNT) + if (_config.ColumnList.Count < COLUMN_COUNT) { _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); } @@ -262,7 +262,7 @@ public void LoadConfig(string configDir) } } - public Priority GetPriority(string fileName, IEnumerable samples) + public Priority GetPriority (string fileName, IEnumerable samples) { Priority result = Priority.NotSupport; if (fileName.EndsWith("xml", StringComparison.OrdinalIgnoreCase)) @@ -276,18 +276,18 @@ public Priority GetPriority(string fileName, IEnumerable samples) #region Private Methods - private string[] GetAllColumnNames() => ["Timestamp", "Level", "Logger", "Thread", "Class", "Method", "File", "Line", "Message"]; + private string[] GetAllColumnNames () => ["Timestamp", "Level", "Logger", "Thread", "Class", "Method", "File", "Line", "Message"]; /// /// Returns only the columns which are "active". The order of the columns depends on the column order in the config /// /// /// - private Column[] MapColumns(Column[] cols) + private Column[] MapColumns (Column[] cols) { List output = []; var index = 0; - foreach (Log4jColumnEntry entry in _config.columnList) + foreach (Log4jColumnEntry entry in _config.ColumnList) { if (entry.Visible) { @@ -296,7 +296,7 @@ private Column[] MapColumns(Column[] cols) if (entry.MaxLen > 0 && column.FullValue.Length > entry.MaxLen) { - column.FullValue = column.FullValue.Substring(column.FullValue.Length - entry.MaxLen); + column.FullValue = column.FullValue[^entry.MaxLen..]; } } index++; diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs index 186a7cfd..3d070108 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace Log4jXmlColumnizer; @@ -6,16 +6,9 @@ namespace Log4jXmlColumnizer; [Serializable] public class Log4jXmlColumnizerConfig { - #region Fields - - public List columnList = []; - public bool localTimestamps = true; - - #endregion - #region cTor - public Log4jXmlColumnizerConfig(string[] columnNames) + public Log4jXmlColumnizerConfig (string[] columnNames) { FillDefaults(columnNames); } @@ -33,13 +26,14 @@ public int ActiveColumnCount get { var count = 0; - foreach (Log4jColumnEntry entry in columnList) + foreach (Log4jColumnEntry entry in ColumnList) { if (entry.Visible) { count++; } } + return count; } } @@ -53,27 +47,32 @@ public string[] ActiveColumnNames { var names = new string[ActiveColumnCount]; var index = 0; - foreach (Log4jColumnEntry entry in columnList) + foreach (Log4jColumnEntry entry in ColumnList) { if (entry.Visible) { names[index++] = entry.ColumnName; } } + return names; } } + public List ColumnList { get; set; } = []; + + public bool LocalTimestamps { get; set; } = true; + #endregion #region Public methods - public void FillDefaults(string[] columnNames) + public void FillDefaults (string[] columnNames) { - columnList.Clear(); + ColumnList.Clear(); for (var i = 0; i < columnNames.Length; ++i) { - columnList.Add(new Log4jColumnEntry(columnNames[i], i, 0)); + ColumnList.Add(new Log4jColumnEntry(columnNames[i], i, 0)); } } diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs index a07ff9b3..00fc2a71 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs @@ -25,7 +25,7 @@ public Log4jXmlColumnizerConfigDlg(Log4jXmlColumnizerConfig config) _config = config; InitializeComponent(); FillListBox(); - localTimeCheckBox.Checked = _config.localTimestamps; + localTimeCheckBox.Checked = _config.LocalTimestamps; ResumeLayout(); } @@ -39,7 +39,7 @@ private void FillListBox() var nameColumn = (DataGridViewTextBoxColumn)columnGridView.Columns[1]; var lenColumn = (DataGridViewTextBoxColumn)columnGridView.Columns[2]; - foreach (Log4jColumnEntry entry in _config.columnList) + foreach (Log4jColumnEntry entry in _config.ColumnList) { DataGridViewRow row = new(); row.Cells.Add(new DataGridViewCheckBoxCell()); @@ -64,19 +64,19 @@ private void OkButton_Click(object sender, EventArgs e) // } for (var i = 0; i < columnGridView.Rows.Count; ++i) { - _config.columnList[i].Visible = (bool)columnGridView.Rows[i].Cells[0].Value; + _config.ColumnList[i].Visible = (bool)columnGridView.Rows[i].Cells[0].Value; var sLen = (string)columnGridView.Rows[i].Cells[2].Value; if (int.TryParse(sLen, out var len)) { - _config.columnList[i].MaxLen = len; + _config.ColumnList[i].MaxLen = len; } else { - _config.columnList[i].MaxLen = 0; + _config.ColumnList[i].MaxLen = 0; } } - _config.localTimestamps = localTimeCheckBox.Checked; + _config.LocalTimestamps = localTimeCheckBox.Checked; } #endregion diff --git a/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs index d5cf9614..433eda96 100644 --- a/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs +++ b/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs @@ -1,26 +1,25 @@ -using System; using System.Globalization; -using System.Linq; using System.Text.RegularExpressions; namespace LogExpert.Core.Classes.Columnizer; public class ClfColumnizer : ILogLineColumnizer { + private const string DateTimeFormat = "dd/MMM/yyyy:HH:mm:ss zzz"; #region Fields - private readonly Regex lineRegex = new("(.*) (-) (.*) (\\[.*\\]) (\".*\") (.*) (.*) (\".*\") (\".*\")"); + private readonly Regex _lineRegex = new("(.*) (-) (.*) (\\[.*\\]) (\".*\") (.*) (.*) (\".*\") (\".*\")"); - protected CultureInfo cultureInfo = new("de-DE"); - protected int timeOffset; + private readonly CultureInfo _cultureInfo = new("en-US"); + private int _timeOffset; #endregion #region cTor - // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" + // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" - public ClfColumnizer() + public ClfColumnizer () { } @@ -28,22 +27,22 @@ public ClfColumnizer() #region Public methods - public bool IsTimeshiftImplemented() + public bool IsTimeshiftImplemented () { return true; } - public void SetTimeOffset(int msecOffset) + public void SetTimeOffset (int msecOffset) { - timeOffset = msecOffset; + _timeOffset = msecOffset; } - public int GetTimeOffset() + public int GetTimeOffset () { - return timeOffset; + return _timeOffset; } - public DateTime GetTimestamp(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { IColumnizedLogLine cols = SplitLine(callback, line); if (cols == null || cols.ColumnValues.Length < 8) @@ -58,8 +57,7 @@ public DateTime GetTimestamp(LogExpert.ILogLineColumnizerCallback callback, ILog try { - var dateTime = DateTime.ParseExact(cols.ColumnValues[2].FullValue, "dd/MMM/yyyy:HH:mm:ss zzz", - new CultureInfo("en-US")); + var dateTime = DateTime.ParseExact(cols.ColumnValues[2].FullValue, DateTimeFormat, _cultureInfo); return dateTime; } catch (Exception) @@ -68,19 +66,19 @@ public DateTime GetTimestamp(LogExpert.ILogLineColumnizerCallback callback, ILog } } - public void PushValue(LogExpert.ILogLineColumnizerCallback callback, int column, string value, string oldValue) + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) { if (column == 2) { try { var newDateTime = - DateTime.ParseExact(value, "dd/MMM/yyyy:HH:mm:ss zzz", new CultureInfo("en-US")); + DateTime.ParseExact(value, DateTimeFormat, _cultureInfo); var oldDateTime = - DateTime.ParseExact(oldValue, "dd/MMM/yyyy:HH:mm:ss zzz", new CultureInfo("en-US")); + DateTime.ParseExact(oldValue, DateTimeFormat, _cultureInfo); var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - timeOffset = (int)(mSecsNew - mSecsOld); + _timeOffset = (int)(mSecsNew - mSecsOld); } catch (FormatException) { @@ -88,27 +86,27 @@ public void PushValue(LogExpert.ILogLineColumnizerCallback callback, int column, } } - public string GetName() + public string GetName () { return "Webserver CLF Columnizer"; } - public string GetDescription() + public string GetDescription () { return "Common Logfile Format used by webservers."; } - public int GetColumnCount() + public int GetColumnCount () { return 8; } - public string[] GetColumnNames() + public string[] GetColumnNames () { return ["IP", "User", "Date/Time", "Request", "Status", "Bytes", "Referrer", "User agent"]; } - public IColumnizedLogLine SplitLine(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) { ColumnizedLogLine cLogLine = new() { @@ -132,17 +130,17 @@ public IColumnizedLogLine SplitLine(LogExpert.ILogLineColumnizerCallback callbac var temp = line.FullLine; if (temp.Length > 1024) { - // spam - temp = temp.Substring(0, 1024); + // spam + temp = temp[..1024]; columns[3].FullValue = temp; return cLogLine; } // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 - // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" + // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" - if (lineRegex.IsMatch(temp)) + if (_lineRegex.IsMatch(temp)) { - Match match = lineRegex.Match(temp); + Match match = _lineRegex.Match(temp); GroupCollection groups = match.Groups; if (groups.Count == 10) { @@ -159,15 +157,13 @@ public IColumnizedLogLine SplitLine(LogExpert.ILogLineColumnizerCallback callbac // dirty probing of date/time format (much faster than DateTime.ParseExact() if (dateTimeStr[2] == '/' && dateTimeStr[6] == '/' && dateTimeStr[11] == ':') { - if (timeOffset != 0) + if (_timeOffset != 0) { try { - var dateTime = DateTime.ParseExact(dateTimeStr, "dd/MMM/yyyy:HH:mm:ss zzz", - new CultureInfo("en-US")); - dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, timeOffset)); - var newDate = dateTime.ToString("dd/MMM/yyyy:HH:mm:ss zzz", - new CultureInfo("en-US")); + var dateTime = DateTime.ParseExact(dateTimeStr, DateTimeFormat, _cultureInfo); + dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, _timeOffset)); + var newDate = dateTime.ToString(DateTimeFormat, _cultureInfo); columns[2].FullValue = newDate; } catch (Exception) diff --git a/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs b/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs index 33cf2ac8..227fe06e 100644 --- a/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs +++ b/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs @@ -1,16 +1,16 @@ -using LogExpert.Core.Entities; - using System.Reflection; +using LogExpert.Core.Entities; + namespace LogExpert.Core.Classes.Columnizer; public class ColumnizerPicker { - public static ILogLineColumnizer FindColumnizerByName(string name, IList list) + public static ILogLineColumnizer FindColumnizerByName (string name, IList list) { foreach (ILogLineColumnizer columnizer in list) { - if (columnizer.GetName().Equals(name)) + if (columnizer.GetName().Equals(name, StringComparison.Ordinal)) { return columnizer; } @@ -18,11 +18,11 @@ public static ILogLineColumnizer FindColumnizerByName(string name, IList list) + public static ILogLineColumnizer DecideColumnizerByName (string name, IList list) { foreach (ILogLineColumnizer columnizer in list) { - if (columnizer.GetName().Equals(name)) + if (columnizer.GetName().Equals(name, StringComparison.Ordinal)) { return columnizer; } @@ -31,7 +31,7 @@ public static ILogLineColumnizer DecideColumnizerByName(string name, IList /// /// - public static ILogLineColumnizer FindReplacementForAutoColumnizer(string fileName, + public static ILogLineColumnizer FindReplacementForAutoColumnizer (string fileName, IAutoLogLineColumnizerCallback logFileReader, ILogLineColumnizer logLineColumnizer, IList list) @@ -72,7 +72,7 @@ public static ILogLineColumnizer FindReplacementForAutoColumnizer(string fileNam return logLineColumnizer; } - public static ILogLineColumnizer FindBetterColumnizer(string fileName, + public static ILogLineColumnizer FindBetterColumnizer (string fileName, IAutoLogLineColumnizerCallback logFileReader, ILogLineColumnizer logLineColumnizer, IList list) @@ -93,7 +93,7 @@ public static ILogLineColumnizer FindBetterColumnizer(string fileName, /// /// /// - public static ILogLineColumnizer FindColumnizer(string fileName, IAutoLogLineColumnizerCallback logFileReader, IList list) + public static ILogLineColumnizer FindColumnizer (string fileName, IAutoLogLineColumnizerCallback logFileReader, IList list) { if (string.IsNullOrEmpty(fileName)) { diff --git a/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs index 769cf4c4..36c733ca 100644 --- a/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs +++ b/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs @@ -8,8 +8,8 @@ public class SquareBracketColumnizer : ILogLineColumnizer, IColumnizerPriority { #region ILogLineColumnizer implementation - protected int timeOffset; - private TimeFormatDeterminer _timeFormatDeterminer = new(); + private int _timeOffset; + private readonly TimeFormatDeterminer _timeFormatDeterminer = new(); // TODO: need preparing this columnizer with sample log lines before use it. private int _columnCount = 5; @@ -38,15 +38,15 @@ public bool IsTimeshiftImplemented () public void SetTimeOffset (int msecOffset) { - timeOffset = msecOffset; + _timeOffset = msecOffset; } public int GetTimeOffset () { - return timeOffset; + return _timeOffset; } - public DateTime GetTimestamp (LogExpert.ILogLineColumnizerCallback callback, ILogLine line) + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { IColumnizedLogLine cols = SplitLine(callback, line); if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) @@ -78,7 +78,7 @@ public DateTime GetTimestamp (LogExpert.ILogLineColumnizerCallback callback, ILo } } - public void PushValue (LogExpert.ILogLineColumnizerCallback callback, int column, string value, string oldValue) + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) { if (column == 1) { @@ -94,7 +94,7 @@ public void PushValue (LogExpert.ILogLineColumnizerCallback callback, int column var oldDateTime = DateTime.ParseExact(oldValue, formatInfo.TimeFormat, formatInfo.CultureInfo); var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - timeOffset = (int)(mSecsNew - mSecsOld); + _timeOffset = (int)(mSecsNew - mSecsOld); } catch (FormatException) { @@ -187,11 +187,11 @@ public IColumnizedLogLine SplitLine (LogExpert.ILogLineColumnizerCallback callba var dateLen = formatInfo.DateFormat.Length; try { - if (timeOffset != 0) + if (_timeOffset != 0) { - var dateTime = DateTime.ParseExact(temp.Substring(0, endPos), formatInfo.DateTimeFormat, + var dateTime = DateTime.ParseExact(temp[..endPos], formatInfo.DateTimeFormat, formatInfo.CultureInfo); - dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, timeOffset)); + dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, _timeOffset)); var newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); SquareSplit(ref columns, newDate, dateLen, timeLen, endPos, clogLine); @@ -220,7 +220,7 @@ void SquareSplit (ref Column[] columns, string line, int dateLen, int timeLen, i var restColumn = _columnCount; if (_isTimeExists) { - columnList.Add(new Column { FullValue = line.Substring(0, dateLen), Parent = clogLine }); + columnList.Add(new Column { FullValue = line[..dateLen], Parent = clogLine }); columnList.Add(new Column { FullValue = line.Substring(dateLen + 1, timeLen), Parent = clogLine }); restColumn -= 2; } @@ -231,17 +231,17 @@ void SquareSplit (ref Column[] columns, string line, int dateLen, int timeLen, i for (var i = 0; i < restColumn; i++) { - rest = rest.Substring(nextPos); + rest = rest[nextPos..]; //var fullValue = rest.Substring(0, rest.IndexOf(']')).TrimStart(new char[] {' '}).TrimEnd(new char[] { ' ' }); var trimmed = rest.TrimStart([' ']); - if (string.IsNullOrEmpty(trimmed) || trimmed[0] != '[' || rest.IndexOf(']') < 0 || i == restColumn - 1) + if (string.IsNullOrEmpty(trimmed) || trimmed[0] != '[' || rest.IndexOf(']', StringComparison.Ordinal) < 0 || i == restColumn - 1) { columnList.Add(new Column { FullValue = rest, Parent = clogLine }); break; } - nextPos = rest.IndexOf(']') + 1; - var fullValue = rest.Substring(0, nextPos); + nextPos = rest.IndexOf(']', StringComparison.Ordinal) + 1; + var fullValue = rest[..nextPos]; columnList.Add(new Column { FullValue = fullValue, Parent = clogLine }); } @@ -261,7 +261,7 @@ public Priority GetPriority (string fileName, IEnumerable samples) var bracketsExistsCount = 0; var maxBracketNumbers = 1; - foreach (var logline in samples) + foreach (ILogLine logline in samples) { var line = logline?.FullLine; if (string.IsNullOrEmpty(line)) @@ -279,9 +279,9 @@ public Priority GetPriority (string fileName, IEnumerable samples) timeStampExistsCount--; } - var noSpaceLine = line.Replace(" ", string.Empty); - if (noSpaceLine.IndexOf('[') >= 0 && noSpaceLine.IndexOf(']') >= 0 - && noSpaceLine.IndexOf('[') < noSpaceLine.IndexOf(']')) + var noSpaceLine = line.Replace(" ", string.Empty, StringComparison.Ordinal); + if (noSpaceLine.Contains('[', StringComparison.Ordinal) && noSpaceLine.Contains(']', StringComparison.Ordinal) + && noSpaceLine.IndexOf('[', StringComparison.Ordinal) < noSpaceLine.IndexOf(']', StringComparison.Ordinal)) { bracketNumbers += Regex.Matches(noSpaceLine, @"\]\[").Count; bracketsExistsCount++; diff --git a/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs b/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs index cf438dc1..a0a21f38 100644 --- a/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs +++ b/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; namespace LogExpert.Core.Classes.Columnizer; @@ -6,26 +6,16 @@ internal class TimeFormatDeterminer { #region FormatInfo helper class - public class FormatInfo + public class FormatInfo (string dateFormat, string timeFormat, CultureInfo cultureInfo) { - #region cTor - - public FormatInfo(string dateFormat, string timeFormat, CultureInfo cultureInfo) - { - DateFormat = dateFormat; - TimeFormat = timeFormat; - CultureInfo = cultureInfo; - } - - #endregion #region Properties - public string DateFormat { get; } + public string DateFormat { get; } = dateFormat; - public string TimeFormat { get; } + public string TimeFormat { get; } = timeFormat; - public CultureInfo CultureInfo { get; } + public CultureInfo CultureInfo { get; } = cultureInfo; public string DateTimeFormat => DateFormat + " " + TimeFormat; @@ -36,30 +26,30 @@ public FormatInfo(string dateFormat, string timeFormat, CultureInfo cultureInfo) #endregion - protected FormatInfo formatInfo1 = new("dd.MM.yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo2 = new("dd.MM.yyyy", "HH:mm:ss", new CultureInfo("de-DE")); - protected FormatInfo formatInfo3 = new("yyyy/MM/dd", "HH:mm:ss.fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo4 = new("yyyy/MM/dd", "HH:mm:ss", new CultureInfo("en-US")); - protected FormatInfo formatInfo5 = new("yyyy.MM.dd", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo6 = new("yyyy.MM.dd", "HH:mm:ss", new CultureInfo("de-DE")); - protected FormatInfo formatInfo7 = new("dd.MM.yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo8 = new("yyyy/MM/dd", "HH:mm:ss,fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo9 = new("yyyy.MM.dd", "HH:mm:ss,fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo10 = new("yyyy-MM-dd", "HH:mm:ss.fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo11 = new("yyyy-MM-dd", "HH:mm:ss,fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo12 = new("yyyy-MM-dd", "HH:mm:ss", new CultureInfo("en-US")); - protected FormatInfo formatInfo13 = new("dd MMM yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo14 = new("dd MMM yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo15 = new("dd MMM yyyy", "HH:mm:ss", new CultureInfo("de-DE")); - protected FormatInfo formatInfo16 = new("dd.MM.yy", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo17 = new("yyyy-MM-dd", "HH:mm:ss:ffff", new CultureInfo("en-US")); - protected FormatInfo formatInfo18 = new("dd/MM/yyyy", "HH:mm:ss.fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo19 = new("dd/MM/yyyy", "HH:mm:ss:fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo20 = new("yyyy-MM-dd", "HH:mm:ss.ffff", new CultureInfo("en-US")); - protected FormatInfo formatInfo21 = new("yyyy-MM-dd", "HH:mm:ss,ffff", new CultureInfo("en-US")); - - - public FormatInfo DetermineDateTimeFormatInfo(string line) + private readonly FormatInfo formatInfo1 = new("dd.MM.yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo2 = new("dd.MM.yyyy", "HH:mm:ss", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo3 = new("yyyy/MM/dd", "HH:mm:ss.fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo4 = new("yyyy/MM/dd", "HH:mm:ss", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo5 = new("yyyy.MM.dd", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo6 = new("yyyy.MM.dd", "HH:mm:ss", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo7 = new("dd.MM.yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo8 = new("yyyy/MM/dd", "HH:mm:ss,fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo9 = new("yyyy.MM.dd", "HH:mm:ss,fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo10 = new("yyyy-MM-dd", "HH:mm:ss.fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo11 = new("yyyy-MM-dd", "HH:mm:ss,fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo12 = new("yyyy-MM-dd", "HH:mm:ss", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo13 = new("dd MMM yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo14 = new("dd MMM yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo15 = new("dd MMM yyyy", "HH:mm:ss", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo16 = new("dd.MM.yy", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo17 = new("yyyy-MM-dd", "HH:mm:ss:ffff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo18 = new("dd/MM/yyyy", "HH:mm:ss.fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo19 = new("dd/MM/yyyy", "HH:mm:ss:fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo20 = new("yyyy-MM-dd", "HH:mm:ss.ffff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo21 = new("yyyy-MM-dd", "HH:mm:ss,ffff", new CultureInfo("en-US")); + + + public FormatInfo DetermineDateTimeFormatInfo (string line) { if (line.Length < 21) { @@ -70,9 +60,9 @@ public FormatInfo DetermineDateTimeFormatInfo(string line) var ignoreFirst = false; // determine if string starts with bracket and remove it - if (temp[0] == '[' || temp[0] == '(' || temp[0] == '{') + if (temp[0] is '[' or '(' or '{') { - temp = temp.Substring(1); + temp = temp[1..]; ignoreFirst = true; } @@ -212,7 +202,7 @@ public FormatInfo DetermineDateTimeFormatInfo(string line) return null; } - public FormatInfo DetermineTimeFormatInfo(string field) + public FormatInfo DetermineTimeFormatInfo (string field) { // dirty hardcoded probing of time format (much faster than DateTime.ParseExact() if (field[2] == ':' && field[5] == ':') @@ -233,6 +223,7 @@ public FormatInfo DetermineTimeFormatInfo(string field) return formatInfo2; } } + return null; } } \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Filter/FilterParams.cs b/src/LogExpert.Core/Classes/Filter/FilterParams.cs index 57ff7ec2..4daf42c5 100644 --- a/src/LogExpert.Core/Classes/Filter/FilterParams.cs +++ b/src/LogExpert.Core/Classes/Filter/FilterParams.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Drawing; using System.Text.Json.Serialization; using System.Text.RegularExpressions; @@ -111,7 +111,7 @@ public string RangeSearchText /// Returns a new FilterParams object with the current columnizer set to the one used in this object. /// /// - public FilterParams CloneWithCurrentColumnizer() + public FilterParams CloneWithCurrentColumnizer () { FilterParams newParams = Clone(); newParams.Init(); @@ -122,22 +122,22 @@ public FilterParams CloneWithCurrentColumnizer() } // call after deserialization! - public void Init() + public void Init () { LastNonEmptyCols = []; - LowerRangeSearchText = RangeSearchText.ToLower(); - LowerSearchText = SearchText.ToLower(); + LowerRangeSearchText = RangeSearchText.ToLowerInvariant(); + LowerSearchText = SearchText.ToLowerInvariant(); LastLine = string.Empty; } // Reset before a new search - public void Reset() + public void Reset () { LastNonEmptyCols.Clear(); IsInRange = false; } - public void CreateRegex() + public void CreateRegex () { if (SearchText != null) { @@ -153,7 +153,7 @@ public void CreateRegex() /// Shallow Copy /// /// - public FilterParams Clone() + public FilterParams Clone () { return (FilterParams)MemberwiseClone(); } @@ -162,7 +162,7 @@ public FilterParams Clone() /// Shallow Copy /// /// - object ICloneable.Clone() + object ICloneable.Clone () { return Clone(); } diff --git a/src/LogExpert.Core/Classes/Filter/FilterPipe.cs b/src/LogExpert.Core/Classes/Filter/FilterPipe.cs index e99ce716..1b847c4b 100644 --- a/src/LogExpert.Core/Classes/Filter/FilterPipe.cs +++ b/src/LogExpert.Core/Classes/Filter/FilterPipe.cs @@ -1,42 +1,40 @@ -using LogExpert.Core.Classes.Filter; +using System.Text; + using LogExpert.Core.Interface; -using NLog; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; +using NLog; -namespace LogExpert.Classes.Filter; +namespace LogExpert.Core.Classes.Filter; public class FilterPipe { #region Fields - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); - private IList _lineMappingList = new List(); + private IList _lineMappingList = []; private StreamWriter _writer; + private readonly object _fileNameLock = new(); #endregion #region cTor - public FilterPipe(FilterParams filterParams, ILogWindow logWindow) + public FilterPipe (FilterParams filterParams, ILogWindow logWindow) { FilterParams = filterParams; LogWindow = logWindow; IsStopped = false; FileName = Path.GetTempFileName(); - _logger.Info("Created temp file: {0}", FileName); + _logger.Info($"Created temp file: {FileName}"); } #endregion #region Delegates - public delegate void ClosedEventHandler(object sender, EventArgs e); + public delegate void ClosedEventHandler (object sender, EventArgs e); #endregion @@ -54,7 +52,7 @@ public FilterPipe(FilterParams filterParams, ILogWindow logWindow) public FilterParams FilterParams { get; } - public IList LastLinesHistoryList { get; } = new List(); + public IList LastLinesHistoryList { get; } = []; public ILogWindow LogWindow { get; } @@ -64,13 +62,13 @@ public FilterPipe(FilterParams filterParams, ILogWindow logWindow) #region Public methods - public void OpenFile() + public void OpenFile () { FileStream fStream = new(FileName, FileMode.Append, FileAccess.Write, FileShare.Read); _writer = new StreamWriter(fStream, new UnicodeEncoding(false, false)); } - public void CloseFile() + public void CloseFile () { if (_writer != null) { @@ -79,11 +77,11 @@ public void CloseFile() } } - public bool WriteToPipe(ILogLine textLine, int orgLineNum) + public bool WriteToPipe (ILogLine textLine, int orgLineNum) { try { - lock (FileName) + lock (_fileNameLock) { lock (_lineMappingList) { @@ -108,22 +106,19 @@ public bool WriteToPipe(ILogLine textLine, int orgLineNum) } } - public int GetOriginalLineNum(int lineNum) + public int GetOriginalLineNum (int lineNum) { lock (_lineMappingList) { - if (_lineMappingList.Count > lineNum) - { - return _lineMappingList[lineNum]; - } - - return -1; + return _lineMappingList.Count > lineNum + ? _lineMappingList[lineNum] + : -1; } } - public void ShiftLineNums(int offset) + public void ShiftLineNums (int offset) { - _logger.Debug("FilterPipe.ShiftLineNums() offset={0}", offset); + _logger.Debug($"FilterPipe.ShiftLineNums() offset={offset}"); List newList = []; lock (_lineMappingList) { @@ -139,11 +134,12 @@ public void ShiftLineNums(int offset) newList.Add(-1); } } + _lineMappingList = newList; } } - public void ClearLineNums() + public void ClearLineNums () { _logger.Debug("FilterPipe.ClearLineNums()"); lock (_lineMappingList) @@ -155,7 +151,7 @@ public void ClearLineNums() } } - public void ClearLineList() + public void ClearLineList () { lock (_lineMappingList) { @@ -163,13 +159,14 @@ public void ClearLineList() } } - public void RecreateTempFile() + public void RecreateTempFile () { lock (_lineMappingList) { - _lineMappingList = new List(); + _lineMappingList = []; } - lock (FileName) + + lock (_fileNameLock) { CloseFile(); // trunc file @@ -179,7 +176,7 @@ public void RecreateTempFile() } } - public void CloseAndDisconnect() + public void CloseAndDisconnect () { ClearLineList(); OnClosed(); @@ -189,7 +186,7 @@ public void CloseAndDisconnect() #region Private Methods - private void OnClosed() + private void OnClosed () { Closed?.Invoke(this, EventArgs.Empty); } diff --git a/src/LogExpert.Core/Classes/Filter/FilterStarter.cs b/src/LogExpert.Core/Classes/Filter/FilterStarter.cs index 7a2ba26a..efa6a886 100644 --- a/src/LogExpert.Core/Classes/Filter/FilterStarter.cs +++ b/src/LogExpert.Core/Classes/Filter/FilterStarter.cs @@ -160,7 +160,7 @@ private Filter DoWork (FilterParams filterParams, int startLine, int maxCount, P } _ = filter.DoFilter(threadFilterParams, startLine, maxCount, progressCallback); - _logger.Info("Filter worker [{0}] for line {1} has completed.", Thread.CurrentThread.ManagedThreadId, startLine); + _logger.Info("Filter worker [{0}] for line {1} has completed.", Environment.CurrentManagedThreadId, startLine); lock (_filterReadyList) { diff --git a/src/LogExpert.Core/Classes/Log/LogfileReader.cs b/src/LogExpert.Core/Classes/Log/LogfileReader.cs index 87be8741..279b9668 100644 --- a/src/LogExpert.Core/Classes/Log/LogfileReader.cs +++ b/src/LogExpert.Core/Classes/Log/LogfileReader.cs @@ -19,8 +19,8 @@ public class LogfileReader : IAutoLogLineColumnizerCallback private readonly GetLogLineFx _logLineFx; private readonly string _fileName; - private readonly int _MAX_BUFFERS = 10; - private readonly int _MAX_LINES_PER_BUFFER = 100; + private readonly int _max_buffers; + private readonly int _maxLinesPerBuffer; private readonly object _monitor = new(); private readonly MultiFileOptions _multiFileOptions; @@ -64,8 +64,8 @@ public LogfileReader (string fileName, EncodingOptions encodingOptions, bool mul _fileName = fileName; EncodingOptions = encodingOptions; IsMultiFile = multiFile; - _MAX_BUFFERS = bufferCount; - _MAX_LINES_PER_BUFFER = linesPerBuffer; + _max_buffers = bufferCount; + _maxLinesPerBuffer = linesPerBuffer; _multiFileOptions = multiFileOptions; _pluginRegistry = pluginRegistry; _logLineFx = GetLogLineInternal; @@ -102,8 +102,8 @@ public LogfileReader (string[] fileNames, EncodingOptions encodingOptions, int b EncodingOptions = encodingOptions; IsMultiFile = true; - _MAX_BUFFERS = bufferCount; - _MAX_LINES_PER_BUFFER = linesPerBuffer; + _max_buffers = bufferCount; + _maxLinesPerBuffer = linesPerBuffer; _multiFileOptions = multiFileOptions; _pluginRegistry = pluginRegistry; _logLineFx = GetLogLineInternal; @@ -799,9 +799,9 @@ private Task GetLogLineInternal (int lineNum) private void InitLruBuffers () { _bufferList = []; - _bufferLru = new List(_MAX_BUFFERS + 1); + _bufferLru = new List(_max_buffers + 1); //this.lruDict = new Dictionary(this.MAX_BUFFERS + 1); // key=startline, value = index in bufferLru - _lruCacheDict = new Dictionary(_MAX_BUFFERS + 1); + _lruCacheDict = new Dictionary(_max_buffers + 1); _lruCacheDictLock = new ReaderWriterLock(); _bufferListLock = new ReaderWriterLock(); _disposeLock = new ReaderWriterLock(); @@ -853,7 +853,7 @@ private void ReplaceBufferInfos (ILogFileInfo oldLogFileInfo, ILogFileInfo newLo { if (buffer.FileInfo == oldLogFileInfo) { - _logger.Debug("Buffer with startLine={0}, lineCount={1}, filePos={2}, size={3} gets new filename {4}", buffer.StartLine, buffer.LineCount, buffer.StartPos, buffer.Size, newLogFileInfo.FullName); + _logger.Debug($"Buffer with startLine={buffer.StartLine}, lineCount={buffer.LineCount}, filePos={buffer.StartPos}, size={buffer.Size} gets new filename {newLogFileInfo.FullName}"); buffer.FileInfo = newLogFileInfo; } } @@ -863,7 +863,7 @@ private void ReplaceBufferInfos (ILogFileInfo oldLogFileInfo, ILogFileInfo newLo private LogBuffer DeleteBuffersForInfo (ILogFileInfo ILogFileInfo, bool matchNamesOnly) { - _logger.Info("Deleting buffers for file {0}", ILogFileInfo.FullName); + _logger.Info($"Deleting buffers for file {ILogFileInfo.FullName}"); LogBuffer lastRemovedBuffer = null; IList deleteList = []; AcquireBufferListWriterLock(); @@ -872,7 +872,7 @@ private LogBuffer DeleteBuffersForInfo (ILogFileInfo ILogFileInfo, bool matchNam { foreach (LogBuffer buffer in _bufferList) { - if (buffer.FileInfo.FullName.ToLower().Equals(ILogFileInfo.FullName.ToLower())) + if (buffer.FileInfo.FullName.Equals(ILogFileInfo.FullName, StringComparison.Ordinal)) { lastRemovedBuffer = buffer; deleteList.Add(buffer); @@ -938,9 +938,11 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start AcquireBufferListReaderLock(); if (_bufferList.Count == 0) { - logBuffer = new LogBuffer(logFileInfo, _MAX_LINES_PER_BUFFER); - logBuffer.StartLine = startLine; - logBuffer.StartPos = filePos; + logBuffer = new LogBuffer(logFileInfo, _maxLinesPerBuffer) + { + StartLine = startLine, + StartPos = filePos + }; LockCookie cookie = UpgradeBufferListLockToWriter(); AddBufferToList(logBuffer); DowngradeBufferListLockFromWriter(ref cookie); @@ -949,11 +951,13 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start { logBuffer = _bufferList[_bufferList.Count - 1]; - if (!logBuffer.FileInfo.FullName.Equals(logFileInfo.FullName)) + if (!logBuffer.FileInfo.FullName.Equals(logFileInfo.FullName, StringComparison.Ordinal)) { - logBuffer = new LogBuffer(logFileInfo, _MAX_LINES_PER_BUFFER); - logBuffer.StartLine = startLine; - logBuffer.StartPos = filePos; + logBuffer = new LogBuffer(logFileInfo, _maxLinesPerBuffer) + { + StartLine = startLine, + StartPos = filePos + }; LockCookie cookie = UpgradeBufferListLockToWriter(); AddBufferToList(logBuffer); DowngradeBufferListLockFromWriter(ref cookie); @@ -993,12 +997,12 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start } lineCount++; - if (lineCount > _MAX_LINES_PER_BUFFER && reader.IsBufferComplete) + if (lineCount > _maxLinesPerBuffer && reader.IsBufferComplete) { OnLoadFile(new LoadFileEventArgs(logFileInfo.FullName, filePos, false, logFileInfo.Length, false)); Monitor.Exit(logBuffer); - logBuffer = new LogBuffer(logFileInfo, _MAX_LINES_PER_BUFFER); + logBuffer = new LogBuffer(logFileInfo, _maxLinesPerBuffer); Monitor.Enter(logBuffer); logBuffer.StartLine = lineNum; logBuffer.StartPos = filePos; @@ -1132,9 +1136,9 @@ private void GarbageCollectLruCache () var threshold = 10; _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); var diff = 0; - if (_lruCacheDict.Count - (_MAX_BUFFERS + threshold) > 0) + if (_lruCacheDict.Count - (_max_buffers + threshold) > 0) { - diff = _lruCacheDict.Count - _MAX_BUFFERS; + diff = _lruCacheDict.Count - _max_buffers; #if DEBUG if (diff > 0) { diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs index dd142b44..0cd74d6d 100644 --- a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs @@ -1,7 +1,7 @@ -using LogExpert.Core.Entities; - using System.Text; +using LogExpert.Core.Entities; + namespace LogExpert.Core.Classes.Log; public abstract class PositionAwareStreamReaderBase : LogStreamReaderBase @@ -24,7 +24,7 @@ public abstract class PositionAwareStreamReaderBase : LogStreamReaderBase #region cTor - protected PositionAwareStreamReaderBase(Stream stream, EncodingOptions encodingOptions) + protected PositionAwareStreamReaderBase (Stream stream, EncodingOptions encodingOptions) { _stream = new BufferedStream(stream); @@ -82,7 +82,7 @@ public sealed override long Position /// Destroy and release the current stream reader. /// /// Specifies whether or not the managed objects should be released. - protected override void Dispose(bool disposing) + protected override void Dispose (bool disposing) { if (disposing) { @@ -92,13 +92,9 @@ protected override void Dispose(bool disposing) } //TODO This is unsafe and should be refactored - public override unsafe int ReadChar() + public override unsafe int ReadChar () { - //ObjectDisposedException.ThrowIf - if (IsDisposed) - { - throw new ObjectDisposedException(ToString()); - } + ObjectDisposedException.ThrowIf(IsDisposed, GetType().ToString()); try { @@ -123,17 +119,18 @@ public override unsafe int ReadChar() } } - protected virtual void ResetReader() + protected virtual void ResetReader () { _reader.DiscardBufferedData(); } - protected StreamReader GetStreamReader() + protected StreamReader GetStreamReader () { - return IsDisposed ? throw new ObjectDisposedException(ToString()) : _reader; + ObjectDisposedException.ThrowIf(IsDisposed, GetType().ToString()); + return _reader; } - protected void MovePosition(int offset) + protected void MovePosition (int offset) { _position += offset; } @@ -146,7 +143,7 @@ protected void MovePosition(int offset) /// Determines the actual number of preamble bytes in the file. /// /// Number of preamble bytes in the file - private int DetectPreambleLengthAndEncoding(out Encoding detectedEncoding) + private int DetectPreambleLengthAndEncoding (out Encoding detectedEncoding) { /* UTF-8: EF BB BF @@ -189,7 +186,7 @@ private int DetectPreambleLengthAndEncoding(out Encoding detectedEncoding) return 0; } - private Encoding GetUsedEncoding(EncodingOptions encodingOptions, Encoding detectedEncoding) + private Encoding GetUsedEncoding (EncodingOptions encodingOptions, Encoding detectedEncoding) { if (encodingOptions.Encoding != null) { @@ -203,15 +200,15 @@ private Encoding GetUsedEncoding(EncodingOptions encodingOptions, Encoding detec return encodingOptions.DefaultEncoding ?? Encoding.Default; } - private int GetPosIncPrecomputed(Encoding usedEncoding) + private int GetPosIncPrecomputed (Encoding usedEncoding) { switch (usedEncoding) { - case UTF8Encoding _: + case UTF8Encoding: { return 0; } - case UnicodeEncoding _: + case UnicodeEncoding: { return 2; } diff --git a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs index e9327051..c6eab62c 100644 --- a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs +++ b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -47,7 +47,7 @@ public class RolloverFilenameBuilder #region cTor - public RolloverFilenameBuilder(string formatString) + public RolloverFilenameBuilder (string formatString) { ParseFormatString(formatString); } @@ -66,7 +66,7 @@ public RolloverFilenameBuilder(string formatString) #region Public methods - public void SetFileName(string fileName) + public void SetFileName (string fileName) { _currentFileName = fileName; Match match = _regex.Match(fileName); @@ -91,18 +91,18 @@ public void SetFileName(string fileName) } } - public void IncrementDate() + public void IncrementDate () { _dateTime = _dateTime.AddDays(1); } - public void DecrementDate() + public void DecrementDate () { _dateTime = _dateTime.AddDays(-1); } - public string BuildFileName() + public string BuildFileName () { var fileName = _currentFileName; if (_dateGroup != null && _dateGroup.Success) @@ -136,10 +136,10 @@ public string BuildFileName() #region Private Methods - private void ParseFormatString(string formatString) + private void ParseFormatString (string formatString) { var fmt = EscapeNonvarRegions(formatString); - var datePos = formatString.IndexOf("$D("); + var datePos = formatString.IndexOf("$D(", StringComparison.Ordinal); if (datePos != -1) { var endPos = formatString.IndexOf(')', datePos); @@ -151,9 +151,9 @@ private void ParseFormatString(string formatString) var dtf = _dateTimeFormat; dtf = dtf.ToUpper(); - dtf = dtf.Replace("D", "\\d"); - dtf = dtf.Replace("Y", "\\d"); - dtf = dtf.Replace("M", "\\d"); + dtf = dtf.Replace("D", "\\d", StringComparison.Ordinal); + dtf = dtf.Replace("Y", "\\d", StringComparison.Ordinal); + dtf = dtf.Replace("M", "\\d", StringComparison.Ordinal); fmt = fmt.Remove(datePos, 2); // remove $D fmt = fmt.Remove(datePos + 1, _dateTimeFormat.Length); // replace with regex version of format fmt = fmt.Insert(datePos + 1, dtf); @@ -161,7 +161,7 @@ private void ParseFormatString(string formatString) } } - var condPos = fmt.IndexOf("$J("); + var condPos = fmt.IndexOf("$J(", StringComparison.Ordinal); if (condPos != -1) { var endPos = fmt.IndexOf(')', condPos); @@ -172,20 +172,22 @@ private void ParseFormatString(string formatString) } } - fmt = fmt.Replace("*", ".*"); - _hideZeroIndex = fmt.Contains("$J"); - fmt = fmt.Replace("$I", "(?'index'[\\d]+)"); - fmt = fmt.Replace("$J", "(?'index'[\\d]*)"); + fmt = fmt.Replace("*", ".*", StringComparison.Ordinal); + _hideZeroIndex = fmt.Contains("$J", StringComparison.Ordinal); + fmt = fmt.Replace("$I", "(?'index'[\\d]+)", StringComparison.Ordinal); + fmt = fmt.Replace("$J", "(?'index'[\\d]*)", StringComparison.Ordinal); _regex = new Regex(fmt); } - private string EscapeNonvarRegions(string formatString) + private string EscapeNonvarRegions (string formatString) { var fmt = formatString.Replace('*', '\xFFFD'); - StringBuilder result = new(); var state = 0; + + StringBuilder result = new(); StringBuilder segment = new(); + for (var i = 0; i < fmt.Length; ++i) { switch (state) @@ -193,41 +195,45 @@ private string EscapeNonvarRegions(string formatString) case 0: // looking for $ if (fmt[i] == '$') { - result.Append(Regex.Escape(segment.ToString())); + _ = result.Append(Regex.Escape(segment.ToString())); segment = new StringBuilder(); state = 1; } - segment.Append(fmt[i]); + + _ = segment.Append(fmt[i]); break; case 1: // the char behind $ - segment.Append(fmt[i]); - result.Append(segment.ToString()); + _ = segment.Append(fmt[i]); + _ = result.Append(segment); segment = new StringBuilder(); state = 2; break; case 2: // checking if ( or other char if (fmt[i] == '(') { - segment.Append(fmt[i]); + _ = segment.Append(fmt[i]); state = 3; } else { - segment.Append(fmt[i]); + _ = segment.Append(fmt[i]); state = 0; } + break; case 3: // looking for ) - segment.Append(fmt[i]); + _ = segment.Append(fmt[i]); if (fmt[i] == ')') { - result.Append(segment.ToString()); + _ = result.Append(segment); segment = new StringBuilder(); state = 0; } + break; } } + fmt = result.ToString().Replace('\xFFFD', '*'); return fmt; } diff --git a/src/LogExpert.Core/Classes/ParamParser.cs b/src/LogExpert.Core/Classes/ParamParser.cs index 42fbee75..6ca9731f 100644 --- a/src/LogExpert.Core/Classes/ParamParser.cs +++ b/src/LogExpert.Core/Classes/ParamParser.cs @@ -1,41 +1,34 @@ -using System.Text; +using System.Text; using System.Text.RegularExpressions; namespace LogExpert.Core.Classes; -public class ParamParser +public class ParamParser (string argTemplate) { - #region Fields - - private readonly string argLine; - - #endregion - - #region cTor - - public ParamParser(string argTemplate) - { - argLine = argTemplate; - } - - #endregion - #region Public methods - public string ReplaceParams(ILogLine logLine, int lineNum, string fileName) + public string ReplaceParams (ILogLine logLine, int lineNum, string fileName) { FileInfo fileInfo = new(fileName); - StringBuilder builder = new(argLine); - builder.Replace("%L", "" + lineNum); - builder.Replace("%P", - fileInfo.DirectoryName.Contains(" ") ? "\"" + fileInfo.DirectoryName + "\"" : fileInfo.DirectoryName); - builder.Replace("%N", fileInfo.Name.Contains(" ") ? "\"" + fileInfo.Name + "\"" : fileInfo.Name); - builder.Replace("%F", - fileInfo.FullName.Contains(" ") ? "\"" + fileInfo.FullName + "\"" : fileInfo.FullName); - builder.Replace("%E", - fileInfo.Extension.Contains(" ") ? "\"" + fileInfo.Extension + "\"" : fileInfo.Extension); + StringBuilder builder = new(argTemplate); + _ = builder.Replace("%L", "" + lineNum); + _ = builder.Replace("%P", fileInfo.DirectoryName.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.DirectoryName + "\"" + : fileInfo.DirectoryName); + _ = builder.Replace("%N", fileInfo.Name.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.Name + "\"" + : fileInfo.Name); + _ = builder.Replace("%F", + fileInfo.FullName.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.FullName + "\"" + : fileInfo.FullName); + _ = builder.Replace("%E", fileInfo.Extension.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.Extension + "\"" + : fileInfo.Extension); var stripped = StripExtension(fileInfo.Name); - builder.Replace("%M", stripped.Contains(" ") ? "\"" + stripped + "\"" : stripped); + _ = builder.Replace("%M", stripped.Contains(' ', StringComparison.Ordinal) + ? "\"" + stripped + "\"" + : stripped); var sPos = 0; string reg; string replace; @@ -52,21 +45,23 @@ public string ReplaceParams(ILogLine logLine, int lineNum, string fileName) return builder.ToString(); } - public static string StripExtension(string fileName) + public static string StripExtension (string fileName) { var i = fileName.LastIndexOf('.'); + if (i < 0) { i = fileName.Length - 1; } - return fileName.Substring(0, i); + + return fileName[..i]; } #endregion #region Private Methods - private string GetNextGroup(StringBuilder builder, ref int sPos) + private string GetNextGroup (StringBuilder builder, ref int sPos) { int ePos; while (sPos < builder.Length) @@ -81,21 +76,26 @@ private string GetNextGroup(StringBuilder builder, ref int sPos) { count++; } + if (builder[ePos] == '}') { count--; } + if (count == 0) { var reg = builder.ToString(sPos + 1, ePos - sPos - 1); - builder.Remove(sPos, ePos - sPos + 1); + _ = builder.Remove(sPos, ePos - sPos + 1); return reg; } + ePos++; } } + sPos++; } + return null; } diff --git a/src/LogExpert.Core/Classes/PatternBlock.cs b/src/LogExpert.Core/Classes/PatternBlock.cs index 2fc6b6ba..41d23bc1 100644 --- a/src/LogExpert.Core/Classes/PatternBlock.cs +++ b/src/LogExpert.Core/Classes/PatternBlock.cs @@ -1,42 +1,31 @@ -using System.Collections.Generic; - namespace LogExpert.Core.Classes; -public class QualityInfo +public class PatternBlock { - #region Fields + public int BlockId { get; set; } - public int quality; + public int EndLine { get; set; } - #endregion -} + // key: line num + public Dictionary QualityInfoList { get; set; } = []; -public class PatternBlock -{ - #region Fields + public SortedDictionary SrcLines { get; set; } = []; - public int blockId; + public int StartLine { get; set; } - public int endLine; + public int TargetEnd { get; set; } - // key: line num - public Dictionary qualityInfoList = []; + public SortedDictionary TargetLines { get; set; } = []; - public SortedDictionary srcLines = []; - public int startLine; - public int targetEnd; - public SortedDictionary targetLines = []; - public int targetStart; - public int weigth; + public int TargetStart { get; set; } - #endregion + public int Weigth { get; set; } #region Public methods - public override string ToString() + public override string ToString () { - return "srcStart=" + startLine + ", srcEnd=" + endLine + ", targetStart=" + targetStart + - ", targetEnd=" + targetEnd + ", weight=" + weigth; + return $"srcStart={StartLine}, srcEnd={EndLine}, targetStart={TargetStart}, targetEnd={TargetEnd}, weight={Weigth}"; } #endregion diff --git a/src/LogExpert.Core/Classes/Persister/PersistenceData.cs b/src/LogExpert.Core/Classes/Persister/PersistenceData.cs index bd358a72..eefe1a34 100644 --- a/src/LogExpert.Core/Classes/Persister/PersistenceData.cs +++ b/src/LogExpert.Core/Classes/Persister/PersistenceData.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using LogExpert.Core.Classes.Filter; using LogExpert.Core.Entities; @@ -7,36 +7,55 @@ namespace LogExpert.Core.Classes.Persister; public class PersistenceData { - #region Fields - - public SortedList bookmarkList = []; - public int bookmarkListPosition = 300; - public bool bookmarkListVisible; - public string columnizerName; - public int currentLine = -1; - public Encoding encoding; - public string fileName; - public bool filterAdvanced; - public List filterParamsList = []; - public int filterPosition = 222; - public bool filterSaveListVisible; - public List filterTabDataList = []; - public bool filterVisible; - public int firstDisplayedLine = -1; - public bool followTail = true; - public string highlightGroupName; - public int lineCount; - - public bool multiFile; - public int multiFileMaxDays; - public List multiFileNames = []; - public string multiFilePattern; - public SortedList rowHeightList = []; - public string sessionFileName; - public bool showBookmarkCommentColumn; - public string tabName; - - public string settingsSaveLoadLocation; - - #endregion -} + public SortedList BookmarkList { get; set; } = []; + + public int BookmarkListPosition { get; set; } = 300; + + public bool BookmarkListVisible { get; set; } + + public string ColumnizerName { get; set; } + + public int CurrentLine { get; set; } = -1; + + public Encoding Encoding { get; set; } + + public string FileName { get; set; } + + public bool FilterAdvanced { get; set; } + + public List FilterParamsList { get; set; } = []; + + public int FilterPosition { get; set; } = 222; + + public bool FilterSaveListVisible { get; set; } + + public List FilterTabDataList { get; set; } = []; + + public int FirstDisplayedLine { get; set; } = -1; + + public bool FollowTail { get; set; } = true; + + public string HighlightGroupName { get; set; } + + public bool FilterVisible { get; set; } + + public int LineCount { get; set; } + + public bool MultiFile { get; set; } + + public int MultiFileMaxDays { get; set; } + + public List MultiFileNames { get; set; } = []; + + public string MultiFilePattern { get; set; } + + public SortedList RowHeightList { get; set; } = []; + + public string SessionFileName { get; set; } + + public bool ShowBookmarkCommentColumn { get; set; } + + public string TabName { get; set; } + + public string SettingsSaveLoadLocation { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/Persister.cs b/src/LogExpert.Core/Classes/Persister/Persister.cs index c1bf9ce4..8ae747b9 100644 --- a/src/LogExpert.Core/Classes/Persister/Persister.cs +++ b/src/LogExpert.Core/Classes/Persister/Persister.cs @@ -12,7 +12,7 @@ namespace LogExpert.Core.Classes.Persister; //TODO Rewrite as json Persister, xml is outdated and difficult to parse and write -public class Persister +public static class Persister { #region Fields @@ -24,13 +24,13 @@ public class Persister public static string SavePersistenceData (string logFileName, PersistenceData persistenceData, Preferences preferences) { - var fileName = persistenceData.sessionFileName ?? BuildPersisterFileName(logFileName, preferences); + var fileName = persistenceData.SessionFileName ?? BuildPersisterFileName(logFileName, preferences); - if (preferences.saveLocation == SessionSaveLocation.SameDir) + if (preferences.SaveLocation == SessionSaveLocation.SameDir) { // make to log file in .lxp file relative - var filePart = Path.GetFileName(persistenceData.fileName); - persistenceData.fileName = filePart; + var filePart = Path.GetFileName(persistenceData.FileName); + persistenceData.FileName = filePart; } Save(fileName, persistenceData); @@ -91,8 +91,8 @@ public static PersistenceData LoadOptionsOnly (string fileName) { var fileElement = fileNode as XmlElement; ReadOptions(fileElement, persistenceData); - persistenceData.fileName = fileElement.GetAttribute("fileName"); - persistenceData.encoding = ReadEncoding(fileElement); + persistenceData.FileName = fileElement.GetAttribute("fileName"); + persistenceData.Encoding = ReadEncoding(fileElement); } return persistenceData; } @@ -106,7 +106,7 @@ private static string BuildPersisterFileName (string logFileName, Preferences pr string dir; string file; - switch (preferences.saveLocation) + switch (preferences.SaveLocation) { case SessionSaveLocation.SameDir: default: @@ -126,7 +126,7 @@ private static string BuildPersisterFileName (string logFileName, Preferences pr } case SessionSaveLocation.OwnDir: { - dir = preferences.sessionSaveDirectory; + dir = preferences.SessionSaveDirectory; file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); break; } @@ -172,14 +172,14 @@ private static void Save (string fileName, PersistenceData persistenceData) xmlDoc.AppendChild(rootElement); XmlElement fileElement = xmlDoc.CreateElement("file"); rootElement.AppendChild(fileElement); - fileElement.SetAttribute("fileName", persistenceData.fileName); - fileElement.SetAttribute("lineCount", "" + persistenceData.lineCount); - WriteBookmarks(xmlDoc, fileElement, persistenceData.bookmarkList); - WriteRowHeightList(xmlDoc, fileElement, persistenceData.rowHeightList); + fileElement.SetAttribute("fileName", persistenceData.FileName); + fileElement.SetAttribute("lineCount", "" + persistenceData.LineCount); + WriteBookmarks(xmlDoc, fileElement, persistenceData.BookmarkList); + WriteRowHeightList(xmlDoc, fileElement, persistenceData.RowHeightList); WriteOptions(xmlDoc, fileElement, persistenceData); - WriteFilter(xmlDoc, fileElement, persistenceData.filterParamsList); - WriteFilterTabs(xmlDoc, fileElement, persistenceData.filterTabDataList); - WriteEncoding(xmlDoc, fileElement, persistenceData.encoding); + WriteFilter(xmlDoc, fileElement, persistenceData.FilterParamsList); + WriteFilterTabs(xmlDoc, fileElement, persistenceData.FilterTabDataList); + WriteEncoding(xmlDoc, fileElement, persistenceData.Encoding); if (xmlDoc.HasChildNodes) { xmlDoc.Save(fileName); @@ -207,11 +207,11 @@ private static void WriteFilterTabs (XmlDocument xmlDoc, XmlElement rootElement, PersistenceData persistenceData = data.PersistenceData; XmlElement filterTabElement = xmlDoc.CreateElement("filterTab"); filterTabsElement.AppendChild(filterTabElement); - WriteBookmarks(xmlDoc, filterTabElement, persistenceData.bookmarkList); - WriteRowHeightList(xmlDoc, filterTabElement, persistenceData.rowHeightList); + WriteBookmarks(xmlDoc, filterTabElement, persistenceData.BookmarkList); + WriteRowHeightList(xmlDoc, filterTabElement, persistenceData.RowHeightList); WriteOptions(xmlDoc, filterTabElement, persistenceData); - WriteFilter(xmlDoc, filterTabElement, persistenceData.filterParamsList); - WriteFilterTabs(xmlDoc, filterTabElement, persistenceData.filterTabDataList); + WriteFilter(xmlDoc, filterTabElement, persistenceData.FilterParamsList); + WriteFilterTabs(xmlDoc, filterTabElement, persistenceData.FilterTabDataList); XmlElement filterElement = xmlDoc.CreateElement("tabFilter"); filterTabElement.AppendChild(filterElement); List filterList = [data.FilterParams]; @@ -280,7 +280,7 @@ private static List ReadFilter (XmlElement startNode) { foreach (XmlNode subNode in node.ChildNodes) { - if (subNode.Name.Equals("params")) + if (subNode.Name.Equals("params", StringComparison.OrdinalIgnoreCase)) { var base64Text = subNode.InnerText; var data = Convert.FromBase64String(base64Text); @@ -344,18 +344,18 @@ private static PersistenceData ReadPersistenceDataFromNode (XmlNode node) { PersistenceData persistenceData = new(); var fileElement = node as XmlElement; - persistenceData.bookmarkList = ReadBookmarks(fileElement); - persistenceData.rowHeightList = ReadRowHeightList(fileElement); + persistenceData.BookmarkList = ReadBookmarks(fileElement); + persistenceData.RowHeightList = ReadRowHeightList(fileElement); ReadOptions(fileElement, persistenceData); - persistenceData.fileName = fileElement.GetAttribute("fileName"); + persistenceData.FileName = fileElement.GetAttribute("fileName"); var sLineCount = fileElement.GetAttribute("lineCount"); if (sLineCount != null && sLineCount.Length > 0) { - persistenceData.lineCount = int.Parse(sLineCount); + persistenceData.LineCount = int.Parse(sLineCount); } - persistenceData.filterParamsList = ReadFilter(fileElement); - persistenceData.filterTabDataList = ReadFilterTabs(fileElement); - persistenceData.encoding = ReadEncoding(fileElement); + persistenceData.FilterParamsList = ReadFilter(fileElement); + persistenceData.FilterTabDataList = ReadFilterTabs(fileElement); + persistenceData.Encoding = ReadEncoding(fileElement); return persistenceData; } @@ -401,29 +401,29 @@ private static Encoding ReadEncoding (XmlElement fileElement) foreach (XmlAttribute attr in node.Attributes) { - if (attr.Name.Equals("line")) + if (attr.Name.Equals("line", StringComparison.OrdinalIgnoreCase)) { line = attr.InnerText; } } foreach (XmlNode subNode in node.ChildNodes) { - if (subNode.Name.Equals("text")) + if (subNode.Name.Equals("text", StringComparison.OrdinalIgnoreCase)) { text = subNode.InnerText; } - else if (subNode.Name.Equals("posX")) + else if (subNode.Name.Equals("posX", StringComparison.OrdinalIgnoreCase)) { posX = subNode.InnerText; } - else if (subNode.Name.Equals("posY")) + else if (subNode.Name.Equals("posY", StringComparison.OrdinalIgnoreCase)) { posY = subNode.InnerText; } } if (line == null || posX == null || posY == null) { - _logger.Error("Invalid XML format for bookmark: {0}", node.InnerText); + _logger.Error($"Invalid XML format for bookmark: {node.InnerText}"); continue; } var lineNum = int.Parse(line); @@ -469,11 +469,11 @@ private static SortedList ReadRowHeightList (XmlElement sta string line = null; foreach (XmlAttribute attr in node.Attributes) { - if (attr.Name.Equals("line")) + if (attr.Name.Equals("line", StringComparison.OrdinalIgnoreCase)) { line = attr.InnerText; } - else if (attr.Name.Equals("height")) + else if (attr.Name.Equals("height", StringComparison.OrdinalIgnoreCase)) { height = attr.InnerText; } @@ -493,10 +493,10 @@ private static void WriteOptions (XmlDocument xmlDoc, XmlElement rootElement, Pe rootElement.AppendChild(optionsElement); XmlElement element = xmlDoc.CreateElement("multifile"); - element.SetAttribute("enabled", persistenceData.multiFile ? "1" : "0"); - element.SetAttribute("pattern", persistenceData.multiFilePattern); - element.SetAttribute("maxDays", "" + persistenceData.multiFileMaxDays); - foreach (var fileName in persistenceData.multiFileNames) + element.SetAttribute("enabled", persistenceData.MultiFile ? "1" : "0"); + element.SetAttribute("pattern", persistenceData.MultiFilePattern); + element.SetAttribute("maxDays", "" + persistenceData.MultiFileMaxDays); + foreach (var fileName in persistenceData.MultiFileNames) { XmlElement entryElement = xmlDoc.CreateElement("fileEntry"); entryElement.SetAttribute("fileName", "" + fileName); @@ -505,46 +505,46 @@ private static void WriteOptions (XmlDocument xmlDoc, XmlElement rootElement, Pe optionsElement.AppendChild(element); element = xmlDoc.CreateElement("currentline"); - element.SetAttribute("line", "" + persistenceData.currentLine); + element.SetAttribute("line", "" + persistenceData.CurrentLine); optionsElement.AppendChild(element); element = xmlDoc.CreateElement("firstDisplayedLine"); - element.SetAttribute("line", "" + persistenceData.firstDisplayedLine); + element.SetAttribute("line", "" + persistenceData.FirstDisplayedLine); optionsElement.AppendChild(element); element = xmlDoc.CreateElement("filter"); - element.SetAttribute("visible", persistenceData.filterVisible ? "1" : "0"); - element.SetAttribute("advanced", persistenceData.filterAdvanced ? "1" : "0"); - element.SetAttribute("position", "" + persistenceData.filterPosition); + element.SetAttribute("visible", persistenceData.FilterVisible ? "1" : "0"); + element.SetAttribute("advanced", persistenceData.FilterAdvanced ? "1" : "0"); + element.SetAttribute("position", "" + persistenceData.FilterPosition); optionsElement.AppendChild(element); element = xmlDoc.CreateElement("bookmarklist"); - element.SetAttribute("visible", persistenceData.bookmarkListVisible ? "1" : "0"); - element.SetAttribute("position", "" + persistenceData.bookmarkListPosition); + element.SetAttribute("visible", persistenceData.BookmarkListVisible ? "1" : "0"); + element.SetAttribute("position", "" + persistenceData.BookmarkListPosition); optionsElement.AppendChild(element); element = xmlDoc.CreateElement("followTail"); - element.SetAttribute("enabled", persistenceData.followTail ? "1" : "0"); + element.SetAttribute("enabled", persistenceData.FollowTail ? "1" : "0"); optionsElement.AppendChild(element); element = xmlDoc.CreateElement("tab"); - element.SetAttribute("name", persistenceData.tabName); + element.SetAttribute("name", persistenceData.TabName); rootElement.AppendChild(element); element = xmlDoc.CreateElement("columnizer"); - element.SetAttribute("name", persistenceData.columnizerName); + element.SetAttribute("name", persistenceData.ColumnizerName); rootElement.AppendChild(element); element = xmlDoc.CreateElement("highlightGroup"); - element.SetAttribute("name", persistenceData.highlightGroupName); + element.SetAttribute("name", persistenceData.HighlightGroupName); rootElement.AppendChild(element); element = xmlDoc.CreateElement("bookmarkCommentColumn"); - element.SetAttribute("visible", persistenceData.showBookmarkCommentColumn ? "1" : "0"); + element.SetAttribute("visible", persistenceData.ShowBookmarkCommentColumn ? "1" : "0"); optionsElement.AppendChild(element); element = xmlDoc.CreateElement("filterSaveList"); - element.SetAttribute("visible", persistenceData.filterSaveListVisible ? "1" : "0"); + element.SetAttribute("visible", persistenceData.FilterSaveListVisible ? "1" : "0"); optionsElement.AppendChild(element); } @@ -553,16 +553,16 @@ private static void ReadOptions (XmlElement startNode, PersistenceData persisten { XmlNode optionsNode = startNode.SelectSingleNode("options"); var value = GetOptionsAttribute(optionsNode, "multifile", "enabled"); - persistenceData.multiFile = value != null && value.Equals("1"); - persistenceData.multiFilePattern = GetOptionsAttribute(optionsNode, "multifile", "pattern"); + persistenceData.MultiFile = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + persistenceData.MultiFilePattern = GetOptionsAttribute(optionsNode, "multifile", "pattern"); value = GetOptionsAttribute(optionsNode, "multifile", "maxDays"); try { - persistenceData.multiFileMaxDays = value != null ? short.Parse(value) : 0; + persistenceData.MultiFileMaxDays = value != null ? short.Parse(value) : 0; } catch (Exception) { - persistenceData.multiFileMaxDays = 0; + persistenceData.MultiFileMaxDays = 0; } XmlNode multiFileNode = optionsNode.SelectSingleNode("multifile"); @@ -574,67 +574,67 @@ private static void ReadOptions (XmlElement startNode, PersistenceData persisten string fileName = null; foreach (XmlAttribute attr in node.Attributes) { - if (attr.Name.Equals("fileName")) + if (attr.Name.Equals("fileName", StringComparison.OrdinalIgnoreCase)) { fileName = attr.InnerText; } } - persistenceData.multiFileNames.Add(fileName); + persistenceData.MultiFileNames.Add(fileName); } } value = GetOptionsAttribute(optionsNode, "currentline", "line"); if (value != null) { - persistenceData.currentLine = int.Parse(value); + persistenceData.CurrentLine = int.Parse(value); } value = GetOptionsAttribute(optionsNode, "firstDisplayedLine", "line"); if (value != null) { - persistenceData.firstDisplayedLine = int.Parse(value); + persistenceData.FirstDisplayedLine = int.Parse(value); } value = GetOptionsAttribute(optionsNode, "filter", "visible"); - persistenceData.filterVisible = value != null && value.Equals("1"); + persistenceData.FilterVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); value = GetOptionsAttribute(optionsNode, "filter", "advanced"); - persistenceData.filterAdvanced = value != null && value.Equals("1"); + persistenceData.FilterAdvanced = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); value = GetOptionsAttribute(optionsNode, "filter", "position"); if (value != null) { - persistenceData.filterPosition = int.Parse(value); + persistenceData.FilterPosition = int.Parse(value); } value = GetOptionsAttribute(optionsNode, "bookmarklist", "visible"); - persistenceData.bookmarkListVisible = value != null && value.Equals("1"); + persistenceData.BookmarkListVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); value = GetOptionsAttribute(optionsNode, "bookmarklist", "position"); if (value != null) { - persistenceData.bookmarkListPosition = int.Parse(value); + persistenceData.BookmarkListPosition = int.Parse(value); } value = GetOptionsAttribute(optionsNode, "followTail", "enabled"); - persistenceData.followTail = value != null && value.Equals("1"); + persistenceData.FollowTail = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); value = GetOptionsAttribute(optionsNode, "bookmarkCommentColumn", "visible"); - persistenceData.showBookmarkCommentColumn = value != null && value.Equals("1"); + persistenceData.ShowBookmarkCommentColumn = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); value = GetOptionsAttribute(optionsNode, "filterSaveList", "visible"); - persistenceData.filterSaveListVisible = value != null && value.Equals("1"); + persistenceData.FilterSaveListVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); XmlNode tabNode = startNode.SelectSingleNode("tab"); if (tabNode != null) { - persistenceData.tabName = (tabNode as XmlElement).GetAttribute("name"); + persistenceData.TabName = (tabNode as XmlElement).GetAttribute("name"); } XmlNode columnizerNode = startNode.SelectSingleNode("columnizer"); if (columnizerNode != null) { - persistenceData.columnizerName = (columnizerNode as XmlElement).GetAttribute("name"); + persistenceData.ColumnizerName = (columnizerNode as XmlElement).GetAttribute("name"); } XmlNode highlightGroupNode = startNode.SelectSingleNode("highlightGroup"); if (highlightGroupNode != null) { - persistenceData.highlightGroupName = (highlightGroupNode as XmlElement).GetAttribute("name"); + persistenceData.HighlightGroupName = (highlightGroupNode as XmlElement).GetAttribute("name"); } } diff --git a/src/LogExpert.Core/Classes/QualityInfo.cs b/src/LogExpert.Core/Classes/QualityInfo.cs new file mode 100644 index 00000000..7e150c3d --- /dev/null +++ b/src/LogExpert.Core/Classes/QualityInfo.cs @@ -0,0 +1,6 @@ +namespace LogExpert.Core.Classes; + +public class QualityInfo +{ + public int Quality { get; set; } +} diff --git a/src/LogExpert.Core/Classes/Util.cs b/src/LogExpert.Core/Classes/Util.cs index b8b7c904..14523f5b 100644 --- a/src/LogExpert.Core/Classes/Util.cs +++ b/src/LogExpert.Core/Classes/Util.cs @@ -63,7 +63,7 @@ public static string GetFileSizeAsText (long size) public static bool TestFilterCondition (FilterParams filterParams, ILogLine line, ILogLineColumnizerCallback columnizerCallback) { - if (filterParams.LastLine.Equals(line.FullLine)) + if (filterParams.LastLine.Equals(line.FullLine, StringComparison.OrdinalIgnoreCase)) { return filterParams.LastResult; } @@ -550,14 +550,14 @@ private static bool TestMatchSub (FilterParams filterParams, string line, string { if (exactMatch) { - if (line.ToLower().Trim().Equals(lowerSearchText)) + if (line.ToLowerInvariant().Trim().Equals(lowerSearchText, StringComparison.Ordinal)) { return true; } } else { - if (line.Contains(lowerSearchText, StringComparison.CurrentCultureIgnoreCase)) + if (line.Contains(lowerSearchText, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -567,14 +567,14 @@ private static bool TestMatchSub (FilterParams filterParams, string line, string { if (exactMatch) { - if (line.Equals(searchText)) + if (line.Equals(searchText, StringComparison.Ordinal)) { return true; } } else { - if (line.Contains(searchText)) + if (line.Contains(searchText, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -592,7 +592,7 @@ private static bool TestMatchSub (FilterParams filterParams, string line, string if (!filterParams.IsCaseSensitive) { - src = src.ToLower(); + src = src.ToLowerInvariant(); } var dist = DamerauLevenshteinDistance(src, searchText); @@ -603,9 +603,11 @@ private static bool TestMatchSub (FilterParams filterParams, string line, string } } } + return false; } } + return false; } diff --git a/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs b/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs index 37586ec5..9e11b1de 100644 --- a/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs +++ b/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs @@ -1,14 +1,9 @@ -using System; - namespace LogExpert.Core.Config; [Serializable] public class ColumnizerMaskEntry { - #region Fields - - public string columnizerName; - public string mask; + public string ColumnizerName { get; set; } - #endregion + public string Mask { get; set; } } \ No newline at end of file diff --git a/src/LogExpert.Core/Config/HighlightMaskEntry.cs b/src/LogExpert.Core/Config/HighlightMaskEntry.cs index cf1f40d2..8f5fb108 100644 --- a/src/LogExpert.Core/Config/HighlightMaskEntry.cs +++ b/src/LogExpert.Core/Config/HighlightMaskEntry.cs @@ -1,14 +1,9 @@ -using System; - namespace LogExpert.Core.Config; [Serializable] public class HighlightMaskEntry { - #region Fields - - public string highlightGroupName; - public string mask; + public string HighlightGroupName { get; set; } - #endregion + public string Mask { get; set; } } \ No newline at end of file diff --git a/src/LogExpert.Core/Config/Preferences.cs b/src/LogExpert.Core/Config/Preferences.cs index 333465ec..779e6fb8 100644 --- a/src/LogExpert.Core/Config/Preferences.cs +++ b/src/LogExpert.Core/Config/Preferences.cs @@ -1,111 +1,107 @@ +using System.Drawing; + using LogExpert.Core.Entities; using LogExpert.Core.Enums; -using System.Drawing; - namespace LogExpert.Core.Config; [Serializable] public class Preferences { - #region Fields - - public bool allowOnlyOneInstance; - - public bool askForClose; + public List HighlightGroupList { get; set; } = []; - public bool darkMode; + public bool PortableMode { get; set; } - public int bufferCount = 100; + public bool ShowErrorMessageAllowOnlyOneInstances { get; set; } - public List columnizerMaskList = []; + public int MaxLineLength { get; set; } = 20000; - public string defaultEncoding; + public bool AllowOnlyOneInstance { get; set; } - public bool filterSync = true; + public bool AskForClose { get; set; } - public bool filterTail = true; + public bool DarkMode { get; set; } - public bool followTail = true; + public bool UseLegacyReader { get; set; } - public string fontName = "Courier New"; + public List ToolEntries { get; set; } = []; - public float fontSize = 9; + public DragOrientationsEnum TimestampControlDragOrientation { get; set; } = DragOrientationsEnum.Horizontal; - public List highlightMaskList = []; + public bool TimestampControl { get; set; } - public List HighlightGroupList { get; set; } = []; + public bool TimeSpreadTimeMode { get; set; } - public bool isAutoHideFilterList; + /// + /// Save Directory of the last logfile + /// + public string SessionSaveDirectory { get; set; } - public bool isFilterOnLoad; + public bool SaveFilters { get; set; } = true; - public int lastColumnWidth = 2000; + public SessionSaveLocation SaveLocation { get; set; } = SessionSaveLocation.DocumentsDir; - public int linesPerBuffer = 500; + public bool SaveSessions { get; set; } = true; - public int maximumFilterEntries = 30; + public bool SetLastColumnWidth { get; set; } - public int maximumFilterEntriesDisplayed = 20; + public bool ShowBubbles { get; set; } = true; - public bool maskPrio; + public bool ShowColumnFinder { get; set; } - public bool autoPick; + public Color ShowTailColor { get; set; } = Color.FromKnownColor(KnownColor.Blue); - //Refactor Enum - public MultiFileOption multiFileOption; + public bool ShowTailState { get; set; } = true; - //Refactor class? - public MultiFileOptions multiFileOptions; + public bool ShowTimeSpread { get; set; } - public bool multiThreadFilter = true; + public Color TimeSpreadColor { get; set; } = Color.FromKnownColor(KnownColor.Gray); - public bool openLastFiles = true; + public bool IsAutoHideFilterList { get; set; } - public int pollingInterval = 250; + public bool IsFilterOnLoad { get; set; } - public bool reverseAlpha; + public int LastColumnWidth { get; set; } = 2000; - public bool PortableMode { get; set; } + public int LinesPerBuffer { get; set; } = 500; - /// - /// Save Directory of the last logfile - /// - public string sessionSaveDirectory; + public int MaximumFilterEntries { get; set; } = 30; - public bool saveFilters = true; + public int MaximumFilterEntriesDisplayed { get; set; } = 20; - public SessionSaveLocation saveLocation = SessionSaveLocation.DocumentsDir; + public bool MaskPrio { get; set; } - public bool saveSessions = true; + public bool AutoPick { get; set; } - public bool setLastColumnWidth; + //TODO Refactor Enum + public MultiFileOption MultiFileOption { get; set; } - public bool showBubbles = true; + //TODO Refactor Class + public MultiFileOptions MultiFileOptions { get; set; } - public bool showColumnFinder; + public bool MultiThreadFilter { get; set; } = true; - public Color showTailColor = Color.FromKnownColor(KnownColor.Blue); + public bool OpenLastFiles { get; set; } = true; - public bool showTailState = true; + public int PollingInterval { get; set; } = 250; - public bool showTimeSpread; + public bool ReverseAlpha { get; set; } - public Color timeSpreadColor = Color.FromKnownColor(KnownColor.Gray); + public int BufferCount { get; set; } = 100; - public bool timeSpreadTimeMode; + public List ColumnizerMaskList { get; set; } = []; - public bool timestampControl = true; + public string DefaultEncoding { get; set; } - public DragOrientationsEnum timestampControlDragOrientation = DragOrientationsEnum.Horizontal; + public bool FilterSync { get; set; } = true; - public List toolEntries = []; + public bool FilterTail { get; set; } = true; - public bool useLegacyReader; + public bool FollowTail { get; set; } = true; - public bool ShowErrorMessageAllowOnlyOneInstances { get; set; } + public string FontName { get; set; } = "Courier New"; - public int MaxLineLength { get; set; } = 20000; + public float FontSize { get; set; } = 9; - #endregion + public List HighlightMaskList { get; set; } = []; } \ No newline at end of file diff --git a/src/LogExpert.Core/Config/SessionSaveLocation.cs b/src/LogExpert.Core/Config/SessionSaveLocation.cs index 7e559d6c..2759cb19 100644 --- a/src/LogExpert.Core/Config/SessionSaveLocation.cs +++ b/src/LogExpert.Core/Config/SessionSaveLocation.cs @@ -14,7 +14,7 @@ public enum SessionSaveLocation SameDir, //uses configured folder to save the session files /// - /// + /// /// OwnDir, /// diff --git a/src/LogExpert.Core/Config/Settings.cs b/src/LogExpert.Core/Config/Settings.cs index 461ec6d9..51375e41 100644 --- a/src/LogExpert.Core/Config/Settings.cs +++ b/src/LogExpert.Core/Config/Settings.cs @@ -8,47 +8,43 @@ namespace LogExpert.Core.Config; [Serializable] public class Settings { - #region Fields - - public bool alwaysOnTop; - - public Rectangle appBounds; + public Preferences Preferences { get; set; } = new(); - public Rectangle appBoundsFullscreen; + public RegexHistory RegexHistory { get; set; } = new(); - public IList columnizerHistoryList = []; + public bool AlwaysOnTop { get; set; } - public List fileColors = []; + public Rectangle AppBounds { get; set; } - public List fileHistoryList = []; + public Rectangle AppBoundsFullscreen { get; set; } - public List filterHistoryList = []; + public IList ColumnizerHistoryList { get; set; } = []; - public List filterList = []; + public List FileColors { get; set; } = []; - public FilterParams filterParams = new(); + public List FileHistoryList { get; set; } = []; - public List filterRangeHistoryList = []; + public List FilterHistoryList { get; set; } = []; - public bool hideLineColumn; + public List FilterList { get; set; } = []; - public bool isMaximized; + public FilterParams FilterParams { get; set; } = new(); - public string lastDirectory; + public List FilterRangeHistoryList { get; set; } = []; - public List lastOpenFilesList = []; + public bool HideLineColumn { get; set; } - public Preferences Preferences { get; set; } = new(); + public bool IsMaximized { get; set; } - public RegexHistory RegexHistory { get; set; } = new(); + public string LastDirectory { get; set; } - public List searchHistoryList = []; + public List LastOpenFilesList { get; set; } = []; - public SearchParams searchParams = new(); + public List SearchHistoryList { get; set; } = []; - public IList uriHistoryList = []; + public SearchParams SearchParams { get; set; } = new(); - public int versionBuild; + public IList UriHistoryList { get; set; } = []; - #endregion + public int VersionBuild { get; set; } } \ No newline at end of file diff --git a/src/LogExpert.Core/Config/ToolEntry.cs b/src/LogExpert.Core/Config/ToolEntry.cs index bb5d4d1e..107ed1d3 100644 --- a/src/LogExpert.Core/Config/ToolEntry.cs +++ b/src/LogExpert.Core/Config/ToolEntry.cs @@ -1,5 +1,3 @@ -using System; - using LogExpert.Core.Classes; namespace LogExpert.Core.Config; @@ -7,39 +5,45 @@ namespace LogExpert.Core.Config; [Serializable] public class ToolEntry { - #region Fields - - public string args = ""; - public string cmd = ""; - public string columnizerName = ""; - public string iconFile; - public int iconIndex; - public bool isFavourite; - public string name; - public bool sysout; - public string workingDir = ""; + public string Args { get; set; } = string.Empty; - #endregion + public string Cmd { get; set; } = string.Empty; + + public string ColumnizerName { get; set; } = string.Empty; + + public string IconFile { get; set; } + + public int IconIndex { get; set; } + + public bool IsFavourite { get; set; } + + public string Name { get; set; } + + public bool Sysout { get; set; } + + public string WorkingDir { get; set; } = string.Empty; #region Public methods - public override string ToString() + public override string ToString () { - return Util.IsNull(name) ? cmd : name; + return Util.IsNull(Name) ? Cmd : Name; } - public ToolEntry Clone() + public ToolEntry Clone () { - ToolEntry clone = new(); - clone.cmd = cmd; - clone.args = args; - clone.name = name; - clone.sysout = sysout; - clone.columnizerName = columnizerName; - clone.isFavourite = isFavourite; - clone.iconFile = iconFile; - clone.iconIndex = iconIndex; - clone.workingDir = workingDir; + ToolEntry clone = new() + { + Cmd = Cmd, + Args = Args, + Name = Name, + Sysout = Sysout, + ColumnizerName = ColumnizerName, + IsFavourite = IsFavourite, + IconFile = IconFile, + IconIndex = IconIndex, + WorkingDir = WorkingDir + }; return clone; } diff --git a/src/LogExpert.Tests/BufferShiftTest.cs b/src/LogExpert.Tests/BufferShiftTest.cs index bbbefee5..985f3a5d 100644 --- a/src/LogExpert.Tests/BufferShiftTest.cs +++ b/src/LogExpert.Tests/BufferShiftTest.cs @@ -41,7 +41,7 @@ public void TestShiftBuffers1 () Encoding = Encoding.Default }; - PluginRegistry.PluginRegistry.Instance.Create(testDirectory.FullName, 500); + PluginRegistry.PluginRegistry.Instance.Create(TestDirectory.FullName, 500); LogfileReader reader = new(files.Last.Value, encodingOptions, true, 40, 50, options, PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); @@ -110,7 +110,7 @@ public void TestShiftBuffers1 () { LogBuffer logBuffer = logBuffers[i]; ILogLine line = logBuffer.GetLineOfBlock(0); - Assert.That(line.FullLine.Contains(enumerator.Current)); + Assert.That(line.FullLine.Contains(enumerator.Current, System.StringComparison.Ordinal)); enumerator.MoveNext(); } enumerator.MoveNext(); @@ -119,7 +119,7 @@ public void TestShiftBuffers1 () { LogBuffer logBuffer = logBuffers[i]; ILogLine line = logBuffer.GetLineOfBlock(0); - Assert.That(line.FullLine.Contains(enumerator.Current)); + Assert.That(line.FullLine.Contains(enumerator.Current, System.StringComparison.Ordinal)); } oldCount = lil.Count; @@ -142,6 +142,6 @@ public void TestShiftBuffers1 () ILogLine firstLine = reader.GetLogLine(0); var names = new string[files.Count]; files.CopyTo(names, 0); - Assert.That(firstLine.FullLine.Contains(names[2])); + Assert.That(firstLine.FullLine.Contains(names[2], System.StringComparison.Ordinal)); } } \ No newline at end of file diff --git a/src/LogExpert.Tests/JSONSaveTest.cs b/src/LogExpert.Tests/JSONSaveTest.cs index e4193294..01f542a3 100644 --- a/src/LogExpert.Tests/JSONSaveTest.cs +++ b/src/LogExpert.Tests/JSONSaveTest.cs @@ -15,7 +15,7 @@ public class JSONSaveTest [Test(Author = "Hirogen", Description = "Save Options as JSON and Check if the written file can be cast again into the settings object")] public void SaveOptionsAsJSON() { - ConfigManager.Instance.Settings.alwaysOnTop = true; + ConfigManager.Instance.Settings.AlwaysOnTop = true; ConfigManager.Instance.Save(SettingsFlags.All); var configDir = ConfigManager.Instance.ConfigDir; var settingsFile = configDir + "\\settings.json"; @@ -24,16 +24,16 @@ public void SaveOptionsAsJSON() Assert.DoesNotThrow(CastSettings); Assert.That(settings, Is.Not.Null); - Assert.That(settings.alwaysOnTop, Is.True); + Assert.That(settings.AlwaysOnTop, Is.True); - ConfigManager.Instance.Settings.alwaysOnTop = false; + ConfigManager.Instance.Settings.AlwaysOnTop = false; ConfigManager.Instance.Save(SettingsFlags.All); settings = null; Assert.DoesNotThrow(CastSettings); Assert.That(settings, !Is.Null); - Assert.That(settings.alwaysOnTop, Is.False); + Assert.That(settings.AlwaysOnTop, Is.False); void CastSettings() diff --git a/src/LogExpert.Tests/RolloverHandlerTestBase.cs b/src/LogExpert.Tests/RolloverHandlerTestBase.cs index ea84c2cd..445a1579 100644 --- a/src/LogExpert.Tests/RolloverHandlerTestBase.cs +++ b/src/LogExpert.Tests/RolloverHandlerTestBase.cs @@ -1,9 +1,9 @@ -using LogExpert.Core.Classes.Log; - using System; using System.Collections.Generic; using System.IO; +using LogExpert.Core.Classes.Log; + namespace LogExpert.Tests; internal class RolloverHandlerTestBase @@ -11,43 +11,43 @@ internal class RolloverHandlerTestBase #region Fields public const string TEST_DIR_NAME = "test"; - public DirectoryInfo testDirectory; #endregion + public DirectoryInfo TestDirectory { get; set; } - protected LinkedList CreateTestFilesWithDate() + protected LinkedList CreateTestFilesWithDate () { LinkedList createdFiles = new(); DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); - testDirectory = dInfo; - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_1.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_0.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-10_0.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_1.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_0.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_2.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_1.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_0.log")); + TestDirectory = dInfo; + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_1.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_0.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-10_0.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_1.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_0.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_2.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_1.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_0.log")); return createdFiles; } - protected LinkedList CreateTestFilesWithoutDate() + protected LinkedList CreateTestFilesWithoutDate () { LinkedList createdFiles = new(); DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); - testDirectory = dInfo; - createdFiles.AddLast(CreateFile(dInfo, "engine.log.6")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.5")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.4")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.3")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.2")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.1")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log")); + TestDirectory = dInfo; + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.6")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.5")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.4")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.3")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.2")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.1")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log")); return createdFiles; } - protected LinkedList RolloverSimulation(LinkedList files, string formatPattern, + protected LinkedList RolloverSimulation (LinkedList files, string formatPattern, bool deleteLatestFile) { LinkedList fileList = files; @@ -65,6 +65,7 @@ protected LinkedList RolloverSimulation(LinkedList files, string File.Move(nextEnumerator.Current, enumerator.Current); enumerator.MoveNext(); } + CreateFile(null, nextEnumerator.Current); if (deleteLatestFile) @@ -72,11 +73,12 @@ protected LinkedList RolloverSimulation(LinkedList files, string File.Delete(fileList.First.Value); fileList.RemoveFirst(); } + return fileList; } - protected void Cleanup() + protected void Cleanup () { try { @@ -87,7 +89,7 @@ protected void Cleanup() } } - protected string CreateFile(DirectoryInfo dInfo, string fileName) + protected string CreateFile (DirectoryInfo dInfo, string fileName) { var lineCount = 10; var fullName = dInfo == null ? fileName : dInfo.FullName + Path.DirectorySeparatorChar + fileName; diff --git a/src/LogExpert.UI/Controls/BufferedDataGridView.cs b/src/LogExpert.UI/Controls/BufferedDataGridView.cs index e279178f..c52e73bc 100644 --- a/src/LogExpert.UI/Controls/BufferedDataGridView.cs +++ b/src/LogExpert.UI/Controls/BufferedDataGridView.cs @@ -1,4 +1,5 @@ using System.Drawing.Drawing2D; +using System.Runtime.Versioning; using LogExpert.Core.Entities; using LogExpert.Core.EventArguments; @@ -8,6 +9,7 @@ namespace LogExpert.Dialogs; +[SupportedOSPlatform("windows")] public partial class BufferedDataGridView : DataGridView { #region Fields diff --git a/src/LogExpert.UI/Controls/DateTimeDragControl.cs b/src/LogExpert.UI/Controls/DateTimeDragControl.cs index 8ae0e23f..676e9f86 100644 --- a/src/LogExpert.UI/Controls/DateTimeDragControl.cs +++ b/src/LogExpert.UI/Controls/DateTimeDragControl.cs @@ -1,14 +1,10 @@ -using LogExpert.Core.Classes.DateTimeParser; -using LogExpert.Core.Enums; - -using System; -using System.Collections.Generic; using System.ComponentModel; using System.Data; -using System.Drawing; using System.Globalization; -using System.Linq; -using System.Windows.Forms; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes.DateTimeParser; +using LogExpert.Core.Enums; namespace LogExpert.Dialogs; @@ -18,6 +14,7 @@ namespace LogExpert.Dialogs; /// We currently support only three: US (mm/dd/yyyy), French (yyyy-mm-dd) and German (dd.mm.yyyy). /// The control raises events (ValueChanged, ValueDragged) when the date/time changes so that owner can react accordingly. /// +[SupportedOSPlatform("windows")] public partial class DateTimeDragControl : UserControl { #region Fields @@ -27,11 +24,12 @@ public partial class DateTimeDragControl : UserControl private DateTime _dateTime; - private readonly IList _digitRects = new List(); + private readonly IList _digitRects = []; + private readonly StringFormat _digitsFormat = new(); private int _draggedDigit; - public DragOrientationsEnum dragOrientation = DragOrientationsEnum.Vertical; + private DragOrientationsEnum _dragOrientation = DragOrientationsEnum.Vertical; private readonly ToolStripItem toolStripItemHorizontalDrag = new ToolStripMenuItem(); private readonly ToolStripItem toolStripItemVerticalDrag = new ToolStripMenuItem(); @@ -51,7 +49,7 @@ public partial class DateTimeDragControl : UserControl /// /// Default Constructor /// - public DateTimeDragControl() + public DateTimeDragControl () { InitializeComponent(); @@ -70,9 +68,9 @@ public DateTimeDragControl() #region Delegates - public delegate void ValueChangedEventHandler(object sender, EventArgs e); + public delegate void ValueChangedEventHandler (object sender, EventArgs e); - public delegate void ValueDraggedEventHandler(object sender, EventArgs e); + public delegate void ValueDraggedEventHandler (object sender, EventArgs e); #endregion @@ -91,10 +89,10 @@ public DateTimeDragControl() public DragOrientationsEnum DragOrientation { - get => dragOrientation; + get => _dragOrientation; set { - dragOrientation = value; + _dragOrientation = value; UpdateContextMenu(); } } @@ -124,7 +122,7 @@ public DateTime DateTime #region Private Methods // Returns the index of the rectangle (digitRects) under the mouse cursor - private int DetermineDraggedDigit(MouseEventArgs e) + private int DetermineDraggedDigit (MouseEventArgs e) { for (var i = 0; i < _digitRects.Count; ++i) { @@ -138,39 +136,41 @@ private int DetermineDraggedDigit(MouseEventArgs e) } // Return the value corresponding to current dragged digit - private int GetDraggedValue() + private int GetDraggedValue () { var datePart = _dateParts[_draggedDigit]; - if (datePart.StartsWith("y", StringComparison.OrdinalIgnoreCase)) + if (datePart.StartsWith('y')) { return _dateTime.Year; } - if (datePart.StartsWith("M")) + if (datePart.StartsWith('M')) { return _dateTime.Month; } - if (datePart.StartsWith("d", StringComparison.OrdinalIgnoreCase)) + if (datePart.StartsWith('d')) { return _dateTime.Day; } - if (datePart.StartsWith("h", StringComparison.OrdinalIgnoreCase)) + if (datePart.StartsWith('h')) { return _dateTime.Hour; } - if (datePart.StartsWith("m")) + if (datePart.StartsWith('m')) { return _dateTime.Minute; } - return datePart.StartsWith("s", StringComparison.OrdinalIgnoreCase) ? _dateTime.Second : NO_DIGIT_DRAGGED; + return datePart.StartsWith('s') + ? _dateTime.Second + : NO_DIGIT_DRAGGED; } - private bool SetDraggedValue(int delta) + private bool SetDraggedValue (int delta) { if (_draggedDigit == NO_DIGIT_DRAGGED) { @@ -182,27 +182,27 @@ private bool SetDraggedValue(int delta) { var datePart = _dateParts[_draggedDigit]; - if (datePart.StartsWith("y", StringComparison.OrdinalIgnoreCase)) + if (datePart.StartsWith('y')) { _dateTime = _dateTime.AddYears(delta); } - else if (datePart.StartsWith("M")) + else if (datePart.StartsWith('M')) { _dateTime = _dateTime.AddMonths(delta); } - else if (datePart.StartsWith("d", StringComparison.OrdinalIgnoreCase)) + else if (datePart.StartsWith('d')) { _dateTime = _dateTime.AddDays(delta); } - else if (datePart.StartsWith("h", StringComparison.OrdinalIgnoreCase)) + else if (datePart.StartsWith('h')) { _dateTime = _dateTime.AddHours(delta); } - else if (datePart.StartsWith("m")) + else if (datePart.StartsWith('m')) { _dateTime = _dateTime.AddMinutes(delta); } - else if (datePart.StartsWith("s", StringComparison.OrdinalIgnoreCase)) + else if (datePart.StartsWith('s')) { _dateTime = _dateTime.AddSeconds(delta); } @@ -217,6 +217,7 @@ private bool SetDraggedValue(int delta) _dateTime = MaxDateTime; changed = false; } + if (_dateTime < MinDateTime) { _dateTime = MinDateTime; @@ -226,7 +227,7 @@ private bool SetDraggedValue(int delta) return changed; } - private void InitCustomRects(Section dateSection) + private void InitCustomRects (Section dateSection) { _dateParts = dateSection .GeneralTextDateDurationParts @@ -248,9 +249,9 @@ private void InitCustomRects(Section dateSection) } - private void InitDigitRects() + private void InitDigitRects () { - CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture; + CultureInfo culture = CultureInfo.CurrentCulture; var datePattern = string.Concat(culture.DateTimeFormat.ShortDatePattern, " ", culture.DateTimeFormat.LongTimePattern); @@ -270,7 +271,7 @@ private void InitDigitRects() #region Events handler - private void DateTimeDragControl_Load(object sender, EventArgs e) + private void DateTimeDragControl_Load (object sender, EventArgs e) { InitDigitRects(); @@ -279,22 +280,25 @@ private void DateTimeDragControl_Load(object sender, EventArgs e) #endregion - protected void OnValueChanged(EventArgs e) + protected void OnValueChanged (EventArgs e) { ValueChanged?.Invoke(this, e); } - protected void OnValueDragged(EventArgs e) + protected void OnValueDragged (EventArgs e) { ValueDragged?.Invoke(this, e); } #region Contextual Menu - private void BuildContextualMenu() + private void BuildContextualMenu () { - ContextMenuStrip = new ContextMenuStrip(); - ContextMenuStrip.Name = "Timestamp selector"; + ContextMenuStrip = new ContextMenuStrip + { + Name = "Timestamp selector" + }; + ContextMenuStrip.Items.Add(toolStripItemHorizontalDrag); ContextMenuStrip.Items.Add(toolStripItemVerticalDrag); ContextMenuStrip.Items.Add(toolStripItemVerticalInvertedDrag); @@ -313,14 +317,14 @@ private void BuildContextualMenu() UpdateContextMenu(); } - private void UpdateContextMenu() + private void UpdateContextMenu () { toolStripItemHorizontalDrag.Enabled = DragOrientation != DragOrientationsEnum.Horizontal; toolStripItemVerticalDrag.Enabled = DragOrientation != DragOrientationsEnum.Vertical; toolStripItemVerticalInvertedDrag.Enabled = DragOrientation != DragOrientationsEnum.InvertedVertical; } - private void OnContextMenuStripOpening(object sender, CancelEventArgs e) + private void OnContextMenuStripOpening (object sender, CancelEventArgs e) { if (Capture) { @@ -328,7 +332,7 @@ private void OnContextMenuStripOpening(object sender, CancelEventArgs e) } } - private void OnToolStripItemHorizontalDragClick(object sender, EventArgs e) + private void OnToolStripItemHorizontalDragClick (object sender, EventArgs e) { DragOrientation = DragOrientationsEnum.Horizontal; toolStripItemHorizontalDrag.Enabled = false; @@ -336,7 +340,7 @@ private void OnToolStripItemHorizontalDragClick(object sender, EventArgs e) toolStripItemVerticalInvertedDrag.Enabled = true; } - private void OnToolStripItemVerticalDragClick(object sender, EventArgs e) + private void OnToolStripItemVerticalDragClick (object sender, EventArgs e) { DragOrientation = DragOrientationsEnum.Vertical; toolStripItemHorizontalDrag.Enabled = true; @@ -344,7 +348,7 @@ private void OnToolStripItemVerticalDragClick(object sender, EventArgs e) toolStripItemVerticalInvertedDrag.Enabled = true; } - private void OnToolStripItemVerticalInvertedDragClick(object sender, EventArgs e) + private void OnToolStripItemVerticalInvertedDragClick (object sender, EventArgs e) { DragOrientation = DragOrientationsEnum.InvertedVertical; toolStripItemHorizontalDrag.Enabled = true; @@ -356,7 +360,7 @@ private void OnToolStripItemVerticalInvertedDragClick(object sender, EventArgs e #region Rendering - protected override void OnPaint(PaintEventArgs e) + protected override void OnPaint (PaintEventArgs e) { base.OnPaint(e); @@ -370,37 +374,35 @@ protected override void OnPaint(PaintEventArgs e) } // Display current value with user-defined date format and fixed time format ("HH:mm:ss") - using (Brush brush = new SolidBrush(Color.Black)) + using Brush brush = new SolidBrush(Color.Black); + for (var i = 0; i < _dateParts.Length; i++) { - for (var i = 0; i < _dateParts.Length; i++) - { - var datePart = _dateParts[i]; - Rectangle rect = _digitRects[i]; - string value; + var datePart = _dateParts[i]; + Rectangle rect = _digitRects[i]; + string value; - if (Token.IsDatePart(datePart)) + if (Token.IsDatePart(datePart)) + { + try { - try - { - value = _dateTime.ToString("-" + datePart + "-"); - value = value.Substring(1, value.Length - 2); - } - catch - { - value = datePart; - } + value = _dateTime.ToString("-" + datePart + "-"); + value = value[1..^1]; } - else + catch { value = datePart; } - - e.Graphics.DrawString(value, Font, brush, rect, _digitsFormat); } + else + { + value = datePart; + } + + e.Graphics.DrawString(value, Font, brush, rect, _digitsFormat); } } - private void DateTimeDragControl_Resize(object sender, EventArgs e) + private void DateTimeDragControl_Resize (object sender, EventArgs e) { InitDigitRects(); } @@ -409,7 +411,7 @@ private void DateTimeDragControl_Resize(object sender, EventArgs e) #region Mouse callbacks - protected override void OnMouseDown(MouseEventArgs e) + protected override void OnMouseDown (MouseEventArgs e) { base.OnMouseDown(e); @@ -420,6 +422,7 @@ protected override void OnMouseDown(MouseEventArgs e) { return; } + Capture = true; _startMouseY = e.Y; _startMouseX = e.X; @@ -431,10 +434,11 @@ protected override void OnMouseDown(MouseEventArgs e) Capture = false; SetDraggedValue(0); //undo } + Invalidate(); // repaint with the selected item (or none) } - protected override void OnMouseUp(MouseEventArgs e) + protected override void OnMouseUp (MouseEventArgs e) { if (!Capture) { @@ -450,7 +454,7 @@ protected override void OnMouseUp(MouseEventArgs e) OnValueChanged(EventArgs.Empty); } - protected override void OnMouseMove(MouseEventArgs e) + protected override void OnMouseMove (MouseEventArgs e) { base.OnMouseMove(e); @@ -479,7 +483,7 @@ protected override void OnMouseMove(MouseEventArgs e) } } - var delta = diff / 5 - _addedValue; // one unit per 5 pixels move + var delta = (diff / 5) - _addedValue; // one unit per 5 pixels move if (delta == 0) { @@ -496,7 +500,7 @@ protected override void OnMouseMove(MouseEventArgs e) OnValueDragged(EventArgs.Empty); } - private void DateTimeDragControl_MouseLeave(object sender, EventArgs e) + private void DateTimeDragControl_MouseLeave (object sender, EventArgs e) { if (Capture) { diff --git a/src/LogExpert.UI/Controls/LogTextColumn.cs b/src/LogExpert.UI/Controls/LogTextColumn.cs index 2bca5e54..3f2e44b7 100644 --- a/src/LogExpert.UI/Controls/LogTextColumn.cs +++ b/src/LogExpert.UI/Controls/LogTextColumn.cs @@ -1,4 +1,4 @@ -using System.Windows.Forms; +using System.Runtime.Versioning; namespace LogExpert.UI.Controls; @@ -6,7 +6,8 @@ public class LogTextColumn : DataGridViewColumn { #region cTor - public LogTextColumn() : base(new LogGridCell()) + [SupportedOSPlatform("windows")] + public LogTextColumn () : base(new LogGridCell()) { } diff --git a/src/LogExpert.UI/Controls/LogWindow/AbstractLogTabWindow.cs b/src/LogExpert.UI/Controls/LogWindow/AbstractLogTabWindow.cs index 7336d535..2a7caae9 100644 --- a/src/LogExpert.UI/Controls/LogWindow/AbstractLogTabWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/AbstractLogTabWindow.cs @@ -1,13 +1,17 @@ +using System.Runtime.Versioning; + using LogExpert.Core.Interface; +using LogExpert.UI.Dialogs.LogTabWindow; -namespace LogExpert.UI.Dialogs.LogTabWindow; +namespace LogExpert.UI.Controls.LogWindow; public abstract class AbstractLogTabWindow () { public static StaticLogTabWindowData StaticData { get; set; } = new StaticLogTabWindowData(); + [SupportedOSPlatform("windows")] public static ILogTabWindow Create (string[] fileNames, int instanceNumber, bool showInstanceNumbers, IConfigManager configManager) { - return new Controls.LogTabWindow.LogTabWindow(fileNames, instanceNumber, showInstanceNumbers, configManager); + return new LogTabWindow.LogTabWindow(fileNames, instanceNumber, showInstanceNumbers, configManager); } } \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index dec9982f..34e04cc6 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -1,4 +1,5 @@ -using LogExpert.Classes.Filter; +using System.Runtime.Versioning; + using LogExpert.Core.Callback; using LogExpert.Core.Classes.Bookmark; using LogExpert.Core.Classes.Filter; @@ -23,6 +24,7 @@ namespace LogExpert.UI.Controls.LogWindow; //TODO: Implemented 4 interfaces explicitly. Find them by searching: ILogWindow. +[SupportedOSPlatform("windows")] public partial class LogWindow : DockContent, ILogPaintContextUI, ILogView, ILogWindow { #region Fields @@ -134,6 +136,7 @@ public partial class LogWindow : DockContent, ILogPaintContextUI, ILogView, ILog #region cTor + [SupportedOSPlatform("windows")] public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTempFile, bool forcePersistenceLoading, IConfigManager configManager) { SuspendLayout(); @@ -190,12 +193,12 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp //this.toolwinTabControl.TabPages.Add(this.bookmarkWindow); _filterParams = new FilterParams(); - foreach (var item in configManager.Settings.filterHistoryList) + foreach (var item in configManager.Settings.FilterHistoryList) { filterComboBox.Items.Add(item); } - filterComboBox.DropDownHeight = filterComboBox.ItemHeight * configManager.Settings.Preferences.maximumFilterEntriesDisplayed; + filterComboBox.DropDownHeight = filterComboBox.ItemHeight * configManager.Settings.Preferences.MaximumFilterEntriesDisplayed; AutoResizeFilterBox(); filterRegexCheckBox.Checked = _filterParams.IsRegex; @@ -232,9 +235,9 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp Settings settings = configManager.Settings; - if (settings.appBounds.Right > 0) + if (settings.AppBounds.Right > 0) { - Bounds = settings.appBounds; + Bounds = settings.AppBounds; } _waitingForClose = false; @@ -267,6 +270,8 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp #endregion #region ColorTheme + + [SupportedOSPlatform("windows")] public void ChangeTheme (Control.ControlCollection container) { #region ApplyColorToAllControls @@ -448,6 +453,7 @@ private set } } + [SupportedOSPlatform("windows")] public bool ShowBookmarkBubbles { get => _guiStateArgs.ShowBookmarkBubbles; @@ -563,12 +569,14 @@ internal IColumnizedLogLine GetColumnsForLine (int lineNumber) //} } + [SupportedOSPlatform("windows")] internal void RefreshAllGrids () { dataGridView.Refresh(); filterGridView.Refresh(); } + [SupportedOSPlatform("windows")] internal void ChangeMultifileMask () { MultiFileMaskDialog dlg = new(this, FileName) @@ -589,6 +597,7 @@ internal void ChangeMultifileMask () } } + [SupportedOSPlatform("windows")] internal void ToggleColumnFinder (bool show, bool setFocus) { _guiStateArgs.ColumnFinderVisible = show; @@ -621,6 +630,7 @@ protected override string GetPersistString () #endregion + [SupportedOSPlatform("windows")] private void OnButtonSizeChanged (object sender, EventArgs e) { if (sender is Button button && button.Image != null) @@ -660,6 +670,7 @@ private void OnButtonSizeChanged (object sender, EventArgs e) // =================== ILogLineColumnizerCallback ============================ #if DEBUG + [SupportedOSPlatform("windows")] internal void DumpBufferInfo () { var currentLineNum = dataGridView.CurrentCellAddress.Y; @@ -671,16 +682,19 @@ internal void DumpBufferDiagnostic () _logFileReader.LogBufferDiagnostic(); } + [SupportedOSPlatform("windows")] void ILogWindow.SelectLine (int lineNum, bool v1, bool v2) { SelectLine(lineNum, v1, v2); } + [SupportedOSPlatform("windows")] void ILogWindow.AddTempFileTab (string fileName, string title) { AddTempFileTab(fileName, title); } + [SupportedOSPlatform("windows")] void ILogWindow.WritePipeTab (IList lineEntryList, string title) { WritePipeTab(lineEntryList, title); diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index d18bf035..40d1647c 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -1,6 +1,6 @@ using System.ComponentModel; +using System.Runtime.Versioning; -using LogExpert.Classes.Filter; using LogExpert.Core.Classes; using LogExpert.Core.Classes.Filter; using LogExpert.Core.Classes.Highlight; @@ -17,6 +17,7 @@ namespace LogExpert.UI.Controls.LogWindow; partial class LogWindow { + [SupportedOSPlatform("windows")] private void AutoResizeFilterBox () { filterSplitContainer.SplitterDistance = filterComboBox.Left + filterComboBox.GetMaxTextWidth(); @@ -100,11 +101,13 @@ protected void OnDeRegisterCancelHandler (IBackgroundProcessCancelHandler handle } } + [SupportedOSPlatform("windows")] private void OnLogWindowLoad (object sender, EventArgs e) { PreferencesChanged(_parentLogTabWin.Preferences, true, SettingsFlags.GuiOrColors); } + [SupportedOSPlatform("windows")] private void OnLogWindowDisposed (object sender, EventArgs e) { _waitingForClose = true; @@ -114,11 +117,13 @@ private void OnLogWindowDisposed (object sender, EventArgs e) FreeFromTimeSync(); } + [SupportedOSPlatform("windows")] private void OnLogFileReaderLoadingStarted (object sender, LoadFileEventArgs e) { Invoke(LoadingStarted, e); } + [SupportedOSPlatform("windows")] private void OnLogFileReaderFinishedLoading (object sender, EventArgs e) { //Thread.CurrentThread.Name = "FinishedLoading event thread"; @@ -151,6 +156,7 @@ private void OnLogFileReaderFinishedLoading (object sender, EventArgs e) _reloadMemento = null; } + [SupportedOSPlatform("windows")] private void OnLogFileReaderFileNotFound (object sender, EventArgs e) { if (!IsDisposed && !Disposing) @@ -161,14 +167,16 @@ private void OnLogFileReaderFileNotFound (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnLogFileReaderRespawned (object sender, EventArgs e) { BeginInvoke(new MethodInvoker(LogfileRespawned)); } + [SupportedOSPlatform("windows")] private void OnLogWindowClosing (object sender, CancelEventArgs e) { - if (Preferences.askForClose) + if (Preferences.AskForClose) { if (MessageBox.Show("Sure to close?", "LogExpert", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { @@ -181,6 +189,7 @@ private void OnLogWindowClosing (object sender, CancelEventArgs e) CloseLogWindow(); } + [SupportedOSPlatform("windows")] private void OnDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { e.Handled = true; @@ -190,6 +199,7 @@ private void OnDataGridViewColumnDividerDoubleClick (object sender, DataGridView /** * Event handler for the Load event from LogfileReader */ + [SupportedOSPlatform("windows")] private void OnLogFileReaderLoadFile (object sender, LoadFileEventArgs e) { if (e.NewFile) @@ -233,6 +243,7 @@ private void OnFileSizeChanged (object sender, LogEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { var startCount = CurrentColumnizer?.GetColumnCount() ?? 0; @@ -252,6 +263,7 @@ private void OnDataGridViewCellValueNeeded (object sender, DataGridViewCellValue } } + [SupportedOSPlatform("windows")] private void OnDataGridViewCellValuePushed (object sender, DataGridViewCellValueEventArgs e) { if (!CurrentColumnizer.IsTimeshiftImplemented()) @@ -287,11 +299,13 @@ private void OnDataGridViewCellValuePushed (object sender, DataGridViewCellValue SendGuiStateUpdate(); } + [SupportedOSPlatform("windows")] private void OnDataGridViewRowHeightInfoNeeded (object sender, DataGridViewRowHeightInfoNeededEventArgs e) { e.Height = GetRowHeight(e.RowIndex); } + [SupportedOSPlatform("windows")] private void OnDataGridViewCurrentCellChanged (object sender, EventArgs e) { if (dataGridView.CurrentRow != null) @@ -303,7 +317,7 @@ private void OnDataGridViewCurrentCellChanged (object sender, EventArgs e) SyncFilterGridPos(); } - if (CurrentColumnizer.IsTimeshiftImplemented() && Preferences.timestampControl) + if (CurrentColumnizer.IsTimeshiftImplemented() && Preferences.TimestampControl) { SyncTimestampDisplay(); } @@ -318,26 +332,31 @@ private void OnDataGridViewCellEndEdit (object sender, DataGridViewCellEventArgs StatusLineText(string.Empty); } + [SupportedOSPlatform("windows")] private void OnEditControlKeyUp (object sender, KeyEventArgs e) { UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); } + [SupportedOSPlatform("windows")] private void OnEditControlKeyPress (object sender, KeyPressEventArgs e) { UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); } + [SupportedOSPlatform("windows")] private void OnEditControlClick (object sender, EventArgs e) { UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); } + [SupportedOSPlatform("windows")] private void OnEditControlKeyDown (object sender, KeyEventArgs e) { UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); } + [SupportedOSPlatform("windows")] private void OnDataGridViewPaint (object sender, PaintEventArgs e) { if (ShowBookmarkBubbles) @@ -350,11 +369,13 @@ private void OnDataGridViewPaint (object sender, PaintEventArgs e) // Filter Grid stuff // ====================================================================================== + [SupportedOSPlatform("windows")] private void OnFilterSearchButtonClick (object sender, EventArgs e) { FilterSearch(); } + [SupportedOSPlatform("windows")] private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) { var gridView = (BufferedDataGridView)sender; @@ -446,7 +467,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti }; Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - Font font = new("Verdana", Preferences.fontSize, FontStyle.Bold); + Font font = new("Verdana", Preferences.FontSize, FontStyle.Bold); e.Graphics.DrawString("!", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); font.Dispose(); brush2.Dispose(); @@ -459,6 +480,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti } } + [SupportedOSPlatform("windows")] private void OnFilterGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) @@ -471,11 +493,13 @@ private void OnFilterGridViewCellValueNeeded (object sender, DataGridViewCellVal e.Value = GetCellValue(lineNum, e.ColumnIndex); } + [SupportedOSPlatform("windows")] private void OnFilterGridViewRowHeightInfoNeeded (object sender, DataGridViewRowHeightInfoNeededEventArgs e) { e.Height = _lineHeight; } + [SupportedOSPlatform("windows")] private void OnFilterComboBoxKeyDown (object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) @@ -484,6 +508,7 @@ private void OnFilterComboBoxKeyDown (object sender, KeyEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { @@ -492,6 +517,7 @@ private void OnFilterGridViewColumnDividerDoubleClick (object sender, BeginInvoke(fx, filterGridView); } + [SupportedOSPlatform("windows")] private void OnFilterGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) @@ -507,12 +533,14 @@ private void OnFilterGridViewCellDoubleClick (object sender, DataGridViewCellEve } } + [SupportedOSPlatform("windows")] private void OnRangeCheckBoxCheckedChanged (object sender, EventArgs e) { filterRangeComboBox.Enabled = rangeCheckBox.Checked; CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnDataGridViewScroll (object sender, ScrollEventArgs e) { if (e.ScrollOrientation == ScrollOrientation.VerticalScroll) @@ -540,6 +568,7 @@ private void OnDataGridViewScroll (object sender, ScrollEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterGridViewKeyDown (object sender, KeyEventArgs e) { switch (e.KeyCode) @@ -562,6 +591,7 @@ private void OnFilterGridViewKeyDown (object sender, KeyEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnDataGridViewKeyDown (object sender, KeyEventArgs e) { switch (e.KeyCode) @@ -584,6 +614,7 @@ private void OnDataGridViewKeyDown (object sender, KeyEventArgs e) _shouldCallTimeSync = true; } + [SupportedOSPlatform("windows")] private void OnDataGridViewPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.Tab && e.Control) @@ -592,6 +623,7 @@ private void OnDataGridViewPreviewKeyDown (object sender, PreviewKeyDownEventArg } } + [SupportedOSPlatform("windows")] private void OnDataGridViewCellContentDoubleClick (object sender, DataGridViewCellEventArgs e) { if (dataGridView.CurrentCell != null) @@ -600,6 +632,7 @@ private void OnDataGridViewCellContentDoubleClick (object sender, DataGridViewCe } } + [SupportedOSPlatform("windows")] private void OnSyncFilterCheckBoxCheckedChanged (object sender, EventArgs e) { if (syncFilterCheckBox.Checked) @@ -608,26 +641,31 @@ private void OnSyncFilterCheckBoxCheckedChanged (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnDataGridViewLeave (object sender, EventArgs e) { InvalidateCurrentRow(dataGridView); } + [SupportedOSPlatform("windows")] private void OnDataGridViewEnter (object sender, EventArgs e) { InvalidateCurrentRow(dataGridView); } + [SupportedOSPlatform("windows")] private void OnFilterGridViewEnter (object sender, EventArgs e) { InvalidateCurrentRow(filterGridView); } + [SupportedOSPlatform("windows")] private void OnFilterGridViewLeave (object sender, EventArgs e) { InvalidateCurrentRow(filterGridView); } + [SupportedOSPlatform("windows")] private void OnDataGridViewResize (object sender, EventArgs e) { if (_logFileReader != null && dataGridView.RowCount > 0 && _guiStateArgs.FollowTail) @@ -641,6 +679,7 @@ private void OnDataGridViewSelectionChanged (object sender, EventArgs e) UpdateSelectionDisplay(); } + [SupportedOSPlatform("windows")] private void OnSelectionChangedTriggerSignal (object sender, EventArgs e) { var selCount = 0; @@ -671,11 +710,13 @@ private void OnSelectionChangedTriggerSignal (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterKnobControlValueChanged (object sender, EventArgs e) { CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnFilterToTabButtonClick (object sender, EventArgs e) { FilterToTab(); @@ -697,22 +738,26 @@ private void OnPipeDisconnected (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnAdvancedButtonClick (object sender, EventArgs e) { _showAdvanced = !_showAdvanced; ShowAdvancedFilterPanel(_showAdvanced); } + [SupportedOSPlatform("windows")] private void OnFilterSplitContainerMouseDown (object sender, MouseEventArgs e) { ((SplitContainer)sender).IsSplitterFixed = true; } + [SupportedOSPlatform("windows")] private void OnFilterSplitContainerMouseUp (object sender, MouseEventArgs e) { ((SplitContainer)sender).IsSplitterFixed = false; } + [SupportedOSPlatform("windows")] private void OnFilterSplitContainerMouseMove (object sender, MouseEventArgs e) { var splitContainer = (SplitContainer)sender; @@ -744,6 +789,7 @@ private void OnFilterSplitContainerMouseMove (object sender, MouseEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterSplitContainerMouseDoubleClick (object sender, MouseEventArgs e) { AutoResizeFilterBox(); @@ -751,6 +797,7 @@ private void OnFilterSplitContainerMouseDoubleClick (object sender, MouseEventAr #region Context Menu + [SupportedOSPlatform("windows")] private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e) { var lineNum = -1; @@ -856,16 +903,18 @@ private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e TimeSyncList.Count > 1; } + [SupportedOSPlatform("windows")] private void OnHandlePluginContextMenu (object sender, EventArgs args) { if (sender is ToolStripItem item) { var menuArgs = item.Tag as ContextMenuPluginEventArgs; - var logLines = menuArgs.LogLines; + IList logLines = menuArgs.LogLines; menuArgs.Entry.MenuSelected(logLines.Count, menuArgs.Columnizer, menuArgs.Callback.GetLogLine(logLines[0])); } } + [SupportedOSPlatform("windows")] private void OnHandleSyncContextMenu (object sender, EventArgs args) { if (sender is ToolStripItem item) @@ -884,6 +933,7 @@ private void OnHandleSyncContextMenu (object sender, EventArgs args) } } + [SupportedOSPlatform("windows")] private void OnCopyToolStripMenuItemClick (object sender, EventArgs e) { CopyMarkedLinesToClipboard(); @@ -894,6 +944,7 @@ private void OnCopyToTabToolStripMenuItemClick (object sender, EventArgs e) CopyMarkedLinesToTab(); } + [SupportedOSPlatform("windows")] private void OnScrollAllTabsToTimestampToolStripMenuItemClick (object sender, EventArgs e) { if (CurrentColumnizer.IsTimeshiftImplemented()) @@ -913,6 +964,7 @@ private void OnScrollAllTabsToTimestampToolStripMenuItemClick (object sender, Ev } } + [SupportedOSPlatform("windows")] private void OnLocateLineInOriginalFileToolStripMenuItemClick (object sender, EventArgs e) { if (dataGridView.CurrentRow != null && FilterPipe != null) @@ -931,6 +983,7 @@ private void OnToggleBoomarkToolStripMenuItemClick (object sender, EventArgs e) ToggleBookmark(); } + [SupportedOSPlatform("windows")] private void OnMarkEditModeToolStripMenuItemClick (object sender, EventArgs e) { StartEditMode(); @@ -944,6 +997,7 @@ private void OnLogWindowSizeChanged (object sender, EventArgs e) #region BookMarkList + [SupportedOSPlatform("windows")] private void OnColumnRestrictCheckBoxCheckedChanged (object sender, EventArgs e) { columnButton.Enabled = columnRestrictCheckBox.Checked; @@ -961,6 +1015,7 @@ private void OnColumnRestrictCheckBoxCheckedChanged (object sender, EventArgs e) CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnColumnButtonClick (object sender, EventArgs e) { _filterParams.CurrentColumnizer = _currentColumnizer; @@ -979,6 +1034,7 @@ private void OnColumnButtonClick (object sender, EventArgs e) #region Column Header Context Menu + [SupportedOSPlatform("windows")] private void OnDataGridViewCellContextMenuStripNeeded (object sender, DataGridViewCellContextMenuStripNeededEventArgs e) { if (e.RowIndex >= 0 && e.RowIndex < dataGridView.RowCount && !dataGridView.Rows[e.RowIndex].Selected) @@ -1010,6 +1066,7 @@ private void OnDataGridViewCellContextMenuStripNeeded (object sender, DataGridVi // } //} + [SupportedOSPlatform("windows")] private void OnFilterGridViewCellContextMenuStripNeeded (object sender, DataGridViewCellContextMenuStripNeededEventArgs e) { if (e.ContextMenuStrip == columnContextMenuStrip) @@ -1018,6 +1075,7 @@ private void OnFilterGridViewCellContextMenuStripNeeded (object sender, DataGrid } } + [SupportedOSPlatform("windows")] private void OnColumnContextMenuStripOpening (object sender, CancelEventArgs e) { Control ctl = columnContextMenuStrip.SourceControl; @@ -1080,6 +1138,7 @@ private void OnColumnContextMenuStripOpening (object sender, CancelEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnHandleColumnItemContextMenu (object sender, EventArgs args) { if (sender is ToolStripItem item) @@ -1090,6 +1149,7 @@ private void OnHandleColumnItemContextMenu (object sender, EventArgs args) } } + [SupportedOSPlatform("windows")] private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick (object sender, EventArgs e) { Control ctl = columnContextMenuStrip.SourceControl; @@ -1109,6 +1169,7 @@ private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick (object sender, } } + [SupportedOSPlatform("windows")] private void OnMoveToLastColumnToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; @@ -1119,6 +1180,7 @@ private void OnMoveToLastColumnToolStripMenuItemClick (object sender, EventArgs } } + [SupportedOSPlatform("windows")] private void OnMoveLeftToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; @@ -1129,6 +1191,7 @@ private void OnMoveLeftToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnMoveRightToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; @@ -1139,6 +1202,7 @@ private void OnMoveRightToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnHideColumnToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; @@ -1146,6 +1210,7 @@ private void OnHideColumnToolStripMenuItemClick (object sender, EventArgs e) col.Visible = false; } + [SupportedOSPlatform("windows")] private void OnRestoreColumnsToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; @@ -1155,16 +1220,19 @@ private void OnRestoreColumnsToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnTimeSpreadingControlLineSelected (object sender, SelectLineEventArgs e) { SelectLine(e.Line, false, true); } + [SupportedOSPlatform("windows")] private void OnBookmarkCommentToolStripMenuItemClick (object sender, EventArgs e) { AddBookmarkAndEditComment(); } + [SupportedOSPlatform("windows")] private void OnHighlightSelectionInLogFileToolStripMenuItemClick (object sender, EventArgs e) { if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) @@ -1194,6 +1262,7 @@ private void OnHighlightSelectionInLogFileToolStripMenuItemClick (object sender, } } + [SupportedOSPlatform("windows")] private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick (object sender, EventArgs e) { if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) @@ -1224,6 +1293,7 @@ private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick (object } } + [SupportedOSPlatform("windows")] private void OnEditModeCopyToolStripMenuItemClick (object sender, EventArgs e) { if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) @@ -1235,11 +1305,13 @@ private void OnEditModeCopyToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnRemoveAllToolStripMenuItemClick (object sender, EventArgs e) { RemoveTempHighlights(); } + [SupportedOSPlatform("windows")] private void OnMakePermanentToolStripMenuItemClick (object sender, EventArgs e) { lock (_tempHighlightEntryListLock) @@ -1253,11 +1325,13 @@ private void OnMakePermanentToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnMarkCurrentFilterRangeToolStripMenuItemClick (object sender, EventArgs e) { MarkCurrentFilterRange(); } + [SupportedOSPlatform("windows")] private void OnFilterForSelectionToolStripMenuItemClick (object sender, EventArgs e) { if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) @@ -1268,6 +1342,7 @@ private void OnFilterForSelectionToolStripMenuItemClick (object sender, EventArg } } + [SupportedOSPlatform("windows")] private void OnSetSelectedTextAsBookmarkCommentToolStripMenuItemClick (object sender, EventArgs e) { if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) @@ -1281,6 +1356,7 @@ private void OnDataGridViewCellClick (object sender, DataGridViewCellEventArgs e _shouldCallTimeSync = true; } + [SupportedOSPlatform("windows")] private void OnDataGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) @@ -1289,11 +1365,13 @@ private void OnDataGridViewCellDoubleClick (object sender, DataGridViewCellEvent } } + [SupportedOSPlatform("windows")] private void OnDataGridViewOverlayDoubleClicked (object sender, OverlayEventArgs e) { BookmarkComment(e.BookmarkOverlay.Bookmark); } + [SupportedOSPlatform("windows")] private void OnFilterRegexCheckBoxMouseUp (object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) @@ -1324,6 +1402,7 @@ private void OnFilterRegexCheckBoxMouseUp (object sender, MouseEventArgs e) #region Filter-Highlight + [SupportedOSPlatform("windows")] private void OnToggleHighlightPanelButtonClick (object sender, EventArgs e) { ToggleHighlightPanel(highlightSplitContainer.Panel2Collapsed); @@ -1333,17 +1412,18 @@ private void OnSaveFilterButtonClick (object sender, EventArgs e) { FilterParams newParams = _filterParams.Clone(); newParams.Color = Color.FromKnownColor(KnownColor.Black); - ConfigManager.Settings.filterList.Add(newParams); + ConfigManager.Settings.FilterList.Add(newParams); OnFilterListChanged(this); } + [SupportedOSPlatform("windows")] private void OnDeleteFilterButtonClick (object sender, EventArgs e) { var index = filterListBox.SelectedIndex; if (index >= 0) { var filterParams = (FilterParams)filterListBox.Items[index]; - ConfigManager.Settings.filterList.Remove(filterParams); + ConfigManager.Settings.FilterList.Remove(filterParams); OnFilterListChanged(this); if (filterListBox.Items.Count > 0) { @@ -1352,20 +1432,22 @@ private void OnDeleteFilterButtonClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterUpButtonClick (object sender, EventArgs e) { var i = filterListBox.SelectedIndex; if (i > 0) { var filterParams = (FilterParams)filterListBox.Items[i]; - ConfigManager.Settings.filterList.RemoveAt(i); + ConfigManager.Settings.FilterList.RemoveAt(i); i--; - ConfigManager.Settings.filterList.Insert(i, filterParams); + ConfigManager.Settings.FilterList.Insert(i, filterParams); OnFilterListChanged(this); filterListBox.SelectedIndex = i; } } + [SupportedOSPlatform("windows")] private void OnFilterDownButtonClick (object sender, EventArgs e) { var i = filterListBox.SelectedIndex; @@ -1377,14 +1459,15 @@ private void OnFilterDownButtonClick (object sender, EventArgs e) if (i < filterListBox.Items.Count - 1) { var filterParams = (FilterParams)filterListBox.Items[i]; - ConfigManager.Settings.filterList.RemoveAt(i); + ConfigManager.Settings.FilterList.RemoveAt(i); i++; - ConfigManager.Settings.filterList.Insert(i, filterParams); + ConfigManager.Settings.FilterList.Insert(i, filterParams); OnFilterListChanged(this); filterListBox.SelectedIndex = i; } } + [SupportedOSPlatform("windows")] private void OnFilterListBoxMouseDoubleClick (object sender, MouseEventArgs e) { if (filterListBox.SelectedIndex >= 0) @@ -1411,6 +1494,7 @@ private void OnFilterListBoxMouseDoubleClick (object sender, MouseEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterListBoxDrawItem (object sender, DrawItemEventArgs e) { e.DrawBackground(); @@ -1437,6 +1521,7 @@ private void OnFilterListBoxDrawItem (object sender, DrawItemEventArgs e) } } + [SupportedOSPlatform("windows")] // Color for filter list entry private void OnColorToolStripMenuItemClick (object sender, EventArgs e) { @@ -1444,9 +1529,12 @@ private void OnColorToolStripMenuItemClick (object sender, EventArgs e) if (i < filterListBox.Items.Count && i >= 0) { var filterParams = (FilterParams)filterListBox.Items[i]; - ColorDialog dlg = new(); - dlg.CustomColors = [filterParams.Color.ToArgb()]; - dlg.Color = filterParams.Color; + ColorDialog dlg = new() + { + CustomColors = [filterParams.Color.ToArgb()], + Color = filterParams.Color + }; + if (dlg.ShowDialog() == DialogResult.OK) { filterParams.Color = dlg.Color; @@ -1455,11 +1543,13 @@ private void OnColorToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnFilterCaseSensitiveCheckBoxCheckedChanged (object sender, EventArgs e) { CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnFilterRegexCheckBoxCheckedChanged (object sender, EventArgs e) { fuzzyKnobControl.Enabled = !filterRegexCheckBox.Checked; @@ -1467,26 +1557,31 @@ private void OnFilterRegexCheckBoxCheckedChanged (object sender, EventArgs e) CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnInvertFilterCheckBoxCheckedChanged (object sender, EventArgs e) { CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnFilterRangeComboBoxTextChanged (object sender, EventArgs e) { CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnFuzzyKnobControlValueChanged (object sender, EventArgs e) { CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnFilterComboBoxTextChanged (object sender, EventArgs e) { CheckForFilterDirty(); } + [SupportedOSPlatform("windows")] private void OnSetBookmarksOnSelectedLinesToolStripMenuItemClick (object sender, EventArgs e) { SetBookmarksForSelectedFilterLines(); @@ -1498,21 +1593,25 @@ private void OnParentHighlightSettingsChanged (object sender, EventArgs e) SetCurrentHighlightGroup(groupName); } + [SupportedOSPlatform("windows")] private void OnFilterOnLoadCheckBoxMouseClick (object sender, MouseEventArgs e) { HandleChangedFilterOnLoadSetting(); } + [SupportedOSPlatform("windows")] private void OnFilterOnLoadCheckBoxKeyPress (object sender, KeyPressEventArgs e) { HandleChangedFilterOnLoadSetting(); } + [SupportedOSPlatform("windows")] private void OnHideFilterListOnLoadCheckBoxMouseClick (object sender, MouseEventArgs e) { HandleChangedFilterOnLoadSetting(); } + [SupportedOSPlatform("windows")] private void OnFilterToTabToolStripMenuItemClick (object sender, EventArgs e) { FilterToTab(); @@ -1523,7 +1622,7 @@ private void OnTimeSyncListWindowRemoved (object sender, EventArgs e) var syncList = sender as TimeSyncList; lock (_timeSyncListLock) { - if (syncList.Count == 0 || syncList.Count == 1 && syncList.Contains(this)) + if (syncList.Count == 0 || (syncList.Count == 1 && syncList.Contains(this))) { if (syncList == TimeSyncList) { @@ -1539,25 +1638,32 @@ private void OnFreeThisWindowFromTimeSyncToolStripMenuItemClick (object sender, FreeFromTimeSync(); } + [SupportedOSPlatform("windows")] private void OnSplitContainerSplitterMoved (object sender, SplitterEventArgs e) { advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; } + [SupportedOSPlatform("windows")] private void OnMarkFilterHitsInLogViewToolStripMenuItemClick (object sender, EventArgs e) { - SearchParams p = new(); - p.SearchText = _filterParams.SearchText; - p.IsRegex = _filterParams.IsRegex; - p.IsCaseSensitive = _filterParams.IsCaseSensitive; + SearchParams p = new() + { + SearchText = _filterParams.SearchText, + IsRegex = _filterParams.IsRegex, + IsCaseSensitive = _filterParams.IsCaseSensitive + }; + AddSearchHitHighlightEntry(p); } + [SupportedOSPlatform("windows")] private void OnColumnComboBoxSelectionChangeCommitted (object sender, EventArgs e) { SelectColumn(); } + [SupportedOSPlatform("windows")] private void OnColumnComboBoxKeyDown (object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) @@ -1567,6 +1673,7 @@ private void OnColumnComboBoxKeyDown (object sender, KeyEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnColumnComboBoxPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.Down && e.Modifiers == Keys.Alt) @@ -1580,6 +1687,7 @@ private void OnColumnComboBoxPreviewKeyDown (object sender, PreviewKeyDownEventA } } + [SupportedOSPlatform("windows")] private void OnBookmarkProviderBookmarkRemoved (object sender, EventArgs e) { if (!_isLoading) @@ -1589,6 +1697,7 @@ private void OnBookmarkProviderBookmarkRemoved (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnBookmarkProviderBookmarkAdded (object sender, EventArgs e) { if (!_isLoading) @@ -1613,6 +1722,7 @@ private void OnLogWindowEnter (object sender, EventArgs e) InvalidateCurrentRow(); } + [SupportedOSPlatform("windows")] private void OnDataGridViewRowUnshared (object sender, DataGridViewRowEventArgs e) { if (_logger.IsTraceEnabled) @@ -1627,6 +1737,7 @@ private void OnDataGridViewRowUnshared (object sender, DataGridViewRowEventArgs #endregion + [SupportedOSPlatform("windows")] private void MeasureItem (object sender, MeasureItemEventArgs e) { e.ItemHeight = filterListBox.Font.Height; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs index 5ea20a31..49b9f505 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; @@ -22,6 +23,7 @@ partial class LogWindow { #region Private Methods + [SupportedOSPlatform("windows")] private void RegisterLogFileReaderEvents () { _logFileReader.LoadFile += OnLogFileReaderLoadFile; @@ -32,6 +34,7 @@ private void RegisterLogFileReaderEvents () // FileSizeChanged is not registered here because it's registered after loading has finished } + [SupportedOSPlatform("windows")] private void UnRegisterLogFileReaderEvents () { if (_logFileReader != null) @@ -45,6 +48,7 @@ private void UnRegisterLogFileReaderEvents () } } + [SupportedOSPlatform("windows")] private void CreateDefaultViewStyle () { DataGridViewCellStyle dataGridViewCellStyleMainGrid = new(); @@ -69,6 +73,7 @@ private void CreateDefaultViewStyle () filterGridView.DefaultCellStyle = dataGridViewCellStyleFilterGrid; } + [SupportedOSPlatform("windows")] private bool LoadPersistenceOptions () { if (InvokeRequired) @@ -76,23 +81,16 @@ private bool LoadPersistenceOptions () return (bool)Invoke(new BoolReturnDelegate(LoadPersistenceOptions)); } - if (!Preferences.saveSessions && ForcedPersistenceFileName == null) + if (!Preferences.SaveSessions && ForcedPersistenceFileName == null) { return false; } try { - PersistenceData persistenceData; - if (ForcedPersistenceFileName == null) - { - persistenceData = Persister.LoadPersistenceDataOptionsOnly(FileName, Preferences); - } - else - { - persistenceData = - Persister.LoadPersistenceDataOptionsOnlyFromFixedFile(ForcedPersistenceFileName); - } + PersistenceData persistenceData = ForcedPersistenceFileName == null + ? Persister.LoadPersistenceDataOptionsOnly(FileName, Preferences) + : Persister.LoadPersistenceDataOptionsOnlyFromFixedFile(ForcedPersistenceFileName); if (persistenceData == null) { @@ -100,40 +98,42 @@ private bool LoadPersistenceOptions () return false; } - IsMultiFile = persistenceData.multiFile; - _multiFileOptions = new MultiFileOptions(); - _multiFileOptions.FormatPattern = persistenceData.multiFilePattern; - _multiFileOptions.MaxDayTry = persistenceData.multiFileMaxDays; + IsMultiFile = persistenceData.MultiFile; + _multiFileOptions = new MultiFileOptions + { + FormatPattern = persistenceData.MultiFilePattern, + MaxDayTry = persistenceData.MultiFileMaxDays + }; if (string.IsNullOrEmpty(_multiFileOptions.FormatPattern)) { - _multiFileOptions = ObjectClone.Clone(Preferences.multiFileOptions); + _multiFileOptions = ObjectClone.Clone(Preferences.MultiFileOptions); } - splitContainerLogWindow.SplitterDistance = persistenceData.filterPosition; - splitContainerLogWindow.Panel2Collapsed = !persistenceData.filterVisible; - ToggleHighlightPanel(persistenceData.filterSaveListVisible); - ShowAdvancedFilterPanel(persistenceData.filterAdvanced); + splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; + splitContainerLogWindow.Panel2Collapsed = !persistenceData.FilterVisible; + ToggleHighlightPanel(persistenceData.FilterSaveListVisible); + ShowAdvancedFilterPanel(persistenceData.FilterAdvanced); if (_reloadMemento == null) { - PreselectColumnizer(persistenceData.columnizerName); + PreselectColumnizer(persistenceData.ColumnizerName); } - FollowTailChanged(persistenceData.followTail, false); - if (persistenceData.tabName != null) + FollowTailChanged(persistenceData.FollowTail, false); + if (persistenceData.TabName != null) { - Text = persistenceData.tabName; + Text = persistenceData.TabName; } AdjustHighlightSplitterWidth(); - SetCurrentHighlightGroup(persistenceData.highlightGroupName); + SetCurrentHighlightGroup(persistenceData.HighlightGroupName); - if (persistenceData.multiFileNames.Count > 0) + if (persistenceData.MultiFileNames.Count > 0) { _logger.Info("Detected MultiFile name list in persistence options"); - _fileNames = new string[persistenceData.multiFileNames.Count]; - persistenceData.multiFileNames.CopyTo(_fileNames); + _fileNames = new string[persistenceData.MultiFileNames.Count]; + persistenceData.MultiFileNames.CopyTo(_fileNames); } else { @@ -141,7 +141,7 @@ private bool LoadPersistenceOptions () } //this.bookmarkWindow.ShowBookmarkCommentColumn = persistenceData.showBookmarkCommentColumn; - SetExplicitEncoding(persistenceData.encoding); + SetExplicitEncoding(persistenceData.Encoding); return true; } catch (Exception ex) @@ -151,14 +151,16 @@ private bool LoadPersistenceOptions () } } + [SupportedOSPlatform("windows")] private void SetDefaultsFromPrefs () { - filterTailCheckBox.Checked = Preferences.filterTail; - syncFilterCheckBox.Checked = Preferences.filterSync; - FollowTailChanged(Preferences.followTail, false); - _multiFileOptions = ObjectClone.Clone(Preferences.multiFileOptions); + filterTailCheckBox.Checked = Preferences.FilterTail; + syncFilterCheckBox.Checked = Preferences.FilterSync; + FollowTailChanged(Preferences.FollowTail, false); + _multiFileOptions = ObjectClone.Clone(Preferences.MultiFileOptions); } + [SupportedOSPlatform("windows")] private void LoadPersistenceData () { if (InvokeRequired) @@ -167,7 +169,7 @@ private void LoadPersistenceData () return; } - if (!Preferences.saveSessions && !ForcePersistenceLoading && ForcedPersistenceFileName == null) + if (!Preferences.SaveSessions && !ForcePersistenceLoading && ForcedPersistenceFileName == null) { SetDefaultsFromPrefs(); return; @@ -183,18 +185,11 @@ private void LoadPersistenceData () try { - PersistenceData persistenceData; - - if (ForcedPersistenceFileName == null) - { - persistenceData = Persister.LoadPersistenceData(FileName, Preferences); - } - else - { - persistenceData = Persister.LoadPersistenceDataFromFixedFile(ForcedPersistenceFileName); - } + PersistenceData persistenceData = ForcedPersistenceFileName == null + ? Persister.LoadPersistenceData(FileName, Preferences) + : Persister.LoadPersistenceDataFromFixedFile(ForcedPersistenceFileName); - if (persistenceData.lineCount > _logFileReader.LineCount) + if (persistenceData.LineCount > _logFileReader.LineCount) { // outdated persistence data (logfile rollover) // MessageBox.Show(this, "Persistence data for " + this.FileName + " is outdated. It was discarded.", "Log Expert"); @@ -203,13 +198,13 @@ private void LoadPersistenceData () return; } - _bookmarkProvider.SetBookmarks(persistenceData.bookmarkList); - _rowHeightList = persistenceData.rowHeightList; + _bookmarkProvider.SetBookmarks(persistenceData.BookmarkList); + _rowHeightList = persistenceData.RowHeightList; try { - if (persistenceData.currentLine >= 0 && persistenceData.currentLine < dataGridView.RowCount) + if (persistenceData.CurrentLine >= 0 && persistenceData.CurrentLine < dataGridView.RowCount) { - SelectLine(persistenceData.currentLine, false, true); + SelectLine(persistenceData.CurrentLine, false, true); } else { @@ -220,15 +215,15 @@ private void LoadPersistenceData () } } - if (persistenceData.firstDisplayedLine >= 0 && - persistenceData.firstDisplayedLine < dataGridView.RowCount) + if (persistenceData.FirstDisplayedLine >= 0 && + persistenceData.FirstDisplayedLine < dataGridView.RowCount) { - dataGridView.FirstDisplayedScrollingRowIndex = persistenceData.firstDisplayedLine; + dataGridView.FirstDisplayedScrollingRowIndex = persistenceData.FirstDisplayedLine; } - if (persistenceData.followTail) + if (persistenceData.FollowTail) { - FollowTailChanged(persistenceData.followTail, false); + FollowTailChanged(persistenceData.FollowTail, false); } } catch (ArgumentOutOfRangeException) @@ -236,7 +231,7 @@ private void LoadPersistenceData () // FirstDisplayedScrollingRowIndex calculates sometimes the wrong scrolling ranges??? } - if (Preferences.saveFilters) + if (Preferences.SaveFilters) { RestoreFilters(persistenceData); } @@ -248,11 +243,12 @@ private void LoadPersistenceData () } } + [SupportedOSPlatform("windows")] private void RestoreFilters (PersistenceData persistenceData) { - if (persistenceData.filterParamsList.Count > 0) + if (persistenceData.FilterParamsList.Count > 0) { - _filterParams = persistenceData.filterParamsList[0]; + _filterParams = persistenceData.FilterParamsList[0]; ReInitFilterParams(_filterParams); } @@ -260,15 +256,15 @@ private void RestoreFilters (PersistenceData persistenceData) BeginInvoke(new MethodInvoker(FilterSearch)); try { - splitContainerLogWindow.SplitterDistance = persistenceData.filterPosition; - splitContainerLogWindow.Panel2Collapsed = !persistenceData.filterVisible; + splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; + splitContainerLogWindow.Panel2Collapsed = !persistenceData.FilterVisible; } catch (InvalidOperationException e) { _logger.Error(e, "Error setting splitter distance: "); } - ShowAdvancedFilterPanel(persistenceData.filterAdvanced); + ShowAdvancedFilterPanel(persistenceData.FilterAdvanced); if (_filterPipeList.Count == 0) // don't restore if it's only a reload { RestoreFilterTabs(persistenceData); @@ -277,7 +273,7 @@ private void RestoreFilters (PersistenceData persistenceData) private void RestoreFilterTabs (PersistenceData persistenceData) { - foreach (FilterTabData data in persistenceData.filterTabDataList) + foreach (FilterTabData data in persistenceData.FilterTabDataList) { FilterParams persistFilterParams = data.FilterParams; ReInitFilterParams(persistFilterParams); @@ -286,7 +282,7 @@ private void RestoreFilterTabs (PersistenceData persistenceData) List filterHitList = []; Filter(persistFilterParams, filterResultList, _lastFilterLinesList, filterHitList); FilterPipe pipe = new(persistFilterParams.Clone(), this); - WritePipeToTab(pipe, filterResultList, data.PersistenceData.tabName, data.PersistenceData); + WritePipeToTab(pipe, filterResultList, data.PersistenceData.TabName, data.PersistenceData); } } @@ -338,6 +334,7 @@ private void EnterLoadFileStatus () _logger.Debug("EnterLoadFileStatus end"); } + [SupportedOSPlatform("windows")] private void PositionAfterReload (ReloadMemento reloadMemento) { if (_reloadMemento.CurrentLine < dataGridView.RowCount && _reloadMemento.CurrentLine >= 0) @@ -351,6 +348,7 @@ private void PositionAfterReload (ReloadMemento reloadMemento) } } + [SupportedOSPlatform("windows")] private void LogfileDead () { _logger.Info("File not found."); @@ -377,6 +375,7 @@ private void LogfileDead () OnFileNotFound(EventArgs.Empty); } + [SupportedOSPlatform("windows")] private void LogfileRespawned () { _logger.Info("LogfileDead(): Reloading file because it has been respawned."); @@ -387,21 +386,17 @@ private void LogfileRespawned () Reload(); } + [SupportedOSPlatform("windows")] private void SetGuiAfterLoading () { if (Text.Length == 0) { - if (IsTempFile) - { - Text = TempTitleName; - } - else - { - Text = Util.GetNameFromPath(FileName); - } + Text = IsTempFile + ? TempTitleName + : Util.GetNameFromPath(FileName); } - ShowBookmarkBubbles = Preferences.showBubbles; + ShowBookmarkBubbles = Preferences.ShowBubbles; //if (this.forcedColumnizer == null) { ILogLineColumnizer columnizer; @@ -435,6 +430,7 @@ private void SetGuiAfterLoading () Invoke(new SetColumnizerFx(SetColumnizer), columnizer); } + dataGridView.Enabled = true; DisplayCurrentFileOnStatusline(); //this.guiStateArgs.FollowTail = this.Preferences.followTail; @@ -452,31 +448,25 @@ private void SetGuiAfterLoading () //} if (CurrentColumnizer.IsTimeshiftImplemented()) { - if (Preferences.timestampControl) + if (Preferences.TimestampControl) { SetTimestampLimits(); SyncTimestampDisplay(); } Settings settings = ConfigManager.Settings; - ShowLineColumn(!settings.hideLineColumn); + ShowLineColumn(!settings.HideLineColumn); } - ShowTimeSpread(Preferences.showTimeSpread && CurrentColumnizer.IsTimeshiftImplemented()); + ShowTimeSpread(Preferences.ShowTimeSpread && CurrentColumnizer.IsTimeshiftImplemented()); locateLineInOriginalFileToolStripMenuItem.Enabled = FilterPipe != null; } private ILogLineColumnizer FindColumnizer () { - ILogLineColumnizer columnizer; - if (Preferences.maskPrio) - { - columnizer = _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)) ?? _parentLogTabWin.GetColumnizerHistoryEntry(FileName); - } - else - { - columnizer = _parentLogTabWin.GetColumnizerHistoryEntry(FileName) ?? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)); - } + ILogLineColumnizer columnizer = Preferences.MaskPrio + ? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)) ?? _parentLogTabWin.GetColumnizerHistoryEntry(FileName) + : _parentLogTabWin.GetColumnizerHistoryEntry(FileName) ?? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)); return columnizer; } @@ -487,14 +477,16 @@ private void ReloadNewFile () lock (_reloadLock) { _reloadOverloadCounter++; - _logger.Info("ReloadNewFile(): counter = {0}", _reloadOverloadCounter); + _logger.Info($"ReloadNewFile(): counter = {_reloadOverloadCounter}"); if (_reloadOverloadCounter <= 1) { SavePersistenceData(false); _loadingFinishedEvent.Reset(); _externaLoadingFinishedEvent.Reset(); - Thread reloadFinishedThread = new(ReloadFinishedThreadFx); - reloadFinishedThread.IsBackground = true; + Thread reloadFinishedThread = new(ReloadFinishedThreadFx) + { + IsBackground = true + }; reloadFinishedThread.Start(); LoadFile(FileName, EncodingOptions); @@ -519,6 +511,7 @@ private void ReloadNewFile () } } + [SupportedOSPlatform("windows")] private void ReloadFinishedThreadFx () { _logger.Info("Waiting for loading to be complete."); @@ -741,7 +734,7 @@ private void UpdateGrid (LogEventArgs e) OnTailFollowed(EventArgs.Empty); } - if (Preferences.timestampControl && !_isLoading) + if (Preferences.TimestampControl && !_isLoading) { SetTimestampLimits(); } @@ -1054,8 +1047,8 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) } Settings settings = ConfigManager.Settings; - ShowLineColumn(!settings.hideLineColumn); - ShowTimeSpread(Preferences.showTimeSpread && columnizer.IsTimeshiftImplemented()); + ShowLineColumn(!settings.HideLineColumn); + ShowTimeSpread(Preferences.ShowTimeSpread && columnizer.IsTimeshiftImplemented()); } if (!columnizer.IsTimeshiftImplemented() && IsTimeSynced) @@ -1080,13 +1073,13 @@ private void AutoResizeColumns (BufferedDataGridView gridView) try { gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - if (gridView.Columns.Count > 1 && Preferences.setLastColumnWidth && - gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.lastColumnWidth + if (gridView.Columns.Count > 1 && Preferences.SetLastColumnWidth && + gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.LastColumnWidth ) { // It seems that using 'MinimumWidth' instead of 'Width' prevents the DataGridView's NullReferenceExceptions //gridView.Columns[gridView.Columns.Count - 1].Width = this.Preferences.lastColumnWidth; - gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.lastColumnWidth; + gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.LastColumnWidth; } } catch (NullReferenceException e) @@ -1315,14 +1308,14 @@ private bool CheckHighlightEntryMatch (HighlightEntry entry, ITextValue column) { if (entry.IsCaseSensitive) { - if (column.Text.Contains(entry.SearchText)) + if (column.Text.Contains(entry.SearchText, StringComparison.Ordinal)) { return true; } } else { - if (column.Text.ToLower().Contains(entry.SearchText.ToLower())) + if (column.Text.ToUpperInvariant().Contains(entry.SearchText.ToUpperInvariant(), StringComparison.OrdinalIgnoreCase)) { return true; } @@ -1364,10 +1357,13 @@ private void GetHighlightEntryMatches (ITextValue line, IList hi MatchCollection matches = entry.Regex.Matches(line.Text); foreach (Match match in matches) { - HilightMatchEntry me = new(); - me.HilightEntry = entry; - me.StartPos = match.Index; - me.Length = match.Length; + HilightMatchEntry me = new() + { + HilightEntry = entry, + StartPos = match.Index, + Length = match.Length + }; + resultList.Add(me); } } @@ -1375,18 +1371,20 @@ private void GetHighlightEntryMatches (ITextValue line, IList hi { if (CheckHighlightEntryMatch(entry, line)) { - HilightMatchEntry me = new(); - me.HilightEntry = entry; - me.StartPos = 0; - me.Length = line.Text.Length; + HilightMatchEntry me = new() + { + HilightEntry = entry, + StartPos = 0, + Length = line.Text.Length + }; + resultList.Add(me); } } } } - private void GetHilightActions (IList matchingList, out bool noLed, out bool stopTail, - out bool setBookmark, out string bookmarkComment) + private void GetHilightActions (IList matchingList, out bool noLed, out bool stopTail, out bool setBookmark, out string bookmarkComment) { noLed = stopTail = setBookmark = false; bookmarkComment = string.Empty; @@ -1430,6 +1428,7 @@ private void StopTimestampSyncThread () cts.Cancel(); } + [SupportedOSPlatform("windows")] private void SyncTimestampDisplay () { if (CurrentColumnizer.IsTimeshiftImplemented()) @@ -1441,6 +1440,7 @@ private void SyncTimestampDisplay () } } + [SupportedOSPlatform("windows")] private void SyncTimestampDisplay (int lineNum) { _timeShiftSyncLine = lineNum; @@ -1448,6 +1448,7 @@ private void SyncTimestampDisplay (int lineNum) _timeShiftSyncWakeupEvent.Set(); } + [SupportedOSPlatform("windows")] private void SyncTimestampDisplayWorker () { const int WAIT_TIME = 500; @@ -1532,6 +1533,7 @@ private void SyncTimestampDisplayWorker () } } + [SupportedOSPlatform("windows")] private void SyncFilterGridPos () { try @@ -1570,6 +1572,7 @@ private void StatusLineFileSize (long size) SendStatusLineUpdate(); } + [SupportedOSPlatform("windows")] private int Search (SearchParams searchParams) { if (searchParams.SearchText == null) @@ -1581,7 +1584,7 @@ private int Search (SearchParams searchParams) ? 0 : searchParams.CurrentLine; - var lowerSearchText = searchParams.SearchText.ToLower(); + var lowerSearchText = searchParams.SearchText.ToLowerInvariant(); var count = 0; var hasWrapped = false; @@ -1636,16 +1639,16 @@ private int Search (SearchParams searchParams) } else { - if (!searchParams.IsCaseSensitive) + if (searchParams.IsCaseSensitive) { - if (line.FullLine.Contains(lowerSearchText, StringComparison.CurrentCultureIgnoreCase)) + if (line.FullLine.Contains(searchParams.SearchText, StringComparison.Ordinal)) { return lineNum; } } else { - if (line.FullLine.Contains(searchParams.SearchText)) + if (line.FullLine.Contains(lowerSearchText, StringComparison.OrdinalIgnoreCase)) { return lineNum; } @@ -1690,6 +1693,7 @@ private void ResetProgressBar () SendProgressBarUpdate(); } + [SupportedOSPlatform("windows")] private void SelectLine (int line, bool triggerSyncCall, bool shouldScroll) { try @@ -1738,6 +1742,7 @@ private void SelectLine (int line, bool triggerSyncCall, bool shouldScroll) } } + [SupportedOSPlatform("windows")] private void StartEditMode () { if (!dataGridView.CurrentCell.ReadOnly) @@ -1762,6 +1767,7 @@ private void StartEditMode () } } + [SupportedOSPlatform("windows")] private void UpdateEditColumnDisplay (DataGridViewTextBoxEditingControl editControl) { // prevents key events after edit mode has ended @@ -1773,6 +1779,7 @@ private void UpdateEditColumnDisplay (DataGridViewTextBoxEditingControl editCont } } + [SupportedOSPlatform("windows")] private void SelectPrevHighlightLine () { var lineNum = dataGridView.CurrentCellAddress.Y; @@ -1792,6 +1799,7 @@ private void SelectPrevHighlightLine () } } + [SupportedOSPlatform("windows")] private void SelectNextHighlightLine () { var lineNum = dataGridView.CurrentCellAddress.Y; @@ -1811,6 +1819,7 @@ private void SelectNextHighlightLine () } } + [SupportedOSPlatform("windows")] private int FindNextBookmarkIndex (int lineNum) { if (lineNum >= dataGridView.RowCount) @@ -1825,6 +1834,7 @@ private int FindNextBookmarkIndex (int lineNum) return _bookmarkProvider.FindNextBookmarkIndex(lineNum); } + [SupportedOSPlatform("windows")] private int FindPrevBookmarkIndex (int lineNum) { if (lineNum <= 0) @@ -1876,6 +1886,7 @@ private void ShiftFilterPipes (int offset) } } + [SupportedOSPlatform("windows")] private void LoadFilterPipes () { lock (_filterPipeList) @@ -1906,6 +1917,7 @@ private void DisconnectFilterPipes () } } + [SupportedOSPlatform("windows")] private void ApplyFilterParams () { filterComboBox.Text = _filterParams.SearchText; @@ -1921,6 +1933,7 @@ private void ApplyFilterParams () filterRangeComboBox.Text = _filterParams.RangeSearchText; } + [SupportedOSPlatform("windows")] private void ResetFilterControls () { filterComboBox.Text = ""; @@ -1936,12 +1949,13 @@ private void ResetFilterControls () filterRangeComboBox.Text = ""; } + [SupportedOSPlatform("windows")] private void FilterSearch () { if (filterComboBox.Text.Length == 0) { - _filterParams.SearchText = ""; - _filterParams.LowerSearchText = ""; + _filterParams.SearchText = string.Empty; + _filterParams.LowerSearchText = string.Empty; _filterParams.IsRangeSearch = false; ClearFilterList(); filterSearchButton.Image = null; @@ -1953,23 +1967,24 @@ private void FilterSearch () FilterSearch(filterComboBox.Text); } + [SupportedOSPlatform("windows")] private async void FilterSearch (string text) { FireCancelHandlers(); // make sure that there's no other filter running (maybe from filter restore) _filterParams.SearchText = text; - _filterParams.LowerSearchText = text.ToLower(); - ConfigManager.Settings.filterHistoryList.Remove(text); - ConfigManager.Settings.filterHistoryList.Insert(0, text); - var maxHistory = ConfigManager.Settings.Preferences.maximumFilterEntries; + _filterParams.LowerSearchText = text.ToLowerInvariant(); + ConfigManager.Settings.FilterHistoryList.Remove(text); + ConfigManager.Settings.FilterHistoryList.Insert(0, text); + var maxHistory = ConfigManager.Settings.Preferences.MaximumFilterEntries; - if (ConfigManager.Settings.filterHistoryList.Count > maxHistory) + if (ConfigManager.Settings.FilterHistoryList.Count > maxHistory) { - ConfigManager.Settings.filterHistoryList.RemoveAt(filterComboBox.Items.Count - 1); + ConfigManager.Settings.FilterHistoryList.RemoveAt(filterComboBox.Items.Count - 1); } filterComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.filterHistoryList) + foreach (var item in ConfigManager.Settings.FilterHistoryList) { filterComboBox.Items.Add(item); } @@ -1980,15 +1995,15 @@ private async void FilterSearch (string text) _filterParams.RangeSearchText = filterRangeComboBox.Text; if (_filterParams.IsRangeSearch) { - ConfigManager.Settings.filterRangeHistoryList.Remove(filterRangeComboBox.Text); - ConfigManager.Settings.filterRangeHistoryList.Insert(0, filterRangeComboBox.Text); - if (ConfigManager.Settings.filterRangeHistoryList.Count > maxHistory) + ConfigManager.Settings.FilterRangeHistoryList.Remove(filterRangeComboBox.Text); + ConfigManager.Settings.FilterRangeHistoryList.Insert(0, filterRangeComboBox.Text); + if (ConfigManager.Settings.FilterRangeHistoryList.Count > maxHistory) { - ConfigManager.Settings.filterRangeHistoryList.RemoveAt(filterRangeComboBox.Items.Count - 1); + ConfigManager.Settings.FilterRangeHistoryList.RemoveAt(filterRangeComboBox.Items.Count - 1); } filterRangeComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.filterRangeHistoryList) + foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) { filterRangeComboBox.Items.Add(item); } @@ -2019,7 +2034,7 @@ private async void FilterSearch (string text) _filterParams.ColumnRestrict = columnRestrictCheckBox.Checked; //ConfigManager.SaveFilterParams(this.filterParams); - ConfigManager.Settings.filterParams = _filterParams; // wozu eigentlich? sinnlos seit MDI? + ConfigManager.Settings.FilterParams = _filterParams; // wozu eigentlich? sinnlos seit MDI? _shouldCancel = false; _isSearching = true; @@ -2036,7 +2051,7 @@ private async void FilterSearch (string text) Settings settings = ConfigManager.Settings; //FilterFx fx = settings.preferences.multiThreadFilter ? MultiThreadedFilter : new FilterFx(Filter); - FilterFxAction = settings.Preferences.multiThreadFilter ? MultiThreadedFilter : Filter; + FilterFxAction = settings.Preferences.MultiThreadFilter ? MultiThreadedFilter : Filter; //Task.Run(() => fx.Invoke(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList)); var filterFxActionTask = Task.Run(() => Filter(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList)); @@ -2048,14 +2063,17 @@ private async void FilterSearch (string text) CheckForFilterDirty(); } - private void MultiThreadedFilter (FilterParams filterParams, List filterResultLines, - List lastFilterLinesList, List filterHitList) + private void MultiThreadedFilter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) { ColumnizerCallback callback = new(this); - FilterStarter fs = new(callback, Environment.ProcessorCount + 2); - fs.FilterHitList = _filterHitList; - fs.FilterResultLines = _filterResultList; - fs.LastFilterLinesList = _lastFilterLinesList; + + FilterStarter fs = new(callback, Environment.ProcessorCount + 2) + { + FilterHitList = _filterHitList, + FilterResultLines = _filterResultList, + LastFilterLinesList = _lastFilterLinesList + }; + var cancelHandler = new FilterCancelHandler(fs); OnRegisterCancelHandler(cancelHandler); long startTime = Environment.TickCount; @@ -2064,7 +2082,7 @@ private void MultiThreadedFilter (FilterParams filterParams, List filterRes long endTime = Environment.TickCount; - _logger.Debug("Multi threaded filter duration: {0} ms.", endTime - startTime); + _logger.Debug($"Multi threaded filter duration: {endTime - startTime} ms."); OnDeRegisterCancelHandler(cancelHandler); StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); @@ -2075,8 +2093,8 @@ private void FilterProgressCallback (int lineCount) UpdateProgressBar(lineCount); } - private void Filter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, - List filterHitList) + [SupportedOSPlatform("windows")] + private void Filter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) { long startTime = Environment.TickCount; try @@ -2115,14 +2133,12 @@ private void Filter (FilterParams filterParams, List filterResultLines, Lis catch (Exception ex) { _logger.Error(ex, "Exception while filtering. Please report to developer: "); - MessageBox.Show(null, - "Exception while filtering. Please report to developer: \n\n" + ex + "\n\n" + ex.StackTrace, - "LogExpert"); + MessageBox.Show(null, $"Exception while filtering. Please report to developer: \n\n{ex}\n\n{ex.StackTrace}", "LogExpert"); } long endTime = Environment.TickCount; - _logger.Info("Single threaded filter duration: {0} ms.", endTime - startTime); + _logger.Info($"Single threaded filter duration: {endTime - startTime} ms."); StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); } @@ -2182,8 +2198,8 @@ private IList GetAdditionalFilterResults (FilterParams filterParams, int li return resultList; } - private void AddFilterLine (int lineNum, bool immediate, FilterParams filterParams, List filterResultLines, - List lastFilterLinesList, List filterHitList) + [SupportedOSPlatform("windows")] + private void AddFilterLine (int lineNum, bool immediate, FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) { int count; lock (_filterResultList) @@ -2210,6 +2226,7 @@ private void AddFilterLine (int lineNum, bool immediate, FilterParams filterPara } } + [SupportedOSPlatform("windows")] private void TriggerFilterLineGuiUpdate () { //lock (this.filterUpdateThread) @@ -2272,6 +2289,7 @@ private void TriggerFilterLineGuiUpdate () // this.filterUpdateThread.Join(); //} + [SupportedOSPlatform("windows")] private void AddFilterLineGuiUpdate () { try @@ -2316,6 +2334,7 @@ private void UpdateProgressBar (int value) SendProgressBarUpdate(); } + [SupportedOSPlatform("windows")] private void FilterComplete () { if (!IsDisposed && !_waitingForClose && !Disposing) @@ -2324,6 +2343,7 @@ private void FilterComplete () } } + [SupportedOSPlatform("windows")] private void FilterComplete (IAsyncResult result) { if (!IsDisposed && !_waitingForClose && !Disposing) @@ -2332,6 +2352,7 @@ private void FilterComplete (IAsyncResult result) } } + [SupportedOSPlatform("windows")] private void ResetStatusAfterFilter () { try @@ -2361,6 +2382,7 @@ private void ResetStatusAfterFilter () } } + [SupportedOSPlatform("windows")] private void ClearFilterList () { try @@ -2394,7 +2416,7 @@ private void ClearBookmarkList () /** * Shift filter list line entries after a logfile rollover */ - + [SupportedOSPlatform("windows")] private void ShiftFilterLines (int offset) { List newFilterList = []; @@ -2439,6 +2461,7 @@ private void ShiftFilterLines (int offset) TriggerFilterLineGuiUpdate(); } + [SupportedOSPlatform("windows")] private void CheckForFilterDirty () { if (IsFilterSearchDirty(_filterParams)) @@ -2453,9 +2476,10 @@ private void CheckForFilterDirty () } } + [SupportedOSPlatform("windows")] private bool IsFilterSearchDirty (FilterParams filterParams) { - if (!filterParams.SearchText.Equals(filterComboBox.Text)) + if (!filterParams.SearchText.Equals(filterComboBox.Text, StringComparison.Ordinal)) { return true; } @@ -2465,7 +2489,7 @@ private bool IsFilterSearchDirty (FilterParams filterParams) return true; } - if (filterParams.IsRangeSearch && !filterParams.RangeSearchText.Equals(filterRangeComboBox.Text)) + if (filterParams.IsRangeSearch && !filterParams.RangeSearchText.Equals(filterRangeComboBox.Text, StringComparison.Ordinal)) { return true; } @@ -2508,6 +2532,7 @@ private bool IsFilterSearchDirty (FilterParams filterParams) return false; } + [SupportedOSPlatform("windows")] private void AdjustMinimumGridWith () { if (dataGridView.Columns.Count > 1) @@ -2526,6 +2551,7 @@ private void AdjustMinimumGridWith () } } + [SupportedOSPlatform("windows")] private void InvalidateCurrentRow (BufferedDataGridView gridView) { if (gridView.CurrentCellAddress.Y > -1) @@ -2540,6 +2566,7 @@ private void InvalidateCurrentRow () InvalidateCurrentRow(filterGridView); } + [SupportedOSPlatform("windows")] private void DisplayCurrentFileOnStatusline () { if (_logFileReader.IsMultiFile) @@ -2574,17 +2601,18 @@ private void UpdateSelectionDisplay () } } + [SupportedOSPlatform("windows")] private void UpdateFilterHistoryFromSettings () { - ConfigManager.Settings.filterHistoryList = ConfigManager.Settings.filterHistoryList; + ConfigManager.Settings.FilterHistoryList = ConfigManager.Settings.FilterHistoryList; filterComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.filterHistoryList) + foreach (var item in ConfigManager.Settings.FilterHistoryList) { filterComboBox.Items.Add(item); } filterRangeComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.filterRangeHistoryList) + foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) { filterRangeComboBox.Items.Add(item); } @@ -2623,6 +2651,7 @@ private void SendStatusLineUpdate () OnStatusLine(_statusEventArgs); } + [SupportedOSPlatform("windows")] private void ShowAdvancedFilterPanel (bool show) { if (show) @@ -2641,44 +2670,37 @@ private void ShowAdvancedFilterPanel (bool show) _showAdvanced = show; } + [SupportedOSPlatform("windows")] private void CheckForAdvancedButtonDirty () { - if (IsAdvancedOptionActive() && !_showAdvanced) - { - advancedButton.Image = _advancedButtonImage; - } - else - { - advancedButton.Image = null; - } + advancedButton.Image = IsAdvancedOptionActive() && !_showAdvanced + ? _advancedButtonImage + : null; } + [SupportedOSPlatform("windows")] private void FilterToTab () { filterSearchButton.Enabled = false; Task.Run(() => WriteFilterToTab()); } + [SupportedOSPlatform("windows")] private void WriteFilterToTab () { FilterPipe pipe = new(_filterParams.Clone(), this); lock (_filterResultList) { var namePrefix = "->F"; - string title; - if (IsTempFile) - { - title = TempTitleName + namePrefix + ++_filterPipeNameCounter; - } - else - { - title = Util.GetNameFromPath(FileName) + namePrefix + ++_filterPipeNameCounter; - } + var title = IsTempFile + ? TempTitleName + namePrefix + ++_filterPipeNameCounter + : Util.GetNameFromPath(FileName) + namePrefix + ++_filterPipeNameCounter; WritePipeToTab(pipe, _filterResultList, title, null); } } + [SupportedOSPlatform("windows")] private void WritePipeToTab (FilterPipe pipe, IList lineNumberList, string name, PersistenceData persistenceData) { _logger.Info("WritePipeToTab(): {0} lines.", lineNumberList.Count); @@ -2729,6 +2751,7 @@ private void WritePipeToTab (FilterPipe pipe, IList lineNumberList, string Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), pipe, name, persistenceData); } + [SupportedOSPlatform("windows")] private void WriteFilterToTabFinished (FilterPipe pipe, string name, PersistenceData persistenceData) { _isSearching = false; @@ -2764,25 +2787,29 @@ private void WriteFilterToTabFinished (FilterPipe pipe, string name, Persistence /// /// /// + [SupportedOSPlatform("windows")] internal void WritePipeTab (IList lineEntryList, string title) { - FilterPipe pipe = new(new FilterParams(), this); - pipe.IsStopped = true; + FilterPipe pipe = new(new FilterParams(), this) + { + IsStopped = true + }; pipe.Closed += OnPipeDisconnected; pipe.OpenFile(); foreach (LineEntry entry in lineEntryList) { - pipe.WriteToPipe(entry.logLine, entry.lineNum); + pipe.WriteToPipe(entry.LogLine, entry.LineNum); } pipe.CloseFile(); Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), [pipe, title, null]); } + [SupportedOSPlatform("windows")] private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) { newWin.WaitForLoadingFinished(); - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.columnizerName, + ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); if (columnizer != null) { @@ -2791,12 +2818,13 @@ private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) } else { - _logger.Warn("FilterRestore(): Columnizer {0} not found", persistenceData.columnizerName); + _logger.Warn($"FilterRestore(): Columnizer {persistenceData.ColumnizerName} not found"); } newWin.BeginInvoke(new RestoreFiltersFx(newWin.RestoreFilters), [persistenceData]); } + [SupportedOSPlatform("windows")] private void ProcessFilterPipes (int lineNum) { ILogLine searchLine = _logFileReader.GetLogLine(lineNum); @@ -2805,8 +2833,10 @@ private void ProcessFilterPipes (int lineNum) return; } - ColumnizerCallback callback = new(this); - callback.LineNum = lineNum; + ColumnizerCallback callback = new(this) + { + LineNum = lineNum + }; IList deleteList = []; lock (_filterPipeList) { @@ -2817,7 +2847,7 @@ private void ProcessFilterPipes (int lineNum) continue; } - long startTime = Environment.TickCount; + //long startTime = Environment.TickCount; if (Util.TestFilterCondition(pipe.FilterParams, searchLine, callback)) { IList filterResult = @@ -2842,7 +2872,7 @@ private void ProcessFilterPipes (int lineNum) pipe.CloseFile(); } - long endTime = Environment.TickCount; + //long endTime = Environment.TickCount; //_logger.logDebug("ProcessFilterPipes(" + lineNum + ") duration: " + ((endTime - startTime))); } } @@ -2853,6 +2883,7 @@ private void ProcessFilterPipes (int lineNum) } } + [SupportedOSPlatform("windows")] private void CopyMarkedLinesToClipboard () { if (_guiStateArgs.CellSelectMode) @@ -2902,13 +2933,14 @@ private void SetExplicitEncoding (Encoding encoding) EncodingOptions.Encoding = encoding; } + [SupportedOSPlatform("windows")] private void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, Preferences prefs) { if (dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) > 1) { - if (prefs.setLastColumnWidth) + if (prefs.SetLastColumnWidth) { - dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = prefs.lastColumnWidth; + dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = prefs.LastColumnWidth; } else { @@ -2929,6 +2961,7 @@ private void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, Preferen AutoResizeColumns(dataGridView); } + [SupportedOSPlatform("windows")] private IList GetSelectedContent () { if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) @@ -2954,6 +2987,7 @@ private IList GetSelectedContent () * Timestamp stuff * =======================================================================*/ + [SupportedOSPlatform("windows")] private void SetTimestampLimits () { if (!CurrentColumnizer.IsTimeshiftImplemented()) @@ -2977,10 +3011,13 @@ private void AdjustHighlightSplitterWidth () //this.highlightSplitContainer.SplitterDistance = distance; } + [SupportedOSPlatform("windows")] private void BookmarkComment (Bookmark bookmark) { - BookmarkCommentDlg dlg = new(); - dlg.Comment = bookmark.Text; + BookmarkCommentDlg dlg = new() + { + Comment = bookmark.Text + }; if (dlg.ShowDialog() == DialogResult.OK) { bookmark.Text = dlg.Comment; @@ -2994,6 +3031,7 @@ private void BookmarkComment (Bookmark bookmark) /// /// /// + [SupportedOSPlatform("windows")] private string CalculateColumnNames (FilterParams filter) { var names = string.Empty; @@ -3018,6 +3056,7 @@ private string CalculateColumnNames (FilterParams filter) return names; } + [SupportedOSPlatform("windows")] private void ApplyFrozenState (BufferedDataGridView gridView) { SortedDictionary dict = []; @@ -3037,6 +3076,7 @@ private void ApplyFrozenState (BufferedDataGridView gridView) } } + [SupportedOSPlatform("windows")] private void ShowTimeSpread (bool show) { if (show) @@ -3051,6 +3091,7 @@ private void ShowTimeSpread (bool show) _timeSpreadCalc.Enabled = show; } + [SupportedOSPlatform("windows")] protected internal void AddTempFileTab (string fileName, string title) { _parentLogTabWin.AddTempFileTab(fileName, title); @@ -3062,7 +3103,7 @@ private void InitPatternWindow () _patternWindow = new PatternWindow(this); _patternWindow.SetColumnizer(CurrentColumnizer); //this.patternWindow.SetBlockList(blockList); - _patternWindow.SetFont(Preferences.fontName, Preferences.fontSize); + _patternWindow.SetFont(Preferences.FontName, Preferences.FontSize); _patternWindow.Fuzzy = _patternArgs.Fuzzy; _patternWindow.MaxDiff = _patternArgs.MaxDiffInBlock; _patternWindow.MaxMisses = _patternArgs.MaxMisses; @@ -3070,10 +3111,11 @@ private void InitPatternWindow () //this.patternWindow.Show(); } + [SupportedOSPlatform("windows")] private void TestStatistic (PatternArgs patternArgs) { var beginLine = patternArgs.StartLine; - _logger.Info("TestStatistics() called with start line {0}", beginLine); + _logger.Info($"TestStatistics() called with start line {beginLine}"); _patternArgs = patternArgs; @@ -3115,7 +3157,7 @@ private void TestStatistic (PatternArgs patternArgs) processedLinesDict)) != null) { _logger.Debug("Found block: {0}", block); - if (block.weigth >= _patternArgs.MinWeight) + if (block.Weigth >= _patternArgs.MinWeight) { //PatternBlock existingBlock = FindExistingBlock(block, blockList); //if (existingBlock != null) @@ -3129,18 +3171,18 @@ private void TestStatistic (PatternArgs patternArgs) //else { blockList.Add(block); - addBlockTargetLinesToDict(processedLinesDict, block); + AddBlockTargetLinesToDict(processedLinesDict, block); } - block.blockId = blockId; + block.BlockId = blockId; //if (firstBlock) //{ // addBlockSrcLinesToDict(processedLinesDict, block); //} - searchLine = block.targetEnd + 1; + searchLine = block.TargetEnd + 1; } else { - searchLine = block.targetStart + 1; + searchLine = block.TargetStart + 1; } UpdateProgressBar(searchLine); @@ -3163,14 +3205,11 @@ private void TestStatistic (PatternArgs patternArgs) _logger.Info("TestStatistics() ended"); } - private void addBlockTargetLinesToDict (Dictionary dict, PatternBlock block) + private void AddBlockTargetLinesToDict (Dictionary dict, PatternBlock block) { - foreach (var lineNum in block.targetLines.Keys) + foreach (var lineNum in block.TargetLines.Keys) { - if (!dict.ContainsKey(lineNum)) - { - dict.Add(lineNum, lineNum); - } + _ = dict.TryAdd(lineNum, lineNum); } } @@ -3179,12 +3218,10 @@ private PatternBlock FindExistingBlock (PatternBlock block, List b { foreach (PatternBlock searchBlock in blockList) { - if ((block.startLine > searchBlock.startLine && - block.startLine < searchBlock.endLine - || - block.endLine > searchBlock.startLine && - block.endLine < searchBlock.endLine) && block.startLine != searchBlock.startLine && - block.endLine != searchBlock.endLine + if (((block.StartLine > searchBlock.StartLine && block.StartLine < searchBlock.EndLine) || + (block.EndLine > searchBlock.StartLine && block.EndLine < searchBlock.EndLine)) && + block.StartLine != searchBlock.StartLine && + block.EndLine != searchBlock.EndLine ) { return searchBlock; @@ -3194,8 +3231,7 @@ private PatternBlock FindExistingBlock (PatternBlock block, List b return null; } - private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBlockLen, int maxDiffInBlock, - int maxMisses, Dictionary processedLinesDict) + private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBlockLen, int maxDiffInBlock, int maxMisses, Dictionary processedLinesDict) { var targetLine = FindSimilarLine(startNum, startLineToSearch, processedLinesDict); if (targetLine == -1) @@ -3203,17 +3239,21 @@ private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBl return null; } - PatternBlock block = new(); - block.startLine = startNum; - var srcLine = block.startLine; - block.targetStart = targetLine; + PatternBlock block = new() + { + StartLine = startNum + }; + var srcLine = block.StartLine; + block.TargetStart = targetLine; var srcMisses = 0; - block.srcLines.Add(srcLine, srcLine); + block.SrcLines.Add(srcLine, srcLine); //block.targetLines.Add(targetLine, targetLine); var len = 0; - QualityInfo qi = new(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; + QualityInfo qi = new() + { + Quality = block.Weigth + }; + block.QualityInfoList[targetLine] = qi; while (!_shouldCancel) { @@ -3229,34 +3269,40 @@ private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBl var nextTargetLine = FindSimilarLine(srcLine, targetLine + 1, processedLinesDict); if (nextTargetLine > -1 && nextTargetLine - targetLine - 1 <= maxDiffInBlock) { - block.weigth += maxDiffInBlock - (nextTargetLine - targetLine - 1) + 1; - block.endLine = srcLine; + block.Weigth += maxDiffInBlock - (nextTargetLine - targetLine - 1) + 1; + block.EndLine = srcLine; //block.targetLines.Add(nextTargetLine, nextTargetLine); - block.srcLines.Add(srcLine, srcLine); + block.SrcLines.Add(srcLine, srcLine); if (nextTargetLine - targetLine > 1) { - var tempWeight = block.weigth; + var tempWeight = block.Weigth; for (var tl = targetLine + 1; tl < nextTargetLine; ++tl) { - qi = new QualityInfo(); - qi.quality = --tempWeight; - block.qualityInfoList[tl] = qi; + qi = new QualityInfo + { + Quality = --tempWeight + }; + block.QualityInfoList[tl] = qi; } } targetLine = nextTargetLine; - qi = new QualityInfo(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; + qi = new QualityInfo + { + Quality = block.Weigth + }; + block.QualityInfoList[targetLine] = qi; } else { srcMisses++; - block.weigth--; + block.Weigth--; targetLine++; - qi = new QualityInfo(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; + qi = new QualityInfo + { + Quality = block.Weigth + }; + block.QualityInfoList[targetLine] = qi; if (srcMisses > maxMisses) { break; @@ -3264,13 +3310,17 @@ private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBl } } - block.targetEnd = targetLine; - qi = new QualityInfo(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; - for (var k = block.targetStart; k <= block.targetEnd; ++k) + block.TargetEnd = targetLine; + qi = new QualityInfo { - block.targetLines.Add(k, k); + Quality = block.Weigth + }; + + block.QualityInfoList[targetLine] = qi; + + for (var k = block.TargetStart; k <= block.TargetEnd; ++k) + { + block.TargetLines.Add(k, k); } return block; @@ -3288,7 +3338,7 @@ private void PrepareDict () var msg = GetMsgForLine(i); if (msg != null) { - msg = msg.ToLower(); + msg = msg.ToLowerInvariant(); msg = regex.Replace(msg, "0"); msg = regex2.Replace(msg, " "); var chars = msg.ToCharArray(); @@ -3321,7 +3371,7 @@ private void PrepareDict () } } - private int _FindSimilarLine (int srcLine, int startLine) + private int FindSimilarLine (int srcLine, int startLine) { var value = _lineHashList[srcLine]; @@ -3424,6 +3474,7 @@ private string GetMsgForLine (int i) return cols.ColumnValues.Last().FullValue; } + [SupportedOSPlatform("windows")] private void ChangeRowHeight (bool decrease) { var rowNum = dataGridView.CurrentCellAddress.Y; @@ -3434,13 +3485,12 @@ private void ChangeRowHeight (bool decrease) if (decrease) { - if (!_rowHeightList.ContainsKey(rowNum)) + if (!_rowHeightList.TryGetValue(rowNum, out RowHeightEntry? entry)) { return; } else { - RowHeightEntry entry = _rowHeightList[rowNum]; entry.Height -= _lineHeight; if (entry.Height <= _lineHeight) { @@ -3451,16 +3501,19 @@ private void ChangeRowHeight (bool decrease) else { RowHeightEntry entry; - if (!_rowHeightList.ContainsKey(rowNum)) + if (!_rowHeightList.TryGetValue(rowNum, out RowHeightEntry? value)) { - entry = new RowHeightEntry(); - entry.LineNum = rowNum; - entry.Height = _lineHeight; + entry = new RowHeightEntry + { + LineNum = rowNum, + Height = _lineHeight + }; + _rowHeightList[rowNum] = entry; } else { - entry = _rowHeightList[rowNum]; + entry = value; } entry.Height += _lineHeight; @@ -3477,14 +3530,9 @@ private void ChangeRowHeight (bool decrease) private int GetRowHeight (int rowNum) { - if (_rowHeightList.ContainsKey(rowNum)) - { - return _rowHeightList[rowNum].Height; - } - else - { - return _lineHeight; - } + return _rowHeightList.TryGetValue(rowNum, out RowHeightEntry? value) + ? value.Height + : _lineHeight; } private void AddBookmarkAtLineSilently (int lineNum) @@ -3495,6 +3543,7 @@ private void AddBookmarkAtLineSilently (int lineNum) } } + [SupportedOSPlatform("windows")] private void AddBookmarkAndEditComment () { var lineNum = dataGridView.CurrentCellAddress.Y; @@ -3506,6 +3555,7 @@ private void AddBookmarkAndEditComment () BookmarkComment(_bookmarkProvider.GetBookmarkForLine(lineNum)); } + [SupportedOSPlatform("windows")] private void AddBookmarkComment (string text) { var lineNum = dataGridView.CurrentCellAddress.Y; @@ -3525,6 +3575,7 @@ private void AddBookmarkComment (string text) OnBookmarkTextChanged(bookmark); } + [SupportedOSPlatform("windows")] private void MarkCurrentFilterRange () { _filterParams.RangeSearchText = filterRangeComboBox.Text; @@ -3545,6 +3596,7 @@ private void MarkCurrentFilterRange () } } + [SupportedOSPlatform("windows")] private void RemoveTempHighlights () { lock (_tempHighlightEntryListLock) @@ -3555,6 +3607,7 @@ private void RemoveTempHighlights () RefreshAllGrids(); } + [SupportedOSPlatform("windows")] private void ToggleHighlightPanel (bool open) { highlightSplitContainer.Panel2Collapsed = !open; @@ -3563,6 +3616,7 @@ private void ToggleHighlightPanel (bool open) : new Bitmap(_panelOpenButtonImage, new Size(btnToggleHighlightPanel.Size.Height, btnToggleHighlightPanel.Size.Height)); } + [SupportedOSPlatform("windows")] private void SetBookmarksForSelectedFilterLines () { lock (_filterResultList) @@ -3592,10 +3646,11 @@ private void SetDefaultHighlightGroup () } } + [SupportedOSPlatform("windows")] private void HandleChangedFilterOnLoadSetting () { - _parentLogTabWin.Preferences.isFilterOnLoad = filterOnLoadCheckBox.Checked; - _parentLogTabWin.Preferences.isAutoHideFilterList = hideFilterListOnLoadCheckBox.Checked; + _parentLogTabWin.Preferences.IsFilterOnLoad = filterOnLoadCheckBox.Checked; + _parentLogTabWin.Preferences.IsAutoHideFilterList = hideFilterListOnLoadCheckBox.Checked; OnFilterListChanged(this); } @@ -3603,7 +3658,7 @@ private void FireCancelHandlers () { lock (_cancelHandlerList) { - foreach (var handler in _cancelHandlerList) + foreach (Core.Interface.IBackgroundProcessCancelHandler handler in _cancelHandlerList) { handler.EscapePressed(); } @@ -3618,6 +3673,7 @@ private void SyncOtherWindows (DateTime timestamp) } } + [SupportedOSPlatform("windows")] private void AddSlaveToTimesync (LogWindow slave) { lock (_timeSyncListLock) @@ -3660,6 +3716,7 @@ private void OnSyncModeChanged () SyncModeChanged?.Invoke(this, new SyncModeEventArgs(IsTimeSynced)); } + [SupportedOSPlatform("windows")] private void AddSearchHitHighlightEntry (SearchParams para) { HighlightEntry he = new() @@ -3686,6 +3743,7 @@ private void AddSearchHitHighlightEntry (SearchParams para) RefreshAllGrids(); } + [SupportedOSPlatform("windows")] private void RemoveAllSearchHighlightEntries () { lock (_tempHighlightEntryListLock) @@ -3705,11 +3763,12 @@ private void RemoveAllSearchHighlightEntries () RefreshAllGrids(); } + [SupportedOSPlatform("windows")] private DataGridViewColumn GetColumnByName (BufferedDataGridView dataGridView, string name) { foreach (DataGridViewColumn col in dataGridView.Columns) { - if (col.HeaderText.Equals(name)) + if (col.HeaderText.Equals(name, StringComparison.Ordinal)) { return col; } @@ -3718,6 +3777,7 @@ private DataGridViewColumn GetColumnByName (BufferedDataGridView dataGridView, s return null; } + [SupportedOSPlatform("windows")] private void SelectColumn () { var colName = columnComboBox.SelectedItem as string; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs index 20e1451e..7b3ae108 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs @@ -1,6 +1,5 @@ -using System.Text; +using System.Text; -using LogExpert.Classes.Filter; using LogExpert.Core.Classes; using LogExpert.Core.Classes.Bookmark; using LogExpert.Core.Classes.Columnizer; @@ -79,9 +78,9 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) try { - _logFileReader = new(fileName, EncodingOptions, IsMultiFile, Preferences.bufferCount, Preferences.linesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) + _logFileReader = new(fileName, EncodingOptions, IsMultiFile, Preferences.BufferCount, Preferences.LinesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) { - UseNewReader = !Preferences.useLegacyReader + UseNewReader = !Preferences.UseLegacyReader }; } catch (LogFileException lfe) @@ -119,7 +118,7 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) if (isUsingDefaultColumnizer) { - if (Preferences.autoPick) + if (Preferences.AutoPick) { ILogLineColumnizer newColumnizer = ColumnizerPicker.FindBetterColumnizer(FileName, _logFileReader, CurrentColumnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); @@ -154,9 +153,9 @@ public void LoadFilesAsMulti (string[] fileNames, EncodingOptions encodingOption EncodingOptions = encodingOptions; _columnCache = new ColumnCache(); - _logFileReader = new(fileNames, EncodingOptions, Preferences.bufferCount, Preferences.linesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) + _logFileReader = new(fileNames, EncodingOptions, Preferences.BufferCount, Preferences.LinesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) { - UseNewReader = !Preferences.useLegacyReader + UseNewReader = !Preferences.UseLegacyReader }; RegisterLogFileReaderEvents(); @@ -174,7 +173,7 @@ public string SavePersistenceData (bool force) { if (!force) { - if (!Preferences.saveSessions) + if (!Preferences.SaveSessions) { return null; } @@ -212,30 +211,30 @@ public PersistenceData GetPersistenceData () { PersistenceData persistenceData = new() { - bookmarkList = _bookmarkProvider.BookmarkList, - rowHeightList = _rowHeightList, - multiFile = IsMultiFile, - multiFilePattern = _multiFileOptions.FormatPattern, - multiFileMaxDays = _multiFileOptions.MaxDayTry, - currentLine = dataGridView.CurrentCellAddress.Y, - firstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex, - filterVisible = !splitContainerLogWindow.Panel2Collapsed, - filterAdvanced = !advancedFilterSplitContainer.Panel1Collapsed, - filterPosition = splitContainerLogWindow.SplitterDistance, - followTail = _guiStateArgs.FollowTail, - fileName = FileName, - tabName = Text, - sessionFileName = SessionFileName, - columnizerName = CurrentColumnizer.GetName(), - lineCount = _logFileReader.LineCount + BookmarkList = _bookmarkProvider.BookmarkList, + RowHeightList = _rowHeightList, + MultiFile = IsMultiFile, + MultiFilePattern = _multiFileOptions.FormatPattern, + MultiFileMaxDays = _multiFileOptions.MaxDayTry, + CurrentLine = dataGridView.CurrentCellAddress.Y, + FirstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex, + FilterVisible = !splitContainerLogWindow.Panel2Collapsed, + FilterAdvanced = !advancedFilterSplitContainer.Panel1Collapsed, + FilterPosition = splitContainerLogWindow.SplitterDistance, + FollowTail = _guiStateArgs.FollowTail, + FileName = FileName, + TabName = Text, + SessionFileName = SessionFileName, + ColumnizerName = CurrentColumnizer.GetName(), + LineCount = _logFileReader.LineCount }; _filterParams.IsFilterTail = filterTailCheckBox.Checked; // this option doesnt need a press on 'search' - if (Preferences.saveFilters) + if (Preferences.SaveFilters) { List filterList = [_filterParams]; - persistenceData.filterParamsList = filterList; + persistenceData.FilterParamsList = filterList; foreach (FilterPipe filterPipe in _filterPipeList) { @@ -244,30 +243,30 @@ public PersistenceData GetPersistenceData () PersistenceData = filterPipe.OwnLogWindow.GetPersistenceData(), FilterParams = filterPipe.FilterParams }; - persistenceData.filterTabDataList.Add(data); + persistenceData.FilterTabDataList.Add(data); } } if (_currentHighlightGroup != null) { - persistenceData.highlightGroupName = _currentHighlightGroup.GroupName; + persistenceData.HighlightGroupName = _currentHighlightGroup.GroupName; } if (_fileNames != null && IsMultiFile) { - persistenceData.multiFileNames.AddRange(_fileNames); + persistenceData.MultiFileNames.AddRange(_fileNames); } //persistenceData.showBookmarkCommentColumn = this.bookmarkWindow.ShowBookmarkCommentColumn; - persistenceData.filterSaveListVisible = !highlightSplitContainer.Panel2Collapsed; - persistenceData.encoding = _logFileReader.CurrentEncoding; + persistenceData.FilterSaveListVisible = !highlightSplitContainer.Panel2Collapsed; + persistenceData.Encoding = _logFileReader.CurrentEncoding; return persistenceData; } public void Close (bool dontAsk) { - Preferences.askForClose = !dontAsk; + Preferences.AskForClose = !dontAsk; Close(); } @@ -487,7 +486,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV Alignment = StringAlignment.Center }; Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - Font font = new("Courier New", Preferences.fontSize, FontStyle.Bold); + Font font = new("Courier New", Preferences.FontSize, FontStyle.Bold); e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); font.Dispose(); @@ -1138,7 +1137,7 @@ public void LogWindowActivated () { OnTailFollowed(EventArgs.Empty); } - if (Preferences.timestampControl) + if (Preferences.TimestampControl) { SetTimestampLimits(); SyncTimestampDisplay(); @@ -1265,9 +1264,9 @@ public void PreferencesChanged (Preferences newPreferences, bool isLoadTime, Set { if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) { - NormalFont = new Font(new FontFamily(newPreferences.fontName), newPreferences.fontSize); + NormalFont = new Font(new FontFamily(newPreferences.FontName), newPreferences.FontSize); BoldFont = new Font(NormalFont, FontStyle.Bold); - MonospacedFont = new Font("Courier New", Preferences.fontSize, FontStyle.Bold); + MonospacedFont = new Font("Courier New", Preferences.FontSize, FontStyle.Bold); var lineSpacing = NormalFont.FontFamily.GetLineSpacing(FontStyle.Regular); var lineSpacingPixel = NormalFont.Size * lineSpacing / NormalFont.FontFamily.GetEmHeight(FontStyle.Regular); @@ -1277,32 +1276,32 @@ public void PreferencesChanged (Preferences newPreferences, bool isLoadTime, Set _lineHeight = NormalFont.Height + 4; dataGridView.RowTemplate.Height = NormalFont.Height + 4; - ShowBookmarkBubbles = Preferences.showBubbles; + ShowBookmarkBubbles = Preferences.ShowBubbles; ApplyDataGridViewPrefs(dataGridView, newPreferences); ApplyDataGridViewPrefs(filterGridView, newPreferences); - if (Preferences.timestampControl) + if (Preferences.TimestampControl) { SetTimestampLimits(); SyncTimestampDisplay(); } if (isLoadTime) { - filterTailCheckBox.Checked = Preferences.filterTail; - syncFilterCheckBox.Checked = Preferences.filterSync; + filterTailCheckBox.Checked = Preferences.FilterTail; + syncFilterCheckBox.Checked = Preferences.FilterSync; //this.FollowTailChanged(this.Preferences.followTail, false); } - _timeSpreadCalc.TimeMode = Preferences.timeSpreadTimeMode; - timeSpreadingControl.ForeColor = Preferences.timeSpreadColor; - timeSpreadingControl.ReverseAlpha = Preferences.reverseAlpha; + _timeSpreadCalc.TimeMode = Preferences.TimeSpreadTimeMode; + timeSpreadingControl.ForeColor = Preferences.TimeSpreadColor; + timeSpreadingControl.ReverseAlpha = Preferences.ReverseAlpha; if (CurrentColumnizer.IsTimeshiftImplemented()) { timeSpreadingControl.Invoke(new MethodInvoker(timeSpreadingControl.Refresh)); - ShowTimeSpread(Preferences.showTimeSpread); + ShowTimeSpread(Preferences.ShowTimeSpread); } - ToggleColumnFinder(Preferences.showColumnFinder, false); + ToggleColumnFinder(Preferences.ShowColumnFinder, false); } if ((flags & SettingsFlags.FilterList) == SettingsFlags.FilterList) @@ -1739,7 +1738,7 @@ public void HandleChangedFilterListWorker () { var index = filterListBox.SelectedIndex; filterListBox.Items.Clear(); - foreach (FilterParams filterParam in ConfigManager.Settings.filterList) + foreach (FilterParams filterParam in ConfigManager.Settings.FilterList) { filterListBox.Items.Add(filterParam); } @@ -1748,8 +1747,8 @@ public void HandleChangedFilterListWorker () { filterListBox.SelectedIndex = index; } - filterOnLoadCheckBox.Checked = Preferences.isFilterOnLoad; - hideFilterListOnLoadCheckBox.Checked = Preferences.isAutoHideFilterList; + filterOnLoadCheckBox.Checked = Preferences.IsFilterOnLoad; + hideFilterListOnLoadCheckBox.Checked = Preferences.IsAutoHideFilterList; } public void SetCurrentHighlightGroup (string groupName) diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs index d7d9ae3b..84614aef 100644 --- a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs @@ -1,36 +1,35 @@ -using LogExpert.Core.Classes; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes; using LogExpert.Core.EventArguments; using LogExpert.Dialogs; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; namespace LogExpert.UI.Controls.LogWindow; +[SupportedOSPlatform("windows")] internal partial class PatternWindow : Form //TODO: Can this be changed to UserControl? { #region Fields - private readonly List> blockList = []; - private PatternBlock currentBlock; - private List currentList; + private readonly List> _blockList = []; + private PatternBlock _currentBlock; + private List _currentList; - private readonly LogWindow logWindow; - private PatternArgs patternArgs = new(); + private readonly LogWindow _logWindow; + private PatternArgs _patternArgs = new(); #endregion #region cTor - public PatternWindow() + public PatternWindow () { InitializeComponent(); } - public PatternWindow(LogWindow logWindow) + public PatternWindow (LogWindow logWindow) { - this.logWindow = logWindow; + this._logWindow = logWindow; InitializeComponent(); recalcButton.Enabled = false; } @@ -67,10 +66,10 @@ public int Weight #region Public methods - public void SetBlockList(List flatBlockList, PatternArgs patternArgs) + public void SetBlockList (List flatBlockList, PatternArgs patternArgs) { - this.patternArgs = patternArgs; - blockList.Clear(); + this._patternArgs = patternArgs; + _blockList.Clear(); List singeList = []; //int blockId = -1; for (var i = 0; i < flatBlockList.Count; ++i) @@ -94,15 +93,15 @@ public void SetBlockList(List flatBlockList, PatternArgs patternAr // singeList.Add(block); //} } - blockList.Add(singeList); + _blockList.Add(singeList); Invoke(new MethodInvoker(SetBlockListGuiStuff)); } - public void SetColumnizer(ILogLineColumnizer columnizer) + public void SetColumnizer (ILogLineColumnizer columnizer) { - logWindow.SetColumnizer(columnizer, patternHitsDataGridView); - logWindow.SetColumnizer(columnizer, contentDataGridView); + _logWindow.SetColumnizer(columnizer, patternHitsDataGridView); + _logWindow.SetColumnizer(columnizer, contentDataGridView); patternHitsDataGridView.Columns[0].Width = 20; contentDataGridView.Columns[0].Width = 20; @@ -126,7 +125,7 @@ public void SetColumnizer(ILogLineColumnizer columnizer) contentDataGridView.Columns.Insert(1, contentInfoColumn); } - public void SetFont(string fontName, float fontSize) + public void SetFont (string fontName, float fontSize) { Font font = new(new FontFamily(fontName), fontSize); var lineSpacing = font.FontFamily.GetLineSpacing(FontStyle.Regular); @@ -143,7 +142,7 @@ public void SetFont(string fontName, float fontSize) #region Private Methods - private void SetBlockListGuiStuff() + private void SetBlockListGuiStuff () { patternHitsDataGridView.RowCount = 0; blockCountLabel.Text = "0"; @@ -151,32 +150,32 @@ private void SetBlockListGuiStuff() blockLinesLabel.Text = "0"; recalcButton.Enabled = true; setRangeButton.Enabled = true; - if (blockList.Count > 0) + if (_blockList.Count > 0) { - SetCurrentList(blockList[0]); + SetCurrentList(_blockList[0]); } } - private void SetCurrentList(List patternList) + private void SetCurrentList (List patternList) { patternHitsDataGridView.RowCount = 0; - currentList = patternList; - patternHitsDataGridView.RowCount = currentList.Count; + _currentList = patternList; + patternHitsDataGridView.RowCount = _currentList.Count; patternHitsDataGridView.Refresh(); - blockCountLabel.Text = "" + currentList.Count; + blockCountLabel.Text = "" + _currentList.Count; } - private int GetLineForHitGrid(int rowIndex) + private int GetLineForHitGrid (int rowIndex) { int line; - line = currentList[rowIndex].targetStart; + line = _currentList[rowIndex].TargetStart; return line; } - private int GetLineForContentGrid(int rowIndex) + private int GetLineForContentGrid (int rowIndex) { int line; - line = currentBlock.targetStart + rowIndex; + line = _currentBlock.TargetStart + rowIndex; return line; } @@ -184,9 +183,9 @@ private int GetLineForContentGrid(int rowIndex) #region Events handler - private void patternHitsDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) + private void patternHitsDataGridView_CellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { - if (currentList == null || e.RowIndex < 0) + if (_currentList == null || e.RowIndex < 0) { return; } @@ -194,7 +193,7 @@ private void patternHitsDataGridView_CellValueNeeded(object sender, DataGridView var colIndex = e.ColumnIndex; if (colIndex == 1) { - e.Value = currentList[e.RowIndex].weigth; + e.Value = _currentList[e.RowIndex].Weigth; } else { @@ -202,21 +201,23 @@ private void patternHitsDataGridView_CellValueNeeded(object sender, DataGridView { colIndex--; // correct the additional inserted col } - e.Value = logWindow.GetCellValue(rowIndex, colIndex); + + e.Value = _logWindow.GetCellValue(rowIndex, colIndex); } } - private void patternHitsDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) + private void patternHitsDataGridView_CellPainting (object sender, DataGridViewCellPaintingEventArgs e) { - if (currentList == null || e.RowIndex < 0) + if (_currentList == null || e.RowIndex < 0) { return; } + if (e.ColumnIndex == 1) { e.PaintBackground(e.CellBounds, false); - var selCount = patternArgs.EndLine - patternArgs.StartLine; - var maxWeight = patternArgs.MaxDiffInBlock * selCount + selCount; + var selCount = _patternArgs.EndLine - _patternArgs.StartLine; + var maxWeight = _patternArgs.MaxDiffInBlock * selCount + selCount; if (maxWeight > 0) { var width = (int)((int)e.Value / (double)maxWeight * e.CellBounds.Width); @@ -235,11 +236,11 @@ private void patternHitsDataGridView_CellPainting(object sender, DataGridViewCel { var gridView = (BufferedDataGridView)sender; var rowIndex = GetLineForHitGrid(e.RowIndex); - logWindow.CellPainting(gridView, rowIndex, e); + _logWindow.CellPainting(gridView, rowIndex, e); } } - private void patternHitsDataGridView_MouseDoubleClick(object sender, MouseEventArgs e) + private void patternHitsDataGridView_MouseDoubleClick (object sender, MouseEventArgs e) { //if (this.currentList == null || patternHitsDataGridView.CurrentRow == null) // return; @@ -248,27 +249,29 @@ private void patternHitsDataGridView_MouseDoubleClick(object sender, MouseEventA //this.logWindow.SelectLogLine(rowIndex); } - private void patternHitsDataGridView_CurrentCellChanged(object sender, EventArgs e) + private void patternHitsDataGridView_CurrentCellChanged (object sender, EventArgs e) { - if (currentList == null || patternHitsDataGridView.CurrentRow == null) + if (_currentList == null || patternHitsDataGridView.CurrentRow == null) { return; } - if (patternHitsDataGridView.CurrentRow.Index > currentList.Count - 1) + + if (patternHitsDataGridView.CurrentRow.Index > _currentList.Count - 1) { return; } + contentDataGridView.RowCount = 0; - currentBlock = currentList[patternHitsDataGridView.CurrentRow.Index]; - contentDataGridView.RowCount = currentBlock.targetEnd - currentBlock.targetStart + 1; + _currentBlock = _currentList[patternHitsDataGridView.CurrentRow.Index]; + contentDataGridView.RowCount = _currentBlock.TargetEnd - _currentBlock.TargetStart + 1; contentDataGridView.Refresh(); contentDataGridView.CurrentCell = contentDataGridView.Rows[0].Cells[0]; blockLinesLabel.Text = "" + contentDataGridView.RowCount; } - private void contentDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) + private void contentDataGridView_CellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { - if (currentBlock == null || e.RowIndex < 0) + if (_currentBlock == null || e.RowIndex < 0) { return; } @@ -277,9 +280,9 @@ private void contentDataGridView_CellValueNeeded(object sender, DataGridViewCell if (colIndex == 1) { QualityInfo qi; - if (currentBlock.qualityInfoList.TryGetValue(rowIndex, out qi)) + if (_currentBlock.QualityInfoList.TryGetValue(rowIndex, out qi)) { - e.Value = qi.quality; + e.Value = qi.Quality; } else { @@ -292,67 +295,67 @@ private void contentDataGridView_CellValueNeeded(object sender, DataGridViewCell { colIndex--; // adjust the inserted column } - e.Value = logWindow.GetCellValue(rowIndex, colIndex); + e.Value = _logWindow.GetCellValue(rowIndex, colIndex); } } - private void contentDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) + private void contentDataGridView_CellPainting (object sender, DataGridViewCellPaintingEventArgs e) { - if (currentBlock == null || e.RowIndex < 0) + if (_currentBlock == null || e.RowIndex < 0) { return; } var gridView = (BufferedDataGridView)sender; var rowIndex = GetLineForContentGrid(e.RowIndex); - logWindow.CellPainting(gridView, rowIndex, e); + _logWindow.CellPainting(gridView, rowIndex, e); } - private void contentDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) + private void contentDataGridView_CellMouseDoubleClick (object sender, DataGridViewCellMouseEventArgs e) { - if (currentBlock == null || contentDataGridView.CurrentRow == null) + if (_currentBlock == null || contentDataGridView.CurrentRow == null) { return; } var rowIndex = GetLineForContentGrid(contentDataGridView.CurrentRow.Index); - logWindow.SelectLogLine(rowIndex); + _logWindow.SelectLogLine(rowIndex); } - private void recalcButton_Click(object sender, EventArgs e) + private void recalcButton_Click (object sender, EventArgs e) { - patternArgs.Fuzzy = fuzzyKnobControl.Value; - patternArgs.MaxDiffInBlock = maxDiffKnobControl.Value; - patternArgs.MaxMisses = maxMissesKnobControl.Value; - patternArgs.MinWeight = weigthKnobControl.Value; - logWindow.PatternStatistic(patternArgs); + _patternArgs.Fuzzy = fuzzyKnobControl.Value; + _patternArgs.MaxDiffInBlock = maxDiffKnobControl.Value; + _patternArgs.MaxMisses = maxMissesKnobControl.Value; + _patternArgs.MinWeight = weigthKnobControl.Value; + _logWindow.PatternStatistic(_patternArgs); recalcButton.Enabled = false; setRangeButton.Enabled = false; } - private void closeButton_Click(object sender, EventArgs e) + private void closeButton_Click (object sender, EventArgs e) { Close(); } - private void contentDataGridView_ColumnDividerDoubleClick(object sender, + private void contentDataGridView_ColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { e.Handled = true; contentDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } - private void patternHitsDataGridView_ColumnDividerDoubleClick(object sender, + private void patternHitsDataGridView_ColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { e.Handled = true; patternHitsDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } - private void setRangeButton_Click(object sender, EventArgs e) + private void setRangeButton_Click (object sender, EventArgs e) { - logWindow.PatternStatisticSelectRange(patternArgs); + _logWindow.PatternStatisticSelectRange(_patternArgs); recalcButton.Enabled = true; - rangeLabel.Text = "Start: " + patternArgs.StartLine + "\r\nEnd: " + patternArgs.EndLine; + rangeLabel.Text = "Start: " + _patternArgs.StartLine + "\r\nEnd: " + _patternArgs.EndLine; } #endregion diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs index 952136e7..c65bc9a9 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs @@ -1,10 +1,14 @@ -using LogExpert.Core.Classes; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes; using LogExpert.Core.EventArguments; using LogExpert.UI.Extensions; + using NLog; namespace LogExpert.UI.Controls.LogWindow; +[SupportedOSPlatform("windows")] internal partial class TimeSpreadingControl : UserControl { private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); @@ -25,7 +29,7 @@ internal partial class TimeSpreadingControl : UserControl #region cTor - public TimeSpreadingControl() + public TimeSpreadingControl () { InitializeComponent(); _toolTip = new ToolTip(); @@ -40,7 +44,7 @@ public TimeSpreadingControl() #region Delegates - public delegate void LineSelectedEventHandler(object sender, SelectLineEventArgs e); + public delegate void LineSelectedEventHandler (object sender, SelectLineEventArgs e); #endregion @@ -70,7 +74,7 @@ internal TimeSpreadCalculator TimeSpreadCalc #region Overrides - protected override void OnPaint(PaintEventArgs e) + protected override void OnPaint (PaintEventArgs e) { base.OnPaint(e); lock (_monitor) @@ -94,7 +98,7 @@ protected override void OnPaint(PaintEventArgs e) #region Private Methods - private SpreadEntry GetEntryForMouse(MouseEventArgs e) + private SpreadEntry GetEntryForMouse (MouseEventArgs e) { List list = TimeSpreadCalc.DiffList; var y = e.Y - _edgeOffset; @@ -113,26 +117,25 @@ private SpreadEntry GetEntryForMouse(MouseEventArgs e) lock (_monitor) { - if (y >= list.Count || y < 0) - { - return null; - } - return list[y]; + return y >= list.Count || y < 0 + ? null + : list[y]; } } - private void DragContrast(MouseEventArgs e) + private void DragContrast (MouseEventArgs e) { if (_lastMouseY == 0) { _lastMouseY = _lastMouseY = e.Y; return; } + _timeSpreadCalc.Contrast += (_lastMouseY - e.Y) * 5; _lastMouseY = e.Y; } - private void OnLineSelected(SelectLineEventArgs e) + private void OnLineSelected (SelectLineEventArgs e) { LineSelected?.Invoke(this, e); } @@ -141,7 +144,7 @@ private void OnLineSelected(SelectLineEventArgs e) #region Events handler - private void TimeSpreadCalc_CalcDone(object sender, EventArgs e) + private void TimeSpreadCalc_CalcDone (object sender, EventArgs e) { _logger.Debug("timeSpreadCalc_CalcDone()"); @@ -203,10 +206,11 @@ private void TimeSpreadCalc_CalcDone(object sender, EventArgs e) } } } + BeginInvoke(new MethodInvoker(Refresh)); } - private void TimeSpreadCalc_StartCalc(object sender, EventArgs e) + private void TimeSpreadCalc_StartCalc (object sender, EventArgs e) { lock (_monitor) { @@ -241,7 +245,7 @@ private void TimeSpreadCalc_StartCalc(object sender, EventArgs e) BeginInvoke(new MethodInvoker(Refresh)); } - private void TimeSpreadingControl_SizeChanged(object sender, EventArgs e) + private void TimeSpreadingControl_SizeChanged (object sender, EventArgs e) { if (TimeSpreadCalc != null) { @@ -250,11 +254,11 @@ private void TimeSpreadingControl_SizeChanged(object sender, EventArgs e) } } - private void TimeSpreadingControl_MouseDown(object sender, MouseEventArgs e) + private void TimeSpreadingControl_MouseDown (object sender, MouseEventArgs e) { } - private void TimeSpreadingControl_MouseUp(object sender, MouseEventArgs e) + private void TimeSpreadingControl_MouseUp (object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { @@ -263,21 +267,22 @@ private void TimeSpreadingControl_MouseUp(object sender, MouseEventArgs e) { return; } + OnLineSelected(new SelectLineEventArgs(entry.LineNum)); } } - private void TimeSpreadingControl_MouseEnter(object sender, EventArgs e) + private void TimeSpreadingControl_MouseEnter (object sender, EventArgs e) { _toolTip.Active = true; } - private void TimeSpreadingControl_MouseLeave(object sender, EventArgs e) + private void TimeSpreadingControl_MouseLeave (object sender, EventArgs e) { _toolTip.Active = false; } - private void TimeSpreadingControl_MouseMove(object sender, MouseEventArgs e) + private void TimeSpreadingControl_MouseMove (object sender, MouseEventArgs e) { if (e.Y == _lastMouseY) { @@ -296,6 +301,7 @@ private void TimeSpreadingControl_MouseMove(object sender, MouseEventArgs e) { return; } + _lastMouseY = e.Y; var dts = entry.Timestamp.ToString("dd.MM.yyyy HH:mm:ss"); _toolTip.SetToolTip(this, "Line " + (entry.LineNum + 1) + "\n" + dts); diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs index bb5ac3c1..5cf5a90c 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs @@ -1,3 +1,5 @@ +using System.Runtime.Versioning; + namespace LogExpert.UI.Controls.LogWindow; /// @@ -7,7 +9,7 @@ public class TimeSyncList { #region Fields - private readonly IList logWindowList = new List(); + private readonly IList logWindowList = []; #endregion @@ -27,12 +29,14 @@ public class TimeSyncList public DateTime CurrentTimestamp { get; set; } + [SupportedOSPlatform("windows")] public int Count => logWindowList.Count; #endregion #region Public methods + [SupportedOSPlatform("windows")] public void AddWindow (LogWindow logWindow) { lock (logWindowList) @@ -44,7 +48,7 @@ public void AddWindow (LogWindow logWindow) } } - + [SupportedOSPlatform("windows")] public void RemoveWindow (LogWindow logWindow) { lock (logWindowList) @@ -61,6 +65,7 @@ public void RemoveWindow (LogWindow logWindow) /// /// /// + [SupportedOSPlatform("windows")] public void NavigateToTimestamp (DateTime timestamp, LogWindow sender) { CurrentTimestamp = timestamp; @@ -76,7 +81,7 @@ public void NavigateToTimestamp (DateTime timestamp, LogWindow sender) } } - + [SupportedOSPlatform("windows")] public bool Contains (LogWindow logWindow) { return logWindowList.Contains(logWindow); diff --git a/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs b/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs index 717d3e00..3c046848 100644 --- a/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs +++ b/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs @@ -1,23 +1,24 @@ -using System.Windows.Forms; +using System.Runtime.Versioning; namespace LogExpert.Dialogs; +[SupportedOSPlatform("windows")] public partial class AllowOnlyOneInstanceErrorDialog : Form { public bool DoNotShowThisMessageAgain { get; private set; } - public AllowOnlyOneInstanceErrorDialog() + public AllowOnlyOneInstanceErrorDialog () { InitializeComponent(); SetText(); } - private void SetText() + private void SetText () { labelErrorText.Text = @"Only one instance allowed, uncheck ""View Settings => Allow only 1 Instances"" to start multiple instances!"; } - private void OnButtonOkClick(object sender, System.EventArgs e) + private void OnButtonOkClick (object sender, System.EventArgs e) { DoNotShowThisMessageAgain = checkBoxIgnoreMessage.Checked; } diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 6853a51e..0ee8d848 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -1,3 +1,5 @@ +using System.Runtime.Versioning; + using LogExpert.Core.Config; using LogExpert.Core.Entities; using LogExpert.Core.Enums; @@ -13,6 +15,7 @@ namespace LogExpert.Dialogs; //TODO can be moved to Logexpert.UI if the PaintHelper has been refactored +[SupportedOSPlatform("windows")] public partial class BookmarkWindow : DockContent, ISharedToolWindow, IBookmarkView { #region Fields @@ -198,11 +201,11 @@ public void PreferencesChanged (Preferences newPreferences, bool isLoadTime, Set { if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) { - SetFont(newPreferences.fontName, newPreferences.fontSize); - if (bookmarkDataGridView.Columns.Count > 1 && newPreferences.setLastColumnWidth) + SetFont(newPreferences.FontName, newPreferences.FontSize); + if (bookmarkDataGridView.Columns.Count > 1 && newPreferences.SetLastColumnWidth) { bookmarkDataGridView.Columns[bookmarkDataGridView.Columns.Count - 1].MinimumWidth = - newPreferences.lastColumnWidth; + newPreferences.LastColumnWidth; } PaintHelper.ApplyDataGridViewPrefs(bookmarkDataGridView, newPreferences, configManager); diff --git a/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs b/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs index 16698f1b..da5350c8 100644 --- a/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs +++ b/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs @@ -1,16 +1,15 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; using System.Net.Sockets; using System.Runtime.Serialization; using System.Runtime.Versioning; + //using System.Windows.Forms; using System.Xml; +using Newtonsoft.Json; + //TODO: This whole Eminus folder is not in use. Can be deleted? What is it? //[assembly: SupportedOSPlatform("windows")] -namespace LogExpert; +namespace LogExpert.UI.Dialogs.Eminus; internal class Eminus : IContextMenuEntry, ILogExpertPluginConfigurator { @@ -35,7 +34,8 @@ internal class Eminus : IContextMenuEntry, ILogExpertPluginConfigurator #region Private Methods - private XmlDocument BuildParam(ILogLine line) + [SupportedOSPlatform("windows")] + private XmlDocument BuildParam (ILogLine line) { var fullLogLine = line.FullLine; // no Java stacktrace but some special logging of our applications at work: @@ -127,13 +127,14 @@ private XmlDocument BuildParam(ILogLine line) return null; } - private XmlDocument BuildXmlDocument(string className, string lineNum) + [SupportedOSPlatform("windows")] + private XmlDocument BuildXmlDocument (string className, string lineNum) { XmlDocument xmlDoc = new(); xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); XmlElement rootElement = xmlDoc.CreateElement("eminus"); xmlDoc.AppendChild(rootElement); - rootElement.SetAttribute("authKey", _config.password); + rootElement.SetAttribute("authKey", _config.Password); XmlElement loadElement = xmlDoc.CreateElement("loadclass"); loadElement.SetAttribute("mode", "dialog"); @@ -152,30 +153,27 @@ private XmlDocument BuildXmlDocument(string className, string lineNum) #region IContextMenuEntry Member - public string GetMenuText(IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) + public string GetMenuText (IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) { //not used return string.Empty; } - public string GetMenuText(int logLinesCount, ILogLineColumnizer columnizer, ILogLine logline) + [SupportedOSPlatform("windows")] + public string GetMenuText (int logLinesCount, ILogLineColumnizer columnizer, ILogLine logline) { - if (logLinesCount == 1 && BuildParam(logline) != null) - { - return "Load class in Eclipse"; - } - else - { - return $"{DISABLED}Load class in Eclipse"; - } + return logLinesCount == 1 && BuildParam(logline) != null + ? "Load class in Eclipse" + : $"{DISABLED}Load class in Eclipse"; } - public void MenuSelected(IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) + public void MenuSelected (IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) { //Not used } - public void MenuSelected(int logLinesCount, ILogLineColumnizer columnizer, ILogLine logline) + [SupportedOSPlatform("windows")] + public void MenuSelected (int logLinesCount, ILogLineColumnizer columnizer, ILogLine logline) { if (logLinesCount != 1) { @@ -192,7 +190,7 @@ public void MenuSelected(int logLinesCount, ILogLineColumnizer columnizer, ILogL { try { - TcpClient client = new(_config.host, _config.port); + TcpClient client = new(_config.Host, _config.Port); NetworkStream stream = client.GetStream(); StreamWriter writer = new(stream); doc.Save(writer); @@ -213,7 +211,8 @@ public void MenuSelected(int logLinesCount, ILogLineColumnizer columnizer, ILogL #region ILogExpertPluginConfigurator Member - public void LoadConfig(string configDir) + [SupportedOSPlatform("windows")] + public void LoadConfig (string configDir) { var configPath = configDir + CFG_FILE_NAME; @@ -237,8 +236,8 @@ public void LoadConfig(string configDir) } } - - public void SaveConfig(string configDir) + [SupportedOSPlatform("windows")] + public void SaveConfig (string configDir) { FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + CFG_FILE_NAME); @@ -251,12 +250,13 @@ public void SaveConfig(string configDir) serializer.Serialize(sw, _config); } - public bool HasEmbeddedForm() + public bool HasEmbeddedForm () { return true; } - public void ShowConfigForm(object panel) + [SupportedOSPlatform("windows")] + public void ShowConfigForm (object panel) { dlg = new EminusConfigDlg(tmpConfig) { @@ -270,7 +270,8 @@ public void ShowConfigForm(object panel) /// is pressed (HasEmbeddedForm() must return false for this). /// /// - public void ShowConfigDialog(object owner) + [SupportedOSPlatform("windows")] + public void ShowConfigDialog (object owner) { dlg = new EminusConfigDlg(tmpConfig) { @@ -282,8 +283,8 @@ public void ShowConfigDialog(object owner) dlg.ApplyChanges(); } - - public void HideConfigForm() + [SupportedOSPlatform("windows")] + public void HideConfigForm () { if (dlg != null) { @@ -294,7 +295,7 @@ public void HideConfigForm() } } - public void StartConfig() + public void StartConfig () { tmpConfig = _config.Clone(); } diff --git a/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs b/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs index 444e9dd8..12bda818 100644 --- a/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs +++ b/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs @@ -1,27 +1,23 @@ -using System; - -namespace LogExpert; +namespace LogExpert.UI.Dialogs.Eminus; [Serializable] internal class EminusConfig { - #region Fields + public string Host { get; set; } = "127.0.0.1"; - public string host = "127.0.0.1"; - public string password = ""; - public int port = 12345; + public string Password { get; set; } = string.Empty; - #endregion + public int Port { get; set; } = 12345; #region Public methods - public EminusConfig Clone() + public EminusConfig Clone () { EminusConfig config = new() { - host = host, - port = port, - password = password + Host = Host, + Port = Port, + Password = Password }; return config; } diff --git a/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs index 8b43c982..841a340a 100644 --- a/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs +++ b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs @@ -1,9 +1,10 @@ -using System; -using System.Drawing; -using System.Windows.Forms; +using System.Runtime.Versioning; + +using LogExpert.UI.Dialogs.Eminus; namespace LogExpert; +[SupportedOSPlatform("windows")] internal partial class EminusConfigDlg : Form { #region Fields @@ -12,7 +13,7 @@ internal partial class EminusConfigDlg : Form #region cTor - public EminusConfigDlg(EminusConfig config) + public EminusConfigDlg (EminusConfig config) { SuspendLayout(); @@ -24,9 +25,9 @@ public EminusConfigDlg(EminusConfig config) TopLevel = false; Config = config; - hostTextBox.Text = config.host; - portTextBox.Text = string.Empty + config.port; - passwordTextBox.Text = config.password; + hostTextBox.Text = config.Host; + portTextBox.Text = string.Empty + config.Port; + passwordTextBox.Text = config.Password; ResumeLayout(); } @@ -41,18 +42,19 @@ public EminusConfigDlg(EminusConfig config) #region Public methods - public void ApplyChanges() + public void ApplyChanges () { - Config.host = hostTextBox.Text; + Config.Host = hostTextBox.Text; try { - Config.port = short.Parse(portTextBox.Text); + Config.Port = short.Parse(portTextBox.Text); } catch (FormatException) { - Config.port = 0; + Config.Port = 0; } - Config.password = passwordTextBox.Text; + + Config.Password = passwordTextBox.Text; } #endregion diff --git a/src/LogExpert.UI/Dialogs/ExceptionWindow.cs b/src/LogExpert.UI/Dialogs/ExceptionWindow.cs index 2ab0adb5..486f68b0 100644 --- a/src/LogExpert.UI/Dialogs/ExceptionWindow.cs +++ b/src/LogExpert.UI/Dialogs/ExceptionWindow.cs @@ -1,5 +1,8 @@ -namespace LogExpert.UI.Dialogs; +using System.Runtime.Versioning; +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] public partial class ExceptionWindow : Form { #region Fields @@ -12,9 +15,9 @@ public partial class ExceptionWindow : Form #region cTor - //TODO: for HighDPI SuspendLayout() before InitializeComponent() and then ResumeLayout() as last command in the CTOR can help in complex forms to reduce flickering and miscalculations. Also, it is a good practice. - public ExceptionWindow(string errorText, string stackTrace) + public ExceptionWindow (string errorText, string stackTrace) { + SuspendLayout(); InitializeComponent(); AutoScaleDimensions = new SizeF(96F, 96F); @@ -25,13 +28,14 @@ public ExceptionWindow(string errorText, string stackTrace) stackTraceTextBox.Text = _errorText + @"\n\n" + _stackTrace; stackTraceTextBox.Select(0, 0); + ResumeLayout(); } #endregion #region Private Methods - private void CopyToClipboard() + private void CopyToClipboard () { Clipboard.SetText(_errorText + @"\n\n" + _stackTrace); } @@ -40,7 +44,7 @@ private void CopyToClipboard() #region Events handler - private void copyButton_Click(object sender, EventArgs e) + private void copyButton_Click (object sender, EventArgs e) { CopyToClipboard(); } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs index a23c253a..7fc01ba0 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs @@ -1,11 +1,10 @@ -using LogExpert.Core.Interface; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; +using System.Runtime.Versioning; + +using LogExpert.Core.Interface; namespace LogExpert.Dialogs; +[SupportedOSPlatform("windows")] internal partial class FilterSelectorForm : Form //TODO: Can this be changed to UserControl? { #region Fields @@ -17,7 +16,7 @@ internal partial class FilterSelectorForm : Form //TODO: Can this be changed to #region cTor - public FilterSelectorForm(IList existingColumnizerList, ILogLineColumnizer currentColumnizer, ILogLineColumnizerCallback callback, IConfigManager configManager) + public FilterSelectorForm (IList existingColumnizerList, ILogLineColumnizer currentColumnizer, ILogLineColumnizerCallback callback, IConfigManager configManager) { SelectedColumnizer = currentColumnizer; _callback = callback; @@ -34,7 +33,7 @@ public FilterSelectorForm(IList existingColumnizerList, ILog // columnizer registry. This ensures that changes made in columnizer config dialogs // will apply to the current instance _columnizerList = new List(); - + foreach (ILogLineColumnizer col in existingColumnizerList) { _columnizerList.Add(col.GetType() == SelectedColumnizer.GetType() ? SelectedColumnizer : col); @@ -70,7 +69,7 @@ public FilterSelectorForm(IList existingColumnizerList, ILog #region Events handler - private void OnFilterComboBoxSelectedIndexChanged(object sender, EventArgs e) + private void OnFilterComboBoxSelectedIndexChanged (object sender, EventArgs e) { ILogLineColumnizer col = _columnizerList[filterComboBox.SelectedIndex]; SelectedColumnizer = col; @@ -82,7 +81,7 @@ private void OnFilterComboBoxSelectedIndexChanged(object sender, EventArgs e) //TODO: Check if this logic can be remoed from this class and remove all the config manager instances from here. - private void OnConfigButtonClick(object sender, EventArgs e) + private void OnConfigButtonClick (object sender, EventArgs e) { if (SelectedColumnizer is IColumnizerConfigurator configurator) { diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs index 1b7a06a0..8a150e27 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs @@ -1,4 +1,7 @@ -using LogExpert.Core.Classes.Highlight; +using System.Runtime.Versioning; +using System.Text.RegularExpressions; + +using LogExpert.Core.Classes.Highlight; using LogExpert.Core.Entities; using LogExpert.Core.Interface; using LogExpert.UI.Controls; @@ -6,16 +9,9 @@ using NLog; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Windows.Forms; - namespace LogExpert.Dialogs; +[SupportedOSPlatform("windows")] public partial class HighlightDialog : Form { private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); @@ -32,7 +28,7 @@ public partial class HighlightDialog : Form #region Ctor - public HighlightDialog(IConfigManager configManager) + public HighlightDialog (IConfigManager configManager) { InitializeComponent(); @@ -75,18 +71,18 @@ public List HighlightGroupList #region Event handling Methods - private void OnAddButtonClick(object sender, EventArgs e) + private void OnAddButtonClick (object sender, EventArgs e) { AddNewEntry(); Dirty(); } - private void OnBtnApplyClick(object sender, EventArgs e) + private void OnBtnApplyClick (object sender, EventArgs e) { SaveEntry(); } - private void OnBtnBookmarkCommentClick(object sender, EventArgs e) + private void OnBtnBookmarkCommentClick (object sender, EventArgs e) { BookmarkCommentDlg dlg = new(); dlg.Comment = _bookmarkComment; @@ -97,7 +93,7 @@ private void OnBtnBookmarkCommentClick(object sender, EventArgs e) } } - private void OnBtnCopyGroupClick(object sender, EventArgs e) + private void OnBtnCopyGroupClick (object sender, EventArgs e) { if (comboBoxGroups.SelectedIndex >= 0 && comboBoxGroups.SelectedIndex < HighlightGroupList.Count) { @@ -110,19 +106,19 @@ private void OnBtnCopyGroupClick(object sender, EventArgs e) } } - private void OnBtnCustomBackColorClick(object sender, EventArgs e) + private void OnBtnCustomBackColorClick (object sender, EventArgs e) { ChooseColor(colorBoxBackground); Dirty(); } - private void OnBtnCustomForeColorClick(object sender, EventArgs e) + private void OnBtnCustomForeColorClick (object sender, EventArgs e) { ChooseColor(colorBoxForeground); Dirty(); } - private void OnBtnDelGroupClick(object sender, EventArgs e) + private void OnBtnDelGroupClick (object sender, EventArgs e) { // the last group cannot be deleted if (HighlightGroupList.Count == 1) @@ -147,7 +143,7 @@ private void OnBtnDelGroupClick(object sender, EventArgs e) } //TODO: This class should not knoow ConfigManager? - private void OnBtnExportGroupClick(object sender, EventArgs e) + private void OnBtnExportGroupClick (object sender, EventArgs e) { SaveFileDialog dlg = new() { @@ -164,7 +160,7 @@ private void OnBtnExportGroupClick(object sender, EventArgs e) } } - private void OnBtnGroupDownClick(object sender, EventArgs e) + private void OnBtnGroupDownClick (object sender, EventArgs e) { var index = comboBoxGroups.SelectedIndex; if (index > -1 && index < _highlightGroupList.Count - 1) @@ -176,7 +172,7 @@ private void OnBtnGroupDownClick(object sender, EventArgs e) } } - private void OnBtnGroupUpClick(object sender, EventArgs e) + private void OnBtnGroupUpClick (object sender, EventArgs e) { var index = comboBoxGroups.SelectedIndex; if (index > 0) @@ -188,7 +184,7 @@ private void OnBtnGroupUpClick(object sender, EventArgs e) } } - private void OnBtnImportGroupClick(object sender, EventArgs e) + private void OnBtnImportGroupClick (object sender, EventArgs e) { ImportSettingsDialog dlg = new(Core.Config.ExportImportFlags.HighlightSettings); @@ -238,7 +234,7 @@ private void OnBtnImportGroupClick(object sender, EventArgs e) MessageBox.Show(this, @"Settings imported", @"LogExpert"); } - private void OnBtnMoveDownClick(object sender, EventArgs e) + private void OnBtnMoveDownClick (object sender, EventArgs e) { var index = listBoxHighlight.SelectedIndex; @@ -252,7 +248,7 @@ private void OnBtnMoveDownClick(object sender, EventArgs e) } } - private void OnBtnMoveUpClick(object sender, EventArgs e) + private void OnBtnMoveUpClick (object sender, EventArgs e) { var index = listBoxHighlight.SelectedIndex; if (index > 0) @@ -265,7 +261,7 @@ private void OnBtnMoveUpClick(object sender, EventArgs e) } } - private void OnBtnNewGroupClick(object sender, EventArgs e) + private void OnBtnNewGroupClick (object sender, EventArgs e) { // Propose a unique name const string baseName = "New group"; @@ -274,7 +270,8 @@ private void OnBtnNewGroupClick(object sender, EventArgs e) var i = 1; while (!uniqueName) { - uniqueName = HighlightGroupList.FindIndex(delegate (HighlightGroup g) { return g.GroupName == name; }) < 0; + uniqueName = HighlightGroupList.FindIndex(delegate (HighlightGroup g) + { return g.GroupName == name; }) < 0; if (!uniqueName) { @@ -288,7 +285,7 @@ private void OnBtnNewGroupClick(object sender, EventArgs e) SelectGroup(HighlightGroupList.Count - 1); } - private void OnBtnOkClick(object sender, EventArgs e) + private void OnBtnOkClick (object sender, EventArgs e) { // Apply pending changes if closing the form. if (IsDirty) @@ -298,25 +295,25 @@ private void OnBtnOkClick(object sender, EventArgs e) } } - private void OnChkBoxBoldCheckedChanged(object sender, EventArgs e) + private void OnChkBoxBoldCheckedChanged (object sender, EventArgs e) { Dirty(); } - private void OnChkBoxNoBackgroundCheckedChanged(object sender, EventArgs e) + private void OnChkBoxNoBackgroundCheckedChanged (object sender, EventArgs e) { colorBoxBackground.Enabled = !checkBoxNoBackground.Checked; btnCustomBackColor.Enabled = !checkBoxNoBackground.Checked; Dirty(); } - private void OnChkBoxPluginCheckedChanged(object sender, EventArgs e) + private void OnChkBoxPluginCheckedChanged (object sender, EventArgs e) { Dirty(); btnSelectPlugin.Enabled = checkBoxPlugin.Checked; } - private void OnChkBoxRegexMouseUp(object sender, MouseEventArgs e) + private void OnChkBoxRegexMouseUp (object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { @@ -335,13 +332,13 @@ private void OnChkBoxRegexMouseUp(object sender, MouseEventArgs e) } } - private void OnChkBoxWordMatchCheckedChanged(object sender, EventArgs e) + private void OnChkBoxWordMatchCheckedChanged (object sender, EventArgs e) { Dirty(); checkBoxNoBackground.Enabled = checkBoxWordMatch.Checked; } - private void OnCmbBoxGroupDrawItem(object sender, DrawItemEventArgs e) + private void OnCmbBoxGroupDrawItem (object sender, DrawItemEventArgs e) { e.DrawBackground(); if (e.Index >= 0) @@ -356,17 +353,17 @@ private void OnCmbBoxGroupDrawItem(object sender, DrawItemEventArgs e) } } - private void OnCmbBoxGroupSelectionChangeCommitted(object sender, EventArgs e) + private void OnCmbBoxGroupSelectionChangeCommitted (object sender, EventArgs e) { SelectGroup(comboBoxGroups.SelectedIndex); } - private void OnCmbBoxGroupTextUpdate(object sender, EventArgs e) + private void OnCmbBoxGroupTextUpdate (object sender, EventArgs e) { _currentGroup.GroupName = comboBoxGroups.Text; } - private void OnDeleteButtonClick(object sender, EventArgs e) + private void OnDeleteButtonClick (object sender, EventArgs e) { if (listBoxHighlight.SelectedIndex >= 0) { @@ -390,7 +387,7 @@ private void OnDeleteButtonClick(object sender, EventArgs e) } } - private void OnHighlightDialogLoad(object sender, EventArgs e) + private void OnHighlightDialogLoad (object sender, EventArgs e) { colorBoxForeground.SelectedIndex = 1; colorBoxBackground.SelectedIndex = 2; @@ -402,12 +399,12 @@ private void OnHighlightDialogLoad(object sender, EventArgs e) ReEvaluateHighlightButtonStates(); } - private void OnHighlightDialogShown(object sender, EventArgs e) + private void OnHighlightDialogShown (object sender, EventArgs e) { InitData(); } - private void OnHighlightListBoxDrawItem(object sender, DrawItemEventArgs e) + private void OnHighlightListBoxDrawItem (object sender, DrawItemEventArgs e) { e.DrawBackground(); if (e.Index >= 0) @@ -427,12 +424,12 @@ private void OnHighlightListBoxDrawItem(object sender, DrawItemEventArgs e) } } - private void OnListBoxHighlightSelectedIndexChanged(object sender, EventArgs e) + private void OnListBoxHighlightSelectedIndexChanged (object sender, EventArgs e) { StartEditEntry(); } - private void OnPluginButtonClick(object sender, EventArgs e) + private void OnPluginButtonClick (object sender, EventArgs e) { KeywordActionDlg dlg = new(_currentActionEntry, KeywordActionList); @@ -447,7 +444,7 @@ private void OnPluginButtonClick(object sender, EventArgs e) #region Private Methods - private void AddNewEntry() + private void AddNewEntry () { { try @@ -485,12 +482,12 @@ private void AddNewEntry() } } - private void ChangeToDirty(object sender, EventArgs e) + private void ChangeToDirty (object sender, EventArgs e) { Dirty(); } - private void CheckRegex() + private void CheckRegex () { if (checkBoxRegex.Checked) { @@ -504,7 +501,7 @@ private void CheckRegex() } } - private void ChooseColor(ColorComboBox comboBox) + private void ChooseColor (ColorComboBox comboBox) { ColorDialog colorDialog = new(); colorDialog.AllowFullOpen = true; @@ -517,7 +514,7 @@ private void ChooseColor(ColorComboBox comboBox) } } - private void Dirty() + private void Dirty () { var index = listBoxHighlight.SelectedIndex; if (index > -1) @@ -529,7 +526,7 @@ private void Dirty() btnAdd.Enabled = textBoxSearchString.Text.Length > 0; } - private void FillGroupComboBox() + private void FillGroupComboBox () { SelectGroup(-1); @@ -543,7 +540,7 @@ private void FillGroupComboBox() ReEvaluateGroupButtonStates(); } - private void FillHighlightListBox() + private void FillHighlightListBox () { listBoxHighlight.Items.Clear(); if (_currentGroup != null) @@ -555,7 +552,7 @@ private void FillHighlightListBox() } } - private void InitData() + private void InitData () { const string def = "[Default]"; HighlightGroupList ??= []; @@ -582,7 +579,7 @@ private void InitData() foreach (HighlightGroup group in HighlightGroupList) { - if (group.GroupName.Equals(groupToSelect)) + if (group.GroupName.Equals(groupToSelect, StringComparison.Ordinal)) { _currentGroup = group; comboBoxGroups.SelectedValue = group; @@ -596,7 +593,7 @@ private void InitData() FillHighlightListBox(); } - private void ReEvaluateGroupButtonStates() + private void ReEvaluateGroupButtonStates () { // Refresh button states based on the selection in the combobox var atLeastOneSelected = comboBoxGroups.SelectedItem != null; @@ -610,7 +607,7 @@ private void ReEvaluateGroupButtonStates() btnMoveGroupDown.Enabled = atLeastOneSelected && moreThanOne && !lastSelected; } - private void ReEvaluateHighlightButtonStates() + private void ReEvaluateHighlightButtonStates () { // Refresh button states based on the selection in the combobox var atLeastOneSelected = listBoxHighlight.SelectedItem != null; @@ -623,7 +620,7 @@ private void ReEvaluateHighlightButtonStates() btnMoveDown.Enabled = atLeastOneSelected && moreThanOne && !lastSelected; } - private void SaveEntry() + private void SaveEntry () { try { @@ -656,7 +653,7 @@ private void SaveEntry() } } - private void SelectGroup(int index) + private void SelectGroup (int index) { if (index >= 0 && index < HighlightGroupList.Count) { @@ -677,7 +674,7 @@ private void SelectGroup(int index) ReEvaluateGroupButtonStates(); } - private void StartEditEntry() + private void StartEditEntry () { var entry = (HighlightEntry)listBoxHighlight.SelectedItem; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index 55e54962..254707aa 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -1,4 +1,5 @@ using System.Reflection; +using System.Runtime.Versioning; using System.Text; using LogExpert.Core.Config; @@ -14,6 +15,7 @@ namespace LogExpert.UI.Controls.LogTabWindow; // Data shared over all LogTabWindow instances //TODO: Can we get rid of this class? +[SupportedOSPlatform("windows")] public partial class LogTabWindow : Form, ILogTabWindow { #region Fields @@ -22,7 +24,7 @@ public partial class LogTabWindow : Form, ILogTabWindow private const int MAX_COLOR_HISTORY = 40; private const int DIFF_MAX = 100; private const int MAX_FILE_HISTORY = 10; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly Icon _deadIcon; private readonly Color _defaultTabColor = Color.FromArgb(255, 192, 192, 192); @@ -34,7 +36,7 @@ public partial class LogTabWindow : Form, ILogTabWindow private readonly Rectangle[] _leds = new Rectangle[5]; - private readonly IList _logWindowList = new List(); + private readonly IList _logWindowList = []; private readonly Brush _offLedBrush; private readonly bool _showInstanceNumbers; @@ -43,7 +45,10 @@ public partial class LogTabWindow : Form, ILogTabWindow private readonly EventWaitHandle _statusLineEventHandle = new AutoResetEvent(false); private readonly EventWaitHandle _statusLineEventWakeupHandle = new ManualResetEvent(false); private readonly Brush _syncLedBrush; + + [SupportedOSPlatform("windows")] private readonly StringFormat _tabStringFormat = new(); + private readonly Brush[] _tailLedBrush = new Brush[3]; private BookmarkWindow _bookmarkWindow; @@ -64,6 +69,8 @@ public partial class LogTabWindow : Form, ILogTabWindow #endregion #region cTor + + [SupportedOSPlatform("windows")] public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNumbers, IConfigManager configManager) { AutoScaleDimensions = new SizeF(96F, 96F); @@ -158,9 +165,11 @@ public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNu #endregion #region ColorTheme + + [SupportedOSPlatform("windows")] public void ChangeTheme (Control.ControlCollection container) { - ColorMode.LoadColorMode(ConfigManager.Settings.Preferences.darkMode); + ColorMode.LoadColorMode(ConfigManager.Settings.Preferences.DarkMode); Win32.UseImmersiveDarkMode(Handle, ColorMode.DarkModeEnabled); #region ApplyColorToAllControls @@ -189,7 +198,7 @@ public void ChangeTheme (Control.ControlCollection container) { for (var x = 0; x < item.DropDownItems.Count; x++) { - var children = item.DropDownItems[x]; + ToolStripItem children = item.DropDownItems[x]; children.ForeColor = ColorMode.ForeColor; children.BackColor = ColorMode.MenuBackgroundColor; @@ -197,7 +206,7 @@ public void ChangeTheme (Control.ControlCollection container) { for (var y = 0; y < toolstripDropDownItem.DropDownItems.Count; y++) { - var subChildren = toolstripDropDownItem.DropDownItems[y]; + ToolStripItem subChildren = toolstripDropDownItem.DropDownItems[y]; subChildren.ForeColor = ColorMode.ForeColor; subChildren.BackColor = ColorMode.MenuBackgroundColor; } @@ -228,7 +237,7 @@ public void ChangeTheme (Control.ControlCollection container) // Tabs menu for (var y = 0; y < tabContextMenuStrip.Items.Count; y++) { - var item = tabContextMenuStrip.Items[y]; + ToolStripItem item = tabContextMenuStrip.Items[y]; item.ForeColor = ColorMode.ForeColor; item.BackColor = ColorMode.MenuBackgroundColor; } @@ -284,6 +293,7 @@ public void ChangeTheme (Control.ControlCollection container) #region Properties + [SupportedOSPlatform("windows")] public LogWindow.LogWindow CurrentLogWindow { get => _currentLogWindow; @@ -314,11 +324,12 @@ internal HighlightGroup FindHighlightGroup (string groupName) { foreach (HighlightGroup group in HighlightGroupList) { - if (group.GroupName.Equals(groupName)) + if (group.GroupName.Equals(groupName, StringComparison.Ordinal)) { return group; } } + return null; } } @@ -330,13 +341,28 @@ private class LogWindowData #region Fields // public MdiTabControl.TabPage tabPage; - public Color color = Color.FromKnownColor(KnownColor.Gray); - public int diffSum; - public bool dirty; - public int syncMode; // 0 = off, 1 = timeSynced - public int tailState; // tailState: 0,1,2 = on/off/off by Trigger - public ToolTip toolTip; + public Color Color { get; set; } = Color.FromKnownColor(KnownColor.Gray); + + public int DiffSum { get; set; } + + public bool Dirty { get; set; } + + // tailState: + /// + /// 0 = on

+ /// 1 = off

+ /// 2 = off by Trigger

+ ///
+ public int TailState { get; set; } + + public ToolTip ToolTip { get; set; } + + /// + /// 0 = off

+ /// 1 = timeSynced + ///
+ public int SyncMode { get; set; } #endregion } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index 034172db..3cb32910 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -1,5 +1,6 @@ using System.ComponentModel; using System.Diagnostics; +using System.Runtime.Versioning; using System.Text; using LogExpert.Core.Classes; @@ -8,8 +9,8 @@ using LogExpert.Core.Entities; using LogExpert.Core.EventArguments; using LogExpert.Dialogs; +using LogExpert.UI.Controls.LogWindow; using LogExpert.UI.Dialogs; -using LogExpert.UI.Dialogs.LogTabWindow; using WeifenLuo.WinFormsUI.Docking; @@ -27,23 +28,23 @@ private void OnBookmarkWindowVisibleChanged (object sender, EventArgs e) private void OnLogTabWindowLoad (object sender, EventArgs e) { ApplySettings(ConfigManager.Settings, SettingsFlags.All); - if (ConfigManager.Settings.isMaximized) + if (ConfigManager.Settings.IsMaximized) { - Bounds = ConfigManager.Settings.appBoundsFullscreen; + Bounds = ConfigManager.Settings.AppBoundsFullscreen; WindowState = FormWindowState.Maximized; - Bounds = ConfigManager.Settings.appBounds; + Bounds = ConfigManager.Settings.AppBounds; } else { - if (ConfigManager.Settings.appBounds.Right > 0) + if (ConfigManager.Settings.AppBounds.Right > 0) { - Bounds = ConfigManager.Settings.appBounds; + Bounds = ConfigManager.Settings.AppBounds; } } - if (ConfigManager.Settings.Preferences.openLastFiles && _startupFileNames == null) + if (ConfigManager.Settings.Preferences.OpenLastFiles && _startupFileNames == null) { - List tmpList = ObjectClone.Clone(ConfigManager.Settings.lastOpenFilesList); + List tmpList = ObjectClone.Clone(ConfigManager.Settings.LastOpenFilesList); foreach (var name in tmpList) { @@ -78,7 +79,7 @@ private void OnLogTabWindowClosing (object sender, CancelEventArgs e) _ledThread.Join(); IList deleteLogWindowList = new List(); - ConfigManager.Settings.alwaysOnTop = TopMost && ConfigManager.Settings.Preferences.allowOnlyOneInstance; + ConfigManager.Settings.AlwaysOnTop = TopMost && ConfigManager.Settings.Preferences.AllowOnlyOneInstance; SaveLastOpenFilesList(); foreach (LogWindow.LogWindow logWindow in _logWindowList) @@ -294,6 +295,7 @@ private void OnLogWindowDragDrop (object sender, DragEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnTimeShiftToolStripMenuItemCheckStateChanged (object sender, EventArgs e) { if (!_skipEvents && CurrentLogWindow != null) @@ -305,6 +307,7 @@ private void OnTimeShiftToolStripMenuItemCheckStateChanged (object sender, Event } } + [SupportedOSPlatform("windows")] private void OnAboutToolStripMenuItemClick (object sender, EventArgs e) { AboutBox aboutBox = new(); @@ -317,12 +320,14 @@ private void OnFilterToolStripMenuItemClick (object sender, EventArgs e) CurrentLogWindow?.ToggleFilterPanel(); } + [SupportedOSPlatform("windows")] private void OnMultiFileToolStripMenuItemClick (object sender, EventArgs e) { ToggleMultiFile(); fileToolStripMenuItem.HideDropDown(); } + [SupportedOSPlatform("windows")] private void OnGuiStateUpdate (object sender, GuiStateArgs e) { BeginInvoke(GuiStateUpdateWorker, e); @@ -384,6 +389,7 @@ private void OnCloseFileToolStripMenuItemClick (object sender, EventArgs e) CurrentLogWindow?.Close(); } + [SupportedOSPlatform("windows")] private void OnCellSelectModeToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.SetCellSelectionMode(cellSelectModeToolStripMenuItem.Checked); @@ -408,6 +414,7 @@ private void OnTimeShiftMenuTextBoxKeyDown (object sender, KeyEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnAlwaysOnTopToolStripMenuItemClick (object sender, EventArgs e) { TopMost = alwaysOnTopToolStripMenuItem.Checked; @@ -427,19 +434,19 @@ private void OnFileSizeChanged (object sender, LogEventArgs e) { lock (data) { - data.diffSum += diff; - if (data.diffSum > DIFF_MAX) + data.DiffSum += diff; + if (data.DiffSum > DIFF_MAX) { - data.diffSum = DIFF_MAX; + data.DiffSum = DIFF_MAX; } } //if (this.dockPanel.ActiveContent != null && // this.dockPanel.ActiveContent != sender || data.tailState != 0) if (CurrentLogWindow != null && - CurrentLogWindow != sender || data.tailState != 0) + CurrentLogWindow != sender || data.TailState != 0) { - data.dirty = true; + data.Dirty = true; } Icon icon = GetIcon(diff, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); @@ -490,20 +497,21 @@ private void OnTailFollowed (object sender, EventArgs e) if (dockPanel.ActiveContent == sender) { var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; - data.dirty = false; - Icon icon = GetIcon(data.diffSum, data); + data.Dirty = false; + Icon icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); } } } + [SupportedOSPlatform("windows")] private void OnLogWindowSyncModeChanged (object sender, SyncModeEventArgs e) { if (!Disposing) { var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; - data.syncMode = e.IsTimeSynced ? 1 : 0; - Icon icon = GetIcon(data.diffSum, data); + data.SyncMode = e.IsTimeSynced ? 1 : 0; + Icon icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); } else @@ -512,46 +520,55 @@ private void OnLogWindowSyncModeChanged (object sender, SyncModeEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnToggleBookmarkToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ToggleBookmark(); } + [SupportedOSPlatform("windows")] private void OnJumpToNextToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.JumpNextBookmark(); } + [SupportedOSPlatform("windows")] private void OnJumpToPrevToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.JumpPrevBookmark(); } + [SupportedOSPlatform("windows")] private void OnASCIIToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ChangeEncoding(Encoding.ASCII); } + [SupportedOSPlatform("windows")] private void OnANSIToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ChangeEncoding(Encoding.Default); } + [SupportedOSPlatform("windows")] private void OnUTF8ToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ChangeEncoding(new UTF8Encoding(false)); } + [SupportedOSPlatform("windows")] private void OnUTF16ToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ChangeEncoding(Encoding.Unicode); } + [SupportedOSPlatform("windows")] private void OnISO88591ToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ChangeEncoding(Encoding.GetEncoding("iso-8859-1")); } + [SupportedOSPlatform("windows")] private void OnReloadToolStripMenuItemClick (object sender, EventArgs e) { if (CurrentLogWindow != null) @@ -563,11 +580,13 @@ private void OnReloadToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnSettingsToolStripMenuItemClick (object sender, EventArgs e) { OpenSettings(0); } + [SupportedOSPlatform("windows")] private void OnDateTimeDragControlValueDragged (object sender, EventArgs e) { if (CurrentLogWindow != null) @@ -576,21 +595,25 @@ private void OnDateTimeDragControlValueDragged (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnDateTimeDragControlValueChanged (object sender, EventArgs e) { CurrentLogWindow?.ScrollToTimestamp(dragControlDateTime.DateTime, true, true); } + [SupportedOSPlatform("windows")] private void OnLogTabWindowDeactivate (object sender, EventArgs e) { CurrentLogWindow?.AppFocusLost(); } + [SupportedOSPlatform("windows")] private void OnLogTabWindowActivated (object sender, EventArgs e) { CurrentLogWindow?.AppFocusGained(); } + [SupportedOSPlatform("windows")] private void OnShowBookmarkListToolStripMenuItemClick (object sender, EventArgs e) { if (_bookmarkWindow.Visible) @@ -610,36 +633,43 @@ private void OnShowBookmarkListToolStripMenuItemClick (object sender, EventArgs } } + [SupportedOSPlatform("windows")] private void OnToolStripButtonOpenClick (object sender, EventArgs e) { OpenFileDialog(); } + [SupportedOSPlatform("windows")] private void OnToolStripButtonSearchClick (object sender, EventArgs e) { OpenSearchDialog(); } + [SupportedOSPlatform("windows")] private void OnToolStripButtonFilterClick (object sender, EventArgs e) { CurrentLogWindow?.ToggleFilterPanel(); } + [SupportedOSPlatform("windows")] private void OnToolStripButtonBookmarkClick (object sender, EventArgs e) { CurrentLogWindow?.ToggleBookmark(); } + [SupportedOSPlatform("windows")] private void OnToolStripButtonUpClick (object sender, EventArgs e) { CurrentLogWindow?.JumpPrevBookmark(); } + [SupportedOSPlatform("windows")] private void OnToolStripButtonDownClick (object sender, EventArgs e) { CurrentLogWindow?.JumpNextBookmark(); } + [SupportedOSPlatform("windows")] private void OnShowHelpToolStripMenuItemClick (object sender, EventArgs e) { Help.ShowHelp(this, "LogExpert.chm"); @@ -647,29 +677,31 @@ private void OnShowHelpToolStripMenuItemClick (object sender, EventArgs e) private void OnHideLineColumnToolStripMenuItemClick (object sender, EventArgs e) { - ConfigManager.Settings.hideLineColumn = hideLineColumnToolStripMenuItem.Checked; + ConfigManager.Settings.HideLineColumn = hideLineColumnToolStripMenuItem.Checked; lock (_logWindowList) { foreach (LogWindow.LogWindow logWin in _logWindowList) { - logWin.ShowLineColumn(!ConfigManager.Settings.hideLineColumn); + logWin.ShowLineColumn(!ConfigManager.Settings.HideLineColumn); } } - _bookmarkWindow.LineColumnVisible = ConfigManager.Settings.hideLineColumn; + _bookmarkWindow.LineColumnVisible = ConfigManager.Settings.HideLineColumn; } // ================================================================== // Tab context menu stuff // ================================================================== + [SupportedOSPlatform("windows")] private void OnCloseThisTabToolStripMenuItemClick (object sender, EventArgs e) { (dockPanel.ActiveContent as LogWindow.LogWindow).Close(); } + [SupportedOSPlatform("windows")] private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) { - IList
closeList = new List(); + IList closeList = []; lock (_logWindowList) { foreach (DockContent content in dockPanel.Contents) @@ -686,11 +718,13 @@ private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnCloseAllTabsToolStripMenuItemClick (object sender, EventArgs e) { CloseAllTabs(); } + [SupportedOSPlatform("windows")] private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) { var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; @@ -703,17 +737,17 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) } ColorDialog dlg = new(); - dlg.Color = data.color; + dlg.Color = data.Color; if (dlg.ShowDialog() == DialogResult.OK) { - data.color = dlg.Color; - SetTabColor(logWindow, data.color); + data.Color = dlg.Color; + SetTabColor(logWindow, data.Color); } List delList = []; - foreach (ColorEntry entry in ConfigManager.Settings.fileColors) + foreach (ColorEntry entry in ConfigManager.Settings.FileColors) { - if (entry.FileName.ToLower().Equals(logWindow.FileName.ToLower())) + if (entry.FileName.Equals(logWindow.FileName, StringComparison.Ordinal)) { delList.Add(entry); } @@ -721,16 +755,17 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) foreach (ColorEntry entry in delList) { - ConfigManager.Settings.fileColors.Remove(entry); + ConfigManager.Settings.FileColors.Remove(entry); } - ConfigManager.Settings.fileColors.Add(new ColorEntry(logWindow.FileName, dlg.Color)); + ConfigManager.Settings.FileColors.Add(new ColorEntry(logWindow.FileName, dlg.Color)); - while (ConfigManager.Settings.fileColors.Count > MAX_COLOR_HISTORY) + while (ConfigManager.Settings.FileColors.Count > MAX_COLOR_HISTORY) { - ConfigManager.Settings.fileColors.RemoveAt(0); + ConfigManager.Settings.FileColors.RemoveAt(0); } } + [SupportedOSPlatform("windows")] private void OnLogTabWindowSizeChanged (object sender, EventArgs e) { if (WindowState != FormWindowState.Minimized) @@ -739,6 +774,7 @@ private void OnLogTabWindowSizeChanged (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) { SaveFileDialog dlg = new(); @@ -770,6 +806,7 @@ private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnLoadProjectToolStripMenuItemClick (object sender, EventArgs e) { OpenFileDialog dlg = new(); @@ -783,6 +820,7 @@ private void OnLoadProjectToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnToolStripButtonBubblesClick (object sender, EventArgs e) { if (CurrentLogWindow != null) @@ -791,6 +829,7 @@ private void OnToolStripButtonBubblesClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnCopyPathToClipboardToolStripMenuItemClick (object sender, EventArgs e) { var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; @@ -808,21 +847,25 @@ private void OnFindInExplorerToolStripMenuItemClick (object sender, EventArgs e) explorer.Start(); } + [SupportedOSPlatform("windows")] private void OnExportBookmarksToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ExportBookmarkList(); } + [SupportedOSPlatform("windows")] private void OnHighlightGroupsComboBoxDropDownClosed (object sender, EventArgs e) { ApplySelectedHighlightGroup(); } + [SupportedOSPlatform("windows")] private void OnHighlightGroupsComboBoxSelectedIndexChanged (object sender, EventArgs e) { ApplySelectedHighlightGroup(); } + [SupportedOSPlatform("windows")] private void OnHighlightGroupsComboBoxMouseUp (object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) @@ -840,6 +883,7 @@ private void OnConfigChanged (object sender, ConfigChangedEventArgs e) } } + [SupportedOSPlatform("windows")] private void OnDumpLogBufferInfoToolStripMenuItemClick (object sender, EventArgs e) { #if DEBUG @@ -847,6 +891,7 @@ private void OnDumpLogBufferInfoToolStripMenuItemClick (object sender, EventArgs #endif } + [SupportedOSPlatform("windows")] private void OnDumpBufferDiagnosticToolStripMenuItemClick (object sender, EventArgs e) { #if DEBUG @@ -864,6 +909,7 @@ private void OnGCInfoToolStripMenuItemClick (object sender, EventArgs e) DumpGCInfo(); } + [SupportedOSPlatform("windows")] private void OnToolsToolStripMenuItemDropDownItemClicked (object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Tag is ToolEntry tag) @@ -872,11 +918,13 @@ private void OnToolsToolStripMenuItemDropDownItemClicked (object sender, ToolStr } } + [SupportedOSPlatform("windows")] private void OnExternalToolsToolStripItemClicked (object sender, ToolStripItemClickedEventArgs e) { ToolButtonClick(e.ClickedItem.Tag as ToolEntry); } + [SupportedOSPlatform("windows")] private void OnConfigureToolStripMenuItemClick (object sender, EventArgs e) { OpenSettings(2); @@ -895,8 +943,11 @@ private void OnThrowExceptionBackgroundThToolStripMenuItemClick (object sender, private void OnThrowExceptionBackgroundThreadToolStripMenuItemClick (object sender, EventArgs e) { - Thread thread = new(ThrowExceptionThreadFx); - thread.IsBackground = true; + Thread thread = new(ThrowExceptionThreadFx) + { + IsBackground = true + }; + thread.Start(); } @@ -926,61 +977,70 @@ private void OnLogLevelToolStripMenuItemDropDownOpening (object sender, EventArg //debugToolStripMenuItem1.Checked = _logger.Get_logger().LogLevel == _logger.Level.DEBUG; } + [SupportedOSPlatform("windows")] private void OnDisableWordHighlightModeToolStripMenuItemClick (object sender, EventArgs e) { DebugOptions.DisableWordHighlight = disableWordHighlightModeToolStripMenuItem.Checked; CurrentLogWindow?.RefreshAllGrids(); } + [SupportedOSPlatform("windows")] private void OnMultiFileMaskToolStripMenuItemClick (object sender, EventArgs e) { CurrentLogWindow?.ChangeMultifileMask(); } + [SupportedOSPlatform("windows")] private void OnMultiFileEnabledStripMenuItemClick (object sender, EventArgs e) { ToggleMultiFile(); } + [SupportedOSPlatform("windows")] private void OnLockInstanceToolStripMenuItemClick (object sender, EventArgs e) { AbstractLogTabWindow.StaticData.CurrentLockedMainWindow = lockInstanceToolStripMenuItem.Checked ? null : this; } + [SupportedOSPlatform("windows")] private void OnOptionToolStripMenuItemDropDownOpening (object sender, EventArgs e) { - lockInstanceToolStripMenuItem.Enabled = !ConfigManager.Settings.Preferences.allowOnlyOneInstance; + lockInstanceToolStripMenuItem.Enabled = !ConfigManager.Settings.Preferences.AllowOnlyOneInstance; lockInstanceToolStripMenuItem.Checked = AbstractLogTabWindow.StaticData.CurrentLockedMainWindow == this; } + [SupportedOSPlatform("windows")] private void OnFileToolStripMenuItemDropDownOpening (object sender, EventArgs e) { newFromClipboardToolStripMenuItem.Enabled = Clipboard.ContainsText(); } + [SupportedOSPlatform("windows")] private void OnNewFromClipboardToolStripMenuItemClick (object sender, EventArgs e) { PasteFromClipboard(); } + [SupportedOSPlatform("windows")] private void OnOpenURIToolStripMenuItemClick (object sender, EventArgs e) { OpenUriDialog dlg = new() { - UriHistory = ConfigManager.Settings.uriHistoryList + UriHistory = ConfigManager.Settings.UriHistoryList }; if (DialogResult.OK == dlg.ShowDialog()) { if (dlg.Uri.Trim().Length > 0) { - ConfigManager.Settings.uriHistoryList = dlg.UriHistory; + ConfigManager.Settings.UriHistoryList = dlg.UriHistory; ConfigManager.Save(SettingsFlags.FileHistory); LoadFiles([dlg.Uri], false); } } } + [SupportedOSPlatform("windows")] private void OnColumnFinderToolStripMenuItemClick (object sender, EventArgs e) { if (CurrentLogWindow != null && !_skipEvents) @@ -989,6 +1049,7 @@ private void OnColumnFinderToolStripMenuItemClick (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnDockPanelActiveContentChanged (object sender, EventArgs e) { if (dockPanel.ActiveContent is LogWindow.LogWindow window) @@ -999,6 +1060,7 @@ private void OnDockPanelActiveContentChanged (object sender, EventArgs e) } } + [SupportedOSPlatform("windows")] private void OnTabRenameToolStripMenuItemClick (object sender, EventArgs e) { if (CurrentLogWindow != null) diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs index 173763fd..ec93bd35 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs @@ -4,7 +4,6 @@ using System.Security; using System.Text; -using LogExpert.Classes; using LogExpert.Core.Classes; using LogExpert.Core.Classes.Columnizer; using LogExpert.Core.Classes.Persister; @@ -15,6 +14,7 @@ using LogExpert.Dialogs; using LogExpert.PluginRegistry.FileSystem; using LogExpert.UI.Dialogs; +using LogExpert.UI.Entities; using LogExpert.UI.Extensions; using WeifenLuo.WinFormsUI.Docking; @@ -52,11 +52,13 @@ private void PasteFromClipboard () } } + [SupportedOSPlatform("windows")] private void InitToolWindows () { InitBookmarkWindow(); } + [SupportedOSPlatform("windows")] private void DestroyToolWindows () { DestroyBookmarkWindow(); @@ -85,14 +87,14 @@ private void DestroyBookmarkWindow () private void SaveLastOpenFilesList () { - ConfigManager.Settings.lastOpenFilesList.Clear(); + ConfigManager.Settings.LastOpenFilesList.Clear(); foreach (DockContent content in dockPanel.Contents) { if (content is LogWindow.LogWindow logWin) { if (!logWin.IsTempFile) { - ConfigManager.Settings.lastOpenFilesList.Add(logWin.GivenFileName); + ConfigManager.Settings.LastOpenFilesList.Add(logWin.GivenFileName); } } } @@ -104,15 +106,15 @@ private void SaveWindowPosition () SuspendLayout(); if (WindowState == FormWindowState.Normal) { - ConfigManager.Settings.appBounds = Bounds; - ConfigManager.Settings.isMaximized = false; + ConfigManager.Settings.AppBounds = Bounds; + ConfigManager.Settings.IsMaximized = false; } else { - ConfigManager.Settings.appBoundsFullscreen = Bounds; - ConfigManager.Settings.isMaximized = true; + ConfigManager.Settings.AppBoundsFullscreen = Bounds; + ConfigManager.Settings.IsMaximized = true; WindowState = FormWindowState.Normal; - ConfigManager.Settings.appBounds = Bounds; + ConfigManager.Settings.AppBounds = Bounds; } ResumeLayout(); @@ -125,15 +127,15 @@ private void SetTooltipText (LogWindow.LogWindow logWindow, string logFileName) private void FillDefaultEncodingFromSettings (EncodingOptions encodingOptions) { - if (ConfigManager.Settings.Preferences.defaultEncoding != null) + if (ConfigManager.Settings.Preferences.DefaultEncoding != null) { try { - encodingOptions.DefaultEncoding = Encoding.GetEncoding(ConfigManager.Settings.Preferences.defaultEncoding); + encodingOptions.DefaultEncoding = Encoding.GetEncoding(ConfigManager.Settings.Preferences.DefaultEncoding); } catch (ArgumentException) { - _logger.Warn("Encoding " + ConfigManager.Settings.Preferences.defaultEncoding + " is not a valid encoding"); + _logger.Warn("Encoding " + ConfigManager.Settings.Preferences.DefaultEncoding + " is not a valid encoding"); encodingOptions.DefaultEncoding = null; } } @@ -175,7 +177,7 @@ private void AddLogWindow (LogWindow.LogWindow logWindow, string title, bool doN LogWindowData data = new() { - diffSum = 0 + DiffSum = 0 }; logWindow.Tag = data; @@ -216,22 +218,23 @@ private void DisconnectEventHandlers (LogWindow.LogWindow logWindow) //data.tabPage = null; } + [SupportedOSPlatform("windows")] private void AddToFileHistory (string fileName) { bool FindName (string s) => s.ToUpperInvariant().Equals(fileName.ToUpperInvariant(), StringComparison.Ordinal); - var index = ConfigManager.Settings.fileHistoryList.FindIndex(FindName); + var index = ConfigManager.Settings.FileHistoryList.FindIndex(FindName); if (index != -1) { - ConfigManager.Settings.fileHistoryList.RemoveAt(index); + ConfigManager.Settings.FileHistoryList.RemoveAt(index); } - ConfigManager.Settings.fileHistoryList.Insert(0, fileName); + ConfigManager.Settings.FileHistoryList.Insert(0, fileName); - while (ConfigManager.Settings.fileHistoryList.Count > MAX_FILE_HISTORY) + while (ConfigManager.Settings.FileHistoryList.Count > MAX_FILE_HISTORY) { - ConfigManager.Settings.fileHistoryList.RemoveAt(ConfigManager.Settings.fileHistoryList.Count - 1); + ConfigManager.Settings.FileHistoryList.RemoveAt(ConfigManager.Settings.FileHistoryList.Count - 1); } ConfigManager.Save(SettingsFlags.FileHistory); @@ -272,24 +275,24 @@ private string FindFilenameForSettings (string fileName) return fileName; } - if (!string.IsNullOrEmpty(persistenceData.fileName)) + if (!string.IsNullOrEmpty(persistenceData.FileName)) { - IFileSystemPlugin fs = PluginRegistry.PluginRegistry.Instance.FindFileSystemForUri(persistenceData.fileName); + IFileSystemPlugin fs = PluginRegistry.PluginRegistry.Instance.FindFileSystemForUri(persistenceData.FileName); if (fs != null && !fs.GetType().Equals(typeof(LocalFileSystem))) { - return persistenceData.fileName; + return persistenceData.FileName; } // On relative paths the URI check (and therefore the file system plugin check) will fail. // So fs == null and fs == LocalFileSystem are handled here like normal files. - if (Path.IsPathRooted(persistenceData.fileName)) + if (Path.IsPathRooted(persistenceData.FileName)) { - return persistenceData.fileName; + return persistenceData.FileName; } // handle relative paths in .lxp files var dir = Path.GetDirectoryName(fileName); - return Path.Combine(dir, persistenceData.fileName); + return Path.Combine(dir, persistenceData.FileName); } } @@ -301,7 +304,7 @@ private void FillHistoryMenu () { ToolStripDropDown strip = new ToolStripDropDownMenu(); - foreach (var file in ConfigManager.Settings.fileHistoryList) + foreach (var file in ConfigManager.Settings.FileHistoryList) { ToolStripItem item = new ToolStripMenuItem(file); strip.Items.Add(item); @@ -390,9 +393,9 @@ private void OpenFileDialog () } else { - if (!string.IsNullOrEmpty(ConfigManager.Settings.lastDirectory)) + if (!string.IsNullOrEmpty(ConfigManager.Settings.LastDirectory)) { - openFileDialog.InitialDirectory = ConfigManager.Settings.lastDirectory; + openFileDialog.InitialDirectory = ConfigManager.Settings.LastDirectory; } else { @@ -415,7 +418,7 @@ private void OpenFileDialog () FileInfo info = new(openFileDialog.FileName); if (info.Directory.Exists) { - ConfigManager.Settings.lastDirectory = info.DirectoryName; + ConfigManager.Settings.LastDirectory = info.DirectoryName; ConfigManager.Save(SettingsFlags.FileHistory); } @@ -443,7 +446,7 @@ private void LoadFiles (string[] names, bool invertLogic) return; } - MultiFileOption option = ConfigManager.Settings.Preferences.multiFileOption; + MultiFileOption option = ConfigManager.Settings.Preferences.MultiFileOption; if (option == MultiFileOption.Ask) { MultiLoadRequestDialog dlg = new(); @@ -487,21 +490,21 @@ private void SetColumnizerHistoryEntry (string fileName, ILogLineColumnizer colu ColumnizerHistoryEntry entry = FindColumnizerHistoryEntry(fileName); if (entry != null) { - _ = ConfigManager.Settings.columnizerHistoryList.Remove(entry); + _ = ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); } - ConfigManager.Settings.columnizerHistoryList.Add(new ColumnizerHistoryEntry(fileName, columnizer.GetName())); + ConfigManager.Settings.ColumnizerHistoryList.Add(new ColumnizerHistoryEntry(fileName, columnizer.GetName())); - if (ConfigManager.Settings.columnizerHistoryList.Count > MAX_COLUMNIZER_HISTORY) + if (ConfigManager.Settings.ColumnizerHistoryList.Count > MAX_COLUMNIZER_HISTORY) { - ConfigManager.Settings.columnizerHistoryList.RemoveAt(0); + ConfigManager.Settings.ColumnizerHistoryList.RemoveAt(0); } } private ColumnizerHistoryEntry FindColumnizerHistoryEntry (string fileName) { - foreach (ColumnizerHistoryEntry entry in ConfigManager.Settings.columnizerHistoryList) + foreach (ColumnizerHistoryEntry entry in ConfigManager.Settings.ColumnizerHistoryList) { if (entry.FileName.Equals(fileName, StringComparison.Ordinal)) { @@ -633,7 +636,7 @@ private void GuiStateUpdateWorker (GuiStateArgs e) cellSelectModeToolStripMenuItem.Checked = e.CellSelectMode; RefreshEncodingMenuBar(e.CurrentEncoding); - if (e.TimeshiftPossible && ConfigManager.Settings.Preferences.timestampControl) + if (e.TimeshiftPossible && ConfigManager.Settings.Preferences.TimestampControl) { dragControlDateTime.MinDateTime = e.MinTimestamp; dragControlDateTime.MaxDateTime = e.MaxTimestamp; @@ -778,6 +781,7 @@ private Icon CreateLedIcon (int level, bool dirty, int tailState, int syncMode) return icon; } + [SupportedOSPlatform("windows")] private void CreateIcons () { for (var syncMode = 0; syncMode <= 1; syncMode++) // LED indicating time synced tabs @@ -819,10 +823,10 @@ private void ShowLedPeak (LogWindow.LogWindow logWin) var data = logWin.Tag as LogWindowData; lock (data) { - data.diffSum = DIFF_MAX; + data.DiffSum = DIFF_MAX; } - Icon icon = GetIcon(data.diffSum, data); + Icon icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); } @@ -866,15 +870,15 @@ private void LedThreadProc () foreach (LogWindow.LogWindow logWindow in _logWindowList) { var data = logWindow.Tag as LogWindowData; - if (data.diffSum > 0) + if (data.DiffSum > 0) { - data.diffSum -= 10; - if (data.diffSum < 0) + data.DiffSum -= 10; + if (data.DiffSum < 0) { - data.diffSum = 0; + data.DiffSum = 0; } - Icon icon = GetIcon(data.diffSum, data); + Icon icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); } } @@ -896,8 +900,8 @@ private Icon GetIcon (int diff, LogWindowData data) { Icon icon = _ledIcons[ - GetLevelFromDiff(diff), data.dirty ? 1 : 0, Preferences.showTailState ? data.tailState : 3, - data.syncMode + GetLevelFromDiff(diff), data.Dirty ? 1 : 0, Preferences.ShowTailState ? data.TailState : 3, + data.SyncMode ]; return icon; } @@ -940,6 +944,7 @@ private void RefreshEncodingMenuBar (Encoding encoding) toolStripEncodingANSIItem.Text = Encoding.Default.HeaderName; } + [SupportedOSPlatform("windows")] private void OpenSettings (int tabToOpen) { SettingsDialog dlg = new(ConfigManager.Settings.Preferences, this, tabToOpen, ConfigManager) @@ -955,6 +960,7 @@ private void OpenSettings (int tabToOpen) } } + [SupportedOSPlatform("windows")] private void NotifyWindowsForChangedPrefs (SettingsFlags flags) { _logger.Info("The preferences have changed"); @@ -982,9 +988,9 @@ private void ApplySettings (Settings settings, SettingsFlags flags) { if ((flags & SettingsFlags.WindowPosition) == SettingsFlags.WindowPosition) { - TopMost = alwaysOnTopToolStripMenuItem.Checked = settings.alwaysOnTop; - dragControlDateTime.DragOrientation = settings.Preferences.timestampControlDragOrientation; - hideLineColumnToolStripMenuItem.Checked = settings.hideLineColumn; + TopMost = alwaysOnTopToolStripMenuItem.Checked = settings.AlwaysOnTop; + dragControlDateTime.DragOrientation = settings.Preferences.TimestampControlDragOrientation; + hideLineColumnToolStripMenuItem.Checked = settings.HideLineColumn; } if ((flags & SettingsFlags.FileHistory) == SettingsFlags.FileHistory) @@ -1011,14 +1017,14 @@ private void ApplySettings (Settings settings, SettingsFlags flags) [SupportedOSPlatform("windows")] private void SetTabIcons (Preferences preferences) { - _tailLedBrush[0] = new SolidBrush(preferences.showTailColor); + _tailLedBrush[0] = new SolidBrush(preferences.ShowTailColor); CreateIcons(); lock (_logWindowList) { foreach (LogWindow.LogWindow logWindow in _logWindowList) { var data = logWindow.Tag as LogWindowData; - Icon icon = GetIcon(data.diffSum, data); + Icon icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); } } @@ -1027,7 +1033,7 @@ private void SetTabIcons (Preferences preferences) [SupportedOSPlatform("windows")] private void SetToolIcon (ToolEntry entry, ToolStripItem item) { - Icon icon = Win32.LoadIconFromExe(entry.iconFile, entry.iconIndex); + Icon icon = Win32.LoadIconFromExe(entry.IconFile, entry.IconIndex); if (icon != null) { item.Image = icon.ToBitmap(); @@ -1044,15 +1050,16 @@ private void SetToolIcon (ToolEntry entry, ToolStripItem item) icon.Dispose(); } - if (!string.IsNullOrEmpty(entry.cmd)) + if (!string.IsNullOrEmpty(entry.Cmd)) { - item.ToolTipText = entry.name; + item.ToolTipText = entry.Name; } } + [SupportedOSPlatform("windows")] private void ToolButtonClick (ToolEntry toolEntry) { - if (string.IsNullOrEmpty(toolEntry.cmd)) + if (string.IsNullOrEmpty(toolEntry.Cmd)) { //TODO TabIndex => To Enum OpenSettings(2); @@ -1065,12 +1072,11 @@ private void ToolButtonClick (ToolEntry toolEntry) ILogFileInfo info = CurrentLogWindow.GetCurrentFileInfo(); if (line != null && info != null) { - ArgParser parser = new(toolEntry.args); + ArgParser parser = new(toolEntry.Args); var argLine = parser.BuildArgs(line, CurrentLogWindow.GetRealLineNum() + 1, info, this); if (argLine != null) { - StartTool(toolEntry.cmd, argLine, toolEntry.sysout, toolEntry.columnizerName, - toolEntry.workingDir); + StartTool(toolEntry.Cmd, argLine, toolEntry.Sysout, toolEntry.ColumnizerName, toolEntry.WorkingDir); } } } @@ -1243,9 +1249,9 @@ private void FillToolLauncherBar () externalToolsToolStrip.Items.Clear(); var num = 0; externalToolsToolStrip.SuspendLayout(); - foreach (ToolEntry tool in Preferences.toolEntries) + foreach (ToolEntry tool in Preferences.ToolEntries) { - if (tool.isFavourite) + if (tool.IsFavourite) { ToolStripButton button = new("" + labels[num % 26]) { @@ -1258,7 +1264,7 @@ private void FillToolLauncherBar () } num++; - ToolStripMenuItem menuItem = new(tool.name) + ToolStripMenuItem menuItem = new(tool.Name) { Tag = tool }; @@ -1314,6 +1320,7 @@ private string SaveLayout () return resultXml; } + [SupportedOSPlatform("windows")] private void RestoreLayout (string layoutXml) { using MemoryStream memStream = new(2000); @@ -1326,6 +1333,7 @@ private void RestoreLayout (string layoutXml) dockPanel.LoadFromXml(memStream, DeserializeDockContent, true); } + [SupportedOSPlatform("windows")] private IDockContent DeserializeDockContent (string persistString) { if (persistString.Equals(WindowTypes.BookmarkWindow.ToString(), StringComparison.Ordinal)) @@ -1335,7 +1343,7 @@ private IDockContent DeserializeDockContent (string persistString) if (persistString.StartsWith(WindowTypes.LogWindow.ToString())) { - var fileName = persistString.Substring(WindowTypes.LogWindow.ToString().Length + 1); + var fileName = persistString[(WindowTypes.LogWindow.ToString().Length + 1)..]; LogWindow.LogWindow win = FindWindowForFile(fileName); if (win != null) { diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs index a324dec3..4058efe4 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs @@ -1,8 +1,9 @@ +using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; -using LogExpert.Classes.Filter; using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Classes.Filter; using LogExpert.Core.Config; using LogExpert.Core.Entities; using LogExpert.Core.Interface; @@ -18,36 +19,42 @@ public partial class LogTabWindow { #region Public methods + [SupportedOSPlatform("windows")] public LogWindow.LogWindow AddTempFileTab (string fileName, string title) { return AddFileTab(fileName, true, title, false, null); } + [SupportedOSPlatform("windows")] public LogWindow.LogWindow AddFilterTab (FilterPipe pipe, string title, ILogLineColumnizer preProcessColumnizer) { LogWindow.LogWindow logWin = AddFileTab(pipe.FileName, true, title, false, preProcessColumnizer); if (pipe.FilterParams.SearchText.Length > 0) { ToolTip tip = new(components); + tip.SetToolTip(logWin, "Filter: \"" + pipe.FilterParams.SearchText + "\"" + (pipe.FilterParams.IsInvert ? " (Invert match)" : "") + (pipe.FilterParams.ColumnRestrict ? "\nColumn restrict" : "") ); + tip.AutomaticDelay = 10; tip.AutoPopDelay = 5000; var data = logWin.Tag as LogWindowData; - data.toolTip = tip; + data.ToolTip = tip; } return logWin; } + [SupportedOSPlatform("windows")] public LogWindow.LogWindow AddFileTabDeferred (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer) { return AddFileTab(givenFileName, isTempFile, title, forcePersistenceLoading, preProcessColumnizer, true); } + [SupportedOSPlatform("windows")] public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer, bool doNotAddToDockPanel = false) { var logFileName = FindFilenameForSettings(givenFileName); @@ -87,16 +94,16 @@ public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, st } var data = logWindow.Tag as LogWindowData; - data.color = _defaultTabColor; + data.Color = _defaultTabColor; SetTabColor(logWindow, _defaultTabColor); //data.tabPage.BorderColor = this.defaultTabBorderColor; if (!isTempFile) { - foreach (ColorEntry colorEntry in ConfigManager.Settings.fileColors) + foreach (ColorEntry colorEntry in ConfigManager.Settings.FileColors) { - if (colorEntry.FileName.ToLower().Equals(logFileName.ToLower())) + if (colorEntry.FileName.ToUpperInvariant().Equals(logFileName.ToUpperInvariant(), StringComparison.Ordinal)) { - data.color = colorEntry.Color; + data.Color = colorEntry.Color; SetTabColor(logWindow, colorEntry.Color); break; } @@ -108,7 +115,7 @@ public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, st SetTooltipText(logWindow, logFileName); } - if (givenFileName.EndsWith(".lxp")) + if (givenFileName.EndsWith(".lxp", StringComparison.Ordinal)) { logWindow.ForcedPersistenceFileName = givenFileName; } @@ -118,6 +125,7 @@ public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, st return logWindow; } + [SupportedOSPlatform("windows")] public LogWindow.LogWindow AddMultiFileTab (string[] fileNames) { if (fileNames.Length < 1) @@ -125,8 +133,8 @@ public LogWindow.LogWindow AddMultiFileTab (string[] fileNames) return null; } - LogWindow.LogWindow logWindow = new(this, fileNames[fileNames.Length - 1], false, false, ConfigManager); - AddLogWindow(logWindow, fileNames[fileNames.Length - 1], false); + LogWindow.LogWindow logWindow = new(this, fileNames[^1], false, false, ConfigManager); + AddLogWindow(logWindow, fileNames[^1], false); multiFileToolStripMenuItem.Checked = true; multiFileEnabledStripMenuItem.Checked = true; EncodingOptions encodingOptions = new(); @@ -136,11 +144,13 @@ public LogWindow.LogWindow AddMultiFileTab (string[] fileNames) return logWindow; } + [SupportedOSPlatform("windows")] public void LoadFiles (string[] fileNames) { Invoke(new AddFileTabsDelegate(AddFileTabs), [fileNames]); } + [SupportedOSPlatform("windows")] public void OpenSearchDialog () { if (CurrentLogWindow == null) @@ -151,7 +161,7 @@ public void OpenSearchDialog () SearchDialog dlg = new(); AddOwnedForm(dlg); dlg.TopMost = TopMost; - SearchParams.HistoryList = ConfigManager.Settings.searchHistoryList; + SearchParams.HistoryList = ConfigManager.Settings.SearchHistoryList; dlg.SearchParams = SearchParams; DialogResult res = dlg.ShowDialog(); if (res == DialogResult.OK && dlg.SearchParams != null && !string.IsNullOrWhiteSpace(dlg.SearchParams.SearchText)) @@ -169,13 +179,13 @@ public ILogLineColumnizer GetColumnizerHistoryEntry (string fileName) { foreach (ILogLineColumnizer columnizer in PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers) { - if (columnizer.GetName().Equals(entry.ColumnizerName)) + if (columnizer.GetName().Equals(entry.ColumnizerName, StringComparison.Ordinal)) { return columnizer; } } - ConfigManager.Settings.columnizerHistoryList.Remove(entry); // no valid name -> remove entry + ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); // no valid name -> remove entry } return null; @@ -231,15 +241,15 @@ public void ScrollAllTabsToTimestamp (DateTime timestamp, LogWindow.LogWindow se public ILogLineColumnizer FindColumnizerByFileMask (string fileName) { - foreach (ColumnizerMaskEntry entry in ConfigManager.Settings.Preferences.columnizerMaskList) + foreach (ColumnizerMaskEntry entry in ConfigManager.Settings.Preferences.ColumnizerMaskList) { - if (entry.mask != null) + if (entry.Mask != null) { try { - if (Regex.IsMatch(fileName, entry.mask)) + if (Regex.IsMatch(fileName, entry.Mask)) { - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(entry.columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(entry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); return columnizer; } } @@ -256,15 +266,15 @@ public ILogLineColumnizer FindColumnizerByFileMask (string fileName) public HighlightGroup FindHighlightGroupByFileMask (string fileName) { - foreach (HighlightMaskEntry entry in ConfigManager.Settings.Preferences.highlightMaskList) + foreach (HighlightMaskEntry entry in ConfigManager.Settings.Preferences.HighlightMaskList) { - if (entry.mask != null) + if (entry.Mask != null) { try { - if (Regex.IsMatch(fileName, entry.mask)) + if (Regex.IsMatch(fileName, entry.Mask)) { - HighlightGroup group = FindHighlightGroup(entry.highlightGroupName); + HighlightGroup group = FindHighlightGroup(entry.HighlightGroupName); return group; } } @@ -284,6 +294,7 @@ public void SelectTab (ILogWindow logWindow) logWindow.Activate(); } + [SupportedOSPlatform("windows")] public void SetForeground () { Win32.SetForegroundWindow(Handle); @@ -301,30 +312,31 @@ public void SetForeground () } // called from LogWindow when follow tail was changed + [SupportedOSPlatform("windows")] public void FollowTailChanged (LogWindow.LogWindow logWindow, bool isEnabled, bool offByTrigger) { - var data = logWindow.Tag as LogWindowData; - if (data == null) + if (logWindow.Tag is not LogWindowData data) { return; } if (isEnabled) { - data.tailState = 0; + data.TailState = 0; } else { - data.tailState = offByTrigger ? 2 : 1; + data.TailState = offByTrigger ? 2 : 1; } - if (Preferences.showTailState) + if (Preferences.ShowTailState) { - Icon icon = GetIcon(data.diffSum, data); + Icon icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); } } + [SupportedOSPlatform("windows")] public void NotifySettingsChanged (object sender, SettingsFlags flags) { if (sender != this) @@ -335,7 +347,7 @@ public void NotifySettingsChanged (object sender, SettingsFlags flags) public IList GetListOfOpenFiles () { - IList list = new List(); + IList list = []; lock (_logWindowList) { foreach (LogWindow.LogWindow logWindow in _logWindowList) diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs index 0d5308c7..d6b20a7d 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs @@ -1,3 +1,6 @@ +using System.Runtime.Versioning; +using System.Text; + using LogExpert.Core.Classes; using LogExpert.Core.Classes.Columnizer; using LogExpert.Core.Config; @@ -7,12 +10,11 @@ using LogExpert.UI.Controls.LogTabWindow; using LogExpert.UI.Dialogs; using LogExpert.UI.Extensions; -using System.Runtime.InteropServices; -using System.Text; namespace LogExpert.Dialogs; //TODO: This class should not knoow ConfigManager? +[SupportedOSPlatform("windows")] internal partial class SettingsDialog : Form { #region Fields @@ -27,7 +29,7 @@ internal partial class SettingsDialog : Form #region cTor - private SettingsDialog(Preferences prefs, LogTabWindow logTabWin) + private SettingsDialog (Preferences prefs, LogTabWindow logTabWin) { Preferences = prefs; _logTabWin = logTabWin; //TODO: uses only HighlightGroupList. Can we pass IList instead? @@ -38,7 +40,7 @@ private SettingsDialog(Preferences prefs, LogTabWindow logTabWin) Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } - public SettingsDialog(Preferences prefs, LogTabWindow logTabWin, int tabToOpen, IConfigManager configManager) : this(prefs, logTabWin) + public SettingsDialog (Preferences prefs, LogTabWindow logTabWin, int tabToOpen, IConfigManager configManager) : this(prefs, logTabWin) { tabControlSettings.SelectedIndex = tabToOpen; ConfigManager = configManager; @@ -56,62 +58,62 @@ public SettingsDialog(Preferences prefs, LogTabWindow logTabWin, int tabToOpen, #region Private Methods - private void FillDialog() + private void FillDialog () { Preferences ??= new Preferences(); - if (Preferences.fontName == null) + if (Preferences.FontName == null) { - Preferences.fontName = "Courier New"; + Preferences.FontName = "Courier New"; } - if (Math.Abs(Preferences.fontSize) < 0.1) + if (Math.Abs(Preferences.FontSize) < 0.1) { - Preferences.fontSize = 9.0f; + Preferences.FontSize = 9.0f; } FillPortableMode(); - checkBoxDarkMode.Checked = Preferences.darkMode; - checkBoxTimestamp.Checked = Preferences.timestampControl; - checkBoxSyncFilter.Checked = Preferences.filterSync; - checkBoxFilterTail.Checked = Preferences.filterTail; - checkBoxFollowTail.Checked = Preferences.followTail; + checkBoxDarkMode.Checked = Preferences.DarkMode; + checkBoxTimestamp.Checked = Preferences.TimestampControl; + checkBoxSyncFilter.Checked = Preferences.FilterSync; + checkBoxFilterTail.Checked = Preferences.FilterTail; + checkBoxFollowTail.Checked = Preferences.FollowTail; - radioButtonHorizMouseDrag.Checked = Preferences.timestampControlDragOrientation == DragOrientationsEnum.Horizontal; - radioButtonVerticalMouseDrag.Checked = Preferences.timestampControlDragOrientation == DragOrientationsEnum.Vertical; - radioButtonVerticalMouseDragInverted.Checked = Preferences.timestampControlDragOrientation == DragOrientationsEnum.InvertedVertical; + radioButtonHorizMouseDrag.Checked = Preferences.TimestampControlDragOrientation == DragOrientationsEnum.Horizontal; + radioButtonVerticalMouseDrag.Checked = Preferences.TimestampControlDragOrientation == DragOrientationsEnum.Vertical; + radioButtonVerticalMouseDragInverted.Checked = Preferences.TimestampControlDragOrientation == DragOrientationsEnum.InvertedVertical; - checkBoxSingleInstance.Checked = Preferences.allowOnlyOneInstance; - checkBoxOpenLastFiles.Checked = Preferences.openLastFiles; - checkBoxTailState.Checked = Preferences.showTailState; - checkBoxColumnSize.Checked = Preferences.setLastColumnWidth; - cpDownColumnWidth.Enabled = Preferences.setLastColumnWidth; + checkBoxSingleInstance.Checked = Preferences.AllowOnlyOneInstance; + checkBoxOpenLastFiles.Checked = Preferences.OpenLastFiles; + checkBoxTailState.Checked = Preferences.ShowTailState; + checkBoxColumnSize.Checked = Preferences.SetLastColumnWidth; + cpDownColumnWidth.Enabled = Preferences.SetLastColumnWidth; - if (Preferences.lastColumnWidth != 0) + if (Preferences.LastColumnWidth != 0) { - if (Preferences.lastColumnWidth < cpDownColumnWidth.Minimum) + if (Preferences.LastColumnWidth < cpDownColumnWidth.Minimum) { - Preferences.lastColumnWidth = (int)cpDownColumnWidth.Minimum; + Preferences.LastColumnWidth = (int)cpDownColumnWidth.Minimum; } - if (Preferences.lastColumnWidth > cpDownColumnWidth.Maximum) + if (Preferences.LastColumnWidth > cpDownColumnWidth.Maximum) { - Preferences.lastColumnWidth = (int)cpDownColumnWidth.Maximum; + Preferences.LastColumnWidth = (int)cpDownColumnWidth.Maximum; } - cpDownColumnWidth.Value = Preferences.lastColumnWidth; + cpDownColumnWidth.Value = Preferences.LastColumnWidth; } - checkBoxTimeSpread.Checked = Preferences.showTimeSpread; - checkBoxReverseAlpha.Checked = Preferences.reverseAlpha; + checkBoxTimeSpread.Checked = Preferences.ShowTimeSpread; + checkBoxReverseAlpha.Checked = Preferences.ReverseAlpha; - radioButtonTimeView.Checked = Preferences.timeSpreadTimeMode; - radioButtonLineView.Checked = !Preferences.timeSpreadTimeMode; + radioButtonTimeView.Checked = Preferences.TimeSpreadTimeMode; + radioButtonLineView.Checked = !Preferences.TimeSpreadTimeMode; - checkBoxSaveSessions.Checked = Preferences.saveSessions; + checkBoxSaveSessions.Checked = Preferences.SaveSessions; - switch (Preferences.saveLocation) + switch (Preferences.SaveLocation) { case SessionSaveLocation.OwnDir: { @@ -143,15 +145,15 @@ private void FillDialog() upDownMaximumLineLength.Value = Preferences.MaxLineLength; - upDownMaximumFilterEntriesDisplayed.Value = Preferences.maximumFilterEntriesDisplayed; - upDownMaximumFilterEntries.Value = Preferences.maximumFilterEntries; + upDownMaximumFilterEntriesDisplayed.Value = Preferences.MaximumFilterEntriesDisplayed; + upDownMaximumFilterEntries.Value = Preferences.MaximumFilterEntries; - labelSessionSaveOwnDir.Text = Preferences.sessionSaveDirectory ?? string.Empty; - checkBoxSaveFilter.Checked = Preferences.saveFilters; - upDownBlockCount.Value = Preferences.bufferCount; - upDownLinesPerBlock.Value = Preferences.linesPerBuffer; - upDownPollingInterval.Value = Preferences.pollingInterval; - checkBoxMultiThread.Checked = Preferences.multiThreadFilter; + labelSessionSaveOwnDir.Text = Preferences.SessionSaveDirectory ?? string.Empty; + checkBoxSaveFilter.Checked = Preferences.SaveFilters; + upDownBlockCount.Value = Preferences.BufferCount; + upDownLinesPerBlock.Value = Preferences.LinesPerBuffer; + upDownPollingInterval.Value = Preferences.PollingInterval; + checkBoxMultiThread.Checked = Preferences.MultiThreadFilter; dataGridViewColumnizer.DataError += OnDataGridViewColumnizerDataError; @@ -163,50 +165,50 @@ private void FillDialog() FillMultifileSettings(); FillEncodingList(); - var temp = Encoding.GetEncoding(Preferences.defaultEncoding); + var temp = Encoding.GetEncoding(Preferences.DefaultEncoding); - comboBoxEncoding.SelectedItem = Encoding.GetEncoding(Preferences.defaultEncoding); - checkBoxMaskPrio.Checked = Preferences.maskPrio; - checkBoxAutoPick.Checked = Preferences.autoPick; - checkBoxAskCloseTabs.Checked = Preferences.askForClose; - checkBoxColumnFinder.Checked = Preferences.showColumnFinder; - checkBoxLegacyReader.Checked = Preferences.useLegacyReader; + comboBoxEncoding.SelectedItem = Encoding.GetEncoding(Preferences.DefaultEncoding); + checkBoxMaskPrio.Checked = Preferences.MaskPrio; + checkBoxAutoPick.Checked = Preferences.AutoPick; + checkBoxAskCloseTabs.Checked = Preferences.AskForClose; + checkBoxColumnFinder.Checked = Preferences.ShowColumnFinder; + checkBoxLegacyReader.Checked = Preferences.UseLegacyReader; checkBoxShowErrorMessageOnlyOneInstance.Checked = Preferences.ShowErrorMessageAllowOnlyOneInstances; } - private void FillPortableMode() + private void FillPortableMode () { checkBoxPortableMode.CheckState = Preferences.PortableMode ? CheckState.Checked : CheckState.Unchecked; } - private void DisplayFontName() + private void DisplayFontName () { - labelFont.Text = Preferences.fontName + @" " + (int)Preferences.fontSize; - labelFont.Font = new Font(new FontFamily(Preferences.fontName), Preferences.fontSize); + labelFont.Text = Preferences.FontName + @" " + (int)Preferences.FontSize; + labelFont.Font = new Font(new FontFamily(Preferences.FontName), Preferences.FontSize); } - private void SaveMultifileData() + private void SaveMultifileData () { if (radioButtonLoadEveryFileIntoSeperatedTab.Checked) { - Preferences.multiFileOption = MultiFileOption.SingleFiles; + Preferences.MultiFileOption = MultiFileOption.SingleFiles; } if (radioButtonTreatAllFilesAsOneMultifile.Checked) { - Preferences.multiFileOption = MultiFileOption.MultiFile; + Preferences.MultiFileOption = MultiFileOption.MultiFile; } if (radioButtonAskWhatToDo.Checked) { - Preferences.multiFileOption = MultiFileOption.Ask; + Preferences.MultiFileOption = MultiFileOption.Ask; } - Preferences.multiFileOptions.FormatPattern = textBoxMultifilePattern.Text; - Preferences.multiFileOptions.MaxDayTry = (int)upDownMultifileDays.Value; + Preferences.MultiFileOptions.FormatPattern = textBoxMultifilePattern.Text; + Preferences.MultiFileOptions.MaxDayTry = (int)upDownMultifileDays.Value; } - private void OnBtnToolClickInternal(TextBox textBox) + private void OnBtnToolClickInternal (TextBox textBox) { OpenFileDialog dlg = new(); dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); @@ -227,7 +229,7 @@ private void OnBtnToolClickInternal(TextBox textBox) } //TODO: what is the purpose of this method? - private void OnBtnArgsClickInternal(TextBox textBox) + private void OnBtnArgsClickInternal (TextBox textBox) { ToolArgsDialog dlg = new(_logTabWin, this) { @@ -240,7 +242,7 @@ private void OnBtnArgsClickInternal(TextBox textBox) } } - private void OnBtnWorkingDirClick(TextBox textBox) + private void OnBtnWorkingDirClick (TextBox textBox) { FolderBrowserDialog dlg = new() { @@ -263,15 +265,15 @@ private void OnBtnWorkingDirClick(TextBox textBox) } } - private void FillColumnizerForToolsList() + private void FillColumnizerForToolsList () { if (_selectedTool != null) { - FillColumnizerForToolsList(comboBoxColumnizer, _selectedTool.columnizerName); + FillColumnizerForToolsList(comboBoxColumnizer, _selectedTool.ColumnizerName); } } - private void FillColumnizerForToolsList(ComboBox comboBox, string columnizerName) + private void FillColumnizerForToolsList (ComboBox comboBox, string columnizerName) { var selIndex = 0; comboBox.Items.Clear(); @@ -280,7 +282,7 @@ private void FillColumnizerForToolsList(ComboBox comboBox, string columnizerName foreach (ILogLineColumnizer columnizer in columnizers) { var index = comboBox.Items.Add(columnizer.GetName()); - if (columnizer.GetName().Equals(columnizerName)) + if (columnizer.GetName().Equals(columnizerName, StringComparison.Ordinal)) { selIndex = index; } @@ -292,7 +294,7 @@ private void FillColumnizerForToolsList(ComboBox comboBox, string columnizerName comboBox.SelectedIndex = selIndex; } - private void FillColumnizerList() + private void FillColumnizerList () { dataGridViewColumnizer.Rows.Clear(); @@ -310,7 +312,7 @@ private void FillColumnizerList() //comboColumn.DisplayMember = "Name"; //comboColumn.ValueMember = "Columnizer"; - foreach (ColumnizerMaskEntry maskEntry in Preferences.columnizerMaskList) + foreach (ColumnizerMaskEntry maskEntry in Preferences.ColumnizerMaskList) { DataGridViewRow row = new(); row.Cells.Add(new DataGridViewTextBoxCell()); @@ -322,8 +324,8 @@ private void FillColumnizerList() } row.Cells.Add(cell); - row.Cells[0].Value = maskEntry.mask; - ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(maskEntry.columnizerName, + row.Cells[0].Value = maskEntry.Mask; + ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(maskEntry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); row.Cells[1].Value = columnizer.GetName(); @@ -339,7 +341,7 @@ private void FillColumnizerList() } } - private void FillHighlightMaskList() + private void FillHighlightMaskList () { dataGridViewHighlightMask.Rows.Clear(); @@ -354,7 +356,7 @@ private void FillHighlightMaskList() comboColumn.Items.Add(group.GroupName); } - foreach (HighlightMaskEntry maskEntry in Preferences.highlightMaskList) + foreach (HighlightMaskEntry maskEntry in Preferences.HighlightMaskList) { DataGridViewRow row = new(); row.Cells.Add(new DataGridViewTextBoxCell()); @@ -366,9 +368,9 @@ private void FillHighlightMaskList() } row.Cells.Add(cell); - row.Cells[0].Value = maskEntry.mask; + row.Cells[0].Value = maskEntry.Mask; - HighlightGroup currentGroup = _logTabWin.FindHighlightGroup(maskEntry.highlightGroupName); + HighlightGroup currentGroup = _logTabWin.FindHighlightGroup(maskEntry.HighlightGroupName); var highlightGroupList = _logTabWin.HighlightGroupList; currentGroup ??= highlightGroupList.Count > 0 ? highlightGroupList[0] : new HighlightGroup(); @@ -386,39 +388,39 @@ private void FillHighlightMaskList() } } - private void SaveColumnizerList() + private void SaveColumnizerList () { - Preferences.columnizerMaskList.Clear(); + Preferences.ColumnizerMaskList.Clear(); foreach (DataGridViewRow row in dataGridViewColumnizer.Rows) { if (!row.IsNewRow) { ColumnizerMaskEntry entry = new(); - entry.mask = (string)row.Cells[0].Value; - entry.columnizerName = (string)row.Cells[1].Value; - Preferences.columnizerMaskList.Add(entry); + entry.Mask = (string)row.Cells[0].Value; + entry.ColumnizerName = (string)row.Cells[1].Value; + Preferences.ColumnizerMaskList.Add(entry); } } } - private void SaveHighlightMaskList() + private void SaveHighlightMaskList () { - Preferences.highlightMaskList.Clear(); + Preferences.HighlightMaskList.Clear(); foreach (DataGridViewRow row in dataGridViewHighlightMask.Rows) { if (!row.IsNewRow) { HighlightMaskEntry entry = new(); - entry.mask = (string)row.Cells[0].Value; - entry.highlightGroupName = (string)row.Cells[1].Value; - Preferences.highlightMaskList.Add(entry); + entry.Mask = (string)row.Cells[0].Value; + entry.HighlightGroupName = (string)row.Cells[1].Value; + Preferences.HighlightMaskList.Add(entry); } } } - private void FillPluginList() + private void FillPluginList () { listBoxPlugin.Items.Clear(); @@ -452,7 +454,7 @@ private void FillPluginList() buttonConfigPlugin.Enabled = false; } - private void SavePluginSettings() + private void SavePluginSettings () { _selectedPlugin?.HideConfigForm(); @@ -473,13 +475,13 @@ private void SavePluginSettings() } } - private void FillToolListbox() + private void FillToolListbox () { listBoxTools.Items.Clear(); - foreach (ToolEntry tool in Preferences.toolEntries) + foreach (ToolEntry tool in Preferences.ToolEntries) { - listBoxTools.Items.Add(tool.Clone(), tool.isFavourite); + listBoxTools.Items.Add(tool.Clone(), tool.IsFavourite); } if (listBoxTools.Items.Count > 0) @@ -488,9 +490,9 @@ private void FillToolListbox() } } - private void FillMultifileSettings() + private void FillMultifileSettings () { - switch (Preferences.multiFileOption) + switch (Preferences.MultiFileOption) { case MultiFileOption.SingleFiles: { @@ -509,54 +511,54 @@ private void FillMultifileSettings() } } - textBoxMultifilePattern.Text = Preferences.multiFileOptions.FormatPattern; //TODO: Impport settings file throws an exception. Fix or I caused it? - upDownMultifileDays.Value = Preferences.multiFileOptions.MaxDayTry; + textBoxMultifilePattern.Text = Preferences.MultiFileOptions.FormatPattern; //TODO: Impport settings file throws an exception. Fix or I caused it? + upDownMultifileDays.Value = Preferences.MultiFileOptions.MaxDayTry; } - private void GetToolListBoxData() + private void GetToolListBoxData () { GetCurrentToolValues(); - Preferences.toolEntries.Clear(); + Preferences.ToolEntries.Clear(); for (var i = 0; i < listBoxTools.Items.Count; ++i) { - Preferences.toolEntries.Add(listBoxTools.Items[i] as ToolEntry); - (listBoxTools.Items[i] as ToolEntry).isFavourite = listBoxTools.GetItemChecked(i); + Preferences.ToolEntries.Add(listBoxTools.Items[i] as ToolEntry); + (listBoxTools.Items[i] as ToolEntry).IsFavourite = listBoxTools.GetItemChecked(i); } } - private void GetCurrentToolValues() + private void GetCurrentToolValues () { if (_selectedTool != null) { - _selectedTool.name = Util.IsNullOrSpaces(textBoxToolName.Text) ? textBoxTool.Text : textBoxToolName.Text; - _selectedTool.cmd = textBoxTool.Text; - _selectedTool.args = textBoxArguments.Text; - _selectedTool.columnizerName = comboBoxColumnizer.Text; - _selectedTool.sysout = checkBoxSysout.Checked; - _selectedTool.workingDir = textBoxWorkingDir.Text; + _selectedTool.Name = Util.IsNullOrSpaces(textBoxToolName.Text) ? textBoxTool.Text : textBoxToolName.Text; + _selectedTool.Cmd = textBoxTool.Text; + _selectedTool.Args = textBoxArguments.Text; + _selectedTool.ColumnizerName = comboBoxColumnizer.Text; + _selectedTool.Sysout = checkBoxSysout.Checked; + _selectedTool.WorkingDir = textBoxWorkingDir.Text; } } - private void ShowCurrentToolValues() + private void ShowCurrentToolValues () { if (_selectedTool != null) { - textBoxToolName.Text = _selectedTool.name; - textBoxTool.Text = _selectedTool.cmd; - textBoxArguments.Text = _selectedTool.args; - comboBoxColumnizer.Text = _selectedTool.columnizerName; - checkBoxSysout.Checked = _selectedTool.sysout; - comboBoxColumnizer.Enabled = _selectedTool.sysout; - textBoxWorkingDir.Text = _selectedTool.workingDir; + textBoxToolName.Text = _selectedTool.Name; + textBoxTool.Text = _selectedTool.Cmd; + textBoxArguments.Text = _selectedTool.Args; + comboBoxColumnizer.Text = _selectedTool.ColumnizerName; + checkBoxSysout.Checked = _selectedTool.Sysout; + comboBoxColumnizer.Enabled = _selectedTool.Sysout; + textBoxWorkingDir.Text = _selectedTool.WorkingDir; } } - private void DisplayCurrentIcon() + private void DisplayCurrentIcon () { if (_selectedTool != null) { - Icon icon = Win32.LoadIconFromExe(_selectedTool.iconFile, _selectedTool.iconIndex); + Icon icon = Win32.LoadIconFromExe(_selectedTool.IconFile, _selectedTool.IconIndex); if (icon != null) { Image image = icon.ToBitmap(); @@ -571,7 +573,7 @@ private void DisplayCurrentIcon() } } - private void FillEncodingList() + private void FillEncodingList () { comboBoxEncoding.Items.Clear(); @@ -589,97 +591,97 @@ private void FillEncodingList() #region Events handler - private void OnSettingsDialogLoad(object sender, EventArgs e) + private void OnSettingsDialogLoad (object sender, EventArgs e) { FillDialog(); } - private void OnBtnChangeFontClick(object sender, EventArgs e) + private void OnBtnChangeFontClick (object sender, EventArgs e) { FontDialog dlg = new() { ShowEffects = false, AllowVerticalFonts = false, AllowScriptChange = false, - Font = new Font(new FontFamily(Preferences.fontName), Preferences.fontSize) + Font = new Font(new FontFamily(Preferences.FontName), Preferences.FontSize) }; if (dlg.ShowDialog() == DialogResult.OK) { - Preferences.fontSize = dlg.Font.Size; - Preferences.fontName = dlg.Font.FontFamily.Name; + Preferences.FontSize = dlg.Font.Size; + Preferences.FontName = dlg.Font.FontFamily.Name; } DisplayFontName(); } - private void OnBtnOkClick(object sender, EventArgs e) + private void OnBtnOkClick (object sender, EventArgs e) { - Preferences.timestampControl = checkBoxTimestamp.Checked; - Preferences.filterSync = checkBoxSyncFilter.Checked; - Preferences.filterTail = checkBoxFilterTail.Checked; - Preferences.followTail = checkBoxFollowTail.Checked; + Preferences.TimestampControl = checkBoxTimestamp.Checked; + Preferences.FilterSync = checkBoxSyncFilter.Checked; + Preferences.FilterTail = checkBoxFilterTail.Checked; + Preferences.FollowTail = checkBoxFollowTail.Checked; if (radioButtonVerticalMouseDrag.Checked) { - Preferences.timestampControlDragOrientation = DragOrientationsEnum.Vertical; + Preferences.TimestampControlDragOrientation = DragOrientationsEnum.Vertical; } else if (radioButtonVerticalMouseDragInverted.Checked) { - Preferences.timestampControlDragOrientation = DragOrientationsEnum.InvertedVertical; + Preferences.TimestampControlDragOrientation = DragOrientationsEnum.InvertedVertical; } else { - Preferences.timestampControlDragOrientation = DragOrientationsEnum.Horizontal; + Preferences.TimestampControlDragOrientation = DragOrientationsEnum.Horizontal; } SaveColumnizerList(); - Preferences.maskPrio = checkBoxMaskPrio.Checked; - Preferences.autoPick = checkBoxAutoPick.Checked; - Preferences.askForClose = checkBoxAskCloseTabs.Checked; - Preferences.allowOnlyOneInstance = checkBoxSingleInstance.Checked; - Preferences.openLastFiles = checkBoxOpenLastFiles.Checked; - Preferences.showTailState = checkBoxTailState.Checked; - Preferences.setLastColumnWidth = checkBoxColumnSize.Checked; - Preferences.lastColumnWidth = (int)cpDownColumnWidth.Value; - Preferences.showTimeSpread = checkBoxTimeSpread.Checked; - Preferences.reverseAlpha = checkBoxReverseAlpha.Checked; - Preferences.timeSpreadTimeMode = radioButtonTimeView.Checked; - - Preferences.saveSessions = checkBoxSaveSessions.Checked; - Preferences.sessionSaveDirectory = labelSessionSaveOwnDir.Text; + Preferences.MaskPrio = checkBoxMaskPrio.Checked; + Preferences.AutoPick = checkBoxAutoPick.Checked; + Preferences.AskForClose = checkBoxAskCloseTabs.Checked; + Preferences.AllowOnlyOneInstance = checkBoxSingleInstance.Checked; + Preferences.OpenLastFiles = checkBoxOpenLastFiles.Checked; + Preferences.ShowTailState = checkBoxTailState.Checked; + Preferences.SetLastColumnWidth = checkBoxColumnSize.Checked; + Preferences.LastColumnWidth = (int)cpDownColumnWidth.Value; + Preferences.ShowTimeSpread = checkBoxTimeSpread.Checked; + Preferences.ReverseAlpha = checkBoxReverseAlpha.Checked; + Preferences.TimeSpreadTimeMode = radioButtonTimeView.Checked; + + Preferences.SaveSessions = checkBoxSaveSessions.Checked; + Preferences.SessionSaveDirectory = labelSessionSaveOwnDir.Text; if (radioButtonsessionSaveDocuments.Checked) { - Preferences.saveLocation = SessionSaveLocation.DocumentsDir; + Preferences.SaveLocation = SessionSaveLocation.DocumentsDir; } else if (radioButtonSessionSaveOwn.Checked) { - Preferences.saveLocation = SessionSaveLocation.OwnDir; + Preferences.SaveLocation = SessionSaveLocation.OwnDir; } else if (radioButtonSessionApplicationStartupDir.Checked) { - Preferences.saveLocation = SessionSaveLocation.ApplicationStartupDir; + Preferences.SaveLocation = SessionSaveLocation.ApplicationStartupDir; } else { - Preferences.saveLocation = SessionSaveLocation.SameDir; + Preferences.SaveLocation = SessionSaveLocation.SameDir; } - Preferences.saveFilters = checkBoxSaveFilter.Checked; - Preferences.bufferCount = (int)upDownBlockCount.Value; - Preferences.linesPerBuffer = (int)upDownLinesPerBlock.Value; - Preferences.pollingInterval = (int)upDownPollingInterval.Value; - Preferences.multiThreadFilter = checkBoxMultiThread.Checked; - Preferences.defaultEncoding = comboBoxEncoding.SelectedItem != null ? (comboBoxEncoding.SelectedItem as Encoding).HeaderName : Encoding.Default.HeaderName; - Preferences.showColumnFinder = checkBoxColumnFinder.Checked; - Preferences.useLegacyReader = checkBoxLegacyReader.Checked; - - Preferences.maximumFilterEntries = (int)upDownMaximumFilterEntries.Value; - Preferences.maximumFilterEntriesDisplayed = (int)upDownMaximumFilterEntriesDisplayed.Value; + Preferences.SaveFilters = checkBoxSaveFilter.Checked; + Preferences.BufferCount = (int)upDownBlockCount.Value; + Preferences.LinesPerBuffer = (int)upDownLinesPerBlock.Value; + Preferences.PollingInterval = (int)upDownPollingInterval.Value; + Preferences.MultiThreadFilter = checkBoxMultiThread.Checked; + Preferences.DefaultEncoding = comboBoxEncoding.SelectedItem != null ? (comboBoxEncoding.SelectedItem as Encoding).HeaderName : Encoding.Default.HeaderName; + Preferences.ShowColumnFinder = checkBoxColumnFinder.Checked; + Preferences.UseLegacyReader = checkBoxLegacyReader.Checked; + + Preferences.MaximumFilterEntries = (int)upDownMaximumFilterEntries.Value; + Preferences.MaximumFilterEntriesDisplayed = (int)upDownMaximumFilterEntriesDisplayed.Value; Preferences.ShowErrorMessageAllowOnlyOneInstances = checkBoxShowErrorMessageOnlyOneInstance.Checked; - Preferences.darkMode = checkBoxDarkMode.Checked; + Preferences.DarkMode = checkBoxDarkMode.Checked; SavePluginSettings(); SaveHighlightMaskList(); @@ -687,19 +689,19 @@ private void OnBtnOkClick(object sender, EventArgs e) SaveMultifileData(); } - private void OnBtnToolClick(object sender, EventArgs e) + private void OnBtnToolClick (object sender, EventArgs e) { OnBtnToolClickInternal(textBoxTool); } //TODO: what is the purpose of this click? - private void OnBtnArgClick(object sender, EventArgs e) + private void OnBtnArgClick (object sender, EventArgs e) { OnBtnArgsClickInternal(textBoxArguments); } //TODO Remove or refactor this function - private void OnDataGridViewColumnizerRowsAdded(object sender, DataGridViewRowsAddedEventArgs e) + private void OnDataGridViewColumnizerRowsAdded (object sender, DataGridViewRowsAddedEventArgs e) { var comboCell = (DataGridViewComboBoxCell)dataGridViewColumnizer.Rows[e.RowIndex].Cells[1]; if (comboCell.Items.Count > 0) @@ -708,7 +710,7 @@ private void OnDataGridViewColumnizerRowsAdded(object sender, DataGridViewRowsAd } } - private void OnBtnDeleteClick(object sender, EventArgs e) + private void OnBtnDeleteClick (object sender, EventArgs e) { if (dataGridViewColumnizer.CurrentRow != null && !dataGridViewColumnizer.CurrentRow.IsNewRow) { @@ -718,48 +720,48 @@ private void OnBtnDeleteClick(object sender, EventArgs e) } } - private void OnDataGridViewColumnizerDataError(object sender, DataGridViewDataErrorEventArgs e) + private void OnDataGridViewColumnizerDataError (object sender, DataGridViewDataErrorEventArgs e) { e.Cancel = true; } - private void OnChkBoxSysoutCheckedChanged(object sender, EventArgs e) + private void OnChkBoxSysoutCheckedChanged (object sender, EventArgs e) { comboBoxColumnizer.Enabled = checkBoxSysout.Checked; } - private void OnBtnTailColorClick(object sender, EventArgs e) + private void OnBtnTailColorClick (object sender, EventArgs e) { ColorDialog dlg = new() { - Color = Preferences.showTailColor + Color = Preferences.ShowTailColor }; if (dlg.ShowDialog() == DialogResult.OK) { - Preferences.showTailColor = dlg.Color; + Preferences.ShowTailColor = dlg.Color; } } - private void OnChkBoxColumnSizeCheckedChanged(object sender, EventArgs e) + private void OnChkBoxColumnSizeCheckedChanged (object sender, EventArgs e) { cpDownColumnWidth.Enabled = checkBoxColumnSize.Checked; } - private void OnBtnTimespreadColorClick(object sender, EventArgs e) + private void OnBtnTimespreadColorClick (object sender, EventArgs e) { ColorDialog dlg = new() { - Color = Preferences.timeSpreadColor + Color = Preferences.TimeSpreadColor }; if (dlg.ShowDialog() == DialogResult.OK) { - Preferences.timeSpreadColor = dlg.Color; + Preferences.TimeSpreadColor = dlg.Color; } } - private void OnListBoxPluginSelectedIndexChanged(object sender, EventArgs e) + private void OnListBoxPluginSelectedIndexChanged (object sender, EventArgs e) { _selectedPlugin?.HideConfigForm(); @@ -791,13 +793,13 @@ private void OnListBoxPluginSelectedIndexChanged(object sender, EventArgs e) } } - private void OnBtnSessionSaveDirClick(object sender, EventArgs e) + private void OnBtnSessionSaveDirClick (object sender, EventArgs e) { FolderBrowserDialog dlg = new(); - if (Preferences.sessionSaveDirectory != null) + if (Preferences.SessionSaveDirectory != null) { - dlg.SelectedPath = Preferences.sessionSaveDirectory; + dlg.SelectedPath = Preferences.SessionSaveDirectory; } dlg.ShowNewFolderButton = true; @@ -809,7 +811,7 @@ private void OnBtnSessionSaveDirClick(object sender, EventArgs e) } } - private void OnPortableModeCheckedChanged(object sender, EventArgs e) + private void OnPortableModeCheckedChanged (object sender, EventArgs e) { try { @@ -858,7 +860,7 @@ private void OnPortableModeCheckedChanged(object sender, EventArgs e) } - private void OnBtnConfigPluginClick(object sender, EventArgs e) + private void OnBtnConfigPluginClick (object sender, EventArgs e) { if (!_selectedPlugin.HasEmbeddedForm()) { @@ -866,12 +868,12 @@ private void OnBtnConfigPluginClick(object sender, EventArgs e) } } - private void OnNumericUpDown1ValueChanged(object sender, EventArgs e) + private void OnNumericUpDown1ValueChanged (object sender, EventArgs e) { //TODO implement } - private void OnListBoxToolSelectedIndexChanged(object sender, EventArgs e) + private void OnListBoxToolSelectedIndexChanged (object sender, EventArgs e) { GetCurrentToolValues(); _selectedTool = listBoxTools.SelectedItem as ToolEntry; @@ -881,7 +883,7 @@ private void OnListBoxToolSelectedIndexChanged(object sender, EventArgs e) DisplayCurrentIcon(); } - private void OnBtnToolUpClick(object sender, EventArgs e) + private void OnBtnToolUpClick (object sender, EventArgs e) { var i = listBoxTools.SelectedIndex; @@ -897,7 +899,7 @@ private void OnBtnToolUpClick(object sender, EventArgs e) } } - private void OnBtnToolDownClick(object sender, EventArgs e) + private void OnBtnToolDownClick (object sender, EventArgs e) { var i = listBoxTools.SelectedIndex; @@ -913,13 +915,15 @@ private void OnBtnToolDownClick(object sender, EventArgs e) } } - private void OnBtnToolAddClick(object sender, EventArgs e) + [SupportedOSPlatform("windows")] + private void OnBtnToolAddClick (object sender, EventArgs e) { listBoxTools.Items.Add(new ToolEntry()); listBoxTools.SelectedIndex = listBoxTools.Items.Count - 1; } - private void OnToolDeleteButtonClick(object sender, EventArgs e) + [SupportedOSPlatform("windows")] + private void OnToolDeleteButtonClick (object sender, EventArgs e) { var i = listBoxTools.SelectedIndex; @@ -940,11 +944,12 @@ private void OnToolDeleteButtonClick(object sender, EventArgs e) } } - private void OnBtnIconClick(object sender, EventArgs e) + [SupportedOSPlatform("windows")] + private void OnBtnIconClick (object sender, EventArgs e) { if (_selectedTool != null) { - var iconFile = _selectedTool.iconFile; + var iconFile = _selectedTool.IconFile; if (Util.IsNullOrSpaces(iconFile)) { @@ -955,30 +960,32 @@ private void OnBtnIconClick(object sender, EventArgs e) if (dlg.ShowDialog() == DialogResult.OK) { - _selectedTool.iconFile = dlg.FileName; - _selectedTool.iconIndex = dlg.IconIndex; + _selectedTool.IconFile = dlg.FileName; + _selectedTool.IconIndex = dlg.IconIndex; DisplayCurrentIcon(); } } } - private void OnBtnCancelClick(object sender, EventArgs e) + private void OnBtnCancelClick (object sender, EventArgs e) { _selectedPlugin?.HideConfigForm(); } - private void OnBtnWorkingDirClick(object sender, EventArgs e) + private void OnBtnWorkingDirClick (object sender, EventArgs e) { OnBtnWorkingDirClick(textBoxWorkingDir); } - private void OnMultiFilePatternTextChanged(object sender, EventArgs e) + [SupportedOSPlatform("windows")] + private void OnMultiFilePatternTextChanged (object sender, EventArgs e) { var pattern = textBoxMultifilePattern.Text; - upDownMultifileDays.Enabled = pattern.Contains("$D"); + upDownMultifileDays.Enabled = pattern.Contains("$D", System.StringComparison.Ordinal); } - private void OnBtnExportClick(object sender, EventArgs e) + [SupportedOSPlatform("windows")] + private void OnBtnExportClick (object sender, EventArgs e) { SaveFileDialog dlg = new() { @@ -1002,7 +1009,7 @@ private void OnBtnExportClick(object sender, EventArgs e) /// /// /// - private void OnBtnImportClick(object sender, EventArgs e) + private void OnBtnImportClick (object sender, EventArgs e) { ImportSettingsDialog dlg = new(ExportImportFlags.All); diff --git a/src/LogExpert.UI/Dialogs/ParamRequesterDialog.Designer.cs b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.Designer.cs index bddf7808..a42f5b83 100644 --- a/src/LogExpert.UI/Dialogs/ParamRequesterDialog.Designer.cs +++ b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.Designer.cs @@ -62,7 +62,7 @@ private void InitializeComponent() this.buttonOk.TabIndex = 2; this.buttonOk.Text = "OK"; this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.okButton_Click); + this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); // // comboBoxValue // diff --git a/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs index 26d38846..ef272593 100644 --- a/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs +++ b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; +using System.Runtime.Versioning; namespace LogExpert.Dialogs; +[SupportedOSPlatform("windows")] public partial class ParamRequesterDialog : Form { #region Fields @@ -16,7 +11,7 @@ public partial class ParamRequesterDialog : Form #region cTor - public ParamRequesterDialog() + public ParamRequesterDialog () { InitializeComponent(); @@ -38,7 +33,7 @@ public ParamRequesterDialog() #region Events handler - private void ParamRequesterDialog_Shown(object sender, EventArgs e) + private void ParamRequesterDialog_Shown (object sender, EventArgs e) { labelValueForParameter.Text = ParamName; @@ -48,11 +43,12 @@ private void ParamRequesterDialog_Shown(object sender, EventArgs e) { comboBoxValue.Items.Add(value); } + comboBoxValue.SelectedIndex = 0; } } - private void okButton_Click(object sender, EventArgs e) + private void OnButtonOkClick (object sender, EventArgs e) { ParamValue = comboBoxValue.Text; } diff --git a/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs b/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs index d564884b..64c99a9f 100644 --- a/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs +++ b/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs @@ -1,4 +1,4 @@ -using System.Runtime.Versioning; +using System.Runtime.Versioning; using System.Text.RegularExpressions; namespace LogExpert.UI.Dialogs; @@ -8,7 +8,7 @@ public partial class RegexHelperDialog : Form { #region Fields - private static readonly int MAX_HISTORY = 30; + private const int MAX_HISTORY = 30; private bool _caseSensitive; private List _expressionHistoryList = []; private List _testtextHistoryList = []; @@ -17,7 +17,7 @@ public partial class RegexHelperDialog : Form #region cTor - public RegexHelperDialog() + public RegexHelperDialog () { InitializeComponent(); @@ -63,7 +63,7 @@ public List TesttextHistoryList #region Private Methods - private void UpdateMatches() + private void UpdateMatches () { textBoxMatches.Text = ""; try @@ -82,7 +82,7 @@ private void UpdateMatches() } } - private void LoadHistory() + private void LoadHistory () { comboBoxRegex.Items.Clear(); comboBoxRegex.DataSource = _expressionHistoryList; @@ -95,18 +95,18 @@ private void LoadHistory() #region Events handler - private void OnRegexHelperDialogLoad(object? sender, EventArgs e) + private void OnRegexHelperDialogLoad (object? sender, EventArgs e) { LoadHistory(); } - private void OnCaseSensitiveCheckBoxCheckedChanged(object sender, EventArgs e) + private void OnCaseSensitiveCheckBoxCheckedChanged (object sender, EventArgs e) { _caseSensitive = checkBoxCaseSensitive.Checked; UpdateMatches(); } - private void OnButtonOkClick(object sender, EventArgs e) + private void OnButtonOkClick (object sender, EventArgs e) { var text = comboBoxRegex.Text; comboBoxRegex.Items.Remove(text); @@ -127,17 +127,17 @@ private void OnButtonOkClick(object sender, EventArgs e) } } - private void OnComboBoxRegexTextChanged(object sender, EventArgs e) + private void OnComboBoxRegexTextChanged (object sender, EventArgs e) { UpdateMatches(); } - private void OnComboBoxTestTextTextChanged(object sender, EventArgs e) + private void OnComboBoxTestTextTextChanged (object sender, EventArgs e) { UpdateMatches(); } - private void OnButtonHelpClick(object sender, EventArgs e) + private void OnButtonHelpClick (object sender, EventArgs e) { Help.ShowHelp(this, "LogExpert.chm", HelpNavigator.Topic, "RegEx.htm"); } diff --git a/src/LogExpert.UI/Dialogs/SearchDialog.cs b/src/LogExpert.UI/Dialogs/SearchDialog.cs index e4542dc5..f1e09da9 100644 --- a/src/LogExpert.UI/Dialogs/SearchDialog.cs +++ b/src/LogExpert.UI/Dialogs/SearchDialog.cs @@ -1,9 +1,9 @@ -using LogExpert.Core.Entities; -using LogExpert.UI.Dialogs; - using System.Runtime.Versioning; using System.Text.RegularExpressions; +using LogExpert.Core.Entities; +using LogExpert.UI.Dialogs; + namespace LogExpert.Dialogs; [SupportedOSPlatform("windows")] @@ -11,13 +11,13 @@ public partial class SearchDialog : Form { #region Fields - private static readonly int MAX_HISTORY = 30; + private const int MAX_HISTORY = 30; #endregion #region cTor - public SearchDialog() + public SearchDialog () { InitializeComponent(); @@ -37,7 +37,7 @@ public SearchDialog() #region Events handler - private void OnSearchDialogLoad(object? sender, EventArgs e) + private void OnSearchDialogLoad (object? sender, EventArgs e) { if (SearchParams != null) { @@ -79,7 +79,7 @@ private void OnSearchDialogLoad(object? sender, EventArgs e) } } - private void OnButtonRegexClick(object sender, EventArgs e) + private void OnButtonRegexClick (object sender, EventArgs e) { RegexHelperDialog dlg = new() { @@ -95,7 +95,7 @@ private void OnButtonRegexClick(object sender, EventArgs e) } } - private void OnButtonOkClick(object sender, EventArgs e) + private void OnButtonOkClick (object sender, EventArgs e) { try { @@ -130,7 +130,7 @@ private void OnButtonOkClick(object sender, EventArgs e) #endregion - private void OnButtonCancelClick(object sender, EventArgs e) + private void OnButtonCancelClick (object sender, EventArgs e) { Close(); } diff --git a/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs b/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs index 60271fdf..a1a68d1f 100644 --- a/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs +++ b/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs @@ -1,14 +1,12 @@ -using LogExpert.Classes; +using System.Runtime.Versioning; + using LogExpert.UI.Controls.LogTabWindow; using LogExpert.UI.Dialogs; - -using System; -using System.Drawing; -using System.Windows.Forms; - +using LogExpert.UI.Entities; namespace LogExpert.Dialogs; +[SupportedOSPlatform("windows")] internal partial class ToolArgsDialog : Form { #region Fields @@ -19,7 +17,7 @@ internal partial class ToolArgsDialog : Form #region cTor - public ToolArgsDialog(LogTabWindow logTabWin, Form parent) + public ToolArgsDialog (LogTabWindow logTabWin, Form parent) { this.logTabWin = logTabWin; parent.AddOwnedForm(this); @@ -40,7 +38,7 @@ public ToolArgsDialog(LogTabWindow logTabWin, Form parent) #region Events handler - private void OnToolArgsDialogLoad(object sender, EventArgs e) + private void OnToolArgsDialogLoad (object sender, EventArgs e) { labelHelp.Text = "" + "%L = Current line number\n" + @@ -62,7 +60,7 @@ private void OnToolArgsDialogLoad(object sender, EventArgs e) textBoxArguments.Text = Arg; } - private void OnButtonRegexHelpClick(object sender, EventArgs e) + private void OnButtonRegexHelpClick (object sender, EventArgs e) { RegexHelperDialog regexDlg = new(); if (regexDlg.ShowDialog() == DialogResult.OK) @@ -72,7 +70,7 @@ private void OnButtonRegexHelpClick(object sender, EventArgs e) } //TODO: what is the purpose of this in the settings? Can we just send the line and info instead of the object? - private void OnButtonTestClick(object sender, EventArgs e) + private void OnButtonTestClick (object sender, EventArgs e) { if (logTabWin.CurrentLogWindow != null) { @@ -87,7 +85,7 @@ private void OnButtonTestClick(object sender, EventArgs e) } } - private void OnButtonOkClick(object sender, EventArgs e) + private void OnButtonOkClick (object sender, EventArgs e) { Arg = textBoxArguments.Text; } diff --git a/src/LogExpert.UI/Entities/ArgParser.cs b/src/LogExpert.UI/Entities/ArgParser.cs index 215a1981..8aa65cfd 100644 --- a/src/LogExpert.UI/Entities/ArgParser.cs +++ b/src/LogExpert.UI/Entities/ArgParser.cs @@ -1,51 +1,40 @@ -using System.Text; +using System.Runtime.Versioning; +using System.Text; using System.Text.RegularExpressions; using LogExpert.Core.Classes; using LogExpert.Dialogs; -namespace LogExpert.Classes; +namespace LogExpert.UI.Entities; -internal class ArgParser +internal class ArgParser (string argTemplate) { - #region Fields - - private readonly string argLine; - - #endregion - - #region cTor - - public ArgParser (string argTemplate) - { - argLine = argTemplate; - } - - #endregion - #region Public methods + [SupportedOSPlatform("windows")] public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo, Form parent) { - StringBuilder builder = new(argLine); - builder.Replace("%L", "" + lineNum); - builder.Replace("%P", logFileInfo.DirectoryName); - builder.Replace("%N", logFileInfo.FileName); - builder.Replace("%F", logFileInfo.FullName); - builder.Replace("%E", Util.GetExtension(logFileInfo.FileName)); - var stripped = Util.StripExtension(logFileInfo.FileName); - builder.Replace("%M", stripped); + StringBuilder builder = new(argTemplate); - builder.Replace("%URI", logFileInfo.Uri.AbsoluteUri); + _ = builder.Replace("%L", "" + lineNum); + _ = builder.Replace("%P", logFileInfo.DirectoryName); + _ = builder.Replace("%N", logFileInfo.FileName); + _ = builder.Replace("%F", logFileInfo.FullName); + _ = builder.Replace("%E", Util.GetExtension(logFileInfo.FileName)); + var stripped = Util.StripExtension(logFileInfo.FileName); + _ = builder.Replace("%M", stripped); + _ = builder.Replace("%URI", logFileInfo.Uri.AbsoluteUri); var user = logFileInfo.Uri.UserInfo; - if (user.Contains(":")) + + if (user.Contains(':', StringComparison.Ordinal)) { - user = user.Substring(0, user.IndexOf(':')); + user = user[..user.IndexOf(':', StringComparison.Ordinal)]; } - builder.Replace("%S", user); - builder.Replace("%R", logFileInfo.Uri.PathAndQuery); - builder.Replace("%H", logFileInfo.Uri.Host); - builder.Replace("%T", logFileInfo.Uri.Port.ToString()); + + _ = builder.Replace("%S", user); + _ = builder.Replace("%R", logFileInfo.Uri.PathAndQuery); + _ = builder.Replace("%H", logFileInfo.Uri.Host); + _ = builder.Replace("%T", logFileInfo.Uri.Port.ToString()); var sPos = 0; string reg; @@ -57,7 +46,7 @@ public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo if (reg != null && replace != null) { var result = Regex.Replace(logLine.FullLine, reg, replace); - builder.Insert(sPos, result); + _ = builder.Insert(sPos, result); } } while (replace != null); @@ -76,12 +65,15 @@ public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo { end = builder.Length - 1; } + ask = builder.ToString().Substring(i + 2, end - i - 2); } + string[] values = null; + if (builder[end + 1] == '(') { - var end2 = builder.ToString().IndexOf(')'); + var end2 = builder.ToString().IndexOf(')', StringComparison.Ordinal); if (end2 == -1) { end2 = builder.Length - 1; @@ -91,17 +83,20 @@ public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo end = end2; } - ParamRequesterDialog dlg = new(); - dlg.ParamName = ask; - dlg.Values = values; + ParamRequesterDialog dlg = new() + { + ParamName = ask, + Values = values + }; + DialogResult res = dlg.ShowDialog(parent); - if (res == DialogResult.OK) + if (res is DialogResult.OK) { - builder.Remove(i, end - i + 1); - builder.Insert(i, dlg.ParamValue); + _ = builder.Remove(i, end - i + 1); + _ = builder.Insert(i, dlg.ParamValue); } - else if (res == DialogResult.Cancel || res == DialogResult.Abort) + else if (res is DialogResult.Cancel or DialogResult.Abort) { return null; } @@ -126,27 +121,33 @@ private string GetNextGroup (StringBuilder builder, ref int sPos) { ePos = sPos + 1; var count = 1; + while (ePos < builder.Length) { if (builder[ePos] == '{') { count++; } + if (builder[ePos] == '}') { count--; } + if (count == 0) { var reg = builder.ToString(sPos + 1, ePos - sPos - 1); - builder.Remove(sPos, ePos - sPos + 1); + _ = builder.Remove(sPos, ePos - sPos + 1); return reg; } + ePos++; } } + sPos++; } + return null; } diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index 6c795af4..4d760cde 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -1,10 +1,13 @@ -using LogExpert.Core.Classes.Highlight; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes.Highlight; using LogExpert.Core.Config; using LogExpert.Core.Entities; using LogExpert.Core.Interface; using LogExpert.Dialogs; using LogExpert.UI.Controls; using LogExpert.UI.Interface; + using NLog; namespace LogExpert.UI.Entities; @@ -24,13 +27,15 @@ internal static class PaintHelper #region Properties public static IConfigManager ConfigManager { get; set; } + private static Preferences Preferences => ConfigManager.Settings.Preferences; #endregion #region Public methods - public static void CellPainting(ILogPaintContextUI logPaintCtx, BufferedDataGridView gridView, int rowIndex, + [SupportedOSPlatform("windows")] + public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) { if (rowIndex < 0 || e.ColumnIndex < 0) @@ -102,9 +107,11 @@ public static void CellPainting(ILogPaintContextUI logPaintCtx, BufferedDataGrid brush.Dispose(); if (bookmark.Text.Length > 0) { - StringFormat format = new(); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Center; + StringFormat format = new() + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Center + }; Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); Font font = logPaintCtx.MonospacedFont; e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), @@ -119,45 +126,55 @@ public static void CellPainting(ILogPaintContextUI logPaintCtx, BufferedDataGrid } } - public static DataGridViewTextBoxColumn CreateMarkerColumn() + [SupportedOSPlatform("windows")] + public static DataGridViewTextBoxColumn CreateMarkerColumn () { - DataGridViewTextBoxColumn markerColumn = new(); - markerColumn.HeaderText = ""; - markerColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - markerColumn.Resizable = DataGridViewTriState.False; - markerColumn.DividerWidth = 1; - markerColumn.ReadOnly = true; - markerColumn.SortMode = DataGridViewColumnSortMode.NotSortable; + DataGridViewTextBoxColumn markerColumn = new() + { + HeaderText = "", + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.False, + DividerWidth = 1, + ReadOnly = true, + SortMode = DataGridViewColumnSortMode.NotSortable + }; return markerColumn; } - public static DataGridViewTextBoxColumn CreateLineNumberColumn() + [SupportedOSPlatform("windows")] + public static DataGridViewTextBoxColumn CreateLineNumberColumn () { - DataGridViewTextBoxColumn lineNumberColumn = new(); - lineNumberColumn.HeaderText = "Line"; - lineNumberColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - lineNumberColumn.Resizable = DataGridViewTriState.NotSet; - lineNumberColumn.DividerWidth = 1; - lineNumberColumn.ReadOnly = true; - lineNumberColumn.SortMode = DataGridViewColumnSortMode.NotSortable; + DataGridViewTextBoxColumn lineNumberColumn = new() + { + HeaderText = "Line", + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.NotSet, + DividerWidth = 1, + ReadOnly = true, + SortMode = DataGridViewColumnSortMode.NotSortable + }; return lineNumberColumn; } - public static DataGridViewColumn CreateTitleColumn(string colName) + [SupportedOSPlatform("windows")] + public static DataGridViewColumn CreateTitleColumn (string colName) { - DataGridViewColumn titleColumn = new LogTextColumn(); - titleColumn.HeaderText = colName; - titleColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - titleColumn.Resizable = DataGridViewTriState.NotSet; - titleColumn.DividerWidth = 1; - titleColumn.SortMode = DataGridViewColumnSortMode.NotSortable; + DataGridViewColumn titleColumn = new LogTextColumn + { + HeaderText = colName, + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.NotSet, + DividerWidth = 1, + SortMode = DataGridViewColumnSortMode.NotSortable + }; return titleColumn; } - public static void SetColumnizer(ILogLineColumnizer columnizer, BufferedDataGridView gridView) + [SupportedOSPlatform("windows")] + public static void SetColumnizer (ILogLineColumnizer columnizer, BufferedDataGridView gridView) { var rowCount = gridView.RowCount; var currLine = gridView.CurrentCellAddress.Y; @@ -188,6 +205,7 @@ public static void SetColumnizer(ILogLineColumnizer columnizer, BufferedDataGrid { gridView.CurrentCell = gridView.Rows[currLine].Cells[0]; } + if (currFirstLine != -1) { gridView.FirstDisplayedScrollingRowIndex = currFirstLine; @@ -198,18 +216,19 @@ public static void SetColumnizer(ILogLineColumnizer columnizer, BufferedDataGrid //TODO: Original name is AutoResizeColumn. Where is this used? //TODO: Rename ConfigManager to configManager - private static void AutoResizeColumns(BufferedDataGridView gridView, IConfigManager CnofigManager) + [SupportedOSPlatform("windows")] + private static void AutoResizeColumns (BufferedDataGridView gridView, IConfigManager configManager) { try { gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - if (gridView.Columns.Count > 1 && Preferences.setLastColumnWidth && - gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.lastColumnWidth + if (gridView.Columns.Count > 1 && Preferences.SetLastColumnWidth && + gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.LastColumnWidth ) { // It seems that using 'MinimumWidth' instead of 'Width' prevents the DataGridView's NullReferenceExceptions //gridView.Columns[gridView.Columns.Count - 1].Width = this.Preferences.lastColumnWidth; - gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.lastColumnWidth; + gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.LastColumnWidth; } } catch (NullReferenceException e) @@ -222,18 +241,17 @@ private static void AutoResizeColumns(BufferedDataGridView gridView, IConfigMana } } - public static void ApplyDataGridViewPrefs(BufferedDataGridView dataGridView, Preferences prefs, IConfigManager configManager) + [SupportedOSPlatform("windows")] + public static void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, Preferences prefs, IConfigManager configManager) { //TODO: This is a very bad solution and should be solved ASAP - if (ConfigManager == null) { - ConfigManager = configManager; - } + ConfigManager ??= configManager; if (dataGridView.Columns.Count > 1) { - if (prefs.setLastColumnWidth) + if (prefs.SetLastColumnWidth) { - dataGridView.Columns[dataGridView.Columns.Count - 1].MinimumWidth = prefs.lastColumnWidth; + dataGridView.Columns[dataGridView.Columns.Count - 1].MinimumWidth = prefs.LastColumnWidth; } else { @@ -243,20 +261,24 @@ public static void ApplyDataGridViewPrefs(BufferedDataGridView dataGridView, Pre dataGridView.Columns[dataGridView.Columns.Count - 1].MinimumWidth = 5; // default } } + if (dataGridView.RowCount > 0) { dataGridView.UpdateRowHeightInfo(0, true); } + dataGridView.Invalidate(); dataGridView.Refresh(); AutoResizeColumns(dataGridView, ConfigManager); } - public static Rectangle BorderWidths(DataGridViewAdvancedBorderStyle advancedBorderStyle) + [SupportedOSPlatform("windows")] + public static Rectangle BorderWidths (DataGridViewAdvancedBorderStyle advancedBorderStyle) { - Rectangle rect = new(); - - rect.X = advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; + Rectangle rect = new() + { + X = advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1 + }; if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble || advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble) { @@ -294,12 +316,14 @@ public static Rectangle BorderWidths(DataGridViewAdvancedBorderStyle advancedBor #region Private Methods - private static void PaintCell(ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) + [SupportedOSPlatform("windows")] + private static void PaintCell (ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) { PaintHighlightedCell(logPaintCtx, e, gridView, noBackgroundFill, groundEntry); } - private static void PaintHighlightedCell(ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) + [SupportedOSPlatform("windows")] + private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) { var value = e.Value ?? string.Empty; @@ -312,11 +336,13 @@ private static void PaintHighlightedCell(ILogPaintContextUI logPaintCtx, DataGri if (value is Column column) { - if (string.IsNullOrEmpty(column.FullValue) == false) + if (!string.IsNullOrEmpty(column.FullValue)) { - HilightMatchEntry hme = new(); - hme.StartPos = 0; - hme.Length = column.FullValue.Length; + HilightMatchEntry hme = new() + { + StartPos = 0, + Length = column.FullValue.Length + }; var he = new HighlightEntry { @@ -386,7 +412,7 @@ private static void PaintHighlightedCell(ILogPaintContextUI logPaintCtx, DataGri var matchWord = string.Empty; if (value is Column again) { - if (string.IsNullOrEmpty(again.FullValue) == false) + if (!string.IsNullOrEmpty(again.FullValue)) { matchWord = again.FullValue.Substring(matchEntry.StartPos, matchEntry.Length); } @@ -411,6 +437,7 @@ private static void PaintHighlightedCell(ILogPaintContextUI logPaintCtx, DataGri foreColor = Color.White; } } + TextRenderer.DrawText(e.Graphics, matchWord, font, wordRect, foreColor, flags); wordPos.Offset(wordSize.Width, 0); @@ -428,7 +455,7 @@ private static void PaintHighlightedCell(ILogPaintContextUI logPaintCtx, DataGri /// List of all highlight matches for the current cell /// The entry that is used as the default. /// List of HilightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. - private static IList MergeHighlightMatchEntries(IList matchList, HilightMatchEntry groundEntry) + private static IList MergeHighlightMatchEntries (IList matchList, HilightMatchEntry groundEntry) { // Fill an area with lenth of whole text with a default hilight entry var entryArray = new HighlightEntry[groundEntry.Length]; @@ -456,7 +483,7 @@ private static IList MergeHighlightMatchEntries(IList mergedList = new List(); + IList mergedList = []; if (entryArray.Length > 0) { HighlightEntry currentEntry = entryArray[0]; @@ -466,21 +493,26 @@ private static IList MergeHighlightMatchEntries(IList LogWindow.FileName; public LogWindow LogWindow { get; } = logWindow; diff --git a/src/LogExpert.UI/Extensions/Utils.cs b/src/LogExpert.UI/Extensions/Utils.cs index 6b2c2d67..27d000b0 100644 --- a/src/LogExpert.UI/Extensions/Utils.cs +++ b/src/LogExpert.UI/Extensions/Utils.cs @@ -1,8 +1,12 @@ -namespace LogExpert.UI.Extensions; +using System.Runtime.Versioning; + +namespace LogExpert.UI.Extensions; + internal static class Utils { - public static string GetWordFromPos(int xPos, string text, Graphics g, Font font) + [SupportedOSPlatform("windows")] + public static string GetWordFromPos (int xPos, string text, Graphics g, Font font) { var words = text.Split([' ', '.', ':', ';']); @@ -44,13 +48,8 @@ public static string GetWordFromPos(int xPos, string text, Graphics g, Font font y++; } - if (found) - { - return words[y]; - } - else - { - return null; - } + return found + ? words[y] + : null; } } diff --git a/src/LogExpert/Classes/CommandLine/CmdLineInt.cs b/src/LogExpert/Classes/CommandLine/CmdLineInt.cs index c67dd9ad..c9bfead4 100644 --- a/src/LogExpert/Classes/CommandLine/CmdLineInt.cs +++ b/src/LogExpert/Classes/CommandLine/CmdLineInt.cs @@ -14,8 +14,8 @@ public class CmdLineInt : CmdLineParameter { #region Fields - private readonly int _max = int.MaxValue; - private readonly int _min = int.MinValue; + private readonly int _max; + private readonly int _min; #endregion @@ -27,9 +27,11 @@ public class CmdLineInt : CmdLineParameter /// Name of parameter. /// Require that the parameter is present in the command line. /// The explanation of the parameter to add to the help screen. - public CmdLineInt(string name, bool required, string helpMessage) + public CmdLineInt (string name, bool required, string helpMessage) : base(name, required, helpMessage) { + _max = int.MaxValue; + _min = int.MinValue; } /// @@ -40,10 +42,10 @@ public CmdLineInt(string name, bool required, string helpMessage) /// The explanation of the parameter to add to the help screen. /// The minimum value of the parameter. /// The maximum valie of the parameter. - public CmdLineInt(string name, bool required, string helpMessage, int min, int max) + public CmdLineInt (string name, bool required, string helpMessage, int min, int max) : base(name, required, helpMessage) { - _min = min; + _max = min; _max = max; } @@ -54,7 +56,7 @@ public CmdLineInt(string name, bool required, string helpMessage, int min, int m /// /// Returns the current value of the parameter. /// - new public int Value { get; private set; } + public new int Value { get; private set; } #endregion @@ -64,7 +66,7 @@ public CmdLineInt(string name, bool required, string helpMessage, int min, int m /// Sets the value of the parameter. /// /// A string containing a integer expression. - public override void SetValue(string value) + public override void SetValue (string value) { base.SetValue(value); int i; @@ -76,14 +78,17 @@ public override void SetValue(string value) { throw new CmdLineException(Name, "Value is not an integer."); } + if (i < _min) { - throw new CmdLineException(Name, string.Format("Value must be greather or equal to {0}.", _min)); + throw new CmdLineException(Name, $"Value must be greather or equal to {_min}."); } + if (i > _max) { - throw new CmdLineException(Name, string.Format("Value must be less or equal to {0}.", _max)); + throw new CmdLineException(Name, $"Value must be less or equal to {_max}."); } + Value = i; } @@ -92,10 +97,7 @@ public override void SetValue(string value) /// /// /// - public static implicit operator int(CmdLineInt s) - { - return s.Value; - } + public static implicit operator int (CmdLineInt s) => s.Value; #endregion } \ No newline at end of file diff --git a/src/LogExpert/Classes/LogExpertProxy.cs b/src/LogExpert/Classes/LogExpertProxy.cs index 6823f7da..bf122209 100644 --- a/src/LogExpert/Classes/LogExpertProxy.cs +++ b/src/LogExpert/Classes/LogExpertProxy.cs @@ -1,6 +1,6 @@ using LogExpert.Config; using LogExpert.Core.Interface; -using LogExpert.UI.Dialogs.LogTabWindow; +using LogExpert.UI.Controls.LogWindow; using NLog; diff --git a/src/LogExpert/Config/ConfigManager.cs b/src/LogExpert/Config/ConfigManager.cs index 939860b4..cae55ba6 100644 --- a/src/LogExpert/Config/ConfigManager.cs +++ b/src/LogExpert/Config/ConfigManager.cs @@ -26,6 +26,7 @@ public class ConfigManager : IConfigManager private static readonly object _monitor = new(); private static ConfigManager _instance; private readonly object _loadSaveLock = new(); + private readonly object _saveSaveLock = new(); private Settings _settings; #endregion @@ -184,45 +185,45 @@ private Settings LoadOrCreateNew (FileInfo fileInfo) settings.Preferences ??= new Preferences(); - settings.Preferences.toolEntries ??= []; + settings.Preferences.ToolEntries ??= []; - settings.Preferences.columnizerMaskList ??= []; + settings.Preferences.ColumnizerMaskList ??= []; - settings.fileHistoryList ??= []; + settings.FileHistoryList ??= []; - settings.lastOpenFilesList ??= []; + settings.LastOpenFilesList ??= []; - settings.fileColors ??= []; + settings.FileColors ??= []; - if (settings.Preferences.showTailColor == Color.Empty) + if (settings.Preferences.ShowTailColor == Color.Empty) { - settings.Preferences.showTailColor = Color.FromKnownColor(KnownColor.Blue); + settings.Preferences.ShowTailColor = Color.FromKnownColor(KnownColor.Blue); } - if (settings.Preferences.timeSpreadColor == Color.Empty) + if (settings.Preferences.TimeSpreadColor == Color.Empty) { - settings.Preferences.timeSpreadColor = Color.Gray; + settings.Preferences.TimeSpreadColor = Color.Gray; } - if (settings.Preferences.bufferCount < 10) + if (settings.Preferences.BufferCount < 10) { - settings.Preferences.bufferCount = 100; + settings.Preferences.BufferCount = 100; } - if (settings.Preferences.linesPerBuffer < 1) + if (settings.Preferences.LinesPerBuffer < 1) { - settings.Preferences.linesPerBuffer = 500; + settings.Preferences.LinesPerBuffer = 500; } - settings.filterList ??= []; + settings.FilterList ??= []; - settings.searchHistoryList ??= []; + settings.SearchHistoryList ??= []; - settings.filterHistoryList ??= []; + settings.FilterHistoryList ??= []; - settings.filterRangeHistoryList ??= []; + settings.FilterRangeHistoryList ??= []; - foreach (FilterParams filterParams in settings.filterList) + foreach (FilterParams filterParams in settings.FilterList) { filterParams.Init(); } @@ -232,25 +233,25 @@ private Settings LoadOrCreateNew (FileInfo fileInfo) settings.Preferences.HighlightGroupList = []; } - settings.Preferences.highlightMaskList ??= []; + settings.Preferences.HighlightMaskList ??= []; - if (settings.Preferences.pollingInterval < 20) + if (settings.Preferences.PollingInterval < 20) { - settings.Preferences.pollingInterval = 250; + settings.Preferences.PollingInterval = 250; } - settings.Preferences.multiFileOptions ??= new MultiFileOptions(); + settings.Preferences.MultiFileOptions ??= new MultiFileOptions(); - settings.Preferences.defaultEncoding ??= Encoding.Default.HeaderName; + settings.Preferences.DefaultEncoding ??= Encoding.Default.HeaderName; - if (settings.Preferences.maximumFilterEntriesDisplayed == 0) + if (settings.Preferences.MaximumFilterEntriesDisplayed == 0) { - settings.Preferences.maximumFilterEntriesDisplayed = 20; + settings.Preferences.MaximumFilterEntriesDisplayed = 20; } - if (settings.Preferences.maximumFilterEntries == 0) + if (settings.Preferences.MaximumFilterEntries == 0) { - settings.Preferences.maximumFilterEntries = 30; + settings.Preferences.MaximumFilterEntries = 30; } SetBoundsWithinVirtualScreen(settings); @@ -269,19 +270,16 @@ private void Save (Settings settings, SettingsFlags flags) lock (_loadSaveLock) { _logger.Info("Saving settings"); - lock (this) - { - var dir = Settings.Preferences.PortableMode ? Application.StartupPath : ConfigDir; - - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } + var dir = Settings.Preferences.PortableMode ? Application.StartupPath : ConfigDir; - FileInfo fileInfo = new(dir + Path.DirectorySeparatorChar + "settings.json"); - Save(fileInfo, settings); + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); } + FileInfo fileInfo = new(dir + Path.DirectorySeparatorChar + "settings.json"); + Save(fileInfo, settings); + OnConfigChanged(flags); } } @@ -311,7 +309,7 @@ private void Save (FileInfo fileInfo, Settings settings, SettingsFlags flags) private static void SaveAsJSON (FileInfo fileInfo, Settings settings) { - settings.versionBuild = Assembly.GetExecutingAssembly().GetName().Version.Build; + settings.VersionBuild = Assembly.GetExecutingAssembly().GetName().Version.Build; using StreamWriter sw = new(fileInfo.Create()); JsonSerializer serializer = new(); @@ -370,10 +368,10 @@ private Settings Import (Settings currentSettings, FileInfo fileInfo, ExportImpo { newSettings = ownSettings; newSettings.Preferences = ObjectClone.Clone(importSettings.Preferences); - newSettings.Preferences.columnizerMaskList = ownSettings.Preferences.columnizerMaskList; - newSettings.Preferences.highlightMaskList = ownSettings.Preferences.highlightMaskList; + newSettings.Preferences.ColumnizerMaskList = ownSettings.Preferences.ColumnizerMaskList; + newSettings.Preferences.HighlightMaskList = ownSettings.Preferences.HighlightMaskList; newSettings.Preferences.HighlightGroupList = ownSettings.Preferences.HighlightGroupList; - newSettings.Preferences.toolEntries = ownSettings.Preferences.toolEntries; + newSettings.Preferences.ToolEntries = ownSettings.Preferences.ToolEntries; } else { @@ -382,11 +380,11 @@ private Settings Import (Settings currentSettings, FileInfo fileInfo, ExportImpo if ((flags & ExportImportFlags.ColumnizerMasks) == ExportImportFlags.ColumnizerMasks) { - newSettings.Preferences.columnizerMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.columnizerMaskList, importSettings.Preferences.columnizerMaskList); + newSettings.Preferences.ColumnizerMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.ColumnizerMaskList, importSettings.Preferences.ColumnizerMaskList); } if ((flags & ExportImportFlags.HighlightMasks) == ExportImportFlags.HighlightMasks) { - newSettings.Preferences.highlightMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.highlightMaskList, importSettings.Preferences.highlightMaskList); + newSettings.Preferences.HighlightMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.HighlightMaskList, importSettings.Preferences.HighlightMaskList); } if ((flags & ExportImportFlags.HighlightSettings) == ExportImportFlags.HighlightSettings) { @@ -394,7 +392,7 @@ private Settings Import (Settings currentSettings, FileInfo fileInfo, ExportImpo } if ((flags & ExportImportFlags.ToolEntries) == ExportImportFlags.ToolEntries) { - newSettings.Preferences.toolEntries = ReplaceOrKeepExisting(flags, ownSettings.Preferences.toolEntries, importSettings.Preferences.toolEntries); + newSettings.Preferences.ToolEntries = ReplaceOrKeepExisting(flags, ownSettings.Preferences.ToolEntries, importSettings.Preferences.ToolEntries); } return newSettings; @@ -415,10 +413,10 @@ private static List ReplaceOrKeepExisting (ExportImportFlags flags, List GetUsersForHost(string host) + internal IList GetUsersForHost (string host) { IList result = []; foreach (Credentials cred in _credList) { - if (cred.Host.Equals(host)) + if (cred.Host.Equals(host, System.StringComparison.Ordinal)) { result.Add(cred.UserName); } @@ -38,11 +38,11 @@ internal IList GetUsersForHost(string host) return result; } - internal Credentials GetCredentials(string host, string user) + internal Credentials GetCredentials (string host, string user) { foreach (Credentials cred in _credList) { - if (cred.Host.Equals(host) && cred.UserName.Equals(user)) + if (cred.Host.Equals(host, System.StringComparison.Ordinal) && cred.UserName.Equals(user, System.StringComparison.Ordinal)) { return cred; } @@ -51,7 +51,7 @@ internal Credentials GetCredentials(string host, string user) return null; } - internal void Add(Credentials cred) + internal void Add (Credentials cred) { RemoveCredentials(cred.Host, cred.UserName); _credList.Add(cred); diff --git a/src/SftpFileSystemx64/SftpFileSystem.cs b/src/SftpFileSystemx64/SftpFileSystem.cs index d899b430..bdc86465 100644 --- a/src/SftpFileSystemx64/SftpFileSystem.cs +++ b/src/SftpFileSystemx64/SftpFileSystem.cs @@ -1,33 +1,24 @@ -using LogExpert; - -using Renci.SshNet; - using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using System.Xml.Serialization; +using LogExpert; + +using Renci.SshNet; + namespace SftpFileSystem; -public class SftpFileSystem : IFileSystemPlugin, ILogExpertPluginConfigurator +public class SftpFileSystem (IFileSystemCallback callback) : IFileSystemPlugin, ILogExpertPluginConfigurator { #region Private Fields - private readonly ILogExpertLogger _logger; + private readonly ILogExpertLogger _logger = callback.GetLogger(); private ConfigDialog _configDialog; private volatile PrivateKeyFile _privateKeyFile; - - #endregion - - #region Ctor - - public SftpFileSystem(IFileSystemCallback callback) - { - _logger = callback.GetLogger(); - CredentialsCache = new CredentialCache(); - } + private object _lock = new object(); #endregion @@ -37,12 +28,12 @@ public SftpFileSystem(IFileSystemCallback callback) public string Text => "SFTP plugin"; - public bool CanHandleUri(string uriString) + public bool CanHandleUri (string uriString) { try { Uri uri = new(uriString); - return uri.Scheme.Equals("sftp", StringComparison.InvariantCultureIgnoreCase); + return uri.Scheme.Equals("sftp", StringComparison.OrdinalIgnoreCase); } catch (Exception e) { @@ -51,7 +42,7 @@ public bool CanHandleUri(string uriString) } } - public ILogFileInfo GetLogfileInfo(string uriString) + public ILogFileInfo GetLogfileInfo (string uriString) { try { @@ -69,19 +60,20 @@ public ILogFileInfo GetLogfileInfo(string uriString) #region Interface ILogExpertPluginConfigurator - public bool HasEmbeddedForm() + public bool HasEmbeddedForm () { return true; } - public void HideConfigForm() + public void HideConfigForm () { ConfigData = _configDialog.ConfigData; _configDialog.Hide(); _configDialog.Dispose(); } - public void LoadConfig(string configDir) + //TODO JSON config should be used + public void LoadConfig (string configDir) { XmlSerializer xml = new(ConfigData.GetType()); @@ -112,7 +104,7 @@ public void LoadConfig(string configDir) } } - public void SaveConfig(string configDir) + public void SaveConfig (string configDir) { _logger.Info("Saving SFTP config"); XmlSerializer xml = new(ConfigData.GetType()); @@ -137,12 +129,12 @@ public void SaveConfig(string configDir) } } - public void ShowConfigDialog(object owner) + public void ShowConfigDialog (object owner) { throw new NotImplementedException(); } - public void ShowConfigForm(object parentPanel) + public void ShowConfigForm (object parentPanel) { _configDialog = new ConfigDialog(ConfigData) { @@ -152,7 +144,7 @@ public void ShowConfigForm(object parentPanel) _configDialog.Show(); } - public void StartConfig() + public void StartConfig () { } @@ -168,15 +160,15 @@ public PrivateKeyFile PrivateKeyFile set => _privateKeyFile = value; } - private CredentialCache CredentialsCache { get; } + private CredentialCache CredentialsCache { get; } = new CredentialCache(); #endregion - internal Credentials GetCredentials(Uri uri, bool cacheAllowed, bool hidePasswordField) + internal Credentials GetCredentials (Uri uri, bool cacheAllowed, bool hidePasswordField) { // Synchronized access to the GetCredentials() method prevents multiple login dialogs when loading multiple files at once // (e.g. on startup). So the user only needs to enter credentials once for the same host. - lock (this) + lock (_lock) { string userName = null; string password = null;