diff --git a/SerialDisk/Comms/Serial.cs b/SerialDisk/Comms/Serial.cs index 53f82a6..7b64275 100644 --- a/SerialDisk/Comms/Serial.cs +++ b/SerialDisk/Comms/Serial.cs @@ -12,10 +12,10 @@ namespace AtariST.SerialDisk.Comms { public class Serial : ISerial, IDisposable { - private SerialPort _serialPort; + private readonly SerialPort _serialPort; - private ILogger _logger; - private IDisk _localDisk; + private readonly ILogger _logger; + private readonly IDisk _localDisk; private int _receivedDataCounter = 0; @@ -28,7 +28,7 @@ public class Serial : ISerial, IDisposable private ReceiverState _state = ReceiverState.ReceiveStartMagic; - private CancellationTokenSource _listenTokenSource; + private readonly CancellationTokenSource _listenTokenSource; public Serial(SerialPortSettings serialPortSettings, IDisk disk, ILogger log, CancellationTokenSource cancelTokenSource) { @@ -95,7 +95,7 @@ private SerialPort InitializeSerialPort(SerialPortSettings serialSettings) public void StartListening() { - Task serialTask = Listen(); + _ = Listen(); _logger.Log($"Listening for data on {_serialPort.PortName}", LoggingLevel.Info); } @@ -121,22 +121,22 @@ private Task Listen() if (bytesRead != 0) { - for(int i=0;i < bytesRead;i++) ProcessReceivedByte(Convert.ToByte(buffer[i])); + for (int i = 0; i < bytesRead; i++) ProcessReceivedByte(Convert.ToByte(buffer[i])); } } - catch(OperationCanceledException) + catch (OperationCanceledException) { _logger.Log($"Stopped listening on {_serialPort.PortName}", LoggingLevel.Verbose); } - catch(ObjectDisposedException) + catch (ObjectDisposedException) { _logger.Log("Serial object was disposed", LoggingLevel.Verbose); _listenTokenSource.Cancel(); } - catch(Exception ex) + catch (Exception ex) { _logger.LogException(ex, "Error reading from serial port"); _listenTokenSource.Cancel(); @@ -203,7 +203,7 @@ private void ProcessReceivedByte(byte Data) break; } - _logger.Log($"Receiver state: {_state.ToString()}", LoggingLevel.Verbose); + _logger.Log($"Receiver state: {_state}", LoggingLevel.Verbose); _receivedDataCounter = -1; break; @@ -393,7 +393,7 @@ private void SendData() _state = ReceiverState.ReceiveStartMagic; - _logger.Log($"Receiver state: {_state.ToString()}", LoggingLevel.Verbose); + _logger.Log($"Receiver state: {_state}", LoggingLevel.Verbose); } private void SendBIOSParameterBlock() diff --git a/SerialDisk/Interfaces/IDisk.cs b/SerialDisk/Interfaces/IDisk.cs index 93b849a..8b03798 100644 --- a/SerialDisk/Interfaces/IDisk.cs +++ b/SerialDisk/Interfaces/IDisk.cs @@ -1,6 +1,4 @@ using AtariST.SerialDisk.Storage; -using System; -using System.IO; namespace AtariST.SerialDisk.Interfaces { diff --git a/SerialDisk/Models/AtariDiskSettings.cs b/SerialDisk/Models/AtariDiskSettings.cs index b9a1655..c52b817 100644 --- a/SerialDisk/Models/AtariDiskSettings.cs +++ b/SerialDisk/Models/AtariDiskSettings.cs @@ -1,8 +1,4 @@ -using AtariST.SerialDisk.Utilities; -using System; -using System.Collections.Generic; -using System.Text; -using static AtariST.SerialDisk.Common.Constants; +using static AtariST.SerialDisk.Common.Constants; namespace AtariST.SerialDisk.Models { diff --git a/SerialDisk/SerialDisk.cs b/SerialDisk/SerialDisk.cs index 8cfe069..a2774e3 100644 --- a/SerialDisk/SerialDisk.cs +++ b/SerialDisk/SerialDisk.cs @@ -80,7 +80,7 @@ private static void PrintUsage(ApplicationSettings _applicationSettings) private static string ParseLocalDirectoryPath(string _applicationSettingsPath, string[] args) { - string localDirectoryPath = "."; + string localDirectoryPath; // args length is odd, assume final arg is a path if (args.Length % 2 != 0) @@ -113,6 +113,18 @@ private static void ConfigureServices(IServiceCollection serviceCollection) serviceCollection.AddSingleton(); } + private static Task ListenForConsoleExitKeypress() + { + return Task.Factory.StartNew(() => + { + var keyInfo = new ConsoleKeyInfo(); + do + { + keyInfo = Console.ReadKey(true); + } while ((keyInfo.Modifiers & ConsoleModifiers.Control) == 0 && keyInfo.Key != ConsoleKey.X); + }); + } + public static void Main(string[] args) { Console.WriteLine("Serial Disk v" + Assembly.GetExecutingAssembly().GetName().Version); @@ -190,14 +202,14 @@ public static void Main(string[] args) Console.WriteLine("Press Ctrl-X to quit."); - Task keyboardListener = ListenKeyboard(); + Task keyboardExitListener = ListenForConsoleExitKeypress(); try { - keyboardListener.Wait(cancelTokenSource.Token); + keyboardExitListener.Wait(cancelTokenSource.Token); } - catch(OperationCanceledException ex) + catch (OperationCanceledException ex) { _logger.Log("Thread cancellation requested", LoggingLevel.Verbose); _logger.Log(ex.Message, LoggingLevel.Verbose); @@ -208,17 +220,5 @@ public static void Main(string[] args) Console.ResetColor(); } - - private static Task ListenKeyboard() - { - return Task.Factory.StartNew(() => - { - var keyInfo = new ConsoleKeyInfo(); - do - { - keyInfo = Console.ReadKey(true); - } while ((keyInfo.Modifiers & ConsoleModifiers.Control) == 0 && keyInfo.Key != ConsoleKey.X); - }); - } - } + } } \ No newline at end of file diff --git a/SerialDisk/Storage/Disk.cs b/SerialDisk/Storage/Disk.cs index 8bffa26..1fffecd 100644 --- a/SerialDisk/Storage/Disk.cs +++ b/SerialDisk/Storage/Disk.cs @@ -1,26 +1,26 @@ +using AtariST.SerialDisk.Common; using AtariST.SerialDisk.Interfaces; using AtariST.SerialDisk.Models; -using AtariST.SerialDisk.Common; +using AtariST.SerialDisk.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; -using AtariST.SerialDisk.Utilities; namespace AtariST.SerialDisk.Storage { public class Disk : IDisk { - private int _rootDirectoryClusterIndex = 0; + private readonly int _rootDirectoryClusterIndex = 0; private byte[] _rootDirectoryBuffer; private byte[] _fatBuffer; private int _previousFreeClusterIndex; private ClusterInfo[] _clusterInfos; private List _localDirectoryContentInfos; - private FileSystemWatcher _fileSystemWatcher { get; set; } - private ILogger _logger; + private FileSystemWatcher _fileSystemWatcher; + private readonly ILogger _logger; public DiskParameters Parameters { get; set; } public bool FileSystemWatcherEnabled @@ -383,23 +383,22 @@ public byte[] ReadSectors(int sector, int numberOfSectors) { string contentName = _clusterInfos[clusterIndex].ContentName; - if(firstSector == sector) _logger.Log($"Reading local file {contentName}", Constants.LoggingLevel.Info); + if (firstSector == sector) _logger.Log($"Reading local file {contentName}", Constants.LoggingLevel.Info); byte[] fileClusterDataBuffer = new byte[Parameters.BytesPerCluster]; try { - using (FileStream fileStream = File.OpenRead(contentName)) - { - int bytesToRead = Math.Min(Parameters.BytesPerCluster, (int)(fileStream.Length - _clusterInfos[clusterIndex].FileOffset)); + using FileStream fileStream = File.OpenRead(contentName); - fileStream.Seek(_clusterInfos[clusterIndex].FileOffset, SeekOrigin.Begin); + int bytesToRead = Math.Min(Parameters.BytesPerCluster, (int)(fileStream.Length - _clusterInfos[clusterIndex].FileOffset)); - for (int Index = 0; Index < bytesToRead; Index++) - fileClusterDataBuffer[Index] = (byte)fileStream.ReadByte(); + fileStream.Seek(_clusterInfos[clusterIndex].FileOffset, SeekOrigin.Begin); - Array.Copy(fileClusterDataBuffer, (readSector - clusterIndex * Parameters.SectorsPerCluster) * Parameters.BytesPerSector, dataBuffer, dataOffset, Parameters.BytesPerSector); - } + for (int Index = 0; Index < bytesToRead; Index++) + fileClusterDataBuffer[Index] = (byte)fileStream.ReadByte(); + + Array.Copy(fileClusterDataBuffer, (readSector - clusterIndex * Parameters.SectorsPerCluster) * Parameters.BytesPerSector, dataBuffer, dataOffset, Parameters.BytesPerSector); } catch (Exception ex) diff --git a/SerialDisk/Storage/DiskParameters.cs b/SerialDisk/Storage/DiskParameters.cs index 054106f..12759c1 100644 --- a/SerialDisk/Storage/DiskParameters.cs +++ b/SerialDisk/Storage/DiskParameters.cs @@ -12,7 +12,7 @@ public class DiskParameters private int _bytesPerSector; private byte[] _biosParameterBlock; - private ILogger _logger; + private readonly ILogger _logger; public int DiskTotalBytes { @@ -31,7 +31,7 @@ public int DiskTotalBytes } } - catch(ArgumentException argEx) + catch (ArgumentException argEx) { _logger.LogException(argEx); throw argEx; diff --git a/SerialDisk/Utilities/CRC32.cs b/SerialDisk/Utilities/CRC32.cs index 6cfb767..97ff23d 100644 --- a/SerialDisk/Utilities/CRC32.cs +++ b/SerialDisk/Utilities/CRC32.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace AtariST.SerialDisk.Utilities +namespace AtariST.SerialDisk.Utilities { public static class CRC32 { @@ -52,7 +48,7 @@ public static uint CalculateCRC32(byte[] buffer) { uint crc32 = 0; - foreach(byte data in buffer) + foreach (byte data in buffer) { crc32 = (crc32 << 8) ^ Crc32Table[data ^ ((crc32 >> 24) & 0xFF)]; } diff --git a/SerialDisk/Utilities/FAT16Helper.cs b/SerialDisk/Utilities/FAT16Helper.cs index 97795f5..197bf4c 100644 --- a/SerialDisk/Utilities/FAT16Helper.cs +++ b/SerialDisk/Utilities/FAT16Helper.cs @@ -29,7 +29,7 @@ public static string GetShortFileName(string fileName) fileName = invalidCharactersRegex.Replace(fileName.ToUpper(), "_"); int dotIndex = fileName.LastIndexOf("."); - if(dotIndex != -1) fileName = fileName.Substring(0, dotIndex).Replace('.', '_') + fileName[dotIndex..]; + if (dotIndex != -1) fileName = fileName.Substring(0, dotIndex).Replace('.', '_') + fileName[dotIndex..]; string shortFileName; @@ -63,7 +63,7 @@ public static void ValidateLocalDirectory(string localDirectoryPath, int diskSiz DirectoryInfo directoryInfo = new DirectoryInfo(localDirectoryPath); uint localDirectorySizeBytes = (uint)Directory.GetFiles(directoryInfo.FullName, "*", SearchOption.AllDirectories).Sum(file => (new FileInfo(file).Length)); - if(localDirectorySizeBytes > MaxDiskSizeBytes(tosVersion)) + if (localDirectorySizeBytes > MaxDiskSizeBytes(tosVersion)) throw new System.InsufficientMemoryException($"Local directory size is {localDirectorySizeBytes / BytesPerMiB} MiB, which is larger than the maximum allowable virtual disk size ({MaxDiskSizeBytes(tosVersion) / BytesPerMiB} MiB)"); else if (localDirectorySizeBytes > diskSizeBytes) @@ -76,7 +76,7 @@ public static void ValidateLocalDirectory(string localDirectoryPath, int diskSiz throw new System.InsufficientMemoryException($"The root directory has {rootDirectoryEntries} files/directories, which is more than the maximum ({maxRootDirectoryEntries} allowed"); } - catch(Exception ex) + catch (Exception ex) { throw ex; } diff --git a/SerialDisk/Utilities/Logger.cs b/SerialDisk/Utilities/Logger.cs index f4e8bcc..4a190db 100644 --- a/SerialDisk/Utilities/Logger.cs +++ b/SerialDisk/Utilities/Logger.cs @@ -1,8 +1,8 @@ -using System; +using AtariST.SerialDisk.Common; +using AtariST.SerialDisk.Interfaces; +using System; using System.IO; using System.Text; -using AtariST.SerialDisk.Common; -using AtariST.SerialDisk.Interfaces; using static AtariST.SerialDisk.Common.Constants; namespace AtariST.SerialDisk.Utilities @@ -11,7 +11,7 @@ public class Logger : IDisposable, ILogger { private FileStream _fileStream; private string _logFilePath; - private LoggingLevel _logLevel; + private readonly LoggingLevel _logLevel; public Logger(LoggingLevel loggingLevel, string logFileName = null) { @@ -52,7 +52,7 @@ public void Log(string message, LoggingLevel messageLogLevel = LoggingLevel.Verb if (messageLogLevel <= _logLevel) { - if(_logLevel == LoggingLevel.Verbose) Console.Write($"{DateTime.Now}\t"); + if (_logLevel == LoggingLevel.Verbose) Console.Write($"{DateTime.Now}\t"); Console.Write($"{message}\r\n"); } } @@ -67,7 +67,7 @@ public void LogException(Exception exception, string message = "") Console.ResetColor(); if (_logLevel > LoggingLevel.Info) { - Console.WriteLine(exception); + Console.WriteLine(exception); Console.WriteLine(exception.StackTrace); } } @@ -76,10 +76,9 @@ public void LogToFile(string message) { try { - using (StreamWriter fileWriter = new StreamWriter(_fileStream, Encoding.UTF8, 1024, true)) - { - fileWriter.WriteLineAsync($"{DateTime.Now.ToString(Constants.DATE_FORMAT)}\t{DateTime.Now.ToString(Constants.TIME_FORMAT)}\t{message}"); - } + using StreamWriter fileWriter = new StreamWriter(_fileStream, Encoding.UTF8, 1024, true); + + fileWriter.WriteLineAsync($"{DateTime.Now.ToString(Constants.DATE_FORMAT)}\t{DateTime.Now.ToString(Constants.TIME_FORMAT)}\t{message}"); } catch (Exception logException) diff --git a/SerialDisk/Utilities/OSHelper.cs b/SerialDisk/Utilities/OSHelper.cs index da48b28..7e0387c 100644 --- a/SerialDisk/Utilities/OSHelper.cs +++ b/SerialDisk/Utilities/OSHelper.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; +using System.Runtime.InteropServices; namespace AtariST.SerialDisk.Utilities { diff --git a/SerialDiskTests/CRC32Tests.cs b/SerialDiskTests/CRC32Tests.cs index 2d480d0..bd7ecfe 100644 --- a/SerialDiskTests/CRC32Tests.cs +++ b/SerialDiskTests/CRC32Tests.cs @@ -11,7 +11,7 @@ public class CRC32Tests [SetUp] public void Setup() { - + } [Test] diff --git a/SerialDiskTests/DiskParameterTests.cs b/SerialDiskTests/DiskParameterTests.cs index b5d2b93..66a135a 100644 --- a/SerialDiskTests/DiskParameterTests.cs +++ b/SerialDiskTests/DiskParameterTests.cs @@ -1,10 +1,10 @@ -using NUnit.Framework; -using AtariST.SerialDisk.Storage; -using AtariST.SerialDisk.Models; -using static AtariST.SerialDisk.Common.Constants; -using System; using AtariST.SerialDisk.Interfaces; +using AtariST.SerialDisk.Models; +using AtariST.SerialDisk.Storage; using Moq; +using NUnit.Framework; +using System; +using static AtariST.SerialDisk.Common.Constants; namespace Tests { diff --git a/SerialDiskTests/FAT16HelperTests.cs b/SerialDiskTests/FAT16HelperTests.cs index 6613cca..69f8445 100644 --- a/SerialDiskTests/FAT16HelperTests.cs +++ b/SerialDiskTests/FAT16HelperTests.cs @@ -1,5 +1,5 @@ -using NUnit.Framework; -using AtariST.SerialDisk.Utilities; +using AtariST.SerialDisk.Utilities; +using NUnit.Framework; using static AtariST.SerialDisk.Common.Constants; namespace Tests @@ -16,8 +16,8 @@ public void Setup() [TestCase("SerialDisk.tos", "SERIALDI.TOS")] [TestCase("Hello There.mpeg", "HELLO_TH.MPE")] [TestCase(@"*+,/:;<=.æøå", "________.___")] - [TestCase(@">?\[]|.^'¨","______.___")] - [TestCase("tst.dot.exe","TST_DOT.EXE")] + [TestCase(@">?\[]|.^'¨", "______.___")] + [TestCase("tst.dot.exe", "TST_DOT.EXE")] public void CreateShortFileNameFromLongFileName(string longFileName, string expectedShortFileName) { var shortFileName = FAT16Helper.GetShortFileName(longFileName);