diff --git a/TODOs.txt b/TODOs.txt new file mode 100644 index 00000000..cf11bfa9 --- /dev/null +++ b/TODOs.txt @@ -0,0 +1,2 @@ +Add Copilot Instruction txt +Add Copilot HELP md for description what it does \ No newline at end of file diff --git a/src/CsvColumnizer/CsvColumnizer.cs b/src/CsvColumnizer/CsvColumnizer.cs index 9254c4ca..c98eb515 100644 --- a/src/CsvColumnizer/CsvColumnizer.cs +++ b/src/CsvColumnizer/CsvColumnizer.cs @@ -93,7 +93,7 @@ public string[] GetColumnNames () if (_isValidCsv) { var i = 0; - foreach (CsvColumn column in _columnList) + foreach (var column in _columnList) { names[i++] = column.Name; } @@ -156,7 +156,7 @@ public void Selected (ILogLineColumnizerCallback callback) if (_isValidCsv) // see PreProcessLine() { _columnList.Clear(); - ILogLine line = _config.HasFieldNames ? _firstLine : callback.GetLogLine(0); + var line = _config.HasFieldNames ? _firstLine : callback.GetLogLine(0); if (line != null) { @@ -241,7 +241,7 @@ public void LoadConfig (string configDir) public Priority GetPriority (string fileName, IEnumerable samples) { - Priority result = Priority.NotSupport; + var result = Priority.NotSupport; if (fileName.EndsWith("csv", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/FlashIconHighlighter/FlashIconPlugin.cs b/src/FlashIconHighlighter/FlashIconPlugin.cs index fdf4e2f3..73b3d1bb 100644 --- a/src/FlashIconHighlighter/FlashIconPlugin.cs +++ b/src/FlashIconHighlighter/FlashIconPlugin.cs @@ -20,7 +20,7 @@ internal class FlashIconPlugin : IKeywordAction public void Execute (string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer) { - FormCollection openForms = Application.OpenForms; + var openForms = Application.OpenForms; foreach (Form form in openForms) { if (form.TopLevel && form.Name.Equals("LogTabWindow", StringComparison.OrdinalIgnoreCase) && form.Text.Contains(callback.GetFileName(), StringComparison.Ordinal)) diff --git a/src/GlassfishColumnizer/GlassfishColumnizer.cs b/src/GlassfishColumnizer/GlassfishColumnizer.cs index d80cc0c9..c6afcde7 100644 --- a/src/GlassfishColumnizer/GlassfishColumnizer.cs +++ b/src/GlassfishColumnizer/GlassfishColumnizer.cs @@ -76,7 +76,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi var temp = line.FullLine; - Column[] columns = Column.CreateColumns(COLUMN_COUNT, cLogLine); + var columns = Column.CreateColumns(COLUMN_COUNT, cLogLine); cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); // delete '[#|' and '|#]' @@ -100,7 +100,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi { try { - DateTime dateTime = GetTimestamp(callback, line); + var dateTime = GetTimestamp(callback, line); if (dateTime == DateTime.MinValue) { columns[1].FullValue = temp; @@ -114,7 +114,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi columns[0].FullValue = "n/a"; } - Column timestmp = columns[0]; + var timestmp = columns[0]; string[] cols; cols = temp.Split(trimChars, COLUMN_COUNT, StringSplitOptions.None); @@ -180,7 +180,7 @@ public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine logL try { // convert glassfish timestamp into a readable format: - if (DateTime.TryParseExact(value, DATETIME_FORMAT, cultureInfo, DateTimeStyles.None, out DateTime timestamp)) + if (DateTime.TryParseExact(value, DATETIME_FORMAT, cultureInfo, DateTimeStyles.None, out var timestamp)) { return timestamp.AddMilliseconds(timeOffset); } diff --git a/src/JsonColumnizer/JsonColumnizer.cs b/src/JsonColumnizer/JsonColumnizer.cs index 48dacfea..f702d7bf 100644 --- a/src/JsonColumnizer/JsonColumnizer.cs +++ b/src/JsonColumnizer/JsonColumnizer.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; - using LogExpert; using Newtonsoft.Json; @@ -31,11 +27,11 @@ public virtual void Selected (ILogLineColumnizerCallback callback) ColumnList.Clear(); ColumnSet.Clear(); - ILogLine line = callback.GetLogLine(0); + var line = callback.GetLogLine(0); if (line != null) { - JObject json = ParseJson(line); + var json = ParseJson(line); if (json != null) { var fieldCount = json.Properties().Count(); @@ -87,7 +83,7 @@ public virtual string[] GetColumnNames () { var names = new string[GetColumnCount()]; var i = 0; - foreach (JsonColumn column in ColumnList) + foreach (var column in ColumnList) { names[i++] = column.Name; } @@ -97,7 +93,7 @@ public virtual string[] GetColumnNames () public virtual IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) { - JObject json = ParseJson(line); + var json = ParseJson(line); if (json != null) { @@ -106,7 +102,7 @@ public virtual IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback var cLogLine = new ColumnizedLogLine { LogLine = line }; - Column[] columns = Column.CreateColumns(ColumnList.Count, cLogLine); + var columns = Column.CreateColumns(ColumnList.Count, cLogLine); columns.Last().FullValue = line.FullLine; @@ -142,7 +138,7 @@ public virtual void PushValue (ILogLineColumnizerCallback callback, int column, public virtual Priority GetPriority (string fileName, IEnumerable samples) { - Priority result = Priority.NotSupport; + var result = Priority.NotSupport; if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) { result = Priority.WellSupport; @@ -159,7 +155,8 @@ protected static JObject ParseJson (ILogLine line) { return JsonConvert.DeserializeObject(line.FullLine, new JsonSerializerSettings() { - Error = (sender, args) => { args.ErrorContext.Handled = true; } //We ignore the error and handle the null value + //We ignore the error and handle the null value + Error = (sender, args) => args.ErrorContext.Handled = true }); } @@ -179,7 +176,7 @@ protected virtual IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json) var columns = json.Properties().Select(property => new ColumnWithName { FullValue = property.Value.ToString(), ColumnName = property.Name.ToString(), Parent = cLogLine }).ToList(); - foreach (ColumnWithName jsonColumn in columns) + foreach (var 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)) @@ -195,13 +192,13 @@ protected virtual IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json) } // - // Always rearrage the order of all json fields within a line to follow the sequence of columnNameList. + // Always rearrange 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. // List returnColumns = []; - foreach (JsonColumn column in ColumnList) + foreach (var column in ColumnList) { - ColumnWithName existingColumn = columns.Find(x => x.ColumnName == column.Name); + var 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 5cc3b33d..ce9f33b1 100644 --- a/src/JsonCompactColumnizer/JsonCompactColumnizer.cs +++ b/src/JsonCompactColumnizer/JsonCompactColumnizer.cs @@ -38,7 +38,7 @@ public override void Selected (ILogLineColumnizerCallback callback) public override Priority GetPriority (string fileName, IEnumerable samples) { - Priority result = Priority.NotSupport; + var result = Priority.NotSupport; if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) { result = Priority.WellSupport; @@ -49,7 +49,7 @@ public override Priority GetPriority (string fileName, IEnumerable sam try { var line = samples.First(); - JObject json = ParseJson(line); + var json = ParseJson(line); if (json != null) { var columns = SplitJsonLine(samples.First(), json); @@ -98,7 +98,7 @@ protected override IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json { if (column.StartsWith('@')) { - ColumnWithName existingColumn = columns.Find(x => x.ColumnName == column); + var existingColumn = columns.Find(x => x.ColumnName == column); if (existingColumn != null) { diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs index 0d8833a3..d003c648 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs @@ -82,7 +82,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi ColumnizedLogLine clogLine = new(); clogLine.LogLine = line; - Column[] columns = Column.CreateColumns(COLUMN_COUNT, clogLine); + var columns = Column.CreateColumns(COLUMN_COUNT, clogLine); // If the line is too short (i.e. does not follow the format for this columnizer) return the whole line content // in colum 8 (the log message column). Date and time column will be left blank. @@ -94,7 +94,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi { try { - DateTime dateTime = GetTimestamp(callback, line); + var dateTime = GetTimestamp(callback, line); if (dateTime == DateTime.MinValue) { @@ -109,7 +109,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi columns[0].FullValue = "n/a"; } - Column timestmp = columns[0]; + var timestmp = columns[0]; string[] cols; cols = line.FullLine.Split(trimChars, COLUMN_COUNT, StringSplitOptions.None); @@ -137,7 +137,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi } } - Column[] filteredColumns = MapColumns(columns); + var filteredColumns = MapColumns(columns); clogLine.ColumnValues = filteredColumns.Select(a => a as IColumn).ToArray(); @@ -174,6 +174,7 @@ public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line { return DateTime.MinValue; } + var value = line.FullLine.Substring(0, endIndex); try @@ -189,6 +190,7 @@ public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line { dateTime = dateTime.ToLocalTime(); } + return dateTime.AddMilliseconds(_timeOffset); } else @@ -264,11 +266,12 @@ public void LoadConfig (string configDir) public Priority GetPriority (string fileName, IEnumerable samples) { - Priority result = Priority.NotSupport; + var result = Priority.NotSupport; if (fileName.EndsWith("xml", StringComparison.OrdinalIgnoreCase)) { result = Priority.CanSupport; } + return result; } @@ -287,11 +290,11 @@ private Column[] MapColumns (Column[] cols) { List output = []; var index = 0; - foreach (Log4jColumnEntry entry in _config.ColumnList) + foreach (var entry in _config.ColumnList) { if (entry.Visible) { - Column column = cols[index]; + var column = cols[index]; output.Add(column); if (entry.MaxLen > 0 && column.FullValue.Length > entry.MaxLen) @@ -299,6 +302,7 @@ private Column[] MapColumns (Column[] cols) column.FullValue = column.FullValue[^entry.MaxLen..]; } } + index++; } diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs index 3d070108..92e86254 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs @@ -26,7 +26,7 @@ public int ActiveColumnCount get { var count = 0; - foreach (Log4jColumnEntry entry in ColumnList) + foreach (var entry in ColumnList) { if (entry.Visible) { @@ -47,7 +47,7 @@ public string[] ActiveColumnNames { var names = new string[ActiveColumnCount]; var index = 0; - foreach (Log4jColumnEntry entry in ColumnList) + foreach (var entry in ColumnList) { if (entry.Visible) { diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs index 00fc2a71..d3ea3c8f 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs @@ -1,4 +1,4 @@ -using Log4jXmlColumnizer; +using Log4jXmlColumnizer; using System; using System.Drawing; @@ -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 (var entry in _config.ColumnList) { DataGridViewRow row = new(); row.Cells.Add(new DataGridViewCheckBoxCell()); @@ -76,6 +76,7 @@ private void OkButton_Click(object sender, EventArgs e) _config.ColumnList[i].MaxLen = 0; } } + _config.LocalTimestamps = localTimeCheckBox.Checked; } diff --git a/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs b/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs index e8b7373c..6c7de2c4 100644 --- a/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs +++ b/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs @@ -87,7 +87,7 @@ public void ShiftBookmarks (int offset) { SortedList newBookmarkList = []; - foreach (Entities.Bookmark bookmark in BookmarkList.Values) + foreach (var bookmark in BookmarkList.Values) { var line = bookmark.LineNum - offset; if (line >= 0) @@ -102,7 +102,7 @@ public void ShiftBookmarks (int offset) public int FindPrevBookmarkIndex (int lineNum) { - IList values = BookmarkList.Values; + var values = BookmarkList.Values; for (var i = BookmarkList.Count - 1; i >= 0; --i) { if (values[i].LineNum <= lineNum) @@ -116,7 +116,7 @@ public int FindPrevBookmarkIndex (int lineNum) public int FindNextBookmarkIndex (int lineNum) { - IList values = BookmarkList.Values; + var values = BookmarkList.Values; for (var i = 0; i < BookmarkList.Count; ++i) { if (values[i].LineNum >= lineNum) @@ -124,6 +124,7 @@ public int FindNextBookmarkIndex (int lineNum) return i; } } + return 0; } diff --git a/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs index 433eda96..d2d07236 100644 --- a/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs +++ b/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs @@ -44,7 +44,7 @@ public int GetTimeOffset () public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { - IColumnizedLogLine cols = SplitLine(callback, line); + var cols = SplitLine(callback, line); if (cols == null || cols.ColumnValues.Length < 8) { return DateTime.MinValue; @@ -140,8 +140,8 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi if (_lineRegex.IsMatch(temp)) { - Match match = _lineRegex.Match(temp); - GroupCollection groups = match.Groups; + var match = _lineRegex.Match(temp); + var groups = match.Groups; if (groups.Count == 10) { columns[0].FullValue = groups[1].Value; diff --git a/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs b/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs index 22c859dc..3efb807f 100644 --- a/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs +++ b/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs @@ -8,19 +8,20 @@ public static class ColumnizerPicker { public static ILogLineColumnizer FindColumnizerByName (string name, IList list) { - foreach (ILogLineColumnizer columnizer in list) + foreach (var columnizer in list) { if (columnizer.GetName().Equals(name, StringComparison.Ordinal)) { return columnizer; } } + return null; } public static ILogLineColumnizer DecideColumnizerByName (string name, IList list) { - foreach (ILogLineColumnizer columnizer in list) + foreach (var columnizer in list) { if (columnizer.GetName().Equals(name, StringComparison.Ordinal)) { @@ -37,7 +38,8 @@ public static ILogLineColumnizer CloneColumnizer (ILogLineColumnizer columnizer, { return null; } - ConstructorInfo cti = columnizer.GetType().GetConstructor(Type.EmptyTypes); + + var cti = columnizer.GetType().GetConstructor(Type.EmptyTypes); if (cti != null) { @@ -47,8 +49,10 @@ public static ILogLineColumnizer CloneColumnizer (ILogLineColumnizer columnizer, { configurator.LoadConfig(directory); } + return (ILogLineColumnizer)o; } + return null; } @@ -69,6 +73,7 @@ public static ILogLineColumnizer FindReplacementForAutoColumnizer (string fileNa { return FindColumnizer(fileName, logFileReader, list); } + return logLineColumnizer; } @@ -83,6 +88,7 @@ public static ILogLineColumnizer FindBetterColumnizer (string fileName, { return null; } + return newColumnizer; } @@ -125,7 +131,7 @@ public static ILogLineColumnizer FindColumnizer (string fileName, IAutoLogLineCo List<(Priority priority, ILogLineColumnizer columnizer)> priorityListOfColumnizers = []; - foreach (ILogLineColumnizer logLineColumnizer in registeredColumnizer) + foreach (var logLineColumnizer in registeredColumnizer) { Priority priority = default; if (logLineColumnizer is IColumnizerPriority columnizerPriority) @@ -136,7 +142,7 @@ public static ILogLineColumnizer FindColumnizer (string fileName, IAutoLogLineCo priorityListOfColumnizers.Add((priority, logLineColumnizer)); } - ILogLineColumnizer lineColumnizer = priorityListOfColumnizers.OrderByDescending(item => item.priority).Select(item => item.columnizer).First(); + var lineColumnizer = priorityListOfColumnizers.OrderByDescending(item => item.priority).Select(item => item.columnizer).First(); return lineColumnizer; } diff --git a/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs index 123db94b..9dc4e342 100644 --- a/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs +++ b/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs @@ -49,7 +49,7 @@ public int GetTimeOffset () public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { - IColumnizedLogLine cols = SplitLine(callback, line); + var cols = SplitLine(callback, line); if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) { return DateTime.MinValue; @@ -60,7 +60,7 @@ public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line return DateTime.MinValue; } - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); + var formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); if (formatInfo == null) { return DateTime.MinValue; @@ -85,7 +85,7 @@ public void PushValue (ILogLineColumnizerCallback callback, int column, string v { try { - FormatInfo formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); + var formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); if (formatInfo == null) { return; @@ -175,7 +175,7 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi return clogLine; } - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); + var formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); if (formatInfo == null) { columns[2].FullValue = temp; @@ -256,13 +256,13 @@ void SquareSplit (ref Column[] columns, string line, int dateLen, int timeLen, i public Priority GetPriority (string fileName, IEnumerable samples) { - Priority result = Priority.NotSupport; + var result = Priority.NotSupport; TimeFormatDeterminer timeDeterminer = new(); var timeStampExistsCount = 0; var bracketsExistsCount = 0; var maxBracketNumbers = 1; - foreach (ILogLine logline in samples) + foreach (var logline in samples) { var line = logline?.FullLine; if (string.IsNullOrEmpty(line)) diff --git a/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs index 20239ceb..d65a7588 100644 --- a/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs +++ b/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs @@ -1,4 +1,4 @@ -using static LogExpert.Core.Classes.Columnizer.TimeFormatDeterminer; +using static LogExpert.Core.Classes.Columnizer.TimeFormatDeterminer; namespace LogExpert.Core.Classes.Columnizer; @@ -27,16 +27,18 @@ public int GetTimeOffset () public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) { - IColumnizedLogLine cols = SplitLine(callback, line); + var cols = SplitLine(callback, line); if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) { return DateTime.MinValue; } + if (cols.ColumnValues[0].FullValue.Length == 0 || cols.ColumnValues[1].FullValue.Length == 0) { return DateTime.MinValue; } - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); + + var formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); if (formatInfo == null) { return DateTime.MinValue; @@ -62,11 +64,12 @@ public void PushValue (ILogLineColumnizerCallback callback, int column, string v { try { - FormatInfo formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); + var formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); if (formatInfo == null) { return; } + var newDateTime = DateTime.ParseExact(value, formatInfo.TimeFormat, formatInfo.CultureInfo); var oldDateTime = DateTime.ParseExact(oldValue, formatInfo.TimeFormat, formatInfo.CultureInfo); var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; @@ -119,12 +122,13 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi var temp = line.FullLine; - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(temp); + var formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(temp); if (formatInfo == null) { columns[2].FullValue = temp; return clogLine; } + var endPos = formatInfo.DateTimeFormat.Length; var timeLen = formatInfo.TimeFormat.Length; var dateLen = formatInfo.DateFormat.Length; @@ -177,20 +181,22 @@ public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLi columns[1].FullValue = "n/a"; columns[2].FullValue = temp; } + return clogLine; } public Priority GetPriority (string fileName, IEnumerable samples) { - Priority result = Priority.NotSupport; + var result = Priority.NotSupport; var timeStampCount = 0; - foreach (ILogLine line in samples) + foreach (var line in samples) { if (line == null || string.IsNullOrEmpty(line.FullLine)) { continue; } + var timeDeterminer = new TimeFormatDeterminer(); if (null != timeDeterminer.DetermineDateTimeFormatInfo(line.FullLine)) { diff --git a/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs b/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs index 864b96f3..466d60ce 100644 --- a/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs +++ b/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs @@ -47,6 +47,7 @@ public int PeekUntil (int startOffset, int until) return offset - startOffset; } } + return 0; } @@ -59,6 +60,7 @@ public bool PeekOneOf (int offset, string s) return true; } } + return false; } @@ -89,6 +91,7 @@ public bool ReadOneOf (string s) Advance(); return true; } + return false; } diff --git a/src/LogExpert.Core/Classes/Filter/FilterParams.cs b/src/LogExpert.Core/Classes/Filter/FilterParams.cs index 19b11f8e..dde05dfe 100644 --- a/src/LogExpert.Core/Classes/Filter/FilterParams.cs +++ b/src/LogExpert.Core/Classes/Filter/FilterParams.cs @@ -1,9 +1,12 @@ using System.Collections; using System.Collections.ObjectModel; using System.Drawing; -using System.Text.Json.Serialization; using System.Text.RegularExpressions; +using LogExpert.Core.Classes.Persister; + +using Newtonsoft.Json; + namespace LogExpert.Core.Classes.Filter; [Serializable] @@ -52,23 +55,26 @@ public class FilterParams : ICloneable // list of columns in which to search public Collection ColumnList { get; } = []; - [JsonIgnore] - [field: NonSerialized] + [JsonConverter(typeof(ColumnizerJsonConverter))] public ILogLineColumnizer CurrentColumnizer { get; set; } /// /// false=looking for start /// true=looking for end /// + [JsonIgnore] [field: NonSerialized] public bool IsInRange { get; set; } + [JsonIgnore] [field: NonSerialized] public string LastLine { get; set; } = string.Empty; + [JsonIgnore] [field: NonSerialized] public Hashtable LastNonEmptyCols { get; set; } = []; + [JsonIgnore] [field: NonSerialized] public bool LastResult { get; set; } @@ -80,11 +86,13 @@ public class FilterParams : ICloneable [JsonIgnore] internal string NormalizedSearchText => SearchText.ToUpperInvariant(); + [JsonIgnore] [field: NonSerialized] public Regex RangeRex { get; set; } + [JsonIgnore] [field: NonSerialized] - public Regex Rex { get; set; } + public Regex Regex { get; set; } #endregion @@ -96,7 +104,7 @@ public class FilterParams : ICloneable /// public FilterParams CloneWithCurrentColumnizer () { - FilterParams newParams = Clone(); + var newParams = Clone(); newParams.Init(); // removed cloning of columnizer for filtering, because this causes issues with columnizers that hold internal states (like CsvColumnizer) // newParams.currentColumnizer = Util.CloneColumnizer(this.currentColumnizer); @@ -122,8 +130,9 @@ public void CreateRegex () { if (SearchText != null) { - Rex = new Regex(SearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + Regex = new Regex(SearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); } + if (RangeSearchText != null && IsRangeSearch) { RangeRex = new Regex(RangeSearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); diff --git a/src/LogExpert.Core/Classes/Filter/FilterStarter.cs b/src/LogExpert.Core/Classes/Filter/FilterStarter.cs index f09a881c..75a127dc 100644 --- a/src/LogExpert.Core/Classes/Filter/FilterStarter.cs +++ b/src/LogExpert.Core/Classes/Filter/FilterStarter.cs @@ -97,6 +97,7 @@ public async void DoFilter (FilterParams filterParams, int startLine, int maxCou break; } } + _logger.Info(CultureInfo.InvariantCulture, "FilterStarter starts worker for line {0}, lineCount {1}", workStartLine, interval); var filter = await Task.Run(() => DoWork(filterParams, workStartLine, interval, ThreadProgressCallback)).ConfigureAwait(false); diff --git a/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs b/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs index aed89b99..cd0391ee 100644 --- a/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs +++ b/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs @@ -1,17 +1,17 @@ -using Newtonsoft.Json; - using System.Drawing; using System.Text.RegularExpressions; +using Newtonsoft.Json; + namespace LogExpert.Core.Classes.Highlight; [Serializable] [method: JsonConstructor] -public class HighlightEntry() : ICloneable +public class HighlightEntry () : ICloneable { #region Fields - [NonSerialized] private Regex regex = null; + [NonSerialized] private Regex _regex = null; private string _searchText = string.Empty; @@ -23,7 +23,7 @@ public class HighlightEntry() : ICloneable public bool IsSetBookmark { get; set; } - public bool IsRegEx { get; set; } + public bool IsRegex { get; set; } public bool IsCaseSensitive { get; set; } @@ -37,7 +37,7 @@ public string SearchText set { _searchText = value; - regex = null; + _regex = null; } } @@ -53,24 +53,22 @@ public Regex Regex { get { - if (regex == null) - { - if (IsRegEx) - { - regex = new Regex(SearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - } - else - { - regex = new Regex(Regex.Escape(SearchText), IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - } - } - return regex; + _regex ??= IsRegex + ? new Regex(SearchText, IsCaseSensitive + ? RegexOptions.None + : RegexOptions.IgnoreCase) + : new Regex(Regex.Escape(SearchText), + IsCaseSensitive + ? RegexOptions.None + : RegexOptions.IgnoreCase); + + return _regex; } } public bool IsWordMatch { get; set; } - // highlightes search result + // Highlight search result [field: NonSerialized] public bool IsSearchHit { get; set; } @@ -78,14 +76,14 @@ public Regex Regex public bool NoBackground { get; set; } - public object Clone() + public object Clone () { var highLightEntry = new HighlightEntry { SearchText = SearchText, ForegroundColor = ForegroundColor, BackgroundColor = BackgroundColor, - IsRegEx = IsRegEx, + IsRegex = IsRegex, IsCaseSensitive = IsCaseSensitive, IsLedSwitch = IsLedSwitch, IsStopTail = IsStopTail, diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs index 5f072c27..27a9b30f 100644 --- a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs @@ -28,9 +28,9 @@ protected PositionAwareStreamReaderBase (Stream stream, EncodingOptions encoding { _stream = new BufferedStream(stream); - _preambleLength = DetectPreambleLengthAndEncoding(out Encoding detectedEncoding); + _preambleLength = DetectPreambleLengthAndEncoding(out var detectedEncoding); - Encoding usedEncoding = GetUsedEncoding(encodingOptions, detectedEncoding); + var usedEncoding = GetUsedEncoding(encodingOptions, detectedEncoding); _posIncPrecomputed = GetPosIncPrecomputed(usedEncoding); _reader = new StreamReader(_stream, usedEncoding, true); @@ -112,6 +112,7 @@ public override unsafe int ReadChar () _position += _reader.CurrentEncoding.GetByteCount(&readChar, 1); } } + return readInt; } catch (IOException) @@ -160,7 +161,7 @@ private int DetectPreambleLengthAndEncoding (out Encoding detectedEncoding) if (readLen >= 2) { - foreach (Encoding encoding in _preambleEncodings) + foreach (var encoding in _preambleEncodings) { var preamble = encoding.GetPreamble(); var fail = false; diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs index a47eaa0d..daaa97c3 100644 --- a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Entities; +using LogExpert.Core.Entities; namespace LogExpert.Core.Classes.Log; @@ -72,6 +72,7 @@ public override string ReadLine() { return null; // EOF } + _crDetect = false; return result; } diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs index a4f8b4a0..0f11cb60 100644 --- a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Entities; +using LogExpert.Core.Entities; namespace LogExpert.Core.Classes.Log; @@ -34,7 +34,7 @@ public PositionAwareStreamReaderSystem(Stream stream, EncodingOptions encodingOp public override string ReadLine() { - StreamReader reader = GetStreamReader(); + var reader = GetStreamReader(); if (_newLineSequenceLength == 0) { @@ -81,6 +81,7 @@ private int GuessNewLineSequenceLength(StreamReader reader) return Encoding.GetByteCount("\r\n"); } } + return Encoding.GetByteCount(((char)firstChar).ToString()); } diff --git a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs index 3d43806f..3b8f1061 100644 --- a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs +++ b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs @@ -69,7 +69,7 @@ public RolloverFilenameBuilder (string formatString) public void SetFileName (string fileName) { _currentFileName = fileName; - Match match = _regex.Match(fileName); + var match = _regex.Match(fileName); if (match.Success) { _dateGroup = match.Groups["date"]; diff --git a/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs b/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs index 673eebfe..a999690f 100644 --- a/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs +++ b/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Entities; +using LogExpert.Core.Entities; using LogExpert.Core.Interface; using System.Collections.Generic; @@ -91,6 +91,7 @@ public LinkedList GetNameList(IPluginRegistry pluginRegistry) } } } + return fileList; } @@ -100,8 +101,8 @@ public LinkedList GetNameList(IPluginRegistry pluginRegistry) private bool FileExists(string filePath, IPluginRegistry pluginRegistry) { - IFileSystemPlugin fs = pluginRegistry.FindFileSystemForUri(filePath); - ILogFileInfo info = fs.GetLogfileInfo(filePath); + var fs = pluginRegistry.FindFileSystemForUri(filePath); + var info = fs.GetLogfileInfo(filePath); return info.FileExists; } diff --git a/src/LogExpert.Core/Classes/Persister/ColumnizerJsonConverter.cs b/src/LogExpert.Core/Classes/Persister/ColumnizerJsonConverter.cs new file mode 100644 index 00000000..7f9927c4 --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/ColumnizerJsonConverter.cs @@ -0,0 +1,117 @@ +using System.Reflection; + +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace LogExpert.Core.Classes.Persister; + +/// +/// Custom JsonConverter for ILogLineColumnizer implementations. +/// Serializes only properties marked with [JsonColumnizerProperty]. +/// Uses GetName() for type identification. +/// +public class ColumnizerJsonConverter : JsonConverter +{ + public override bool CanConvert (Type objectType) + { + return typeof(ILogLineColumnizer).IsAssignableFrom(objectType); + } + + public override void WriteJson (JsonWriter writer, object? value, JsonSerializer serializer) + { + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(value); + + if (value is not ILogLineColumnizer columnizer) + { + writer.WriteNull(); + return; + } + + var type = value.GetType(); + var stateObj = new JObject(); + foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (prop.GetCustomAttribute() != null && prop.CanRead) + { + var propValue = prop.GetValue(value); + stateObj[prop.Name] = propValue != null ? JToken.FromObject(propValue, serializer) : JValue.CreateNull(); + } + } + + writer.WriteStartObject(); + writer.WritePropertyName("Type"); + writer.WriteValue(columnizer.GetName()); + writer.WritePropertyName("State"); + stateObj.WriteTo(writer); + writer.WriteEndObject(); + } + + public override object ReadJson (JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + { + ArgumentNullException.ThrowIfNull(reader); + + if (reader.TokenType == JsonToken.Null) + { + return null; + } + + var jObject = JObject.Load(reader); + var typeName = jObject["Type"]?.ToString(); + if (typeName == null || jObject["State"] is not JObject state) + { + return null; + } + + // Find the columnizer type by GetName() + var columnizerType = FindColumnizerTypeByName(typeName) ?? throw new JsonSerializationException($"Columnizer type '{typeName}' not found."); + + var instance = Activator.CreateInstance(columnizerType); + + foreach (var prop in columnizerType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (prop.GetCustomAttribute() != null && prop.CanWrite) + { + var token = state[prop.Name]; + if (token != null && token.Type != JTokenType.Null) + { + var value = token.ToObject(prop.PropertyType, serializer); + prop.SetValue(instance, value); + } + } + } + + return instance; + } + + private static Type FindColumnizerTypeByName (string name) + { + // Search all loaded assemblies for a type implementing ILogLineColumnizer with matching GetName() + foreach (var currentAssembly in AppDomain.CurrentDomain.GetAssemblies()) + { + foreach (var type in currentAssembly.GetTypes().Where(t => typeof(ILogLineColumnizer).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)) + { + try + { + if (Activator.CreateInstance(type) is ILogLineColumnizer instance && instance.GetName() == name) + { + return type; + } + } + catch (Exception ex) when (ex is ArgumentNullException or + ArgumentException or + NotSupportedException or + TargetInvocationException or + MethodAccessException or + MemberAccessException or + MissingMethodException or + TypeLoadException) + { + // intentionally ignored + } + } + } + + return null; + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/FilterTabData.cs b/src/LogExpert.Core/Classes/Persister/FilterTabData.cs index f1fc8fc6..f5de599e 100644 --- a/src/LogExpert.Core/Classes/Persister/FilterTabData.cs +++ b/src/LogExpert.Core/Classes/Persister/FilterTabData.cs @@ -1,7 +1,8 @@ -using LogExpert.Core.Classes.Filter; +using LogExpert.Core.Classes.Filter; namespace LogExpert.Core.Classes.Persister; +[Serializable] public class FilterTabData { public FilterParams FilterParams { get; set; } = new(); diff --git a/src/LogExpert.Core/Classes/Persister/JsonColumnizerPropertyAttribute.cs b/src/LogExpert.Core/Classes/Persister/JsonColumnizerPropertyAttribute.cs new file mode 100644 index 00000000..af1219fc --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/JsonColumnizerPropertyAttribute.cs @@ -0,0 +1,10 @@ +namespace LogExpert.Core.Classes.Persister; + +/// +/// Marks a property for inclusion in columnizer JSON serialization. +/// +[AttributeUsage(AttributeTargets.Property)] +public class JsonColumnizerPropertyAttribute : Attribute +{ +} + diff --git a/src/LogExpert.Core/Classes/Persister/PersistenceData.cs b/src/LogExpert.Core/Classes/Persister/PersistenceData.cs index eefe1a34..71a6fea4 100644 --- a/src/LogExpert.Core/Classes/Persister/PersistenceData.cs +++ b/src/LogExpert.Core/Classes/Persister/PersistenceData.cs @@ -5,6 +5,7 @@ namespace LogExpert.Core.Classes.Persister; +[Serializable] public class PersistenceData { public SortedList BookmarkList { get; set; } = []; diff --git a/src/LogExpert.Core/Classes/Persister/Persister.cs b/src/LogExpert.Core/Classes/Persister/Persister.cs index 8ae747b9..6d4dfc15 100644 --- a/src/LogExpert.Core/Classes/Persister/Persister.cs +++ b/src/LogExpert.Core/Classes/Persister/Persister.cs @@ -1,17 +1,13 @@ -using System.Drawing; using System.Text; -using System.Text.Json; -using System.Xml; -using LogExpert.Core.Classes.Filter; using LogExpert.Core.Config; -using LogExpert.Core.Entities; + +using Newtonsoft.Json; using NLog; namespace LogExpert.Core.Classes.Persister; -//TODO Rewrite as json Persister, xml is outdated and difficult to parse and write public static class Persister { #region Fields @@ -22,8 +18,25 @@ public static class Persister #region Public methods + /// + /// Saves the specified persistence data to a file and returns the file name used. + /// + /// If the property of is not set, a file name is generated based on and the + /// provided . If the save location specified in is + /// , the file name is adjusted to be relative to the log file's + /// directory. + /// The name of the log file associated with the session. This is used to generate the file name if one is not + /// provided in . + /// The persistence data to save. This parameter cannot be . + /// The user preferences that determine the save location and other settings. This parameter cannot be . + /// The full path of the file where the persistence data was saved. public static string SavePersistenceData (string logFileName, PersistenceData persistenceData, Preferences preferences) { + ArgumentNullException.ThrowIfNull(preferences); + ArgumentNullException.ThrowIfNull(persistenceData); + var fileName = persistenceData.SessionFileName ?? BuildPersisterFileName(logFileName, preferences); if (preferences.SaveLocation == SessionSaveLocation.SameDir) @@ -37,70 +50,91 @@ public static string SavePersistenceData (string logFileName, PersistenceData pe return fileName; } - public static string SavePersistenceDataWithFixedName (string persistenceFileName, - PersistenceData persistenceData) + /// + /// Saves the specified persistence data to a file with the given name. + /// + /// The name of the file to save the persistence data to. Must not be null or empty. + /// The persistence data to be saved. Must not be null. + /// The name of the file where the persistence data was saved. + public static string SavePersistenceDataWithFixedName (string persistenceFileName, PersistenceData persistenceData) { Save(persistenceFileName, persistenceData); return persistenceFileName; } - + /// + /// Loads persistence data from the specified log file using the provided preferences. + /// + /// The name of the log file to load persistence data from. This value cannot be null. + /// The preferences used to determine the file path and loading behaviour. This value cannot be null. + /// The loaded object containing the persistence information. public static PersistenceData LoadPersistenceData (string logFileName, Preferences preferences) { + ArgumentNullException.ThrowIfNull(preferences); var fileName = BuildPersisterFileName(logFileName, preferences); - return Load(fileName); + return LoadInternal(fileName); } + /// + /// Loads persistence data based on the specified log file name and preferences. + /// + /// The name of the log file used to determine the persistence data file. + /// The preferences that influence the file name generation. Cannot be . + /// A object containing the loaded data. public static PersistenceData LoadPersistenceDataOptionsOnly (string logFileName, Preferences preferences) { + ArgumentNullException.ThrowIfNull(preferences); var fileName = BuildPersisterFileName(logFileName, preferences); - return LoadOptionsOnly(fileName); + return LoadInternal(fileName); } + /// + /// Loads persistence data options from a specified file. + /// + /// This method only loads the options portion of the persistence data from the specified file. + /// Ensure the file format is valid and compatible with the expected structure of . + /// The path to the file containing the persistence data options. The file must exist and be accessible. + /// A object containing the loaded options. public static PersistenceData LoadPersistenceDataOptionsOnlyFromFixedFile (string persistenceFile) { - return LoadOptionsOnly(persistenceFile); + return LoadInternal(persistenceFile); } + /// + /// Loads persistence data from the specified file. + /// + /// The path to the file containing the persistence data. The file must exist and be accessible. + /// A object containing the data loaded from the file. public static PersistenceData LoadPersistenceDataFromFixedFile (string persistenceFile) { - return Load(persistenceFile); + return LoadInternal(persistenceFile); } - /// - /// Loads the persistence options out of the given persistence file name. + /// Loads persistence data from the specified file. /// - /// - /// - public static PersistenceData LoadOptionsOnly (string fileName) + /// The path to the file containing the persistence data. The file must exist and be accessible. + /// A object representing the data loaded from the file. + public static PersistenceData Load (string fileName) { - PersistenceData persistenceData = new(); - XmlDocument xmlDoc = new(); - try - { - xmlDoc.Load(fileName); - } - catch (IOException) - { - return null; - } - - XmlNode fileNode = xmlDoc.SelectSingleNode("logexpert/file"); - if (fileNode != null) - { - var fileElement = fileNode as XmlElement; - ReadOptions(fileElement, persistenceData); - persistenceData.FileName = fileElement.GetAttribute("fileName"); - persistenceData.Encoding = ReadEncoding(fileElement); - } - return persistenceData; + return LoadInternal(fileName); } #endregion #region Private Methods + /// + /// Constructs the file path for the persister file based on the specified log file name and preferences. + /// + /// The method determines the save location for the persister file based on the property. If the specified directory does not exist, the method attempts to + /// create it. If directory creation fails, an error is logged. + /// The name of the log file for which the persister file path is being generated. + /// The preferences that determine the save location and directory structure for the persister file. + /// The full file path of the persister file, including the directory and file name, based on the specified log file + /// name and preferences. private static string BuildPersisterFileName (string logFileName, Preferences preferences) { string dir; @@ -139,22 +173,30 @@ private static string BuildPersisterFileName (string logFileName, Preferences pr } } - if (string.IsNullOrWhiteSpace(dir) == false && Directory.Exists(dir) == false) + if (!string.IsNullOrWhiteSpace(dir) && !Directory.Exists(dir)) { try { - Directory.CreateDirectory(dir); + _ = Directory.CreateDirectory(dir); } - catch (Exception e) + catch (Exception ex) when (ex is IOException or + UnauthorizedAccessException or + PathTooLongException or + DirectoryNotFoundException) { - //TODO this needs to be handled differently - //MessageBox.Show(e.Message, "LogExpert"); + _logger.Error(ex, $"Error creating directory {dir}"); } } return file; } + /// + /// Generates a session file name based on the specified log file path. + /// + /// The full path of the log file to be converted into a session file name. + /// A string representing the session file name, where directory, volume, and path separators are replaced with + /// underscores, and the file name is appended with the ".lxp" extension. private static string BuildSessionFileNameFromPath (string logFileName) { var result = logFileName; @@ -165,494 +207,90 @@ private static string BuildSessionFileNameFromPath (string logFileName) return result; } + /// + /// Saves the specified persistence data to a file in JSON format. + /// + /// The method serializes the object to JSON using specific + /// settings, including a custom JSON converter. The resulting JSON is written to the specified file with UTF-8 + /// encoding. + /// The full path of the file where the data will be saved. This cannot be null or empty. + /// The data to be persisted. This cannot be null. private static void Save (string fileName, PersistenceData persistenceData) { - XmlDocument xmlDoc = new(); - XmlElement rootElement = xmlDoc.CreateElement("logexpert"); - 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); - WriteOptions(xmlDoc, fileElement, persistenceData); - WriteFilter(xmlDoc, fileElement, persistenceData.FilterParamsList); - WriteFilterTabs(xmlDoc, fileElement, persistenceData.FilterTabDataList); - WriteEncoding(xmlDoc, fileElement, persistenceData.Encoding); - if (xmlDoc.HasChildNodes) + var settings = new JsonSerializerSettings { - xmlDoc.Save(fileName); - } - } - - private static void WriteEncoding (XmlDocument xmlDoc, XmlElement rootElement, Encoding encoding) - { - if (encoding != null) - { - XmlElement encodingElement = xmlDoc.CreateElement("encoding"); - rootElement.AppendChild(encodingElement); - encodingElement.SetAttribute("name", encoding.WebName); - } - } - - private static void WriteFilterTabs (XmlDocument xmlDoc, XmlElement rootElement, List dataList) - { - if (dataList.Count > 0) - { - XmlElement filterTabsElement = xmlDoc.CreateElement("filterTabs"); - rootElement.AppendChild(filterTabsElement); - foreach (FilterTabData data in dataList) + Converters = { - PersistenceData persistenceData = data.PersistenceData; - XmlElement filterTabElement = xmlDoc.CreateElement("filterTab"); - filterTabsElement.AppendChild(filterTabElement); - WriteBookmarks(xmlDoc, filterTabElement, persistenceData.BookmarkList); - WriteRowHeightList(xmlDoc, filterTabElement, persistenceData.RowHeightList); - WriteOptions(xmlDoc, filterTabElement, persistenceData); - WriteFilter(xmlDoc, filterTabElement, persistenceData.FilterParamsList); - WriteFilterTabs(xmlDoc, filterTabElement, persistenceData.FilterTabDataList); - XmlElement filterElement = xmlDoc.CreateElement("tabFilter"); - filterTabElement.AppendChild(filterElement); - List filterList = [data.FilterParams]; - WriteFilter(xmlDoc, filterElement, filterList); - } - } - } - - private static List ReadFilterTabs (XmlElement startNode) - { - List dataList = []; - XmlNode filterTabsNode = startNode.SelectSingleNode("filterTabs"); - if (filterTabsNode != null) - { - XmlNodeList filterTabNodeList = filterTabsNode.ChildNodes; // all "filterTab" nodes + new ColumnizerJsonConverter() + }, + Formatting = Formatting.Indented, + }; - foreach (XmlNode node in filterTabNodeList) - { - PersistenceData persistenceData = ReadPersistenceDataFromNode(node); - XmlNode filterNode = node.SelectSingleNode("tabFilter"); - - if (filterNode != null) - { - List filterList = ReadFilter(filterNode as XmlElement); - FilterTabData data = new() - { - PersistenceData = persistenceData, - FilterParams = filterList[0] // there's only 1 - }; - - dataList.Add(data); - } - } - } - return dataList; - } - - - private static void WriteFilter (XmlDocument xmlDoc, XmlElement rootElement, List filterList) - { - XmlElement filtersElement = xmlDoc.CreateElement("filters"); - rootElement.AppendChild(filtersElement); - foreach (FilterParams filterParams in filterList) - { - XmlElement filterElement = xmlDoc.CreateElement("filter"); - XmlElement paramsElement = xmlDoc.CreateElement("params"); - - MemoryStream stream = new(capacity: 200); - JsonSerializer.Serialize(stream, filterParams); - var base64Data = Convert.ToBase64String(stream.ToArray()); - paramsElement.InnerText = base64Data; - filterElement.AppendChild(paramsElement); - filtersElement.AppendChild(filterElement); - } - } - - - private static List ReadFilter (XmlElement startNode) - { - List filterList = []; - XmlNode filtersNode = startNode.SelectSingleNode("filters"); - if (filtersNode != null) - { - XmlNodeList filterNodeList = filtersNode.ChildNodes; // all "filter" nodes - foreach (XmlNode node in filterNodeList) - { - foreach (XmlNode subNode in node.ChildNodes) - { - if (subNode.Name.Equals("params", StringComparison.OrdinalIgnoreCase)) - { - var base64Text = subNode.InnerText; - var data = Convert.FromBase64String(base64Text); - MemoryStream stream = new(data); - - try - { - FilterParams filterParams = JsonSerializer.Deserialize(stream); - filterParams.Init(); - filterList.Add(filterParams); - } - catch (JsonException ex) - { - _logger.Error($"Error while deserializing filter params. Exception Message: {ex.Message}"); - } - } - } - } - } - return filterList; - } - - - private static void WriteBookmarks (XmlDocument xmlDoc, XmlElement rootElement, - SortedList bookmarkList) - { - XmlElement bookmarksElement = xmlDoc.CreateElement("bookmarks"); - rootElement.AppendChild(bookmarksElement); - foreach (Entities.Bookmark bookmark in bookmarkList.Values) - { - XmlElement bookmarkElement = xmlDoc.CreateElement("bookmark"); - bookmarkElement.SetAttribute("line", "" + bookmark.LineNum); - XmlElement textElement = xmlDoc.CreateElement("text"); - textElement.InnerText = bookmark.Text; - XmlElement posXElement = xmlDoc.CreateElement("posX"); - XmlElement posYElement = xmlDoc.CreateElement("posY"); - posXElement.InnerText = "" + bookmark.OverlayOffset.Width; - posYElement.InnerText = "" + bookmark.OverlayOffset.Height; - bookmarkElement.AppendChild(textElement); - bookmarkElement.AppendChild(posXElement); - bookmarkElement.AppendChild(posYElement); - bookmarksElement.AppendChild(bookmarkElement); - } - } - - - private static PersistenceData Load (string fileName) - { - XmlDocument xmlDoc = new(); - xmlDoc.Load(fileName); - XmlNode fileNode = xmlDoc.SelectSingleNode("logexpert/file"); - PersistenceData persistenceData = new(); - if (fileNode != null) + try { - persistenceData = ReadPersistenceDataFromNode(fileNode); + var json = JsonConvert.SerializeObject(persistenceData, settings); + File.WriteAllText(fileName, json, Encoding.UTF8); } - return persistenceData; - } - - private static PersistenceData ReadPersistenceDataFromNode (XmlNode node) - { - PersistenceData persistenceData = new(); - var fileElement = node as XmlElement; - persistenceData.BookmarkList = ReadBookmarks(fileElement); - persistenceData.RowHeightList = ReadRowHeightList(fileElement); - ReadOptions(fileElement, persistenceData); - persistenceData.FileName = fileElement.GetAttribute("fileName"); - var sLineCount = fileElement.GetAttribute("lineCount"); - if (sLineCount != null && sLineCount.Length > 0) + catch (Exception ex) { - persistenceData.LineCount = int.Parse(sLineCount); + _logger.Error(ex, $"Error saving persistence data to {fileName}"); + throw; } - persistenceData.FilterParamsList = ReadFilter(fileElement); - persistenceData.FilterTabDataList = ReadFilterTabs(fileElement); - persistenceData.Encoding = ReadEncoding(fileElement); - return persistenceData; } - - private static Encoding ReadEncoding (XmlElement fileElement) + /// + /// Loads persistence data from the specified file. + /// + /// This method attempts to deserialize the file's contents into a + /// object using JSON. If the deserialization is successful, it initializes any filter parameters within the loaded + /// data. If an error occurs during file access or deserialization, the method logs the error and returns . + /// The full path to the file containing the persistence data. The file must exist and be accessible. + /// An instance of containing the deserialized data from the file, or if the file does not exist, an error occurs during loading, or the data is invalid. + private static PersistenceData LoadInternal (string fileName) { - XmlNode encodingNode = fileElement.SelectSingleNode("encoding"); - if (encodingNode != null) + if (!File.Exists(fileName)) { - XmlAttribute encAttr = encodingNode.Attributes["name"]; - try - { - return encAttr == null ? null : Encoding.GetEncoding(encAttr.Value); - } - catch (ArgumentException e) - { - _logger.Error(e); - return Encoding.Default; - } - catch (NotSupportedException e) - { - _logger.Error(e); - return Encoding.Default; - } + return null; } - return null; - } - - private static SortedList ReadBookmarks (XmlElement startNode) - { - SortedList bookmarkList = []; - XmlNode boomarksNode = startNode.SelectSingleNode("bookmarks"); - if (boomarksNode != null) + try { - XmlNodeList bookmarkNodeList = boomarksNode.ChildNodes; // all "bookmark" nodes - foreach (XmlNode node in bookmarkNodeList) + var settings = new JsonSerializerSettings { - string text = null; - string posX = null; - string posY = null; - string line = null; - - foreach (XmlAttribute attr in node.Attributes) - { - if (attr.Name.Equals("line", StringComparison.OrdinalIgnoreCase)) - { - line = attr.InnerText; - } - } - foreach (XmlNode subNode in node.ChildNodes) - { - if (subNode.Name.Equals("text", StringComparison.OrdinalIgnoreCase)) - { - text = subNode.InnerText; - } - else if (subNode.Name.Equals("posX", StringComparison.OrdinalIgnoreCase)) - { - posX = subNode.InnerText; - } - 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: {node.InnerText}"); - continue; - } - var lineNum = int.Parse(line); - - Entities.Bookmark bookmark = new(lineNum) - { - OverlayOffset = new Size(int.Parse(posX), int.Parse(posY)) - }; - - if (text != null) + Converters = { - bookmark.Text = text; - } - bookmarkList.Add(lineNum, bookmark); - } - } - return bookmarkList; - } - - private static void WriteRowHeightList (XmlDocument xmlDoc, XmlElement rootElement, SortedList rowHeightList) - { - XmlElement rowheightElement = xmlDoc.CreateElement("rowheights"); - rootElement.AppendChild(rowheightElement); - foreach (RowHeightEntry entry in rowHeightList.Values) - { - XmlElement entryElement = xmlDoc.CreateElement("rowheight"); - entryElement.SetAttribute("line", "" + entry.LineNum); - entryElement.SetAttribute("height", "" + entry.Height); - rowheightElement.AppendChild(entryElement); - } - } - - private static SortedList ReadRowHeightList (XmlElement startNode) - { - SortedList rowHeightList = []; - XmlNode rowHeightsNode = startNode.SelectSingleNode("rowheights"); - if (rowHeightsNode != null) - { - XmlNodeList rowHeightNodeList = rowHeightsNode.ChildNodes; // all "rowheight" nodes - foreach (XmlNode node in rowHeightNodeList) + new ColumnizerJsonConverter() + }, + Formatting = Formatting.Indented, + }; + + var json = File.ReadAllText(fileName, Encoding.UTF8); + var data = JsonConvert.DeserializeObject(json, settings); + // Call Init on all FilterParams if needed + if (data?.FilterParamsList != null) { - string height = null; - string line = null; - foreach (XmlAttribute attr in node.Attributes) + foreach (var filter in data.FilterParamsList) { - if (attr.Name.Equals("line", StringComparison.OrdinalIgnoreCase)) - { - line = attr.InnerText; - } - else if (attr.Name.Equals("height", StringComparison.OrdinalIgnoreCase)) - { - height = attr.InnerText; - } + filter?.Init(); } - var lineNum = int.Parse(line); - var heightValue = int.Parse(height); - rowHeightList.Add(lineNum, new RowHeightEntry(lineNum, heightValue)); } - } - return rowHeightList; - } - - private static void WriteOptions (XmlDocument xmlDoc, XmlElement rootElement, PersistenceData persistenceData) - { - XmlElement optionsElement = xmlDoc.CreateElement("options"); - 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) - { - XmlElement entryElement = xmlDoc.CreateElement("fileEntry"); - entryElement.SetAttribute("fileName", "" + fileName); - element.AppendChild(entryElement); - } - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("currentline"); - element.SetAttribute("line", "" + persistenceData.CurrentLine); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("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); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("bookmarklist"); - 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"); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("tab"); - element.SetAttribute("name", persistenceData.TabName); - rootElement.AppendChild(element); - - element = xmlDoc.CreateElement("columnizer"); - element.SetAttribute("name", persistenceData.ColumnizerName); - rootElement.AppendChild(element); - - element = xmlDoc.CreateElement("highlightGroup"); - element.SetAttribute("name", persistenceData.HighlightGroupName); - rootElement.AppendChild(element); - - element = xmlDoc.CreateElement("bookmarkCommentColumn"); - element.SetAttribute("visible", persistenceData.ShowBookmarkCommentColumn ? "1" : "0"); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("filterSaveList"); - element.SetAttribute("visible", persistenceData.FilterSaveListVisible ? "1" : "0"); - optionsElement.AppendChild(element); - } - - - private static void ReadOptions (XmlElement startNode, PersistenceData persistenceData) - { - XmlNode optionsNode = startNode.SelectSingleNode("options"); - var value = GetOptionsAttribute(optionsNode, "multifile", "enabled"); - 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; - } - catch (Exception) - { - persistenceData.MultiFileMaxDays = 0; - } - - XmlNode multiFileNode = optionsNode.SelectSingleNode("multifile"); - if (multiFileNode != null) - { - XmlNodeList multiFileNodeList = multiFileNode.ChildNodes; // all "fileEntry" nodes - foreach (XmlNode node in multiFileNodeList) + if (data?.FilterTabDataList != null) { - string fileName = null; - foreach (XmlAttribute attr in node.Attributes) + foreach (var tab in data.FilterTabDataList) { - if (attr.Name.Equals("fileName", StringComparison.OrdinalIgnoreCase)) - { - fileName = attr.InnerText; - } + tab?.FilterParams?.Init(); } - persistenceData.MultiFileNames.Add(fileName); } - } - - value = GetOptionsAttribute(optionsNode, "currentline", "line"); - if (value != null) - { - persistenceData.CurrentLine = int.Parse(value); - } - value = GetOptionsAttribute(optionsNode, "firstDisplayedLine", "line"); - if (value != null) - { - persistenceData.FirstDisplayedLine = int.Parse(value); - } - - value = GetOptionsAttribute(optionsNode, "filter", "visible"); - persistenceData.FilterVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); - value = GetOptionsAttribute(optionsNode, "filter", "advanced"); - persistenceData.FilterAdvanced = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); - value = GetOptionsAttribute(optionsNode, "filter", "position"); - if (value != null) - { - persistenceData.FilterPosition = int.Parse(value); - } - value = GetOptionsAttribute(optionsNode, "bookmarklist", "visible"); - persistenceData.BookmarkListVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); - value = GetOptionsAttribute(optionsNode, "bookmarklist", "position"); - if (value != null) - { - persistenceData.BookmarkListPosition = int.Parse(value); - } - - value = GetOptionsAttribute(optionsNode, "followTail", "enabled"); - persistenceData.FollowTail = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); - - value = GetOptionsAttribute(optionsNode, "bookmarkCommentColumn", "visible"); - persistenceData.ShowBookmarkCommentColumn = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); - - value = GetOptionsAttribute(optionsNode, "filterSaveList", "visible"); - persistenceData.FilterSaveListVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); - - XmlNode tabNode = startNode.SelectSingleNode("tab"); - if (tabNode != null) - { - persistenceData.TabName = (tabNode as XmlElement).GetAttribute("name"); - } - XmlNode columnizerNode = startNode.SelectSingleNode("columnizer"); - if (columnizerNode != null) - { - persistenceData.ColumnizerName = (columnizerNode as XmlElement).GetAttribute("name"); - } - XmlNode highlightGroupNode = startNode.SelectSingleNode("highlightGroup"); - if (highlightGroupNode != null) - { - persistenceData.HighlightGroupName = (highlightGroupNode as XmlElement).GetAttribute("name"); - } - } - - - private static string GetOptionsAttribute (XmlNode optionsNode, string elementName, string attrName) - { - XmlNode node = optionsNode.SelectSingleNode(elementName); - if (node == null) - { - return null; - } - if (node is XmlElement) - { - var value = (node as XmlElement).GetAttribute(attrName); - return value; + return data; } - else + catch (Exception ex) when (ex is UnauthorizedAccessException or + IOException) { + _logger.Error(ex, $"Error loading persistence data from {fileName}"); return null; } } diff --git a/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs b/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs index 12963b28..19b0de76 100644 --- a/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs +++ b/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Xml; namespace LogExpert.Core.Classes.Persister; @@ -12,18 +12,20 @@ public static ProjectData LoadProjectData(string projectFileName) ProjectData projectData = new(); XmlDocument xmlDoc = new(); xmlDoc.Load(projectFileName); - XmlNodeList fileList = xmlDoc.GetElementsByTagName("member"); + var fileList = xmlDoc.GetElementsByTagName("member"); foreach (XmlNode fileNode in fileList) { var fileElement = fileNode as XmlElement; var fileName = fileElement.GetAttribute("fileName"); projectData.MemberList.Add(fileName); } - XmlNodeList layoutElements = xmlDoc.GetElementsByTagName("layout"); + + var layoutElements = xmlDoc.GetElementsByTagName("layout"); if (layoutElements.Count > 0) { projectData.TabLayoutXml = layoutElements[0].InnerXml; } + return projectData; } @@ -31,17 +33,17 @@ public static ProjectData LoadProjectData(string projectFileName) public static void SaveProjectData(string projectFileName, ProjectData projectData) { XmlDocument xmlDoc = new(); - XmlElement rootElement = xmlDoc.CreateElement("logexpert"); + var rootElement = xmlDoc.CreateElement("logexpert"); xmlDoc.AppendChild(rootElement); - XmlElement projectElement = xmlDoc.CreateElement("project"); + var projectElement = xmlDoc.CreateElement("project"); rootElement.AppendChild(projectElement); - XmlElement membersElement = xmlDoc.CreateElement("members"); + var membersElement = xmlDoc.CreateElement("members"); projectElement.AppendChild(membersElement); SaveProjectMembers(xmlDoc, membersElement, projectData.MemberList); if (projectData.TabLayoutXml != null) { - XmlElement layoutElement = xmlDoc.CreateElement("layout"); + var layoutElement = xmlDoc.CreateElement("layout"); layoutElement.InnerXml = projectData.TabLayoutXml; rootElement.AppendChild(layoutElement); } @@ -57,7 +59,7 @@ private static void SaveProjectMembers(XmlDocument xmlDoc, XmlNode membersNode, { foreach (var fileName in memberList) { - XmlElement memberElement = xmlDoc.CreateElement("member"); + var memberElement = xmlDoc.CreateElement("member"); membersNode.AppendChild(memberElement); memberElement.SetAttribute("fileName", fileName); } diff --git a/src/LogExpert.Core/Classes/SysoutPipe.cs b/src/LogExpert.Core/Classes/SysoutPipe.cs index 4068cf1c..007a755a 100644 --- a/src/LogExpert.Core/Classes/SysoutPipe.cs +++ b/src/LogExpert.Core/Classes/SysoutPipe.cs @@ -84,6 +84,7 @@ protected void ReaderThread() { break; } + _writer.Write(buff, 0, read); } catch (IOException e) diff --git a/src/LogExpert.Core/Classes/Util.cs b/src/LogExpert.Core/Classes/Util.cs index 17c317ba..991d9a4a 100644 --- a/src/LogExpert.Core/Classes/Util.cs +++ b/src/LogExpert.Core/Classes/Util.cs @@ -143,6 +143,7 @@ public static int DamerauLevenshteinDistance (string src, string dest) } } } + return d[str1.Length, str2.Length]; } @@ -440,13 +441,13 @@ public static void AssertTrue (bool condition, string msg) stringFormat.SetMeasurableCharacterRanges(crArray); RectangleF rect = new(0, 0, 3000, 20); - Region[] stringRegions = g.MeasureCharacterRanges(text, font, rect, stringFormat); + var stringRegions = g.MeasureCharacterRanges(text, font, rect, stringFormat); var found = false; var y = 0; - foreach (Region regio in stringRegions) + foreach (var regio in stringRegions) { if (regio.IsVisible(xPos, 3, g)) { @@ -482,7 +483,7 @@ private static bool TestFilterMatch (FilterParams filterParams, ILogLine line, I { normalizedSearchText = filterParams.NormalizedSearchText; searchText = filterParams.SearchText; - rex = filterParams.Rex; + rex = filterParams.Regex; } if (string.IsNullOrEmpty(searchText)) @@ -492,7 +493,7 @@ private static bool TestFilterMatch (FilterParams filterParams, ILogLine line, I if (filterParams.ColumnRestrict) { - IColumnizedLogLine columns = filterParams.CurrentColumnizer.SplitLine(columnizerCallback, line); + var columns = filterParams.CurrentColumnizer.SplitLine(columnizerCallback, line); var found = false; foreach (var colIndex in filterParams.ColumnList) { diff --git a/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs b/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs index 1188c203..f52a8cf7 100644 --- a/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs +++ b/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Log; using System.Text; using System.Xml; @@ -125,6 +125,7 @@ private void SplitToLinesList(string message) line = line.Substring(MAX_LEN); _lineList.Enqueue(part); } + _lineList.Enqueue(line); } } @@ -166,6 +167,7 @@ public override string ReadLine() _lineList.Enqueue("[XML Parser error] " + block); } } + return _lineList.Dequeue(); } diff --git a/src/LogExpert.Core/Classes/xml/XmlLogReader.cs b/src/LogExpert.Core/Classes/xml/XmlLogReader.cs index 43c4e2c7..99ed640f 100644 --- a/src/LogExpert.Core/Classes/xml/XmlLogReader.cs +++ b/src/LogExpert.Core/Classes/xml/XmlLogReader.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Log; using LogExpert.Core.Interface; using System.Text; @@ -131,6 +131,7 @@ public override string ReadLine() state = 0; builder.Clear(); } + break; case 2: builder.Append(readChar); @@ -141,6 +142,7 @@ public override string ReadLine() state = 3; tagIndex = 1; } + break; case 3: builder.Append(readChar); @@ -159,6 +161,7 @@ public override string ReadLine() //_logger.logInfo("state = 2"); state = 2; } + break; } } diff --git a/src/LogExpert.Core/Entities/Bookmark.cs b/src/LogExpert.Core/Entities/Bookmark.cs index 4ebb1e80..642098e8 100644 --- a/src/LogExpert.Core/Entities/Bookmark.cs +++ b/src/LogExpert.Core/Entities/Bookmark.cs @@ -1,19 +1,20 @@ -using System.Drawing; +using System.Drawing; namespace LogExpert.Core.Entities; +[Serializable] public class Bookmark { #region cTor - public Bookmark(int lineNum) + public Bookmark (int lineNum) { LineNum = lineNum; Text = string.Empty; Overlay = new BookmarkOverlay(); } - public Bookmark(int lineNum, string comment) + public Bookmark (int lineNum, string comment) { LineNum = lineNum; Text = comment; diff --git a/src/LogExpert.Core/Entities/BookmarkOverlay.cs b/src/LogExpert.Core/Entities/BookmarkOverlay.cs index 805ee15d..431aafb1 100644 --- a/src/LogExpert.Core/Entities/BookmarkOverlay.cs +++ b/src/LogExpert.Core/Entities/BookmarkOverlay.cs @@ -1,7 +1,8 @@ -using System.Drawing; +using System.Drawing; namespace LogExpert.Core.Entities; +[Serializable] public class BookmarkOverlay { #region Properties diff --git a/src/LogExpert.Core/Entities/HighlightGroup.cs b/src/LogExpert.Core/Entities/HighlightGroup.cs index a599d198..e8f5d8ce 100644 --- a/src/LogExpert.Core/Entities/HighlightGroup.cs +++ b/src/LogExpert.Core/Entities/HighlightGroup.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Classes.Highlight; +using LogExpert.Core.Classes.Highlight; namespace LogExpert.Core.Entities; @@ -11,14 +11,14 @@ public class HighlightGroup : ICloneable public List HighlightEntryList { get; set; } = []; - public object Clone() + public object Clone () { HighlightGroup clone = new() { GroupName = GroupName }; - foreach (HighlightEntry entry in HighlightEntryList) + foreach (var entry in HighlightEntryList) { clone.HighlightEntryList.Add((HighlightEntry)entry.Clone()); } diff --git a/src/LogExpert.Core/Entities/RowHeightEntry.cs b/src/LogExpert.Core/Entities/RowHeightEntry.cs index 00c79bc7..8260b619 100644 --- a/src/LogExpert.Core/Entities/RowHeightEntry.cs +++ b/src/LogExpert.Core/Entities/RowHeightEntry.cs @@ -1,16 +1,17 @@ -namespace LogExpert.Core.Entities; +namespace LogExpert.Core.Entities; +[Serializable] public class RowHeightEntry { #region cTor - public RowHeightEntry() + public RowHeightEntry () { LineNum = 0; Height = 0; } - public RowHeightEntry(int lineNum, int height) + public RowHeightEntry (int lineNum, int height) { LineNum = lineNum; Height = height; diff --git a/src/LogExpert.Tests/BufferShiftTest.cs b/src/LogExpert.Tests/BufferShiftTest.cs index 6279aeeb..5c7ff452 100644 --- a/src/LogExpert.Tests/BufferShiftTest.cs +++ b/src/LogExpert.Tests/BufferShiftTest.cs @@ -34,7 +34,7 @@ public void TestShiftBuffers1 () FormatPattern = "*$J(.)" }; - LinkedList files = CreateTestFilesWithoutDate(); + var files = CreateTestFilesWithoutDate(); EncodingOptions encodingOptions = new() { @@ -45,13 +45,13 @@ public void TestShiftBuffers1 () LogfileReader reader = new(files.Last.Value, encodingOptions, true, 40, 50, options, false, PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); - IList lil = reader.GetLogFileInfoList(); + var lil = reader.GetLogFileInfoList(); Assert.That(lil.Count, Is.EqualTo(files.Count)); - LinkedList.Enumerator enumerator = files.GetEnumerator(); + var enumerator = files.GetEnumerator(); enumerator.MoveNext(); - foreach (LogFileInfo li in lil.Cast()) + foreach (var li in lil.Cast()) { var fileName = enumerator.Current; Assert.That(li.FullName, Is.EqualTo(fileName)); @@ -93,10 +93,10 @@ public void TestShiftBuffers1 () enumerator = files.GetEnumerator(); enumerator.MoveNext(); - IList logBuffers = reader.GetBufferList(); + var logBuffers = reader.GetBufferList(); var startLine = 0; - foreach (LogBuffer logBuffer in logBuffers) + foreach (var logBuffer in logBuffers) { Assert.That(enumerator.Current, Is.EqualTo(logBuffer.FileInfo.FullName)); Assert.That(logBuffer.StartLine, Is.EqualTo(startLine)); @@ -114,8 +114,8 @@ public void TestShiftBuffers1 () for (i = 0; i < logBuffers.Count - 2; ++i) { - LogBuffer logBuffer = logBuffers[i]; - ILogLine line = logBuffer.GetLineOfBlock(0); + var logBuffer = logBuffers[i]; + var line = logBuffer.GetLineOfBlock(0); Assert.That(line.FullLine.Contains(enumerator.Current, StringComparison.Ordinal)); enumerator.MoveNext(); } @@ -124,8 +124,8 @@ public void TestShiftBuffers1 () // the last 2 files now contain the content of the previously watched file for (; i < logBuffers.Count; ++i) { - LogBuffer logBuffer = logBuffers[i]; - ILogLine line = logBuffer.GetLineOfBlock(0); + var logBuffer = logBuffers[i]; + var line = logBuffer.GetLineOfBlock(0); Assert.That(line.FullLine.Contains(enumerator.Current, StringComparison.Ordinal)); } @@ -146,7 +146,7 @@ public void TestShiftBuffers1 () // Check first line to see if buffers are correct // - ILogLine firstLine = reader.GetLogLine(0); + var firstLine = reader.GetLogLine(0); var names = new string[files.Count]; files.CopyTo(names, 0); Assert.That(firstLine.FullLine.Contains(names[2], StringComparison.Ordinal)); diff --git a/src/LogExpert.Tests/CSVColumnizerTest.cs b/src/LogExpert.Tests/CSVColumnizerTest.cs index 5b9e0e33..85883f45 100644 --- a/src/LogExpert.Tests/CSVColumnizerTest.cs +++ b/src/LogExpert.Tests/CSVColumnizerTest.cs @@ -17,12 +17,13 @@ public void Instantiat_CSVFile_BuildCorrectColumnizer (string filename, string[] var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), false, PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); - ILogLine line = reader.GetLogLine(0); + var line = reader.GetLogLine(0); IColumnizedLogLine logline = new ColumnizedLogLine(); if (line != null) { logline = csvColumnizer.SplitLine(null, line); } + var expectedResult = string.Join(",", expectedHeaders); Assert.That(logline.LogLine.FullLine, Is.EqualTo(expectedResult)); } diff --git a/src/LogExpert.Tests/ColumnizerJsonConverterTests.cs b/src/LogExpert.Tests/ColumnizerJsonConverterTests.cs new file mode 100644 index 00000000..0a269035 --- /dev/null +++ b/src/LogExpert.Tests/ColumnizerJsonConverterTests.cs @@ -0,0 +1,76 @@ +using LogExpert.Core.Classes.Persister; + +using Newtonsoft.Json; + +using NUnit.Framework; + +namespace LogExpert.Tests; + +public class MockColumnizer : ILogLineColumnizer +{ + [JsonColumnizerProperty] + public int IntProperty { get; set; } + + [JsonColumnizerProperty] + public string StringProperty { get; set; } + + public string GetName () => "MockColumnizer"; + + public string GetDescription () => "Test columnizer"; + + public int GetColumnCount () => 1; + + public string GetColumnName (int column) => "Col"; + + public string GetColumnValue (LogExpert.ILogLine line, int column) => ""; + + public bool IsTimeshiftImplemented () => false; + + public void PushValue (LogExpert.ILogLine line, int column, string value) { } + + public void SetColumnNames (string[] names) { } + + public void SetParameters (string param) { } + + public void SetConfig (object config) { } + + public string[] GetColumnNames () => throw new NotImplementedException(); + + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) => throw new NotImplementedException(); + + public void SetTimeOffset (int msecOffset) => throw new NotImplementedException(); + + public int GetTimeOffset () => throw new NotImplementedException(); + + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) => throw new NotImplementedException(); + + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) => throw new NotImplementedException(); +} + +[TestFixture] +public class ColumnizerJsonConverterTests +{ + [Test] + public void SerializeDeserialize_MockColumnizer_RoundTripPreservesStateAndType () + { + var original = new MockColumnizer + { + IntProperty = 42, + StringProperty = "TestValue" + }; + + var settings = new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.None, + Converters = { new ColumnizerJsonConverter() } + }; + + var json = JsonConvert.SerializeObject(original, settings); + var deserialized = JsonConvert.DeserializeObject(json, settings); + + Assert.That(deserialized, Is.Not.Null); + Assert.That(original.GetName(), Is.EqualTo(deserialized.GetName())); + Assert.That(42, Is.EqualTo(((MockColumnizer)deserialized).IntProperty)); + Assert.That("TestValue", Is.EqualTo(((MockColumnizer)deserialized).StringProperty)); + } +} \ No newline at end of file diff --git a/src/LogExpert.Tests/JsonColumnizerTest.cs b/src/LogExpert.Tests/JsonColumnizerTest.cs index ad5da6da..caa28329 100644 --- a/src/LogExpert.Tests/JsonColumnizerTest.cs +++ b/src/LogExpert.Tests/JsonColumnizerTest.cs @@ -16,7 +16,7 @@ public void GetColumnNames_HappyFile_ColumnNameMatches (string fileName, string LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), false, PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); - ILogLine line = reader.GetLogLine(0); + var line = reader.GetLogLine(0); if (line != null) { jsonColumnizer.SplitLine(null, line); diff --git a/src/LogExpert.Tests/LocalFileSystemTest.cs b/src/LogExpert.Tests/LocalFileSystemTest.cs index 76a6ee1a..185fee66 100644 --- a/src/LogExpert.Tests/LocalFileSystemTest.cs +++ b/src/LogExpert.Tests/LocalFileSystemTest.cs @@ -1,4 +1,4 @@ -using LogExpert.PluginRegistry.FileSystem; +using LogExpert.PluginRegistry.FileSystem; using NUnit.Framework; @@ -36,14 +36,14 @@ public void TestUriHandle() [Test] public void TestUriToFileStream() { - DirectoryInfo dInfo = Directory.CreateDirectory(RolloverHandlerTest.TEST_DIR_NAME); + var dInfo = Directory.CreateDirectory(RolloverHandlerTest.TEST_DIR_NAME); var fullName = CreateFile(dInfo, "test.log"); LocalFileSystem fs = new(); - ILogFileInfo info = fs.GetLogfileInfo(fullName); + var info = fs.GetLogfileInfo(fullName); Assert.That(info.Length > 0, Is.True); Assert.That(info.OriginalLength == info.Length, Is.True); - Stream stream = info.OpenStream(); + var stream = info.OpenStream(); Assert.That(stream.CanSeek, Is.True); StreamReader reader = new(stream); var line = reader.ReadLine(); diff --git a/src/LogExpert.Tests/RolloverHandlerTest.cs b/src/LogExpert.Tests/RolloverHandlerTest.cs index f93e4045..42006c8f 100644 --- a/src/LogExpert.Tests/RolloverHandlerTest.cs +++ b/src/LogExpert.Tests/RolloverHandlerTest.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Log; using LogExpert.Core.Entities; using LogExpert.PluginRegistry.FileSystem; @@ -20,13 +20,13 @@ public void TestFilenameListWithAppendedIndex(string format, int retries) options.FormatPattern = format; options.MaxDayTry = retries; - LinkedList files = CreateTestFilesWithoutDate(); + var files = CreateTestFilesWithoutDate(); var firstFile = files.Last.Value; ILogFileInfo info = new LogFileInfo(new Uri(firstFile)); RolloverFilenameHandler handler = new(info, options); - LinkedList fileList = handler.GetNameList(PluginRegistry.PluginRegistry.Instance); + var fileList = handler.GetNameList(PluginRegistry.PluginRegistry.Instance); Assert.That(fileList, Is.EqualTo(files)); @@ -41,13 +41,13 @@ public void TestFilenameListWithDate(string format, int retries) options.FormatPattern = format; options.MaxDayTry = retries; - LinkedList files = CreateTestFilesWithDate(); + var files = CreateTestFilesWithDate(); var firstFile = files.Last.Value; ILogFileInfo info = new LogFileInfo(new Uri(firstFile)); RolloverFilenameHandler handler = new(info, options); - LinkedList fileList = handler.GetNameList(PluginRegistry.PluginRegistry.Instance); + var fileList = handler.GetNameList(PluginRegistry.PluginRegistry.Instance); Assert.That(fileList, Is.EqualTo(files)); diff --git a/src/LogExpert.Tests/RolloverHandlerTestBase.cs b/src/LogExpert.Tests/RolloverHandlerTestBase.cs index 26a08906..0bfcdcf6 100644 --- a/src/LogExpert.Tests/RolloverHandlerTestBase.cs +++ b/src/LogExpert.Tests/RolloverHandlerTestBase.cs @@ -15,7 +15,7 @@ internal class RolloverHandlerTestBase protected LinkedList CreateTestFilesWithDate () { LinkedList createdFiles = new(); - DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); + var 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")); @@ -31,7 +31,7 @@ protected LinkedList CreateTestFilesWithDate () protected LinkedList CreateTestFilesWithoutDate () { LinkedList createdFiles = new(); - DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); + var dInfo = Directory.CreateDirectory(TEST_DIR_NAME); TestDirectory = dInfo; _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.6")); _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.5")); @@ -46,14 +46,14 @@ protected LinkedList CreateTestFilesWithoutDate () protected LinkedList RolloverSimulation (LinkedList files, string formatPattern, bool deleteLatestFile) { - LinkedList fileList = files; + var fileList = files; RolloverFilenameBuilder fnb = new(formatPattern); fnb.SetFileName(fileList.Last.Value); fnb.Index += fileList.Count; var newFileName = fnb.BuildFileName(); fileList.AddFirst(newFileName); - LinkedList.Enumerator enumerator = fileList.GetEnumerator(); - LinkedList.Enumerator nextEnumerator = fileList.GetEnumerator(); + var enumerator = fileList.GetEnumerator(); + var nextEnumerator = fileList.GetEnumerator(); nextEnumerator.MoveNext(); // move on 2nd entry enumerator.MoveNext(); diff --git a/src/LogExpert.UI/Controls/ColorComboBox.cs b/src/LogExpert.UI/Controls/ColorComboBox.cs index 3827b7fe..112f479e 100644 --- a/src/LogExpert.UI/Controls/ColorComboBox.cs +++ b/src/LogExpert.UI/Controls/ColorComboBox.cs @@ -94,6 +94,7 @@ private void OnColorComboBoxDrawItem (object sender, DrawItemEventArgs e) e.Graphics.FillRectangle(brush, rectangle); brush.Dispose(); } + e.DrawFocusRectangle(); } } diff --git a/src/LogExpert.UI/Controls/DateTimeDragControl.cs b/src/LogExpert.UI/Controls/DateTimeDragControl.cs index cd804dff..bcc2c796 100644 --- a/src/LogExpert.UI/Controls/DateTimeDragControl.cs +++ b/src/LogExpert.UI/Controls/DateTimeDragControl.cs @@ -110,6 +110,7 @@ public DateTime DateTime { _dateTime = MinDateTime; } + if (_dateTime > MaxDateTime) { _dateTime = MaxDateTime; @@ -250,12 +251,12 @@ private void InitCustomRects (Section dateSection) private void InitDigitRects () { - CultureInfo culture = CultureInfo.CurrentCulture; + var culture = CultureInfo.CurrentCulture; var datePattern = string.Concat(culture.DateTimeFormat.ShortDatePattern, " ", culture.DateTimeFormat.LongTimePattern); - List
sections = Parser.ParseSections(datePattern, out _); - Section dateSection = sections.FirstOrDefault(); + var sections = Parser.ParseSections(datePattern, out _); + var dateSection = sections.FirstOrDefault(); if (dateSection == null) { @@ -377,7 +378,7 @@ protected override void OnPaint (PaintEventArgs e) for (var i = 0; i < _dateParts.Length; i++) { var datePart = _dateParts[i]; - Rectangle rect = _digitRects[i]; + var rect = _digitRects[i]; string value; if (Token.IsDatePart(datePart)) diff --git a/src/LogExpert.UI/Controls/KnobControl.cs b/src/LogExpert.UI/Controls/KnobControl.cs index 6aec9072..d75c2394 100644 --- a/src/LogExpert.UI/Controls/KnobControl.cs +++ b/src/LogExpert.UI/Controls/KnobControl.cs @@ -75,17 +75,18 @@ protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); - Color foregroundColor = Enabled ? Color.Black : Color.Gray; + var foregroundColor = Enabled ? Color.Black : Color.Gray; Pen blackPen = new(foregroundColor, 1); Pen greyPen = new(Color.Gray, 1); - Rectangle rect = ClientRectangle; + var rect = ClientRectangle; var height = Font.Height + 3; if (height > rect.Height) { height = rect.Height + 3; } + rect.Inflate(-1, -height / 2); rect.Offset(0, -height / 2); e.Graphics.DrawEllipse(greyPen, rect); @@ -116,6 +117,7 @@ protected override void OnMouseDown(MouseEventArgs e) _startMouseY = e.Y; _oldValue = Value; } + if (e.Button == MouseButtons.Right) { Capture = false; @@ -161,6 +163,7 @@ protected override void OnMouseMove(MouseEventArgs e) { _value = MaxValue; } + Invalidate(); } diff --git a/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs b/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs index ab9f0746..7a61ef42 100644 --- a/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs +++ b/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs @@ -21,7 +21,7 @@ internal IColumnizedLogLine GetColumnsForLine (LogfileReader logFileReader, int { _lastColumnizer = columnizer; _lastLineNumber = lineNumber; - ILogLine line = logFileReader.GetLogLineWithWait(lineNumber).Result; + var line = logFileReader.GetLogLineWithWait(lineNumber).Result; if (line != null) { diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index 12fa629f..6473f427 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -485,12 +485,12 @@ internal void ToggleColumnFinder (bool show, bool setFocus) if (setFocus) { - columnComboBox.Focus(); + _ = columnComboBox.Focus(); } } else { - dataGridView.Focus(); + _ = dataGridView.Focus(); } tableLayoutPanel1.RowStyles[0].Height = show ? 28 : 0; @@ -660,7 +660,7 @@ protected void OnDeRegisterCancelHandler (IBackgroundProcessCancelHandler handle { lock (_cancelHandlerList) { - _cancelHandlerList.Remove(handler); + _ = _cancelHandlerList.Remove(handler); } } @@ -688,7 +688,7 @@ private void OnLogWindowDisposed (object sender, EventArgs e) [SupportedOSPlatform("windows")] private void OnLogFileReaderLoadingStarted (object sender, LoadFileEventArgs e) { - Invoke(LoadingStarted, e); + _ = Invoke(LoadingStarted, e); } [SupportedOSPlatform("windows")] @@ -700,22 +700,22 @@ private void OnLogFileReaderFinishedLoading (object sender, EventArgs e) _isDeadFile = false; if (!_waitingForClose) { - Invoke(new MethodInvoker(LoadingFinished)); - Invoke(new MethodInvoker(LoadPersistenceData)); - Invoke(new MethodInvoker(SetGuiAfterLoading)); - _loadingFinishedEvent.Set(); - _externaLoadingFinishedEvent.Set(); + _ = Invoke(new MethodInvoker(LoadingFinished)); + _ = Invoke(new MethodInvoker(LoadPersistenceData)); + _ = Invoke(new MethodInvoker(SetGuiAfterLoading)); + _ = _loadingFinishedEvent.Set(); + _ = _externaLoadingFinishedEvent.Set(); _timeSpreadCalc.SetLineCount(_logFileReader.LineCount); if (_reloadMemento != null) { - Invoke(new PositionAfterReloadFx(PositionAfterReload), _reloadMemento); + _ = Invoke(new PositionAfterReloadFx(PositionAfterReload), _reloadMemento); } if (filterTailCheckBox.Checked) { _logger.Info(CultureInfo.InvariantCulture, "Refreshing filter view because of reload."); - Invoke(new MethodInvoker(FilterSearch)); // call on proper thread + _ = Invoke(new MethodInvoker(FilterSearch)); // call on proper thread } HandleChangedFilterList(); @@ -731,14 +731,14 @@ private void OnLogFileReaderFileNotFound (object sender, EventArgs e) { _logger.Info(CultureInfo.InvariantCulture, "Handling file not found event."); _isDeadFile = true; - BeginInvoke(new MethodInvoker(LogfileDead)); + _ = BeginInvoke(new MethodInvoker(LogfileDead)); } } [SupportedOSPlatform("windows")] private void OnLogFileReaderRespawned (object sender, EventArgs e) { - BeginInvoke(new MethodInvoker(LogfileRespawned)); + _ = BeginInvoke(new MethodInvoker(LogfileRespawned)); } [SupportedOSPlatform("windows")] @@ -753,7 +753,7 @@ private void OnLogWindowClosing (object sender, CancelEventArgs e) } } - SavePersistenceData(false); + _ = SavePersistenceData(false); CloseLogWindow(); } @@ -779,14 +779,14 @@ private void OnLogFileReaderLoadFile (object sender, LoadFileEventArgs e) UnRegisterLogFileReaderEvents(); dataGridView.CurrentCellChanged -= OnDataGridViewCurrentCellChanged; MethodInvoker invoker = ReloadNewFile; - BeginInvoke(invoker); + _ = BeginInvoke(invoker); //Thread loadThread = new Thread(new ThreadStart(ReloadNewFile)); //loadThread.Start(); _logger.Debug(CultureInfo.InvariantCulture, "Reloading invoked."); } else if (_isLoading) { - BeginInvoke(UpdateProgress, e); + _ = BeginInvoke(UpdateProgress, e); } } @@ -984,7 +984,7 @@ private void OnFilterGridViewColumnDividerDoubleClick (object sender, { e.Handled = true; AutoResizeColumnsFx fx = AutoResizeColumns; - BeginInvoke(fx, filterGridView); + _ = BeginInvoke(fx, filterGridView); } [SupportedOSPlatform("windows")] @@ -1166,7 +1166,7 @@ private void OnSelectionChangedTriggerSignal (object sender, EventArgs e) if (IsMultiFile) { MethodInvoker invoker = DisplayCurrentFileOnStatusline; - invoker.BeginInvoke(null, null); + _ = invoker.BeginInvoke(null, null); } else { @@ -1198,7 +1198,7 @@ private void OnPipeDisconnected (object sender, EventArgs e) { lock (_filterPipeList) { - _filterPipeList.Remove((FilterPipe)sender); + _ = _filterPipeList.Remove((FilterPipe)sender); if (_filterPipeList.Count == 0) // reset naming counter to 0 if no more open filter tabs for this source window { @@ -1712,7 +1712,7 @@ private void OnHighlightSelectionInLogFileToolStripMenuItemClick (object sender, SearchText = ctl.SelectedText, ForegroundColor = Color.Red, BackgroundColor = Color.Yellow, - IsRegEx = false, + IsRegex = false, IsCaseSensitive = true, IsLedSwitch = false, IsSetBookmark = false, @@ -1726,8 +1726,8 @@ private void OnHighlightSelectionInLogFileToolStripMenuItemClick (object sender, _tempHighlightEntryList.Add(he); } - dataGridView.CancelEdit(); - dataGridView.EndEdit(); + _ = dataGridView.CancelEdit(); + _ = dataGridView.EndEdit(); RefreshAllGrids(); } } @@ -1742,7 +1742,7 @@ private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick (object SearchText = ctl.SelectedText, ForegroundColor = Color.Red, BackgroundColor = Color.Yellow, - IsRegEx = false, + IsRegex = false, IsCaseSensitive = true, IsLedSwitch = false, IsStopTail = false, @@ -1757,8 +1757,8 @@ private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick (object _tempHighlightEntryList.Add(he); } - dataGridView.CancelEdit(); - dataGridView.EndEdit(); + _ = dataGridView.CancelEdit(); + _ = dataGridView.EndEdit(); RefreshAllGrids(); } } @@ -1893,7 +1893,7 @@ private void OnDeleteFilterButtonClick (object sender, EventArgs e) 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) { @@ -2334,7 +2334,7 @@ private void LoadPersistenceData () { if (InvokeRequired) { - Invoke(new MethodInvoker(LoadPersistenceData)); + _ = Invoke(new MethodInvoker(LoadPersistenceData)); return; } @@ -2422,7 +2422,7 @@ private void RestoreFilters (PersistenceData persistenceData) } ApplyFilterParams(); // re-loaded filter settingss - BeginInvoke(new MethodInvoker(FilterSearch)); + _ = BeginInvoke(new MethodInvoker(FilterSearch)); try { splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; @@ -2479,7 +2479,7 @@ private void EnterLoadFileStatus () if (InvokeRequired) { - Invoke(new MethodInvoker(EnterLoadFileStatus)); + _ = Invoke(new MethodInvoker(EnterLoadFileStatus)); return; } @@ -2597,7 +2597,7 @@ private void SetGuiAfterLoading () } } - Invoke(new SetColumnizerFx(SetColumnizer), columnizer); + _ = Invoke(new SetColumnizerFx(SetColumnizer), columnizer); } dataGridView.Enabled = true; @@ -2649,9 +2649,9 @@ private void ReloadNewFile () _logger.Info($"ReloadNewFile(): counter = {_reloadOverloadCounter}"); if (_reloadOverloadCounter <= 1) { - SavePersistenceData(false); - _loadingFinishedEvent.Reset(); - _externaLoadingFinishedEvent.Reset(); + _ = SavePersistenceData(false); + _ = _loadingFinishedEvent.Reset(); + _ = _externaLoadingFinishedEvent.Reset(); Thread reloadFinishedThread = new(ReloadFinishedThreadFx) { IsBackground = true @@ -2660,7 +2660,7 @@ private void ReloadNewFile () LoadFile(FileName, EncodingOptions); ClearBookmarkList(); - SavePersistenceData(false); + _ = SavePersistenceData(false); //if (this.filterTailCheckBox.Checked) //{ @@ -2684,9 +2684,9 @@ private void ReloadNewFile () private void ReloadFinishedThreadFx () { _logger.Info(CultureInfo.InvariantCulture, "Waiting for loading to be complete."); - _loadingFinishedEvent.WaitOne(); + _ = _loadingFinishedEvent.WaitOne(); _logger.Info(CultureInfo.InvariantCulture, "Refreshing filter view because of reload."); - Invoke(new MethodInvoker(FilterSearch)); + _ = Invoke(new MethodInvoker(FilterSearch)); LoadFilterPipes(); } @@ -2774,7 +2774,7 @@ private void LogEventWorker () while (true) { _logger.Debug(CultureInfo.InvariantCulture, "Waiting for signal"); - _logEventArgsEvent.WaitOne(); + _ = _logEventArgsEvent.WaitOne(); _logger.Debug(CultureInfo.InvariantCulture, "Wakeup signal received."); while (true) { @@ -2785,7 +2785,7 @@ private void LogEventWorker () _logger.Info(CultureInfo.InvariantCulture, "{0} events in queue", _logEventArgsList.Count); if (_logEventArgsList.Count == 0) { - _logEventArgsEvent.Reset(); + _ = _logEventArgsEvent.Reset(); break; } @@ -2808,7 +2808,7 @@ private void LogEventWorker () } } - Invoke(UpdateGrid, [e]); + _ = Invoke(UpdateGrid, [e]); CheckFilterAndHighlight(e); _timeSpreadCalc.SetLineCount(e.LineCount); } @@ -2817,7 +2817,7 @@ private void LogEventWorker () private void StopLogEventWorkerThread () { - _logEventArgsEvent.Set(); + _ = _logEventArgsEvent.Set(); cts.Cancel(); //_logEventHandlerThread.Abort(); //_logEventHandlerThread.Join(); @@ -2958,8 +2958,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) //AddFilterLineFx addFx = new AddFilterLineFx(AddFilterLine); //this.Invoke(addFx, new object[] { i, true }); filterLineAdded = true; - AddFilterLine(i, false, _filterParams, _filterResultList, _lastFilterLinesList, - _filterHitList); + AddFilterLine(i, false, _filterParams, _filterResultList, _lastFilterLinesList, _filterHitList); } } @@ -2973,7 +2972,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) if (setBookmark) { SetBookmarkFx fx = SetBookmarkFromTrigger; - fx.BeginInvoke(i, bookmarkComment, null, null); + _ = fx.BeginInvoke(i, bookmarkComment, null, null); } if (stopTail && _guiStateArgs.FollowTail) @@ -2982,7 +2981,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) FollowTailChanged(false, true); if (firstStopTail && wasFollow) { - Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); + _ = Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); firstStopTail = false; } } @@ -3022,7 +3021,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) if (setBookmark) { SetBookmarkFx fx = SetBookmarkFromTrigger; - fx.BeginInvoke(i, bookmarkComment, null, null); + _ = fx.BeginInvoke(i, bookmarkComment, null, null); } if (stopTail && _guiStateArgs.FollowTail) @@ -3031,7 +3030,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) FollowTailChanged(false, true); if (firstStopTail && wasFollow) { - Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); + _ = Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); firstStopTail = false; } } @@ -3065,7 +3064,7 @@ private void LaunchHighlightPlugins (IList matchingList, int lin if (plugin != null) { ActionPluginExecuteFx fx = plugin.Execute; - fx.BeginInvoke(entry.SearchText, entry.ActionEntry.ActionParam, callback, CurrentColumnizer, null, null); + _ = fx.BeginInvoke(entry.SearchText, entry.ActionEntry.ActionParam, callback, CurrentColumnizer, null, null); } } } @@ -3108,7 +3107,7 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) // Check if the filtered columns disappeared, if so must refresh the UI if (_filterParams.ColumnRestrict) { - var newColumns = columnizer != null ? columnizer.GetColumnNames() : Array.Empty(); + var newColumns = columnizer != null ? columnizer.GetColumnNames() : []; var colChanged = false; if (dataGridView.ColumnCount - 2 == newColumns.Length) // two first columns are 'marker' and 'line number' @@ -3230,7 +3229,7 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) foreach (var columnName in columnizer.GetColumnNames()) { - columnComboBox.Items.Add(columnName); + _ = columnComboBox.Items.Add(columnName); } columnComboBox.SelectedIndex = 0; @@ -3461,7 +3460,7 @@ private HighlightEntry FindFirstNoWordMatchHilightEntry (ITextValue line) private bool CheckHighlightEntryMatch (HighlightEntry entry, ITextValue column) { - if (entry.IsRegEx) + if (entry.IsRegex) { //Regex rex = new Regex(entry.SearchText, entry.IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); if (entry.Regex.IsMatch(column.Text)) @@ -3829,7 +3828,7 @@ private int Search (SearchParams searchParams) { if (!Disposing) { - Invoke(UpdateProgressBar, [count]); + _ = Invoke(UpdateProgressBar, [count]); } } catch (ObjectDisposedException ex) // can occur when closing the app while searching @@ -3867,7 +3866,7 @@ private void SelectLine (int lineNum, bool triggerSyncCall, bool shouldScroll) if (lineNum == -1) { // Hmm... is that experimental code from early days? - MessageBox.Show(this, "Not found:", "Search result"); + _ = MessageBox.Show(this, "Not found:", "Search result"); return; } @@ -4285,7 +4284,7 @@ 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; @@ -4386,7 +4385,7 @@ private void TriggerFilterLineGuiUpdate () // this.filterEventCount++; // this.filterUpdateEvent.Set(); //} - Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); + _ = Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); } //private void FilterUpdateWorker() @@ -4491,7 +4490,7 @@ private void FilterComplete () { if (!IsDisposed && !_waitingForClose && !Disposing) { - Invoke(new MethodInvoker(ResetStatusAfterFilter)); + _ = Invoke(new MethodInvoker(ResetStatusAfterFilter)); } } @@ -4500,7 +4499,7 @@ private void FilterComplete (IAsyncResult result) { if (!IsDisposed && !_waitingForClose && !Disposing) { - Invoke(new MethodInvoker(ResetStatusAfterFilter)); + _ = Invoke(new MethodInvoker(ResetStatusAfterFilter)); } } @@ -4520,7 +4519,7 @@ private void ResetStatusAfterFilter () lblFilterCount.Text = "" + _filterResultList.Count; if (filterGridView.RowCount > 0) { - filterGridView.Focus(); + _ = filterGridView.Focus(); } filterSearchButton.Enabled = true; @@ -4556,7 +4555,7 @@ private void ClearFilterList () { _logger.Error(ex, "Wieder dieser sporadische Fehler: "); - MessageBox.Show(null, ex.StackTrace, "Wieder dieser sporadische Fehler:"); + _ = MessageBox.Show(null, ex.StackTrace, "Wieder dieser sporadische Fehler:"); } } @@ -4755,13 +4754,13 @@ private void UpdateFilterHistoryFromSettings () filterComboBox.Items.Clear(); foreach (var item in ConfigManager.Settings.FilterHistoryList) { - filterComboBox.Items.Add(item); + _ = filterComboBox.Items.Add(item); } filterRangeComboBox.Items.Clear(); foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) { - filterRangeComboBox.Items.Add(item); + _ = filterRangeComboBox.Items.Add(item); } } @@ -4829,7 +4828,7 @@ private void CheckForAdvancedButtonDirty () private void FilterToTab () { filterSearchButton.Enabled = false; - Task.Run(() => WriteFilterToTab()); + _ = Task.Run(() => WriteFilterToTab()); } [SupportedOSPlatform("windows")] @@ -4858,7 +4857,7 @@ private void WritePipeToTab (FilterPipe pipe, List lineNumberList, string n _progressEventArgs.MaxValue = lineNumberList.Count; _progressEventArgs.Value = 0; _progressEventArgs.Visible = true; - Invoke(new MethodInvoker(SendProgressBarUpdate)); + _ = Invoke(new MethodInvoker(SendProgressBarUpdate)); _isSearching = true; _shouldCancel = false; @@ -4885,17 +4884,17 @@ private void WritePipeToTab (FilterPipe pipe, List lineNumberList, string n line = (CurrentColumnizer as ILogLineXmlColumnizer).GetLineTextForClipboard(line, callback); } - pipe.WriteToPipe(line, i); + _ = pipe.WriteToPipe(line, i); if (++count % PROGRESS_BAR_MODULO == 0) { _progressEventArgs.Value = count; - Invoke(new MethodInvoker(SendProgressBarUpdate)); + _ = Invoke(new MethodInvoker(SendProgressBarUpdate)); } } pipe.CloseFile(); _logger.Info(CultureInfo.InvariantCulture, "WritePipeToTab(): finished"); - Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), pipe, name, persistenceData); + _ = Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), pipe, name, persistenceData); } [SupportedOSPlatform("windows")] @@ -4916,7 +4915,7 @@ private void WriteFilterToTabFinished (FilterPipe pipe, string name, Persistence pipe.OwnLogWindow = newWin; if (persistenceData != null) { - Task.Run(() => FilterRestore(newWin, persistenceData)); + _ = Task.Run(() => FilterRestore(newWin, persistenceData)); } } @@ -4946,11 +4945,11 @@ internal void WritePipeTab (IList lineEntryList, string title) pipe.OpenFile(); foreach (var entry in lineEntryList) { - pipe.WriteToPipe(entry.LogLine, entry.LineNum); + _ = pipe.WriteToPipe(entry.LogLine, entry.LineNum); } pipe.CloseFile(); - Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), [pipe, title, null]); + _ = Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), [pipe, title, null]); } [SupportedOSPlatform("windows")] @@ -4962,14 +4961,14 @@ private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) if (columnizer != null) { SetColumnizerFx fx = newWin.ForceColumnizer; - newWin.Invoke(fx, [columnizer]); + _ = newWin.Invoke(fx, [columnizer]); } else { _logger.Warn($"FilterRestore(): Columnizer {persistenceData.ColumnizerName} not found"); } - newWin.BeginInvoke(new RestoreFiltersFx(newWin.RestoreFilters), [persistenceData]); + _ = newWin.BeginInvoke(new RestoreFiltersFx(newWin.RestoreFilters), [persistenceData]); } [SupportedOSPlatform("windows")] @@ -5027,7 +5026,7 @@ private void ProcessFilterPipes (int lineNum) foreach (var pipe in deleteList) { - _filterPipeList.Remove(pipe); + _ = _filterPipeList.Remove(pipe); } } @@ -5065,7 +5064,7 @@ private void CopyMarkedLinesToClipboard () line = xmlColumnizer.GetLineTextForClipboard(line, callback); } - clipText.AppendLine(line.ToClipBoardText()); + _ = clipText.AppendLine(line.ToClipBoardText()); } Clipboard.SetText(clipText.ToString()); @@ -5317,6 +5316,7 @@ private void TestStatistic (PatternArgs patternArgs) blockList.Add(block); AddBlockTargetLinesToDict(processedLinesDict, block); } + block.BlockId = blockId; //if (firstBlock) //{ @@ -5639,7 +5639,7 @@ private void ChangeRowHeight (bool decrease) entry.Height -= _lineHeight; if (entry.Height <= _lineHeight) { - _rowHeightList.Remove(rowNum); + _ = _rowHeightList.Remove(rowNum); } } } @@ -5869,7 +5869,7 @@ private void AddSearchHitHighlightEntry (SearchParams para) SearchText = para.SearchText, ForegroundColor = Color.Red, BackgroundColor = Color.Yellow, - IsRegEx = para.IsRegex, + IsRegex = para.IsRegex, IsCaseSensitive = para.IsCaseSensitive, IsLedSwitch = false, IsStopTail = false, @@ -6009,7 +6009,7 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) catch (LogFileException lfe) { _logger.Error(lfe); - MessageBox.Show($"Cannot load file\n{lfe.Message}", "LogExpert"); + _ = MessageBox.Show($"Cannot load file\n{lfe.Message}", "LogExpert"); _ = BeginInvoke(new FunctionWith1BoolParam(Close), true); _isLoadError = true; return; @@ -6111,7 +6111,7 @@ public string SavePersistenceData (bool force) } catch (Exception e) { - MessageBox.Show($"Unexpected error while saving persistence: {e.Message}"); + _ = MessageBox.Show($"Unexpected error while saving persistence: {e.Message}"); } return null; @@ -6143,8 +6143,9 @@ public PersistenceData GetPersistenceData () if (Preferences.SaveFilters) { - List filterList = [_filterParams]; - persistenceData.FilterParamsList = filterList; + //when a filter is added, its added to the Configmanager.Settings.FilterList and not to the _filterParams, this is probably an oversight and maybe a bug + //but for the consistency the FilterList should be saved as whole for every file + persistenceData.FilterParamsList = [.. ConfigManager.Settings.FilterList]; foreach (var filterPipe in _filterPipeList) { @@ -6219,7 +6220,7 @@ public void CloseLogWindow () public void WaitForLoadingFinished () { - _externaLoadingFinishedEvent.WaitOne(); + _ = _externaLoadingFinishedEvent.WaitOne(); } public void ForceColumnizer (ILogLineColumnizer columnizer) @@ -6463,7 +6464,7 @@ public void FollowTailChanged (bool isChecked, bool byTrigger) } } - BeginInvoke(new MethodInvoker(dataGridView.Refresh)); + _ = BeginInvoke(new MethodInvoker(dataGridView.Refresh)); //this.dataGridView.Refresh(); _parentLogTabWin.FollowTailChanged(this, isChecked, byTrigger); SendGuiStateUpdate(); @@ -6530,7 +6531,7 @@ public void StartSearch () _progressEventArgs.Visible = true; SendProgressBarUpdate(); - Task.Run(() => Search(searchParams)).ContinueWith(SearchComplete); + _ = Task.Run(() => Search(searchParams)).ContinueWith(SearchComplete); RemoveAllSearchHighlightEntries(); AddSearchHitHighlightEntry(searchParams); @@ -6545,7 +6546,7 @@ private void SearchComplete (Task task) try { - Invoke(new MethodInvoker(ResetProgressBar)); + _ = Invoke(new MethodInvoker(ResetProgressBar)); var line = task.Result; _guiStateArgs.MenuEnabled = true; GuiStateUpdate(this, _guiStateArgs); @@ -6554,7 +6555,7 @@ private void SearchComplete (Task task) return; } - dataGridView.Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); + _ = dataGridView.Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); } catch (Exception ex) // in the case the windows is already destroyed { @@ -6564,7 +6565,7 @@ private void SearchComplete (Task task) public void SelectLogLine (int line) { - Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); + _ = Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); } public void SelectAndEnsureVisible (int line, bool triggerSyncCall) @@ -6804,6 +6805,7 @@ public void ToggleBookmark () { return; } + lineNum = dataGridView.CurrentCellAddress.Y; } @@ -6823,12 +6825,14 @@ public void ToggleBookmark (int lineNum) return; } } + _bookmarkProvider.RemoveBookmarkForLine(lineNum); } else { _bookmarkProvider.AddBookmark(new Bookmark(lineNum)); } + dataGridView.Refresh(); filterGridView.Refresh(); OnBookmarkAdded(); @@ -6843,6 +6847,7 @@ public void SetBookmarkFromTrigger (int lineNum, string comment) { return; } + var paramParser = new ParamParser(comment); try { @@ -6852,10 +6857,12 @@ public void SetBookmarkFromTrigger (int lineNum, string comment) { // occurs on invalid regex } + if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) { _bookmarkProvider.RemoveBookmarkForLine(lineNum); } + _bookmarkProvider.AddBookmark(new Bookmark(lineNum, comment)); OnBookmarkAdded(); } @@ -6880,12 +6887,14 @@ public void JumpNextBookmark () filterGridView.CurrentCell = filterGridView.Rows[filterLine].Cells[0]; break; } + index++; if (index > _bookmarkProvider.Bookmarks.Count - 1) { index = 0; wrapped = true; } + if (index >= startIndex && wrapped) { break; @@ -6921,6 +6930,7 @@ public void JumpPrevBookmark () { index = _bookmarkProvider.Bookmarks.Count - 1; } + var startIndex = index; var wrapped = false; while (true) @@ -6933,12 +6943,14 @@ public void JumpPrevBookmark () filterGridView.CurrentCell = filterGridView.Rows[filterLine].Cells[0]; break; } + index--; if (index < 0) { index = _bookmarkProvider.Bookmarks.Count - 1; wrapped = true; } + if (index <= startIndex && wrapped) { break; @@ -6973,6 +6985,7 @@ public void DeleteBookmarks (List lineNumList) } } } + if (bookmarksPresent) { if ( @@ -6982,6 +6995,7 @@ public void DeleteBookmarks (List lineNumList) return; } } + _bookmarkProvider.RemoveBookmarksForLines(lineNumList); OnBookmarkRemoved(); } @@ -7002,6 +7016,7 @@ public void SetTimeshiftValue (string value) { text = text.Substring(1); } + var timeSpan = TimeSpan.Parse(text); var diff = (int)(timeSpan.Ticks / TimeSpan.TicksPerMillisecond); CurrentColumnizer.SetTimeOffset(diff); @@ -7015,6 +7030,7 @@ public void SetTimeshiftValue (string value) { CurrentColumnizer.SetTimeOffset(0); } + dataGridView.Refresh(); filterGridView.Refresh(); if (CurrentColumnizer.IsTimeshiftImplemented()) @@ -7035,11 +7051,11 @@ public void ToggleFilterPanel () splitContainerLogWindow.Panel2Collapsed = !splitContainerLogWindow.Panel2Collapsed; if (!splitContainerLogWindow.Panel2Collapsed) { - filterComboBox.Focus(); + _ = filterComboBox.Focus(); } else { - dataGridView.Focus(); + _ = dataGridView.Focus(); } } @@ -7056,7 +7072,7 @@ public void LogWindowActivated () SyncTimestampDisplay(); } - dataGridView.Focus(); + _ = dataGridView.Focus(); SendGuiStateUpdate(); SendStatusLineUpdate(); @@ -7119,7 +7135,7 @@ public void CopyMarkedLinesToTab () writer.Close(); var title = Util.GetNameFromPath(FileName) + "->Clip"; - _parentLogTabWin.AddTempFileTab(fileName, title); + _ = _parentLogTabWin.AddTempFileTab(fileName, title); } } @@ -7141,12 +7157,13 @@ public void ChangeEncoding (Encoding encoding) dataGridView.Refresh(); SendGuiStateUpdate(); } + _guiStateArgs.CurrentEncoding = _logFileReader.CurrentEncoding; } public void Reload () { - SavePersistenceData(false); + _ = SavePersistenceData(false); _reloadMemento = new ReloadMemento { @@ -7215,7 +7232,7 @@ public void PreferencesChanged (string fontName, float fontSize, bool setLastCol if (CurrentColumnizer.IsTimeshiftImplemented()) { - timeSpreadingControl.Invoke(new MethodInvoker(timeSpreadingControl.Refresh)); + _ = timeSpreadingControl.Invoke(new MethodInvoker(timeSpreadingControl.Refresh)); ShowTimeSpread(Preferences.ShowTimeSpread); } @@ -7242,7 +7259,7 @@ public bool ScrollToTimestamp (DateTime timestamp, bool roundToSeconds, bool tri { if (InvokeRequired) { - BeginInvoke(new ScrollToTimestampFx(ScrollToTimestampWorker), timestamp, roundToSeconds, triggerSyncCall); + _ = BeginInvoke(new ScrollToTimestampFx(ScrollToTimestampWorker), timestamp, roundToSeconds, triggerSyncCall); return true; } @@ -7263,6 +7280,7 @@ public bool ScrollToTimestampWorker (DateTime timestamp, bool roundToSeconds, bo { currentLine = 0; } + var foundLine = FindTimestampLine(currentLine, timestamp, roundToSeconds); if (foundLine >= 0) { @@ -7285,13 +7303,14 @@ public int FindTimestampLine (int lineNum, DateTime timestamp, bool roundToSecon foundLine--; foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); } + if (foundLine < 0) { return 0; } foundLine++; - GetTimestampForLineForward(ref foundLine, roundToSeconds); // fwd to next valid timestamp + _ = GetTimestampForLineForward(ref foundLine, roundToSeconds); // fwd to next valid timestamp return foundLine; } @@ -7525,6 +7544,7 @@ public void PatternStatisticSelectRange (PatternArgs patternArgs) lineNumList.Add(row.Index); } } + lineNumList.Sort(); patternArgs.StartLine = lineNumList[0]; patternArgs.EndLine = lineNumList[^1]; @@ -7541,7 +7561,7 @@ public void PatternStatisticSelectRange (PatternArgs patternArgs) public void PatternStatistic (PatternArgs patternArgs) { var fx = new PatternStatisticFx(TestStatistic); - fx.BeginInvoke(patternArgs, null, null); + _ = fx.BeginInvoke(patternArgs, null, null); } public void ExportBookmarkList () @@ -7566,7 +7586,7 @@ public void ExportBookmarkList () catch (IOException e) { _logger.Error(e); - MessageBox.Show("Error while exporting bookmark list: " + e.Message, "LogExpert"); + _ = MessageBox.Show("Error while exporting bookmark list: " + e.Message, "LogExpert"); } } } @@ -7614,13 +7634,14 @@ public void ImportBookmarkList () { OnBookmarkAdded(); } + dataGridView.Refresh(); filterGridView.Refresh(); } catch (IOException e) { _logger.Error(e); - MessageBox.Show($"Error while importing bookmark list: {e.Message}", "LogExpert"); + _ = MessageBox.Show($"Error while importing bookmark list: {e.Message}", "LogExpert"); } } } @@ -7637,7 +7658,7 @@ public bool IsAdvancedOptionActive () public void HandleChangedFilterList () { - Invoke(new MethodInvoker(HandleChangedFilterListWorker)); + _ = Invoke(new MethodInvoker(HandleChangedFilterListWorker)); } public void HandleChangedFilterListWorker () @@ -7646,13 +7667,15 @@ public void HandleChangedFilterListWorker () filterListBox.Items.Clear(); foreach (var filterParam in ConfigManager.Settings.FilterList) { - filterListBox.Items.Add(filterParam); + _ = filterListBox.Items.Add(filterParam); } + filterListBox.Refresh(); if (index >= 0 && index < filterListBox.Items.Count) { filterListBox.SelectedIndex = index; } + filterOnLoadCheckBox.Checked = Preferences.IsFilterOnLoad; hideFilterListOnLoadCheckBox.Checked = Preferences.IsAutoHideFilterList; } @@ -7672,7 +7695,7 @@ public void SetCurrentHighlightGroup (string groupName) } SendGuiStateUpdate(); - BeginInvoke(new MethodInvoker(RefreshAllGrids)); + _ = BeginInvoke(new MethodInvoker(RefreshAllGrids)); } public void SwitchMultiFile (bool enabled) @@ -7714,7 +7737,7 @@ public void AddToTimeSync (LogWindow master) TimeSyncList = master.TimeSyncList; TimeSyncList.AddWindow(this); - ScrollToTimestamp(TimeSyncList.CurrentTimestamp, false, false); + _ = ScrollToTimestamp(TimeSyncList.CurrentTimestamp, false, false); } OnSyncModeChanged(); diff --git a/src/LogExpert.UI/Controls/LogWindow/RangeFinder.cs b/src/LogExpert.UI/Controls/LogWindow/RangeFinder.cs index 68b4d258..cc9333b6 100644 --- a/src/LogExpert.UI/Controls/LogWindow/RangeFinder.cs +++ b/src/LogExpert.UI/Controls/LogWindow/RangeFinder.cs @@ -34,6 +34,7 @@ public Range FindRange(int startLine) _logger.Info(CultureInfo.InvariantCulture, "Range search text not set. Cancelling range search."); return null; } + if (_filterParams.SearchText == null || _filterParams.SearchText.Trim().Length == 0) { _logger.Info(CultureInfo.InvariantCulture, "Search text not set. Cancelling range search."); @@ -48,7 +49,7 @@ public Range FindRange(int startLine) var foundStartLine = false; Range range = new(); - FilterParams tmpParam = _filterParams.CloneWithCurrentColumnizer(); + var tmpParam = _filterParams.CloneWithCurrentColumnizer(); tmpParam.SearchText = _filterParams.RangeSearchText; @@ -64,6 +65,7 @@ public Range FindRange(int startLine) foundStartLine = true; break; } + lineNum--; line = callback.GetLogLine(lineNum); @@ -93,8 +95,10 @@ public Range FindRange(int startLine) { break; } + lineNum++; } + lineNum--; range.EndLine = lineNum; diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs index ab326b5d..9318141c 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs @@ -311,6 +311,7 @@ private void DoCalc_via_Time () { lineNum = -lineNum; } + var lineDiff = lineNum - oldLineNum; _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc_via_Time() test time {0:HH:mm:ss.fff} line diff={1}", searchTimeStamp, lineDiff); @@ -329,6 +330,7 @@ private void DoCalc_via_Time () { _maxDiff = lineDiff; } + maxList.Add(lineDiff); loopCount++; } diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs index fe51937b..3a522678 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs @@ -71,7 +71,7 @@ public void NavigateToTimestamp (DateTime timestamp, LogWindow sender) CurrentTimestamp = timestamp; lock (logWindowList) { - foreach (LogWindow logWindow in logWindowList) + foreach (var logWindow in logWindowList) { if (sender != logWindow) { diff --git a/src/LogExpert.UI/Dialogs/AboutBox.cs b/src/LogExpert.UI/Dialogs/AboutBox.cs index 37afa730..55ba7a03 100644 --- a/src/LogExpert.UI/Dialogs/AboutBox.cs +++ b/src/LogExpert.UI/Dialogs/AboutBox.cs @@ -70,6 +70,7 @@ public string AssemblyTitle return titleAttribute.Title; } } + return Path.GetFileNameWithoutExtension(_assembly.Location); } } diff --git a/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs b/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs index 229f18e8..c1900fe6 100644 --- a/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs +++ b/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs @@ -38,7 +38,7 @@ private void FillIconList() { iconListView.Items.Clear(); - Icon[,] icons = NativeMethods.ExtractIcons(FileName); + var icons = NativeMethods.ExtractIcons(FileName); if (icons == null) { @@ -66,7 +66,7 @@ private void FillIconList() private void DisposeIcons() { - ImageList imageList = iconListView.LargeImageList; + var imageList = iconListView.LargeImageList; iconListView.LargeImageList = null; foreach (Image image in imageList.Images) { diff --git a/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs b/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs index da5350c8..e16d7a78 100644 --- a/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs +++ b/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs @@ -66,7 +66,7 @@ private XmlDocument BuildParam (ILogLine line) } var lineNum = fullLogLine[(pos + 1)..]; - XmlDocument doc = BuildXmlDocument(className, lineNum); + var doc = BuildXmlDocument(className, lineNum); return doc; } @@ -92,6 +92,7 @@ private XmlDocument BuildParam (ILogLine line) { return null; } + className = str[..pos]; } @@ -121,9 +122,10 @@ private XmlDocument BuildParam (ILogLine line) */ - XmlDocument doc = BuildXmlDocument(className, lineNum); + var doc = BuildXmlDocument(className, lineNum); return doc; } + return null; } @@ -132,16 +134,16 @@ private XmlDocument BuildXmlDocument (string className, string lineNum) { XmlDocument xmlDoc = new(); xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); - XmlElement rootElement = xmlDoc.CreateElement("eminus"); + var rootElement = xmlDoc.CreateElement("eminus"); xmlDoc.AppendChild(rootElement); rootElement.SetAttribute("authKey", _config.Password); - XmlElement loadElement = xmlDoc.CreateElement("loadclass"); + var loadElement = xmlDoc.CreateElement("loadclass"); loadElement.SetAttribute("mode", "dialog"); rootElement.AppendChild(loadElement); - XmlElement elemClassName = xmlDoc.CreateElement("classname"); - XmlElement elemLineNum = xmlDoc.CreateElement("linenumber"); + var elemClassName = xmlDoc.CreateElement("classname"); + var elemLineNum = xmlDoc.CreateElement("linenumber"); elemClassName.InnerText = className; elemLineNum.InnerText = lineNum; loadElement.AppendChild(elemClassName); @@ -180,7 +182,7 @@ public void MenuSelected (int logLinesCount, ILogLineColumnizer columnizer, ILog return; } - XmlDocument doc = BuildParam(logline); + var doc = BuildParam(logline); if (doc == null) { @@ -191,7 +193,7 @@ public void MenuSelected (int logLinesCount, ILogLineColumnizer columnizer, ILog try { TcpClient client = new(_config.Host, _config.Port); - NetworkStream stream = client.GetStream(); + var stream = client.GetStream(); StreamWriter writer = new(stream); doc.Save(writer); writer.Flush(); diff --git a/src/LogExpert.UI/Dialogs/FilterSelectorForm.cs b/src/LogExpert.UI/Dialogs/FilterSelectorForm.cs index 7fc01ba0..feba7797 100644 --- a/src/LogExpert.UI/Dialogs/FilterSelectorForm.cs +++ b/src/LogExpert.UI/Dialogs/FilterSelectorForm.cs @@ -34,17 +34,17 @@ public FilterSelectorForm (IList existingColumnizerList, ILo // will apply to the current instance _columnizerList = new List(); - foreach (ILogLineColumnizer col in existingColumnizerList) + foreach (var col in existingColumnizerList) { _columnizerList.Add(col.GetType() == SelectedColumnizer.GetType() ? SelectedColumnizer : col); } - foreach (ILogLineColumnizer col in _columnizerList) + foreach (var col in _columnizerList) { filterComboBox.Items.Add(col); } - foreach (ILogLineColumnizer columnizer in _columnizerList) + foreach (var columnizer in _columnizerList) { if (columnizer.GetType() == SelectedColumnizer.GetType()) { @@ -71,7 +71,7 @@ public FilterSelectorForm (IList existingColumnizerList, ILo private void OnFilterComboBoxSelectedIndexChanged (object sender, EventArgs e) { - ILogLineColumnizer col = _columnizerList[filterComboBox.SelectedIndex]; + var col = _columnizerList[filterComboBox.SelectedIndex]; SelectedColumnizer = col; var description = col.GetDescription(); description += "\r\nSupports timeshift: " + (SelectedColumnizer.IsTimeshiftImplemented() ? "Yes" : "No"); diff --git a/src/LogExpert.UI/Dialogs/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/HighlightDialog.cs index d772f4da..14438680 100644 --- a/src/LogExpert.UI/Dialogs/HighlightDialog.cs +++ b/src/LogExpert.UI/Dialogs/HighlightDialog.cs @@ -344,7 +344,7 @@ private void OnCmbBoxGroupDrawItem (object sender, DrawItemEventArgs e) e.DrawBackground(); if (e.Index >= 0) { - HighlightGroup group = HighlightGroupList[e.Index]; + var group = HighlightGroupList[e.Index]; Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); Brush brush = new SolidBrush(SystemColors.ControlText); @@ -467,7 +467,7 @@ private void AddNewEntry () SearchText = textBoxSearchString.Text, ForegroundColor = colorBoxForeground.SelectedColor, BackgroundColor = colorBoxBackground.SelectedColor, - IsRegEx = checkBoxRegex.Checked, + IsRegex = checkBoxRegex.Checked, IsCaseSensitive = checkBoxCaseSensitive.Checked, IsLedSwitch = checkBoxDontDirtyLed.Checked, IsStopTail = checkBoxStopTail.Checked, @@ -543,7 +543,7 @@ private void FillGroupComboBox () comboBoxGroups.Items.Clear(); - foreach (HighlightGroup group in HighlightGroupList) + foreach (var group in HighlightGroupList) { comboBoxGroups.Items.Add(group); } @@ -556,7 +556,7 @@ private void FillHighlightListBox () listBoxHighlight.Items.Clear(); if (_currentGroup != null) { - foreach (HighlightEntry entry in _currentGroup.HighlightEntryList) + foreach (var entry in _currentGroup.HighlightEntryList) { listBoxHighlight.Items.Add(entry); } @@ -588,7 +588,7 @@ private void InitData () groupToSelect = def; } - foreach (HighlightGroup group in HighlightGroupList) + foreach (var group in HighlightGroupList) { if (group.GroupName.Equals(groupToSelect, StringComparison.Ordinal)) { @@ -642,7 +642,7 @@ private void SaveEntry () entry.ForegroundColor = (Color)colorBoxForeground.SelectedItem; entry.BackgroundColor = (Color)colorBoxBackground.SelectedItem; entry.SearchText = textBoxSearchString.Text; - entry.IsRegEx = checkBoxRegex.Checked; + entry.IsRegex = checkBoxRegex.Checked; entry.IsCaseSensitive = checkBoxCaseSensitive.Checked; btnApply.Enabled = false; btnApply.Image = null; @@ -714,7 +714,7 @@ private void StartEditEntry () colorBoxBackground.SelectedItem = entry.BackgroundColor; } - checkBoxRegex.Checked = entry.IsRegEx; + checkBoxRegex.Checked = entry.IsRegex; checkBoxCaseSensitive.Checked = entry.IsCaseSensitive; checkBoxDontDirtyLed.Checked = entry.IsLedSwitch; checkBoxBookmark.Checked = entry.IsSetBookmark; diff --git a/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs b/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs index dbc508f0..b6a11c20 100644 --- a/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs +++ b/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs @@ -29,7 +29,7 @@ public KeywordActionDlg(ActionEntry entry, IList actionList) actionComboBox.Items.Clear(); - foreach (IKeywordAction action in actionList) + foreach (var action in actionList) { actionComboBox.Items.Add(action.GetName()); _actionDict[action.GetName()] = action; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index b75a674c..2f95deec 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -169,7 +169,7 @@ public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNu // get a list of resource names from the manifest var resNames = a.GetManifestResourceNames(); - Bitmap bmp = Resources.Deceased; + var bmp = Resources.Deceased; _deadIcon = Icon.FromHandle(bmp.GetHicon()); bmp.Dispose(); Closing += OnLogTabWindowClosing; @@ -236,7 +236,7 @@ internal HighlightGroup FindHighlightGroup (string groupName) { lock (HighlightGroupList) { - foreach (HighlightGroup group in HighlightGroupList) + foreach (var group in HighlightGroupList) { if (group.GroupName.Equals(groupName, StringComparison.Ordinal)) { @@ -875,9 +875,9 @@ private LogWindow.LogWindow FindWindowForFile (string fileName) /// private string FindFilenameForSettings (string fileName) { - if (fileName.EndsWith(".lxp")) + if (fileName.EndsWith(".lxp", StringComparison.InvariantCulture)) { - var persistenceData = Persister.LoadOptionsOnly(fileName); + var persistenceData = Persister.Load(fileName); if (persistenceData == null) { return fileName; @@ -2412,6 +2412,7 @@ private void OnFileSizeChanged (object sender, LogEventArgs e) { data.Dirty = true; } + var icon = GetIcon(diff, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); } @@ -2440,6 +2441,7 @@ private void OnLogWindowFilterListChanged (object sender, FilterListChangedEvent } } } + ConfigManager.Save(SettingsFlags.FilterList); } @@ -2456,6 +2458,7 @@ private void OnTailFollowed (object sender, EventArgs e) { return; } + if (sender.GetType().IsAssignableFrom(typeof(LogWindow.LogWindow))) { if (dockPanel.ActiveContent == sender) @@ -2649,6 +2652,7 @@ private void OnHideLineColumnToolStripMenuItemClick (object sender, EventArgs e) logWin.ShowLineColumn(!ConfigManager.Settings.HideLineColumn); } } + _bookmarkWindow.LineColumnVisible = ConfigManager.Settings.HideLineColumn; } diff --git a/src/LogExpert.UI/Dialogs/OpenUriDialog.cs b/src/LogExpert.UI/Dialogs/OpenUriDialog.cs index 0b9f8cd7..06bb7fa8 100644 --- a/src/LogExpert.UI/Dialogs/OpenUriDialog.cs +++ b/src/LogExpert.UI/Dialogs/OpenUriDialog.cs @@ -59,6 +59,7 @@ private void OnBtnOkClick(object sender, EventArgs e) { UriHistory.Remove(cmbUri.Text); } + UriHistory.Insert(0, cmbUri.Text); while (UriHistory.Count > 20) diff --git a/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs b/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs index ac7df7c5..ac401d8b 100644 --- a/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs +++ b/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs @@ -69,7 +69,7 @@ private void UpdateMatches () try { Regex rex = new(comboBoxRegex.Text, _caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - MatchCollection matches = rex.Matches(comboBoxTestText.Text); + var matches = rex.Matches(comboBoxTestText.Text); foreach (Match match in matches) { diff --git a/src/LogExpert.UI/Dialogs/SettingsDialog.cs b/src/LogExpert.UI/Dialogs/SettingsDialog.cs index bdf5df26..5a76f8c0 100644 --- a/src/LogExpert.UI/Dialogs/SettingsDialog.cs +++ b/src/LogExpert.UI/Dialogs/SettingsDialog.cs @@ -119,11 +119,13 @@ private void FillDialog () { radioButtonSessionSaveOwn.Checked = true; } + break; case SessionSaveLocation.SameDir: { radioButtonSessionSameDir.Checked = true; } + break; case SessionSaveLocation.DocumentsDir: { @@ -277,9 +279,9 @@ private void FillColumnizerForToolsList (ComboBox comboBox, string columnizerNam { var selIndex = 0; comboBox.Items.Clear(); - IList columnizers = PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers; + var columnizers = PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers; - foreach (ILogLineColumnizer columnizer in columnizers) + foreach (var columnizer in columnizers) { var index = comboBox.Items.Add(columnizer.GetName()); if (columnizer.GetName().Equals(columnizerName, StringComparison.Ordinal)) @@ -303,29 +305,29 @@ private void FillColumnizerList () var textColumn = (DataGridViewTextBoxColumn)dataGridViewColumnizer.Columns[0]; - IList columnizers = PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers; + var columnizers = PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers; - foreach (ILogLineColumnizer columnizer in columnizers) + foreach (var columnizer in columnizers) { comboColumn.Items.Add(columnizer.GetName()); } //comboColumn.DisplayMember = "Name"; //comboColumn.ValueMember = "Columnizer"; - foreach (ColumnizerMaskEntry maskEntry in Preferences.ColumnizerMaskList) + foreach (var maskEntry in Preferences.ColumnizerMaskList) { DataGridViewRow row = new(); row.Cells.Add(new DataGridViewTextBoxCell()); DataGridViewComboBoxCell cell = new(); - foreach (ILogLineColumnizer logColumnizer in columnizers) + foreach (var logColumnizer in columnizers) { cell.Items.Add(logColumnizer.GetName()); } row.Cells.Add(cell); row.Cells[0].Value = maskEntry.Mask; - ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(maskEntry.ColumnizerName, + var columnizer = ColumnizerPicker.DecideColumnizerByName(maskEntry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); row.Cells[1].Value = columnizer.GetName(); @@ -351,18 +353,18 @@ private void FillHighlightMaskList () //TODO Remove if not necessary var textColumn = (DataGridViewTextBoxColumn)dataGridViewHighlightMask.Columns[0]; - foreach (HighlightGroup group in (IList)_logTabWin.HighlightGroupList) + foreach (var group in (IList)_logTabWin.HighlightGroupList) { comboColumn.Items.Add(group.GroupName); } - foreach (HighlightMaskEntry maskEntry in Preferences.HighlightMaskList) + foreach (var maskEntry in Preferences.HighlightMaskList) { DataGridViewRow row = new(); row.Cells.Add(new DataGridViewTextBoxCell()); DataGridViewComboBoxCell cell = new(); - foreach (HighlightGroup group in (IList)_logTabWin.HighlightGroupList) + foreach (var group in (IList)_logTabWin.HighlightGroupList) { cell.Items.Add(group.GroupName); } @@ -370,7 +372,7 @@ private void FillHighlightMaskList () row.Cells.Add(cell); row.Cells[0].Value = maskEntry.Mask; - HighlightGroup currentGroup = _logTabWin.FindHighlightGroup(maskEntry.HighlightGroupName); + var currentGroup = _logTabWin.FindHighlightGroup(maskEntry.HighlightGroupName); var highlightGroupList = _logTabWin.HighlightGroupList; currentGroup ??= highlightGroupList.Count > 0 ? highlightGroupList[0] : new HighlightGroup(); @@ -424,7 +426,7 @@ private void FillPluginList () { listBoxPlugin.Items.Clear(); - foreach (IContextMenuEntry entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) { listBoxPlugin.Items.Add(entry); if (entry is ILogExpertPluginConfigurator configurator) @@ -433,7 +435,7 @@ private void FillPluginList () } } - foreach (IKeywordAction entry in PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions) + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions) { listBoxPlugin.Items.Add(entry); if (entry is ILogExpertPluginConfigurator configurator) @@ -442,7 +444,7 @@ private void FillPluginList () } } - foreach (IFileSystemPlugin entry in PluginRegistry.PluginRegistry.Instance.RegisteredFileSystemPlugins) + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredFileSystemPlugins) { listBoxPlugin.Items.Add(entry); if (entry is ILogExpertPluginConfigurator configurator) @@ -458,7 +460,7 @@ private void SavePluginSettings () { _selectedPlugin?.HideConfigForm(); - foreach (IContextMenuEntry entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) { if (entry is ILogExpertPluginConfigurator configurator) { @@ -466,7 +468,7 @@ private void SavePluginSettings () } } - foreach (IKeywordAction entry in PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions) + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions) { if (entry is ILogExpertPluginConfigurator configurator) { @@ -479,7 +481,7 @@ private void FillToolListbox () { listBoxTools.Items.Clear(); - foreach (ToolEntry tool in Preferences.ToolEntries) + foreach (var tool in Preferences.ToolEntries) { listBoxTools.Items.Add(tool.Clone(), tool.IsFavourite); } @@ -558,7 +560,7 @@ private void DisplayCurrentIcon () { if (_selectedTool != null) { - Icon icon = NativeMethods.LoadIconFromExe(_selectedTool.IconFile, _selectedTool.IconIndex); + var icon = NativeMethods.LoadIconFromExe(_selectedTool.IconFile, _selectedTool.IconIndex); if (icon != null) { Image image = icon.ToBitmap(); @@ -995,7 +997,7 @@ private void OnBtnExportClick (object sender, EventArgs e) Filter = @"Settings (*.json)|*.json|All files (*.*)|*.*" }; - DialogResult result = dlg.ShowDialog(); + var result = dlg.ShowDialog(); if (result == DialogResult.OK) { diff --git a/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs b/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs index a1a68d1f..f8a18284 100644 --- a/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs +++ b/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs @@ -74,8 +74,8 @@ private void OnButtonTestClick (object sender, EventArgs e) { if (logTabWin.CurrentLogWindow != null) { - ILogLine line = logTabWin.CurrentLogWindow.GetCurrentLine(); - ILogFileInfo info = logTabWin.CurrentLogWindow.GetCurrentFileInfo(); + var line = logTabWin.CurrentLogWindow.GetCurrentLine(); + var info = logTabWin.CurrentLogWindow.GetCurrentFileInfo(); if (line != null && info != null) { ArgParser parser = new(textBoxArguments.Text); diff --git a/src/LogExpert.UI/Entities/ArgParser.cs b/src/LogExpert.UI/Entities/ArgParser.cs index 8aa65cfd..5c4f9b8d 100644 --- a/src/LogExpert.UI/Entities/ArgParser.cs +++ b/src/LogExpert.UI/Entities/ArgParser.cs @@ -78,6 +78,7 @@ public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo { end2 = builder.Length - 1; } + var valueStr = builder.ToString().Substring(end + 2, end2 - end - 2); values = valueStr.Split([','], StringSplitOptions.None); end = end2; @@ -89,7 +90,7 @@ public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo Values = values }; - DialogResult res = dlg.ShowDialog(parent); + var res = dlg.ShowDialog(parent); if (res is DialogResult.OK) { diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index b58b26a4..16df16ff 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -349,7 +349,7 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr //TODO change to white if the background color is darker BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), - IsRegEx = false, + IsRegex = false, IsCaseSensitive = false, IsLedSwitch = false, IsStopTail = false, diff --git a/src/LogExpert.UI/Extensions/BookmarkExporter.cs b/src/LogExpert.UI/Extensions/BookmarkExporter.cs index 70381f9a..62733fca 100644 --- a/src/LogExpert.UI/Extensions/BookmarkExporter.cs +++ b/src/LogExpert.UI/Extensions/BookmarkExporter.cs @@ -24,6 +24,7 @@ public static void ExportBookmarkList (SortedList bookmarkList, s var line = $"{logfileName};{bookmark.LineNum};{bookmark.Text.Replace(replacementForNewLine, @"\" + replacementForNewLine, StringComparison.OrdinalIgnoreCase).Replace("\r\n", replacementForNewLine, StringComparison.OrdinalIgnoreCase)}"; writer.WriteLine(line); } + writer.Close(); fs.Close(); } diff --git a/src/LogExpert.UI/Extensions/LockFinder.cs b/src/LogExpert.UI/Extensions/LockFinder.cs index ad4c74c7..bf7706de 100644 --- a/src/LogExpert.UI/Extensions/LockFinder.cs +++ b/src/LogExpert.UI/Extensions/LockFinder.cs @@ -31,6 +31,7 @@ static public string FindLockedProcessName (string path) throw new Exception( "No processes are locking the path specified"); } + return list[0].ProcessName; } @@ -46,6 +47,7 @@ static public bool CheckIfFileIsLocked (string path) var list = FindLockProcesses(path); if (list.Count > 0) { return true; } + return false; } @@ -81,6 +83,7 @@ static public List FindLockProcesses (string path) { throw new Exception("Could not register resource."); } + res = NativeMethods.RmGetList(handle, out var pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons); const int ERROR_MORE_DATA = 234; diff --git a/src/LogExpert.UI/Extensions/NativeMethods.cs b/src/LogExpert.UI/Extensions/NativeMethods.cs index 41d97fa1..23a7dfc5 100644 --- a/src/LogExpert.UI/Extensions/NativeMethods.cs +++ b/src/LogExpert.UI/Extensions/NativeMethods.cs @@ -153,19 +153,21 @@ public static Icon LoadIconFromExe (string fileName, int index) { nint smallIcons = new(); nint largeIcons = new(); - int num = (int)ExtractIconEx(fileName, index, out largeIcons, out smallIcons, 1); + var num = (int)ExtractIconEx(fileName, index, out largeIcons, out smallIcons, 1); if (num > 0 && smallIcons != nint.Zero) { var icon = (Icon)Icon.FromHandle(smallIcons).Clone(); DestroyIcon(smallIcons); return icon; } + if (num > 0 && largeIcons != nint.Zero) { var icon = (Icon)Icon.FromHandle(largeIcons).Clone(); DestroyIcon(largeIcons); return icon; } + return null; } diff --git a/src/LogExpert.UI/Extensions/Utils.cs b/src/LogExpert.UI/Extensions/Utils.cs index 27d000b0..fc6622e3 100644 --- a/src/LogExpert.UI/Extensions/Utils.cs +++ b/src/LogExpert.UI/Extensions/Utils.cs @@ -31,13 +31,13 @@ public static string GetWordFromPos (int xPos, string text, Graphics g, Font fon stringFormat.SetMeasurableCharacterRanges(crArray); RectangleF rect = new(0, 0, 3000, 20); - Region[] stringRegions = g.MeasureCharacterRanges(text, font, rect, stringFormat); + var stringRegions = g.MeasureCharacterRanges(text, font, rect, stringFormat); var found = false; var y = 0; - foreach (Region regio in stringRegions) + foreach (var regio in stringRegions) { if (regio.IsVisible(xPos, 3, g)) { diff --git a/src/LogExpert/Classes/CommandLine/CmdLine.cs b/src/LogExpert/Classes/CommandLine/CmdLine.cs index a269f214..d5358431 100644 --- a/src/LogExpert/Classes/CommandLine/CmdLine.cs +++ b/src/LogExpert/Classes/CommandLine/CmdLine.cs @@ -63,10 +63,11 @@ public CmdLineParameter this[string name] { get { - if (parameters.TryGetValue(name, out CmdLineParameter value) == false) + if (parameters.TryGetValue(name, out var value) == false) { throw new CmdLineException(name, "Not a registered parameter."); } + return value; } } @@ -85,6 +86,7 @@ public void RegisterParameter(CmdLineParameter parameter) { throw new CmdLineException(parameter.Name, "Parameter is already registered."); } + parameters.Add(parameter.Name, parameter); } @@ -94,7 +96,7 @@ public void RegisterParameter(CmdLineParameter parameter) /// The parameter to add. public void RegisterParameter(CmdLineParameter[] parameters) { - foreach (CmdLineParameter p in parameters) + foreach (var p in parameters) { RegisterParameter(p); } @@ -133,7 +135,8 @@ public string[] Parse(string[] args) i++; } } - if (parameters.TryGetValue(key, out CmdLineParameter cmdLineParameter) == false) + + if (parameters.TryGetValue(key, out var cmdLineParameter) == false) { throw new CmdLineException(key, "Parameter is not allowed."); } @@ -184,9 +187,11 @@ public string HelpScreen() { s += " "; } + s += parameters[key].Help + "\n"; help += s; } + return help; } diff --git a/src/LogExpert/Classes/LogExpertProxy.cs b/src/LogExpert/Classes/LogExpertProxy.cs index 558899ab..58c4603c 100644 --- a/src/LogExpert/Classes/LogExpertProxy.cs +++ b/src/LogExpert/Classes/LogExpertProxy.cs @@ -63,7 +63,7 @@ public LogExpertProxy(ILogTabWindow logTabWindow) public void LoadFiles(string[] fileNames) { _logger.Info(CultureInfo.InvariantCulture, "Loading files into existing LogTabWindow"); - ILogTabWindow logWin = _windowList[^1]; + var logWin = _windowList[^1]; _ = logWin.Invoke(new MethodInvoker(logWin.SetForeground)); logWin.LoadFiles(fileNames); } @@ -113,7 +113,7 @@ public void NewWindowWorker(string[] fileNames) { _logger.Info(CultureInfo.InvariantCulture, "Creating new LogTabWindow"); IConfigManager configManager = ConfigManager.Instance; - ILogTabWindow logWin = AbstractLogTabWindow.Create(fileNames.Length > 0 ? fileNames : null, _logWindowIndex++, true, configManager); + var logWin = AbstractLogTabWindow.Create(fileNames.Length > 0 ? fileNames : null, _logWindowIndex++, true, configManager); logWin.LogExpertProxy = this; AddWindow(logWin); logWin.Show(); diff --git a/src/LogExpert/Config/ConfigManager.cs b/src/LogExpert/Config/ConfigManager.cs index 9dfec3c5..f9277f88 100644 --- a/src/LogExpert/Config/ConfigManager.cs +++ b/src/LogExpert/Config/ConfigManager.cs @@ -5,7 +5,6 @@ using System.Windows.Forms; using LogExpert.Core.Classes; -using LogExpert.Core.Classes.Filter; using LogExpert.Core.Config; using LogExpert.Core.Entities; using LogExpert.Core.EventArguments; @@ -56,6 +55,7 @@ public static ConfigManager Instance { _instance ??= new ConfigManager(); } + return _instance; } } @@ -94,20 +94,20 @@ public void Export (FileInfo fileInfo) Instance.Save(fileInfo, Settings); } - public void Export (FileInfo fileInfo, SettingsFlags flags) + public void Export (FileInfo fileInfo, SettingsFlags highlightSettings) { - Instance.Save(fileInfo, Settings, flags); + Instance.Save(fileInfo, Settings, highlightSettings); } - public void Import (FileInfo fileInfo, ExportImportFlags flags) + public void Import (FileInfo fileInfo, ExportImportFlags importFlags) { - Instance._settings = Instance.Import(Instance._settings, fileInfo, flags); + Instance._settings = Instance.Import(Instance._settings, fileInfo, importFlags); Save(SettingsFlags.All); } - public void ImportHighlightSettings (FileInfo fileInfo, ExportImportFlags flags) + public void ImportHighlightSettings (FileInfo fileInfo, ExportImportFlags importFlags) { - Instance._settings.Preferences.HighlightGroupList = Instance.Import(Instance._settings.Preferences.HighlightGroupList, fileInfo, flags); + Instance._settings.Preferences.HighlightGroupList = Instance.Import(Instance._settings.Preferences.HighlightGroupList, fileInfo, importFlags); Save(SettingsFlags.All); } @@ -120,7 +120,7 @@ private Settings Load () _logger.Info(CultureInfo.InvariantCulture, "Loading settings"); string dir; - + if (!File.Exists(Path.Combine(PortableModeDir, PortableModeSettingsFileName))) { _logger.Info(CultureInfo.InvariantCulture, "Load settings standard mode"); @@ -244,7 +244,7 @@ private Settings LoadOrCreateNew (FileInfo fileInfo) settings.FilterRangeHistoryList ??= []; - foreach (FilterParams filterParams in settings.FilterList) + foreach (var filterParams in settings.FilterList) { filterParams.Init(); } @@ -403,14 +403,17 @@ private Settings Import (Settings currentSettings, FileInfo fileInfo, ExportImpo { 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); } + if ((flags & ExportImportFlags.HighlightSettings) == ExportImportFlags.HighlightSettings) { newSettings.Preferences.HighlightGroupList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.HighlightGroupList, importSettings.Preferences.HighlightGroupList); } + if ((flags & ExportImportFlags.ToolEntries) == ExportImportFlags.ToolEntries) { newSettings.Preferences.ToolEntries = ReplaceOrKeepExisting(flags, ownSettings.Preferences.ToolEntries, importSettings.Preferences.ToolEntries); diff --git a/src/LogExpert/NLog.config b/src/LogExpert/NLog.config new file mode 100644 index 00000000..5924246a --- /dev/null +++ b/src/LogExpert/NLog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/LogExpert/Program.cs b/src/LogExpert/Program.cs index 53d6678a..a895f909 100644 --- a/src/LogExpert/Program.cs +++ b/src/LogExpert/Program.cs @@ -1,11 +1,18 @@ +using System.Diagnostics; +using System.Globalization; +using System.IO.Pipes; +using System.Reflection; +using System.Security; +using System.Security.Principal; +using System.Text; +using System.Windows.Forms; + using LogExpert.Classes; using LogExpert.Classes.CommandLine; using LogExpert.Config; using LogExpert.Core.Classes.IPC; using LogExpert.Core.Config; -using LogExpert.Core.Interface; using LogExpert.Dialogs; -using LogExpert.UI.Controls.LogWindow; using LogExpert.UI.Dialogs; using LogExpert.UI.Extensions.LogWindow; @@ -14,15 +21,6 @@ using NLog; -using System.Diagnostics; -using System.Globalization; -using System.IO.Pipes; -using System.Reflection; -using System.Security; -using System.Security.Principal; -using System.Text; -using System.Windows.Forms; - namespace LogExpert; internal static class Program @@ -41,7 +39,7 @@ internal static class Program /// The main entry point for the application. /// [STAThread] - private static void Main(string[] args) + private static void Main (string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += Application_ThreadException; @@ -104,7 +102,7 @@ private static void Main(string[] args) var counter = 3; Exception errMsg = null; - Settings settings = ConfigManager.Instance.Settings; + var settings = ConfigManager.Instance.Settings; while (counter > 0) { try @@ -158,7 +156,7 @@ private static void Main(string[] args) } } - private static string SerializeCommandIntoNonFormattedJSON(string[] fileNames, bool allowOnlyOneInstance) + private static string SerializeCommandIntoNonFormattedJSON (string[] fileNames, bool allowOnlyOneInstance) { var message = new IpcMessage() { @@ -172,7 +170,7 @@ private static string SerializeCommandIntoNonFormattedJSON(string[] fileNames, b // This loop tries to convert relative file names into absolute file names (assuming that platform file names are given). // It tolerates errors, to give file system plugins (e.g. sftp) a change later. // TODO: possibly should be moved to LocalFileSystem plugin - private static string[] GenerateAbsoluteFilePaths(string[] remainingArgs) + private static string[] GenerateAbsoluteFilePaths (string[] remainingArgs) { List argsList = []; @@ -192,7 +190,7 @@ private static string[] GenerateAbsoluteFilePaths(string[] remainingArgs) return [.. argsList]; } - private static void SendMessageToProxy(IpcMessage message, LogExpertProxy proxy) + private static void SendMessageToProxy (IpcMessage message, LogExpertProxy proxy) { var payLoad = message.Payload.ToObject(); @@ -227,7 +225,7 @@ private static bool CheckPayload (LoadPayload payLoad) return true; } - private static void SendCommandToServer(string command) + private static void SendCommandToServer (string command) { using var client = new NamedPipeClientStream(".", PIPE_SERVER_NAME, PipeDirection.Out); @@ -255,7 +253,7 @@ private static void SendCommandToServer(string command) writer.WriteLine(command); } - private static async Task RunServerLoopAsync(Action onCommand, LogExpertProxy proxy, CancellationToken cancellationToken) + private static async Task RunServerLoopAsync (Action onCommand, LogExpertProxy proxy, CancellationToken cancellationToken) { while (cancellationToken.IsCancellationRequested == false) { @@ -290,7 +288,7 @@ private static async Task RunServerLoopAsync(Action } [STAThread] - private static void ShowUnhandledException(object exceptionObject) + private static void ShowUnhandledException (object exceptionObject) { var errorText = string.Empty; string stackTrace; @@ -319,7 +317,7 @@ private static void ShowUnhandledException(object exceptionObject) #region Events handler - private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + private static void Application_ThreadException (object sender, ThreadExceptionEventArgs e) { _logger.Fatal(e); @@ -333,7 +331,7 @@ private static void Application_ThreadException(object sender, ThreadExceptionEv thread.Join(); } - private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + private static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e) { _logger.Fatal(e); diff --git a/src/PluginRegistry/FileSystem/LogFileInfo.cs b/src/PluginRegistry/FileSystem/LogFileInfo.cs index 31920565..c78694c1 100644 --- a/src/PluginRegistry/FileSystem/LogFileInfo.cs +++ b/src/PluginRegistry/FileSystem/LogFileInfo.cs @@ -1,4 +1,4 @@ -using NLog; +using NLog; namespace LogExpert.PluginRegistry.FileSystem; @@ -67,6 +67,7 @@ public long Length _logger.Warn(e, "LogFileInfo.Length"); return -1; } + Thread.Sleep(RETRY_SLEEP); } } @@ -97,6 +98,7 @@ public long LengthWithoutRetry { return -1; } + try { fInfo.Refresh(); @@ -137,6 +139,7 @@ public Stream OpenStream() { throw; } + Thread.Sleep(RETRY_SLEEP); } catch (UnauthorizedAccessException uae) @@ -146,6 +149,7 @@ public Stream OpenStream() { throw new IOException("Error opening file", uae); } + Thread.Sleep(RETRY_SLEEP); } } @@ -159,6 +163,7 @@ public bool FileHasChanged() lastLength = LengthWithoutRetry; return true; } + return false; } diff --git a/src/PluginRegistry/PluginRegistry.cs b/src/PluginRegistry/PluginRegistry.cs index 0b7a339b..1d0a595f 100644 --- a/src/PluginRegistry/PluginRegistry.cs +++ b/src/PluginRegistry/PluginRegistry.cs @@ -129,11 +129,12 @@ internal void LoadPlugins () // can happen when a dll dependency is missing if (ex.LoaderExceptions != null && ex.LoaderExceptions.Length != 0) { - foreach (Exception loaderException in ex.LoaderExceptions) + foreach (var loaderException in ex.LoaderExceptions) { _logger.Error(loaderException, "Plugin load failed with '{0}'", dllName); } } + _logger.Error(ex, "Loader exception during load of dll '{0}'", dllName); throw; } @@ -150,15 +151,15 @@ internal void LoadPlugins () private void LoadPluginAssembly (string dllName, string interfaceName) { var assembly = Assembly.LoadFrom(dllName); - Type[] types = assembly.GetTypes(); + var types = assembly.GetTypes(); - foreach (Type type in types) + foreach (var type in types) { _logger.Info($"Type {type.FullName} in assembly {assembly.FullName} implements {interfaceName}"); if (type.GetInterfaces().Any(i => i.FullName == interfaceName)) { - ConstructorInfo cti = type.GetConstructor(Type.EmptyTypes); + var cti = type.GetConstructor(Type.EmptyTypes); if (cti != null) { var instance = cti.Invoke([]); @@ -200,13 +201,13 @@ private void LoadPluginAssembly (string dllName, string interfaceName) public IKeywordAction FindKeywordActionPluginByName (string name) { - _registeredKeywordsDict.TryGetValue(name, out IKeywordAction action); + _registeredKeywordsDict.TryGetValue(name, out var action); return action; } public void CleanupPlugins () { - foreach (ILogExpertPlugin plugin in _pluginList) + foreach (var plugin in _pluginList) { plugin.AppExiting(); } @@ -219,7 +220,7 @@ public IFileSystemPlugin FindFileSystemForUri (string uriString) _logger.Debug(CultureInfo.InvariantCulture, "Trying to find file system plugin for uri {0}", uriString); } - foreach (IFileSystemPlugin fs in RegisteredFileSystemPlugins) + foreach (var fs in RegisteredFileSystemPlugins) { if (_logger.IsDebugEnabled) { @@ -247,7 +248,7 @@ public IFileSystemPlugin FindFileSystemForUri (string uriString) //TODO: Can this be deleted? private bool TryAsContextMenu (Type type) { - IContextMenuEntry me = TryInstantiate(type); + var me = TryInstantiate(type); if (me != null) { @@ -273,7 +274,7 @@ private bool TryAsContextMenu (Type type) //TODO: Can this be delted? private bool TryAsKeywordAction (Type type) { - IKeywordAction ka = TryInstantiate(type); + var ka = TryInstantiate(type); if (ka != null) { RegisteredKeywordActions.Add(ka); @@ -300,7 +301,7 @@ private bool TryAsKeywordAction (Type type) private bool TryAsFileSystem (Type type) { // file system plugins can have optional constructor with IFileSystemCallback argument - IFileSystemPlugin fs = TryInstantiate(type, _fileSystemCallback); + var fs = TryInstantiate(type, _fileSystemCallback); fs ??= TryInstantiate(type); if (fs != null) @@ -327,11 +328,11 @@ private bool TryAsFileSystem (Type type) private static T TryInstantiate (Type loadedType) where T : class { - Type t = typeof(T); - Type inter = loadedType.GetInterface(t.Name); + var t = typeof(T); + var inter = loadedType.GetInterface(t.Name); if (inter != null) { - ConstructorInfo cti = loadedType.GetConstructor(Type.EmptyTypes); + var cti = loadedType.GetConstructor(Type.EmptyTypes); if (cti != null) { var o = cti.Invoke([]); @@ -344,11 +345,11 @@ private static T TryInstantiate (Type loadedType) where T : class private static T TryInstantiate (Type loadedType, IFileSystemCallback fsCallback) where T : class { - Type t = typeof(T); - Type inter = loadedType.GetInterface(t.Name); + var t = typeof(T); + var inter = loadedType.GetInterface(t.Name); if (inter != null) { - ConstructorInfo cti = loadedType.GetConstructor([typeof(IFileSystemCallback)]); + var cti = loadedType.GetConstructor([typeof(IFileSystemCallback)]); if (cti != null) { var o = cti.Invoke([fsCallback]); diff --git a/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs b/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs index 54312b0e..85535a93 100644 --- a/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs +++ b/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs @@ -1,4 +1,4 @@ -using LogExpert; +using LogExpert; using Moq; using NUnit.Framework; using System.Runtime.Versioning; @@ -14,10 +14,10 @@ public class RegexColumnizerTests [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 2)] public void SplitLine_ColumnCountMatches(string lineToParse, string regex, int expectedNumberOfColumns) { - Regex1Columnizer columnizer = CreateInitializedColumnizer(regex); + var columnizer = CreateInitializedColumnizer(regex); TestLogLine testLogLine = new(4, lineToParse); - IColumnizedLogLine parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); + var parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); Assert.That(expectedNumberOfColumns, Is.EqualTo(parsedLogLine.ColumnValues.Length)); } @@ -30,10 +30,10 @@ public void SplitLine_ColumnCountMatches(string lineToParse, string regex, int e public void SplitLine_ColumnValues(string lineToParse, string regex, int columnIndexToTest, string expectedColumnValue) { - Regex1Columnizer columnizer = CreateInitializedColumnizer(regex); + var columnizer = CreateInitializedColumnizer(regex); TestLogLine testLogLine = new(3, lineToParse); - IColumnizedLogLine parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); + var parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); Assert.That(expectedColumnValue, Is.EqualTo(parsedLogLine.ColumnValues[columnIndexToTest].Text)); } diff --git a/src/RegexColumnizer/RegexColumnizerConfigDialog.cs b/src/RegexColumnizer/RegexColumnizerConfigDialog.cs index a355aa38..0e26cdee 100644 --- a/src/RegexColumnizer/RegexColumnizerConfigDialog.cs +++ b/src/RegexColumnizer/RegexColumnizerConfigDialog.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Drawing; using System.Linq; @@ -59,7 +59,7 @@ private bool Check() if (!string.IsNullOrEmpty(tbTestLine.Text)) { - Match match = regex.Match(tbTestLine.Text); + var match = regex.Match(tbTestLine.Text); var row = table.NewRow(); var values = match.Groups.OfType().Skip(offset).Select(group => group.Value).Cast().ToArray(); row.ItemArray = values;