diff --git a/src/LogExpert.Core/Classes/Log/LogfileReader.cs b/src/LogExpert.Core/Classes/Log/LogfileReader.cs index d7f887a4..424e1c34 100644 --- a/src/LogExpert.Core/Classes/Log/LogfileReader.cs +++ b/src/LogExpert.Core/Classes/Log/LogfileReader.cs @@ -154,7 +154,7 @@ public int LineCount { _currLineCount = 0; AcquireBufferListReaderLock(); - foreach (LogBuffer buffer in _bufferList) + foreach (var buffer in _bufferList) { _currLineCount += buffer.LineCount; } @@ -218,7 +218,7 @@ public void ReadFiles () ReleaseBufferListWriterLock(); try { - foreach (ILogFileInfo info in _logFileInfoList) + foreach (var info in _logFileInfoList) { //info.OpenFile(); ReadToBufferList(info, 0, LineCount); @@ -226,7 +226,7 @@ public void ReadFiles () if (_logFileInfoList.Count > 0) { - ILogFileInfo info = _logFileInfoList[_logFileInfoList.Count - 1]; + var info = _logFileInfoList[_logFileInfoList.Count - 1]; _fileLength = info.Length; _watchedILogFileInfo = info; } @@ -263,19 +263,19 @@ public int ShiftBuffers () lock (_monitor) { RolloverFilenameHandler rolloverHandler = new(_watchedILogFileInfo, _multiFileOptions); - LinkedList fileNameList = rolloverHandler.GetNameList(_pluginRegistry); + var fileNameList = rolloverHandler.GetNameList(_pluginRegistry); ResetBufferCache(); IList lostILogFileInfoList = []; IList readNewILogFileInfoList = []; IList newFileInfoList = []; - IEnumerator enumerator = _logFileInfoList.GetEnumerator(); + var enumerator = _logFileInfoList.GetEnumerator(); while (enumerator.MoveNext()) { - ILogFileInfo logFileInfo = enumerator.Current; + var logFileInfo = enumerator.Current; var fileName = logFileInfo.FullName; _logger.Debug(CultureInfo.InvariantCulture, "Testing file {0}", fileName); - LinkedListNode node = fileNameList.Find(fileName); + var node = fileNameList.Find(fileName); if (node == null) { _logger.Warn(CultureInfo.InvariantCulture, "File {0} not found", fileName); @@ -285,7 +285,7 @@ public int ShiftBuffers () if (node.Previous != null) { fileName = node.Previous.Value; - ILogFileInfo newILogFileInfo = GetLogFileInfo(fileName); + var newILogFileInfo = GetLogFileInfo(fileName); _logger.Debug(CultureInfo.InvariantCulture, "{0} exists\r\nOld size={1}, new size={2}", fileName, logFileInfo.OriginalLength, newILogFileInfo.Length); // is the new file the same as the old buffer info? if (newILogFileInfo.Length == logFileInfo.OriginalLength) @@ -335,10 +335,10 @@ public int ShiftBuffers () if (lostILogFileInfoList.Count > 0) { _logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for lost files"); - foreach (ILogFileInfo ILogFileInfo in lostILogFileInfoList) + foreach (var ILogFileInfo in lostILogFileInfoList) { //this.ILogFileInfoList.Remove(ILogFileInfo); - LogBuffer lastBuffer = DeleteBuffersForInfo(ILogFileInfo, false); + var lastBuffer = DeleteBuffersForInfo(ILogFileInfo, false); if (lastBuffer != null) { offset += lastBuffer.StartLine + lastBuffer.LineCount; @@ -347,7 +347,7 @@ public int ShiftBuffers () _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); _logger.Info(CultureInfo.InvariantCulture, "Adjusting StartLine values in {0} buffers by offset {1}", _bufferList.Count, offset); - foreach (LogBuffer buffer in _bufferList) + foreach (var buffer in _bufferList) { SetNewStartLineForBuffer(buffer, buffer.StartLine - offset); } @@ -363,7 +363,7 @@ public int ShiftBuffers () // Read anew all buffers following a buffer info that couldn't be matched with the corresponding existing file _logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for files that must be re-read"); - foreach (ILogFileInfo ILogFileInfo in readNewILogFileInfoList) + foreach (var ILogFileInfo in readNewILogFileInfoList) { DeleteBuffersForInfo(ILogFileInfo, true); //this.ILogFileInfoList.Remove(ILogFileInfo); @@ -373,7 +373,7 @@ public int ShiftBuffers () DeleteBuffersForInfo(_watchedILogFileInfo, true); var startLine = LineCount - 1; _logger.Info(CultureInfo.InvariantCulture, "Re-Reading files"); - foreach (ILogFileInfo ILogFileInfo in readNewILogFileInfoList) + foreach (var ILogFileInfo in readNewILogFileInfoList) { //ILogFileInfo.OpenFile(); ReadToBufferList(ILogFileInfo, 0, LineCount); @@ -456,7 +456,7 @@ public async Task GetLogLineWithWait (int lineNum) public string GetLogFileNameForLine (int lineNum) { AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); + var logBuffer = GetBufferForLine(lineNum); var fileName = logBuffer?.FileInfo.FullName; ReleaseBufferListReaderLock(); return fileName; @@ -470,8 +470,8 @@ public string GetLogFileNameForLine (int lineNum) public ILogFileInfo GetLogFileInfoForLine (int lineNum) { AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - ILogFileInfo info = logBuffer?.FileInfo; + var logBuffer = GetBufferForLine(lineNum); + var info = logBuffer?.FileInfo; ReleaseBufferListReaderLock(); return info; } @@ -486,7 +486,7 @@ public int GetNextMultiFileLine (int lineNum) { var result = -1; AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); + var logBuffer = GetBufferForLine(lineNum); if (logBuffer != null) { var index = _bufferList.IndexOf(logBuffer); @@ -511,7 +511,7 @@ public int GetPrevMultiFileLine (int lineNum) { var result = -1; AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); + var logBuffer = GetBufferForLine(lineNum); if (logBuffer != null) { var index = _bufferList.IndexOf(logBuffer); @@ -544,7 +544,7 @@ public int GetPrevMultiFileLine (int lineNum) public int GetRealLineNumForVirtualLineNum (int lineNum) { AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); + var logBuffer = GetBufferForLine(lineNum); var result = -1; if (logBuffer != null) { @@ -627,7 +627,7 @@ public void DeleteAllContent () _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); _disposeLock.AcquireWriterLock(Timeout.Infinite); - foreach (LogBuffer logBuffer in _bufferList) + foreach (var logBuffer in _bufferList) { if (!logBuffer.IsDisposed) { @@ -685,7 +685,7 @@ public IList GetBufferList () public void LogBufferInfoForLine (int lineNum) { AcquireBufferListReaderLock(); - LogBuffer buffer = GetBufferForLine(lineNum); + var buffer = GetBufferForLine(lineNum); if (buffer == null) { ReleaseBufferListReaderLock(); @@ -721,7 +721,7 @@ public void LogBufferDiagnostic () long minDispose = int.MaxValue; for (var i = 0; i < _bufferList.Count; ++i) { - LogBuffer buffer = _bufferList[i]; + var buffer = _bufferList[i]; _disposeLock.AcquireReaderLock(Timeout.Infinite); if (buffer.StartLine != lineNum) { @@ -750,7 +750,7 @@ public void LogBufferDiagnostic () private ILogFileInfo AddFile (string fileName) { _logger.Info(CultureInfo.InvariantCulture, "Adding file to ILogFileInfoList: " + fileName); - ILogFileInfo info = GetLogFileInfo(fileName); + var info = GetLogFileInfo(fileName); _logFileInfoList.Add(info); return info; } @@ -766,7 +766,7 @@ private Task GetLogLineInternal (int lineNum) } AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); + var logBuffer = GetBufferForLine(lineNum); if (logBuffer == null) { ReleaseBufferListReaderLock(); @@ -778,7 +778,7 @@ private Task GetLogLineInternal (int lineNum) _disposeLock.AcquireReaderLock(Timeout.Infinite); if (logBuffer.IsDisposed) { - LockCookie cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); + var cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); lock (logBuffer.FileInfo) { ReReadBuffer(logBuffer); @@ -787,7 +787,7 @@ private Task GetLogLineInternal (int lineNum) _disposeLock.DowngradeFromWriterLock(ref cookie); } - ILogLine line = logBuffer.GetLineOfBlock(lineNum - logBuffer.StartLine); + var line = logBuffer.GetLineOfBlock(lineNum - logBuffer.StartLine); _disposeLock.ReleaseReaderLock(); ReleaseBufferListReaderLock(); @@ -838,8 +838,8 @@ private void CloseFiles () private ILogFileInfo GetLogFileInfo (string fileNameOrUri) //TODO: I changed to static { //TODO this must be fixed and should be given to the logfilereader not just called (https://github.com/LogExperts/LogExpert/issues/402) - IFileSystemPlugin fs = _pluginRegistry.FindFileSystemForUri(fileNameOrUri) ?? throw new LogFileException("No file system plugin found for " + fileNameOrUri); - ILogFileInfo logFileInfo = fs.GetLogfileInfo(fileNameOrUri); + var fs = _pluginRegistry.FindFileSystemForUri(fileNameOrUri) ?? throw new LogFileException("No file system plugin found for " + fileNameOrUri); + var logFileInfo = fs.GetLogfileInfo(fileNameOrUri); return logFileInfo ?? throw new LogFileException("Cannot find " + fileNameOrUri); } @@ -868,7 +868,7 @@ private LogBuffer DeleteBuffersForInfo (ILogFileInfo ILogFileInfo, bool matchNam _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); if (matchNamesOnly) { - foreach (LogBuffer buffer in _bufferList) + foreach (var buffer in _bufferList) { if (buffer.FileInfo.FullName.Equals(ILogFileInfo.FullName, StringComparison.Ordinal)) { @@ -879,7 +879,7 @@ private LogBuffer DeleteBuffersForInfo (ILogFileInfo ILogFileInfo, bool matchNam } else { - foreach (LogBuffer buffer in _bufferList) + foreach (var buffer in _bufferList) { if (buffer.FileInfo == ILogFileInfo) { @@ -889,7 +889,7 @@ private LogBuffer DeleteBuffersForInfo (ILogFileInfo ILogFileInfo, bool matchNam } } - foreach (LogBuffer buffer in deleteList) + foreach (var buffer in deleteList) { RemoveFromBufferList(buffer); } @@ -924,10 +924,10 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start { try { - using Stream fileStream = logFileInfo.OpenStream(); + using var fileStream = logFileInfo.OpenStream(); try { - using ILogStreamReader reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); + using var reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); reader.Position = filePos; _fileLength = logFileInfo.Length; @@ -941,7 +941,7 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start StartLine = startLine, StartPos = filePos }; - LockCookie cookie = UpgradeBufferListLockToWriter(); + var cookie = UpgradeBufferListLockToWriter(); AddBufferToList(logBuffer); DowngradeBufferListLockFromWriter(ref cookie); } @@ -956,7 +956,7 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start StartLine = startLine, StartPos = filePos }; - LockCookie cookie = UpgradeBufferListLockToWriter(); + var cookie = UpgradeBufferListLockToWriter(); AddBufferToList(logBuffer); DowngradeBufferListLockFromWriter(ref cookie); } @@ -964,7 +964,7 @@ private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start _disposeLock.AcquireReaderLock(Timeout.Infinite); if (logBuffer.IsDisposed) { - LockCookie cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); + var cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); ReReadBuffer(logBuffer); _disposeLock.DowngradeFromWriterLock(ref cookie); } @@ -1058,13 +1058,13 @@ private void AddBufferToList (LogBuffer logBuffer) private void UpdateLruCache (LogBuffer logBuffer) { _lruCacheDictLock.AcquireReaderLock(Timeout.Infinite); - if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out LogBufferCacheEntry cacheEntry)) + if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out var cacheEntry)) { cacheEntry.Touch(); } else { - LockCookie cookie = _lruCacheDictLock.UpgradeToWriterLock(Timeout.Infinite); + var cookie = _lruCacheDictLock.UpgradeToWriterLock(Timeout.Infinite); if (!_lruCacheDict.TryGetValue(logBuffer.StartLine, out cacheEntry) ) // #536: re-test, because multiple threads may have been waiting for _writer lock { @@ -1081,7 +1081,7 @@ private void UpdateLruCache (LogBuffer logBuffer) _logger.Info(CultureInfo.InvariantCulture, "Added buffer:"); DumpBufferInfos(logBuffer); - if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out LogBufferCacheEntry existingEntry)) + if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out var existingEntry)) { _logger.Info(CultureInfo.InvariantCulture, "Existing buffer: "); DumpBufferInfos(existingEntry.LogBuffer); @@ -1145,7 +1145,7 @@ private void GarbageCollectLruCache () #endif SortedList useSorterList = []; // sort by usage counter - foreach (LogBufferCacheEntry entry in _lruCacheDict.Values) + foreach (var entry in _lruCacheDict.Values) { if (!useSorterList.ContainsKey(entry.LastUseTimeStamp)) { @@ -1163,7 +1163,7 @@ private void GarbageCollectLruCache () } var startLine = useSorterList.Values[i]; - LogBufferCacheEntry entry = _lruCacheDict[startLine]; + var entry = _lruCacheDict[startLine]; _lruCacheDict.Remove(startLine); entry.LogBuffer.DisposeContent(); } @@ -1287,7 +1287,7 @@ private void ClearLru () _logger.Info(CultureInfo.InvariantCulture, "Clearing LRU cache."); _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); _disposeLock.AcquireWriterLock(Timeout.Infinite); - foreach (LogBufferCacheEntry entry in _lruCacheDict.Values) + foreach (var entry in _lruCacheDict.Values) { entry.LogBuffer.DisposeContent(); } @@ -1319,7 +1319,7 @@ private void ReReadBuffer (LogBuffer logBuffer) try { - ILogStreamReader reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); + var reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); var filePos = logBuffer.StartPos; reader.Position = logBuffer.StartPos; @@ -1432,7 +1432,7 @@ private void GetLineFinishedCallback (ILogLine line) private LogBuffer GetFirstBufferForFileByLogBuffer (LogBuffer logBuffer) { - ILogFileInfo info = logBuffer.FileInfo; + var info = logBuffer.FileInfo; AcquireBufferListReaderLock(); var index = _bufferList.IndexOf(logBuffer); if (index == -1) @@ -1441,7 +1441,7 @@ private LogBuffer GetFirstBufferForFileByLogBuffer (LogBuffer logBuffer) return null; } - LogBuffer resultBuffer = logBuffer; + var resultBuffer = logBuffer; while (true) { index--; @@ -1575,7 +1575,21 @@ private void FireChangeEvent () LineCount = 0; try { - if (!IsMultiFile) + if (IsMultiFile) + { + var offset = ShiftBuffers(); + //this.currFileSize = newSize; // removed because ShiftBuffers() calls ReadToBuffer() which will set the actual read size + args.FileSize = newSize; + args.LineCount = LineCount; + args.IsRollover = true; + args.RolloverOffset = offset; + _isDeleted = false; + if (!_shouldStop) + { + OnFileSizeChanged(args); + } + } + else { // ReloadBufferList(); // removed because reloading is triggered by owning LogWindow // Trigger "new file" handling (reload) @@ -1593,20 +1607,6 @@ private void FireChangeEvent () _isDeleted = false; } - else - { - var offset = ShiftBuffers(); - //this.currFileSize = newSize; // removed because ShiftBuffers() calls ReadToBuffer() which will set the actual read size - args.FileSize = newSize; - args.LineCount = LineCount; - args.IsRollover = true; - args.RolloverOffset = offset; - _isDeleted = false; - if (!_shouldStop) - { - OnFileSizeChanged(args); - } - } } catch (FileNotFoundException e) { @@ -1626,7 +1626,7 @@ private void FireChangeEvent () private ILogStreamReader GetLogStreamReader (Stream stream, EncodingOptions encodingOptions, bool useNewReader) { - ILogStreamReader reader = CreateLogStreamReader(stream, encodingOptions, useNewReader); + var reader = CreateLogStreamReader(stream, encodingOptions, useNewReader); return IsXmlMode ? new XmlBlockSplitter(new XmlLogReader(reader), XmlLogConfig) : reader; } @@ -1735,7 +1735,7 @@ private LockCookie UpgradeBufferListLockToWriter () { try { - LockCookie cookie = _bufferListLock.UpgradeToWriterLock(10000); + var cookie = _bufferListLock.UpgradeToWriterLock(10000); #if DEBUG && TRACE_LOCKS StackTrace st = new StackTrace(true); StackFrame callerFrame = st.GetFrame(2); diff --git a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs index ae276817..3d43806f 100644 --- a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs +++ b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -83,11 +82,13 @@ public void SetFileName (string fileName) { } } + _indexGroup = match.Groups["index"]; if (_indexGroup.Success) { Index = _indexGroup.Value.Length > 0 ? int.Parse(_indexGroup.Value) : 0; } + _condGroup = match.Groups["cond"]; } } diff --git a/src/LogExpert.Core/Interface/IConfigManager.cs b/src/LogExpert.Core/Interface/IConfigManager.cs index d921e9b4..93a079dd 100644 --- a/src/LogExpert.Core/Interface/IConfigManager.cs +++ b/src/LogExpert.Core/Interface/IConfigManager.cs @@ -1,4 +1,4 @@ -using LogExpert.Core.Config; +using LogExpert.Core.Config; using LogExpert.Core.EventArguments; namespace LogExpert.Core.Interface; @@ -7,14 +7,24 @@ namespace LogExpert.Core.Interface; public interface IConfigManager { Settings Settings { get; } + string PortableModeDir { get; } + string ConfigDir { get; } + IConfigManager Instance { get; } + string PortableModeSettingsFileName { get; } - void Export(FileInfo fileInfo, SettingsFlags highlightSettings); - void Export(FileInfo fileInfo); - void Import(FileInfo fileInfo, ExportImportFlags importFlags); - void ImportHighlightSettings(FileInfo fileInfo, ExportImportFlags importFlags); + + void Export (FileInfo fileInfo, SettingsFlags highlightSettings); + + void Export (FileInfo fileInfo); + + void Import (FileInfo fileInfo, ExportImportFlags importFlags); + + void ImportHighlightSettings (FileInfo fileInfo, ExportImportFlags importFlags); + event EventHandler ConfigChanged; //TODO: All handlers that are public shoulld be in Core - void Save(SettingsFlags flags); + + void Save (SettingsFlags flags); } \ No newline at end of file diff --git a/src/LogExpert.Tests/BufferShiftTest.cs b/src/LogExpert.Tests/BufferShiftTest.cs index 985f3a5d..df3f027e 100644 --- a/src/LogExpert.Tests/BufferShiftTest.cs +++ b/src/LogExpert.Tests/BufferShiftTest.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Linq; using System.Text; using LogExpert.Core.Classes.Log; @@ -35,7 +33,9 @@ public void TestShiftBuffers1 () MaxDayTry = 0, FormatPattern = "*$J(.)" }; + LinkedList files = CreateTestFilesWithoutDate(); + EncodingOptions encodingOptions = new() { Encoding = Encoding.Default @@ -57,6 +57,7 @@ public void TestShiftBuffers1 () Assert.That(li.FullName, Is.EqualTo(fileName)); enumerator.MoveNext(); } + var oldCount = lil.Count; // Simulate rollover @@ -68,6 +69,7 @@ public void TestShiftBuffers1 () reader.ShiftBuffers(); lil = reader.GetLogFileInfoList(); + Assert.That(lil.Count, Is.EqualTo(oldCount + 1)); Assert.That(reader.LineCount, Is.EqualTo(linesPerFile * lil.Count)); @@ -77,6 +79,7 @@ public void TestShiftBuffers1 () Assert.That(lil.Count, Is.EqualTo(files.Count)); enumerator = files.GetEnumerator(); enumerator.MoveNext(); + foreach (LogFileInfo li in lil) { var fileName = enumerator.Current; @@ -89,8 +92,10 @@ public void TestShiftBuffers1 () // enumerator = files.GetEnumerator(); enumerator.MoveNext(); + IList logBuffers = reader.GetBufferList(); var startLine = 0; + foreach (LogBuffer logBuffer in logBuffers) { Assert.That(enumerator.Current, Is.EqualTo(logBuffer.FileInfo.FullName)); @@ -106,20 +111,22 @@ public void TestShiftBuffers1 () enumerator.MoveNext(); // move to 2nd entry. The first file now contains 2nd file's content (because rollover) logBuffers = reader.GetBufferList(); int i; + for (i = 0; i < logBuffers.Count - 2; ++i) { LogBuffer logBuffer = logBuffers[i]; ILogLine line = logBuffer.GetLineOfBlock(0); - Assert.That(line.FullLine.Contains(enumerator.Current, System.StringComparison.Ordinal)); + Assert.That(line.FullLine.Contains(enumerator.Current, StringComparison.Ordinal)); enumerator.MoveNext(); } + enumerator.MoveNext(); // 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); - Assert.That(line.FullLine.Contains(enumerator.Current, System.StringComparison.Ordinal)); + Assert.That(line.FullLine.Contains(enumerator.Current, StringComparison.Ordinal)); } oldCount = lil.Count; @@ -142,6 +149,6 @@ public void TestShiftBuffers1 () ILogLine firstLine = reader.GetLogLine(0); var names = new string[files.Count]; files.CopyTo(names, 0); - Assert.That(firstLine.FullLine.Contains(names[2], System.StringComparison.Ordinal)); + Assert.That(firstLine.FullLine.Contains(names[2], StringComparison.Ordinal)); } } \ No newline at end of file diff --git a/src/LogExpert.Tests/CSVColumnizerTest.cs b/src/LogExpert.Tests/CSVColumnizerTest.cs index 1c9ccce1..e1a2aa54 100644 --- a/src/LogExpert.Tests/CSVColumnizerTest.cs +++ b/src/LogExpert.Tests/CSVColumnizerTest.cs @@ -1,11 +1,8 @@ -using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Log; using LogExpert.Core.Entities; using NUnit.Framework; -using System; -using System.IO; - namespace LogExpert.Tests; [TestFixture] @@ -14,11 +11,11 @@ public class CSVColumnizerTest [TestCase(@".\TestData\organizations-10000.csv", new[] { "Index", "Organization Id", "Name", "Website", "Country", "Description", "Founded", "Industry", "Number of employees" })] [TestCase(@".\TestData\organizations-1000.csv", new[] { "Index", "Organization Id", "Name", "Website", "Country", "Description", "Founded", "Industry", "Number of employees" })] [TestCase(@".\TestData\people-10000.csv", new[] { "Index", "User Id", "First Name", "Last Name", "Sex", "Email", "Phone", "Date of birth", "Job Title" })] - public void Instantiat_CSVFile_BuildCorrectColumnizer(string filename, string[] expectedHeaders) + public void Instantiat_CSVFile_BuildCorrectColumnizer (string filename, string[] expectedHeaders) { CsvColumnizer.CsvColumnizer csvColumnizer = new(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); - LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + LogfileReader reader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); ILogLine line = reader.GetLogLine(0); IColumnizedLogLine logline = new ColumnizedLogLine(); diff --git a/src/LogExpert.Tests/ColumnizerPickerTest.cs b/src/LogExpert.Tests/ColumnizerPickerTest.cs index f6204673..c802d062 100644 --- a/src/LogExpert.Tests/ColumnizerPickerTest.cs +++ b/src/LogExpert.Tests/ColumnizerPickerTest.cs @@ -1,11 +1,12 @@ -using JsonColumnizer; +using JsonColumnizer; + using LogExpert.Core.Classes.Columnizer; using LogExpert.Core.Classes.Log; using LogExpert.Core.Entities; + using Moq; + using NUnit.Framework; -using System; -using System.IO; namespace LogExpert.Tests; @@ -19,7 +20,7 @@ public class ColumnizerPickerTest [TestCase("Square Bracket Columnizer", "30/08/2018 08:51:42.712 [TRACE] hello", "30/08/2018 08:51:42.712 [DATAIO][] world", null, null, null)] [TestCase("Square Bracket Columnizer", "", "30/08/2018 08:51:42.712 [TRACE] hello", "30/08/2018 08:51:42.712 [TRACE] hello", "[DATAIO][b][c] world", null)] [TestCase("Timestamp Columnizer", "30/08/2018 08:51:42.712 no bracket 1", "30/08/2018 08:51:42.712 no bracket 2", "30/08/2018 08:51:42.712 [TRACE] with bracket 1", "30/08/2018 08:51:42.712 [TRACE] with bracket 2", "no bracket 3")] - public void FindColumnizer_ReturnCorrectColumnizer(string expectedColumnizerName, string line0, string line1, string line2, string line3, string line4) + public void FindColumnizer_ReturnCorrectColumnizer (string expectedColumnizerName, string line0, string line1, string line2, string line3, string line4) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test"); @@ -62,11 +63,11 @@ public void FindColumnizer_ReturnCorrectColumnizer(string expectedColumnizerName [TestCase(@".\TestData\JsonColumnizerTest_01.txt", typeof(JsonCompactColumnizer))] [TestCase(@".\TestData\SquareBracketColumnizerTest_02.txt", typeof(SquareBracketColumnizer))] - public void FindReplacementForAutoColumnizer_ValidTextFile_ReturnCorrectColumnizer( + public void FindReplacementForAutoColumnizer_ValidTextFile_ReturnCorrectColumnizer ( string fileName, Type columnizerType) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + LogfileReader reader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); Mock autoColumnizer = new(); @@ -80,7 +81,7 @@ public void FindReplacementForAutoColumnizer_ValidTextFile_ReturnCorrectColumniz } [TestCase(@".\TestData\FileNotExists.txt", typeof(DefaultLogfileColumnizer))] - public void DecideColumnizerByName_WhenReaderIsNotReady_ReturnCorrectColumnizer( + public void DecideColumnizerByName_WhenReaderIsNotReady_ReturnCorrectColumnizer ( string fileName, Type columnizerType) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); @@ -94,7 +95,7 @@ public void DecideColumnizerByName_WhenReaderIsNotReady_ReturnCorrectColumnizer( [TestCase(@"Invalid Name", typeof(DefaultLogfileColumnizer))] [TestCase(@"JSON Columnizer", typeof(JsonColumnizer.JsonColumnizer))] - public void DecideColumnizerByName_ValidTextFile_ReturnCorrectColumnizer( + public void DecideColumnizerByName_ValidTextFile_ReturnCorrectColumnizer ( string columnizerName, Type columnizerType) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, columnizerName); diff --git a/src/LogExpert.Tests/JsonColumnizerTest.cs b/src/LogExpert.Tests/JsonColumnizerTest.cs index 87e5c369..aae3663b 100644 --- a/src/LogExpert.Tests/JsonColumnizerTest.cs +++ b/src/LogExpert.Tests/JsonColumnizerTest.cs @@ -1,22 +1,19 @@ -using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Log; using LogExpert.Core.Entities; using NUnit.Framework; -using System; -using System.IO; - namespace LogExpert.Tests; [TestFixture] public class JsonColumnizerTest { [TestCase(@".\TestData\JsonColumnizerTest_01.txt", "time @m level")] - public void GetColumnNames_HappyFile_ColumnNameMatches(string fileName, string expectedHeaders) + public void GetColumnNames_HappyFile_ColumnNameMatches (string fileName, string expectedHeaders) { var jsonColumnizer = new JsonColumnizer.JsonColumnizer(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + LogfileReader reader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); reader.ReadFiles(); ILogLine line = reader.GetLogLine(0); diff --git a/src/LogExpert.Tests/JsonCompactColumnizerTest.cs b/src/LogExpert.Tests/JsonCompactColumnizerTest.cs index 5811be64..970b7ff4 100644 --- a/src/LogExpert.Tests/JsonCompactColumnizerTest.cs +++ b/src/LogExpert.Tests/JsonCompactColumnizerTest.cs @@ -1,12 +1,8 @@ -using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Log; using LogExpert.Core.Entities; using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.IO; - namespace LogExpert.Tests; [TestFixture] @@ -16,11 +12,11 @@ public class JsonCompactColumnizerTest // As long as the json file contains one of the pre-defined key, it's perfectly supported. [TestCase(@".\TestData\JsonCompactColumnizerTest_02.json", Priority.PerfectlySupport)] [TestCase(@".\TestData\JsonCompactColumnizerTest_03.json", Priority.WellSupport)] - public void GetPriority_HappyFile_PriorityMatches(string fileName, Priority priority) + public void GetPriority_HappyFile_PriorityMatches (string fileName, Priority priority) { var jsonCompactColumnizer = new JsonColumnizer.JsonCompactColumnizer(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader logFileReader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + LogfileReader logFileReader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); logFileReader.ReadFiles(); List loglines = new() { diff --git a/src/LogExpert.Tests/RolloverHandlerTestBase.cs b/src/LogExpert.Tests/RolloverHandlerTestBase.cs index 445a1579..26a08906 100644 --- a/src/LogExpert.Tests/RolloverHandlerTestBase.cs +++ b/src/LogExpert.Tests/RolloverHandlerTestBase.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; - using LogExpert.Core.Classes.Log; namespace LogExpert.Tests; @@ -60,6 +56,7 @@ protected LinkedList RolloverSimulation (LinkedList files, strin LinkedList.Enumerator nextEnumerator = fileList.GetEnumerator(); nextEnumerator.MoveNext(); // move on 2nd entry enumerator.MoveNext(); + while (nextEnumerator.MoveNext()) { File.Move(nextEnumerator.Current, enumerator.Current); @@ -98,7 +95,7 @@ protected string CreateFile (DirectoryInfo dInfo, string fileName) { for (var i = 1; i <= lineCount; ++i) { - writer.WriteLine("Line number " + i.ToString("D3") + " of File " + fullName); + writer.WriteLine($"Line number {i:D3} of File {fullName}"); } writer.Flush(); diff --git a/src/LogExpert.Tests/SquareBracketColumnizerTest.cs b/src/LogExpert.Tests/SquareBracketColumnizerTest.cs index 49f5db6c..2f952833 100644 --- a/src/LogExpert.Tests/SquareBracketColumnizerTest.cs +++ b/src/LogExpert.Tests/SquareBracketColumnizerTest.cs @@ -1,13 +1,9 @@ -using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Classes.Columnizer; using LogExpert.Core.Classes.Log; using LogExpert.Core.Entities; using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.IO; - namespace LogExpert.Tests; [TestFixture] @@ -17,12 +13,12 @@ public class SquareBracketColumnizerTest [TestCase(@".\TestData\SquareBracketColumnizerTest_02.txt", 5)] [TestCase(@".\TestData\SquareBracketColumnizerTest_03.txt", 6)] [TestCase(@".\TestData\SquareBracketColumnizerTest_05.txt", 3)] - public void GetPriority_HappyFile_ColumnCountMatches(string fileName, int count) + public void GetPriority_HappyFile_ColumnCountMatches (string fileName, int count) { SquareBracketColumnizer squareBracketColumnizer = new(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader logFileReader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + LogfileReader logFileReader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); logFileReader.ReadFiles(); List loglines = new() { diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index ba4eac84..6d96f5b8 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -558,6 +558,7 @@ internal void DumpBufferDiagnostic () { _logFileReader.LogBufferDiagnostic(); } +#endif [SupportedOSPlatform("windows")] void ILogWindow.SelectLine (int lineNum, bool triggerSyncCall, bool shouldScroll) @@ -576,7 +577,7 @@ void ILogWindow.WritePipeTab (IList lineEntryList, string title) { WritePipeTab(lineEntryList, title); } -#endif + #region Event Handlers @@ -4848,7 +4849,7 @@ private void WriteFilterToTab () } [SupportedOSPlatform("windows")] - private void WritePipeToTab (FilterPipe pipe, IList lineNumberList, string name, PersistenceData persistenceData) + private void WritePipeToTab (FilterPipe pipe, List lineNumberList, string name, PersistenceData persistenceData) { _logger.Info(CultureInfo.InvariantCulture, "WritePipeToTab(): {0} lines.", lineNumberList.Count); StatusLineText("Writing to temp file... Press ESC to cancel."); @@ -4941,6 +4942,7 @@ internal void WritePipeTab (IList lineEntryList, string title) { IsStopped = true }; + pipe.Closed += OnPipeDisconnected; pipe.OpenFile(); foreach (var entry in lineEntryList) @@ -5227,14 +5229,9 @@ private void ApplyFrozenState (BufferedDataGridView gridView) [SupportedOSPlatform("windows")] private void ShowTimeSpread (bool show) { - if (show) - { - tableLayoutPanel1.ColumnStyles[1].Width = 16; - } - else - { - tableLayoutPanel1.ColumnStyles[1].Width = 0; - } + tableLayoutPanel1.ColumnStyles[1].Width = show + ? 16 + : 0; _timeSpreadCalc.Enabled = show; } @@ -5242,7 +5239,7 @@ private void ShowTimeSpread (bool show) [SupportedOSPlatform("windows")] protected internal void AddTempFileTab (string fileName, string title) { - _parentLogTabWin.AddTempFileTab(fileName, title); + _ = _parentLogTabWin.AddTempFileTab(fileName, title); } private void InitPatternWindow () @@ -5391,6 +5388,7 @@ private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBl { StartLine = startNum }; + var srcLine = block.StartLine; block.TargetStart = targetLine; var srcMisses = 0; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index 1d305985..b75a674c 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -2249,7 +2249,8 @@ private void OnLogWindowDragDrop (object sender, DragEventArgs e) var o = e.Data.GetData(DataFormats.FileDrop); if (o is string[] names) { - LoadFiles(names, (e.KeyState & 4) == 4); // (shift pressed?) + // (shift pressed) https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.drageventargs.keystate + LoadFiles(names, (e.KeyState & 4) == 4); e.Effect = DragDropEffects.Copy; } } diff --git a/src/SftpFileSystemx64/CredentialCache.cs b/src/SftpFileSystemx64/CredentialCache.cs index dc48ff33..c377efc2 100644 --- a/src/SftpFileSystemx64/CredentialCache.cs +++ b/src/SftpFileSystemx64/CredentialCache.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace SftpFileSystem; internal class CredentialCache @@ -14,7 +12,7 @@ internal class CredentialCache private void RemoveCredentials (string host, string user) { - Credentials credentials = GetCredentials(host, user); + var credentials = GetCredentials(host, user); if (credentials != null) { _credList.Remove(credentials); @@ -27,9 +25,9 @@ internal IList GetUsersForHost (string host) { IList result = []; - foreach (Credentials cred in _credList) + foreach (var cred in _credList) { - if (cred.Host.Equals(host, System.StringComparison.Ordinal)) + if (cred.Host.Equals(host, StringComparison.Ordinal)) { result.Add(cred.UserName); } @@ -40,9 +38,9 @@ internal IList GetUsersForHost (string host) internal Credentials GetCredentials (string host, string user) { - foreach (Credentials cred in _credList) + foreach (var cred in _credList) { - if (cred.Host.Equals(host, System.StringComparison.Ordinal) && cred.UserName.Equals(user, System.StringComparison.Ordinal)) + if (cred.Host.Equals(host, StringComparison.Ordinal) && cred.UserName.Equals(user, StringComparison.Ordinal)) { return cred; } @@ -56,4 +54,4 @@ internal void Add (Credentials cred) RemoveCredentials(cred.Host, cred.UserName); _credList.Add(cred); } -} +} \ No newline at end of file diff --git a/src/SftpFileSystemx64/Credentials.cs b/src/SftpFileSystemx64/Credentials.cs index fbd7cecf..bffc2155 100644 --- a/src/SftpFileSystemx64/Credentials.cs +++ b/src/SftpFileSystemx64/Credentials.cs @@ -1,25 +1,3 @@ -namespace SftpFileSystem; +namespace SftpFileSystem; -internal class Credentials -{ - #region Ctor - - internal Credentials(string host, string userName, string password) - { - Host = host; - UserName = userName; - Password = password; - } - - #endregion - - #region Properties / Indexers - - public string Host { get; } - - public string Password { get; } - - public string UserName { get; } - - #endregion -} +internal record Credentials (string Host, string UserName, string Password); diff --git a/src/SftpFileSystemx64/SftpFileSystem.cs b/src/SftpFileSystemx64/SftpFileSystem.cs index 4d43af87..a8583f3d 100644 --- a/src/SftpFileSystemx64/SftpFileSystem.cs +++ b/src/SftpFileSystemx64/SftpFileSystem.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Windows.Forms; using System.Xml.Serialization; using LogExpert; @@ -19,7 +15,7 @@ public class SftpFileSystem (IFileSystemCallback callback) : IFileSystemPlugin, private ConfigDialog _configDialog; private volatile PrivateKeyFile _privateKeyFile; - private object _lock = new object(); + private readonly object _lock = new(); #endregion @@ -187,7 +183,7 @@ internal Credentials GetCredentials (Uri uri, bool cacheAllowed, bool hidePasswo } } - IList usersForHost = CredentialsCache.GetUsersForHost(uri.Host); + var usersForHost = CredentialsCache.GetUsersForHost(uri.Host); if (userName == null && cacheAllowed) { if (usersForHost.Count == 1) @@ -198,7 +194,7 @@ internal Credentials GetCredentials (Uri uri, bool cacheAllowed, bool hidePasswo if (userName != null && password == null && cacheAllowed) { - Credentials cred = CredentialsCache.GetCredentials(uri.Host, userName); + var cred = CredentialsCache.GetCredentials(uri.Host, userName); if (cred != null) { return cred; diff --git a/src/SftpFileSystemx64/SftpFileSystemSSHDotNET.cs b/src/SftpFileSystemx64/SftpFileSystemSSHDotNET.cs deleted file mode 100644 index 7a253d56..00000000 --- a/src/SftpFileSystemx64/SftpFileSystemSSHDotNET.cs +++ /dev/null @@ -1,225 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Xml.Serialization; -using System.IO; -using Renci.SshNet; -using LogExpert; - -namespace SftpFileSystem -{ - public class SftpFileSystem : IFileSystemPlugin, ILogExpertPluginConfigurator - { - #region Fields - - private readonly ILogExpertLogger _logger; - - private ConfigDialog _configDialog; - private volatile PrivateKeyFile _privateKeyFile; - - #endregion - - #region cTor - - public SftpFileSystem(IFileSystemCallback callback) - { - _logger = callback.GetLogger(); - CredentialsCache = new CredentialCache(); - } - - #endregion - - #region Properties - - private CredentialCache CredentialsCache { get; } - - public string Text => "SFTP plugin"; - - public string Description => "Can read log files directly from SFTP server."; - - public ConfigData ConfigData { get; private set; } = new ConfigData(); - - public PrivateKeyFile PrivateKeyFile { get => _privateKeyFile; set => _privateKeyFile = value; } - - #endregion - - #region Public methods - - public bool CanHandleUri(string uriString) - { - try - { - Uri uri = new Uri(uriString); - return uri.Scheme.Equals("sftp", StringComparison.InvariantCultureIgnoreCase); - } - catch (Exception e) - { - _logger.LogError(e.Message); - return false; - } - } - - public ILogFileInfo GetLogfileInfo(string uriString) - { - try - { - Uri uri = new Uri(uriString.Replace('\\', '/')); - return new SftpLogFileInfo(this, uri, _logger); - } - catch (Exception e) - { - _logger.LogError(e.Message); - return null; - } - } - - public bool HasEmbeddedForm() - { - return true; - } - - public void HideConfigForm() - { - ConfigData = _configDialog.ConfigData; - _configDialog.Hide(); - _configDialog.Dispose(); - } - - public void LoadConfig(string configDir) - { - XmlSerializer xml = new XmlSerializer(ConfigData.GetType()); - - FileInfo configFile = new FileInfo(configDir + "\\" + "sftpfilesystem.cfg"); - - if (!configFile.Exists) - { - return; - } - - FileStream fs = null; - - try - { - fs = configFile.OpenRead(); - - ConfigData = (ConfigData) xml.Deserialize(fs); - } - catch (IOException e) - { - _logger.LogError(e.Message); - } - finally - { - fs?.Flush(); - fs?.Close(); - fs?.Dispose(); - } - } - - public void SaveConfig(string configDir) - { - _logger.Info("Saving SFTP config"); - XmlSerializer xml = new XmlSerializer(ConfigData.GetType()); - - FileStream fs = null; - - try - { - fs = new FileStream(configDir + "\\" + "sftpfilesystem.cfg", FileMode.Create); - xml.Serialize(fs, ConfigData); - fs.Close(); - } - catch (IOException e) - { - _logger.LogError(e.Message); - } - finally - { - fs?.Flush(); - fs?.Close(); - fs?.Dispose(); - } - } - - public void ShowConfigDialog(Form owner) - { - throw new NotImplementedException(); - } - - public void ShowConfigForm(Panel parentPanel) - { - _configDialog = new ConfigDialog(ConfigData); - _configDialog.Parent = parentPanel; - _configDialog.Show(); - } - - public void StartConfig() - { - } - - #endregion - - #region Internals - - internal Credentials GetCredentials(Uri uri, bool cacheAllowed, bool hidePasswordField) - { - // Synchronized access to the GetCredentials() method prevents multiple login dialogs when loading multiple files at once - // (e.g. on startup). So the user only needs to enter credentials once for the same host. - lock (this) - { - string userName = null; - string password = null; - if (uri.UserInfo != null && uri.UserInfo.Length > 0) - { - string[] split = uri.UserInfo.Split(new char[] {':'}); - if (split.Length > 0) - { - userName = split[0]; - } - - if (split.Length > 1) - { - password = split[1]; - } - } - - IList usersForHost = CredentialsCache.GetUsersForHost(uri.Host); - if (userName == null && cacheAllowed) - { - if (usersForHost.Count == 1) - { - userName = usersForHost[0]; - } - } - - if (userName != null && password == null && cacheAllowed) - { - Credentials cred = CredentialsCache.GetCredentials(uri.Host, userName); - if (cred != null) - { - return cred; - } - } - - if (userName == null || password == null) - { - LoginDialog dlg = new LoginDialog(uri.Host, usersForHost, hidePasswordField); - dlg.UserName = userName; - if (DialogResult.OK == dlg.ShowDialog()) - { - password = dlg.Password; - userName = dlg.UserName; - } - - dlg.Dispose(); - } - - Credentials credentials = new Credentials(uri.Host, userName, password); - CredentialsCache.Add(credentials); - return credentials; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/SftpFileSystemx64/SftpFileSystemx64.csproj b/src/SftpFileSystemx64/SftpFileSystemx64.csproj index 751e2a0c..2627ca27 100644 --- a/src/SftpFileSystemx64/SftpFileSystemx64.csproj +++ b/src/SftpFileSystemx64/SftpFileSystemx64.csproj @@ -7,6 +7,7 @@ SftpFileSystem true true + true $(SolutionDir)..\bin\$(Configuration)\plugins SftpFileSystem @@ -19,12 +20,4 @@ - - - - - - - - diff --git a/src/SftpFileSystemx64/SftpLogFileInfo.cs b/src/SftpFileSystemx64/SftpLogFileInfo.cs index 5784dc9c..b31ce3b7 100644 --- a/src/SftpFileSystemx64/SftpLogFileInfo.cs +++ b/src/SftpFileSystemx64/SftpLogFileInfo.cs @@ -1,8 +1,3 @@ -using System; -using System.IO; -using System.Threading; -using System.Windows.Forms; - using LogExpert; using Renci.SshNet; @@ -10,7 +5,7 @@ namespace SftpFileSystem; -internal class SftpLogFileInfo : ILogFileInfo +public class SftpLogFileInfo : ILogFileInfo { #region Static/Constants //TODO Add to Options @@ -33,10 +28,10 @@ internal class SftpLogFileInfo : ILogFileInfo #region Ctor - internal SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpertLogger logger) + public SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpertLogger logger) { _logger = logger; - SftpFileSystem sftFileSystem = sftpFileSystem; + var sftFileSystem = sftpFileSystem; Uri = fileUri; _remoteFileName = Uri.PathAndQuery; @@ -51,7 +46,7 @@ internal SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpert while (sftFileSystem.PrivateKeyFile == null) { PrivateKeyPasswordDialog dlg = new(); - DialogResult dialogResult = dlg.ShowDialog(); + var dialogResult = dlg.ShowDialog(); if (dialogResult == DialogResult.Cancel) { cancelled = true; @@ -74,7 +69,7 @@ internal SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpert if (cancelled == false) { success = false; - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, true); + var credentials = sftFileSystem.GetCredentials(Uri, true, true); while (success == false) { //Add ConnectionInfo object @@ -89,7 +84,7 @@ internal SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpert if (success == false) { FailedKeyDialog dlg = new(); - DialogResult res = dlg.ShowDialog(); + var res = dlg.ShowDialog(); dlg.Dispose(); if (res == DialogResult.Cancel) { @@ -111,7 +106,7 @@ internal SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpert if (success == false) { // username/password auth - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, false); + var credentials = sftFileSystem.GetCredentials(Uri, true, false); _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); if (_sftp == null) @@ -153,12 +148,9 @@ public string DirectoryName { var full = FullName; var i = full.LastIndexOf(DirectorySeparatorChar); - if (i != -1) - { - return full.Substring(0, i); - } - - return "."; + return i != -1 + ? full[..i] + : "."; } } @@ -188,7 +180,7 @@ public string FileName { var full = FullName; var i = full.LastIndexOf(DirectorySeparatorChar); - return full.Substring(i + 1); + return full[(i + 1)..]; } } @@ -209,18 +201,12 @@ public int PollInterval { get { - TimeSpan diff = DateTime.Now - _lastChange; - if (diff.TotalSeconds < 4) - { - return 400; - } - - if (diff.TotalSeconds < 30) - { - return (int)diff.TotalSeconds * 100; - } - - return 5000; + var diff = DateTime.Now - _lastChange; + return diff.TotalSeconds < 4 + ? 400 + : diff.TotalSeconds < 30 + ? (int)diff.TotalSeconds * 100 + : 5000; } } @@ -261,4 +247,4 @@ public Stream OpenStream () } #endregion -} +} \ No newline at end of file diff --git a/src/SftpFileSystemx64/SftpLogFileInfoSSHDotNET.cs b/src/SftpFileSystemx64/SftpLogFileInfoSSHDotNET.cs deleted file mode 100644 index 78705afc..00000000 --- a/src/SftpFileSystemx64/SftpLogFileInfoSSHDotNET.cs +++ /dev/null @@ -1,231 +0,0 @@ -using LogExpert; - -using Renci.SshNet; -using Renci.SshNet.Sftp; - -using System; -using System.IO; -using System.Windows.Forms; - -namespace SftpFileSystem -{ - internal class SftpLogFileInfo : ILogFileInfo - { - - private const int RetryCount = 20; - private const int RetrySleep = 250; - private readonly ILogExpertLogger _logger; - private readonly string _remoteFileName; - - private readonly SftpClient _sftp; - private readonly object _sshKeyMonitor = new object(); - private DateTime _lastChange = DateTime.Now; - private long _lastLength; - - internal SftpLogFileInfo(SftpFileSystemSSHDotNET sftpFileSystem, Uri fileUri, ILogExpertLogger logger) - { - _logger = logger; - SftpFileSystemSSHDotNET sftFileSystem = sftpFileSystem; - Uri = fileUri; - _remoteFileName = Uri.PathAndQuery; - - int port = Uri.Port != -1 ? Uri.Port : 22; - - bool success = false; - bool cancelled = false; - if (sftFileSystem.ConfigData.UseKeyfile) - { - lock (_sshKeyMonitor) // prevent multiple password dialogs when opening multiple files at once - { - while (sftFileSystem.PrivateKeyFile == null) - { - PrivateKeyPasswordDialog dlg = new PrivateKeyPasswordDialog(); - DialogResult dialogResult = dlg.ShowDialog(); - if (dialogResult == DialogResult.Cancel) - { - cancelled = true; - break; - } - - PrivateKeyFile privateKeyFile = new PrivateKeyFile(sftFileSystem.ConfigData.KeyFile, dlg.Password); - - if (privateKeyFile != null) - { - sftFileSystem.PrivateKeyFile = privateKeyFile; - } - else - { - MessageBox.Show("Loading key file failed"); - } - } - } - - if (cancelled == false) - { - success = false; - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, true); - while (success == false) - { - //Add ConnectionInfo object - _sftp = new SftpClient(Uri.Host, credentials.UserName, new[] { sftFileSystem.PrivateKeyFile }); - - if (_sftp != null) - { - _sftp.Connect(); - success = true; - } - - if (success == false) - { - FailedKeyDialog dlg = new FailedKeyDialog(); - DialogResult res = dlg.ShowDialog(); - dlg.Dispose(); - if (res == DialogResult.Cancel) - { - return; - } - - if (res == DialogResult.OK) - { - break; // go to user/pw auth - } - - // retries with disabled cache - credentials = sftFileSystem.GetCredentials(Uri, false, true); - } - } - } - } - - if (success == false) - { - // username/password auth - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, false); - _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); - - if (_sftp == null) - { - // first fail -> try again with disabled cache - credentials = sftFileSystem.GetCredentials(Uri, false, false); - _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); - - if (_sftp == null) - { - // 2nd fail -> abort - MessageBox.Show("Authentication failed!"); - //MessageBox.Show(sftp.LastErrorText); - return; - } - } - else - { - _sftp.Connect(); - } - } - - if (_sftp.IsConnected == false) - { - MessageBox.Show("Sftp is not connected"); - return; - } - - OriginalLength = _lastLength = Length; - } - - public string FullName => Uri.ToString(); - - public string FileName - { - get - { - string full = FullName; - int i = full.LastIndexOf(DirectorySeparatorChar); - return full.Substring(i + 1); - } - } - - public string DirectoryName - { - get - { - string full = FullName; - int i = full.LastIndexOf(DirectorySeparatorChar); - if (i != -1) - { - return full.Substring(0, i); - } - - return "."; - } - } - - public char DirectorySeparatorChar => '/'; - - public Uri Uri { get; } - - public long Length - { - get - { - SftpFile file = _sftp.Get(_remoteFileName); - return file.Attributes.Size; - } - } - - public long OriginalLength { get; } - - public bool FileExists - { - get - { - try - { - SftpFile file = _sftp.Get(_remoteFileName); - long len = file.Attributes.Size; - return len != -1; - } - catch (Exception e) - { - _logger.LogError(e.Message); - return false; - } - } - } - - public int PollInterval - { - get - { - TimeSpan diff = DateTime.Now - _lastChange; - if (diff.TotalSeconds < 4) - { - return 400; - } - - if (diff.TotalSeconds < 30) - { - return (int)diff.TotalSeconds * 100; - } - - return 5000; - } - } - - public bool FileHasChanged() - { - if (Length != _lastLength) - { - _lastLength = Length; - _lastChange = DateTime.Now; - return true; - } - - return false; - } - - public Stream OpenStream() - { - return _sftp.OpenRead(_remoteFileName); - } - } -} diff --git a/src/SftpFileSystemx64/SftpLogFileInfoSharpSSH.cs b/src/SftpFileSystemx64/SftpLogFileInfoSharpSSH.cs deleted file mode 100644 index 5a13f323..00000000 --- a/src/SftpFileSystemx64/SftpLogFileInfoSharpSSH.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using LogExpert; -using Tamir.SharpSsh.jsch; -using System.Windows.Forms; - -namespace SftpFileSystem -{ - class SftpLogFileInfoSharpSSH : ILogFileInfo - { - private long originalFileLength = -1; - - private Uri uri; - private string remoteFileName; - - private ChannelSftp sftpChannel; - - internal SftpLogFileInfoSharpSSH(Uri uri) - { - this.uri = uri; - this.remoteFileName = uri.PathAndQuery; - - string userName = null; - string password = null; - if (uri.UserInfo != null && uri.UserInfo.Length > 0) - { - string[] split = uri.UserInfo.Split(new char[] { ':' }); - if (split.Length > 0) - userName = split[0]; - if (split.Length > 1) - password = split[1]; - } - if (userName == null || password == null) - { - IList userNames = new List(); - LoginDialog dlg = new LoginDialog(uri.Host, userNames); - dlg.UserName = userName; - if (DialogResult.OK == dlg.ShowDialog()) - { - password = dlg.Password; - userName = dlg.UserName; - } - } - - UserInfo userInfo = new SharpSshUserInfo(userName, password); - JSch jsch = new JSch(); - int port = uri.Port != -1 ? uri.Port : 22; - Session session = jsch.getSession(userName, this.uri.Host, port); - session.setUserInfo(userInfo); - session.connect(); - Channel channel = session.openChannel("sftp"); - channel.connect(); - this.sftpChannel = (ChannelSftp)channel; - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - this.originalFileLength = sftpAttrs.getSize(); - - } - - #region ILogFileInfo Member - - public System.IO.Stream OpenStream() - { - throw new NotImplementedException(); - } - - public string FileName - { - get { return this.remoteFileName; } - } - - public long Length - { - get - { - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - return sftpAttrs.getSize(); - } - } - - public long OriginalLength - { - get { return this.originalFileLength; } - } - - public bool FileExists - { - get - { - try - { - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - return true; - } - catch (SftpException e) - { - return false; - } - } - } - - #endregion - - #region ILogFileInfo Member - - - public string FullName - { - get { throw new NotImplementedException(); } - } - - public string DirectoryName - { - get { throw new NotImplementedException(); } - } - - public char DirectorySeparatorChar - { - get { throw new NotImplementedException(); } - } - - public Uri Uri - { - get { throw new NotImplementedException(); } - } - - public int PollInterval - { - get { throw new NotImplementedException(); } - } - - public bool FileHasChanged() - { - throw new NotImplementedException(); - } - - #endregion - } -} diff --git a/src/SftpFileSystemx64/SftpStreamSharpSSH.cs b/src/SftpFileSystemx64/SftpStreamSharpSSH.cs deleted file mode 100644 index 8162f664..00000000 --- a/src/SftpFileSystemx64/SftpStreamSharpSSH.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System; -using System.IO; -using Tamir.SharpSsh.jsch; - -namespace SftpFileSystem -{ - class SftpStreamSharpSSH : Stream - { - private ChannelSftp sftpChannel; - private long currentPos; - private string remoteFileName; - - internal SftpStreamSharpSSH(ChannelSftp sftpChannel, string remoteFileName) - { - this.sftpChannel = sftpChannel; - this.currentPos = 0; - this.remoteFileName = remoteFileName; - } - - public override bool CanRead - { - get { return true; } - } - - public override bool CanSeek - { - get { return true; } - } - - public override bool CanWrite - { - get { return false; } - } - - public override void Flush() - { - throw new NotImplementedException(); - } - - public override long Length - { - get - { - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - return sftpAttrs.getSize(); - } - } - - public override long Position - { - get { return this.currentPos; } - set - { - this.currentPos = value; - } - } - - public override int Read(byte[] buffer, int offset, int count) - { - Tamir.SharpSsh.java.io.OutputStream os = new Tamir.SharpSsh.java.io.OutputStream(); - - this.sftpChannel.get(Tamir.SharpSsh.java.String(this.remoteFileName), os, null, ChannelSftp.RESUME, - this.currentPos); - - this.currentPos += bytes.Length; - Array.Copy(bytes, 0, buffer, offset, bytes.Length); - return bytes.Length; - } - - public override long Seek(long offset, SeekOrigin origin) - { - if (origin == SeekOrigin.Begin) - { - this.Position = offset; - } - else if (origin == SeekOrigin.Current) - { - this.Position += offset; - } - else if (origin == SeekOrigin.End) - { - this.Position = this.Length - offset; - } - return this.Position; - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - - public override void Close() - { - base.Close(); - this.sftp.CloseHandle(this.handle); - } - - } -} \ No newline at end of file diff --git a/src/SftpFileSystemx64/SharpSshUserInfo.cs b/src/SftpFileSystemx64/SharpSshUserInfo.cs deleted file mode 100644 index 95dc2497..00000000 --- a/src/SftpFileSystemx64/SharpSshUserInfo.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Tamir.SharpSsh.jsch; -using System.Windows.Forms; - -namespace SftpFileSystem -{ - internal class SharpSshUserInfo : UserInfo - { - private String password; - private String userName; - - internal SharpSshUserInfo(string userName, string password) - { - this.userName = userName; - this.password = password; - } - - - public String getPassword() { return password; } - - public bool promptYesNo(String str) - { - DialogResult returnVal = MessageBox.Show( - str, - "LogExpert", - MessageBoxButtons.YesNo, - MessageBoxIcon.Warning); - return (returnVal == DialogResult.Yes); - } - - public String getPassphrase() { return null; } - - public bool promptPassphrase(String message) { return true; } - - public bool promptPassword(String message) - { - return true; - } - - public void showMessage(String message) - { - MessageBox.Show( - message, - "LogExpert", - MessageBoxButtons.OK, - MessageBoxIcon.Asterisk); - } - } -} diff --git a/src/SftpFileSystemx86/SftpFileSystemx86.csproj b/src/SftpFileSystemx86/SftpFileSystemx86.csproj index d6794794..eb96b544 100644 --- a/src/SftpFileSystemx86/SftpFileSystemx86.csproj +++ b/src/SftpFileSystemx86/SftpFileSystemx86.csproj @@ -7,6 +7,7 @@ SftpFileSystem true true + true SftpFileSystemx86 $(SolutionDir)..\bin\$(Configuration)\pluginsx86 @@ -48,11 +49,11 @@ - - + - + + diff --git a/src/Solution Items/AssemblyInfo.cs b/src/Solution Items/AssemblyInfo.cs index 29f6db81..d27ce7a1 100644 --- a/src/Solution Items/AssemblyInfo.cs +++ b/src/Solution Items/AssemblyInfo.cs @@ -5,9 +5,9 @@ [assembly: AssemblyProduct("LogExpert")] [assembly: AssemblyCopyright("Original work Copyright (c) 2008-2011 Hagen Raab\r\nModified work Copyright (c) 2025 Zarunbal|Hirogen and many others")] -[assembly: AssemblyVersion("1.12.0")] -[assembly: AssemblyFileVersion("1.12.0")] -[assembly: AssemblyInformationalVersion("1.12.0")] +[assembly: AssemblyVersion("1.20.0")] +[assembly: AssemblyFileVersion("1.20.0")] +[assembly: AssemblyInformationalVersion("1.20.0")] [assembly: ComVisible(false)] //warning CA1824: Mark assemblies with NeutralResourcesLanguageAttribute \ No newline at end of file