Skip to content

Commit

Permalink
Automated code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
z80andrew committed Apr 10, 2020
1 parent 8556399 commit e28ed12
Show file tree
Hide file tree
Showing 13 changed files with 69 additions and 84 deletions.
22 changes: 11 additions & 11 deletions SerialDisk/Comms/Serial.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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)
{
Expand Down Expand Up @@ -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);
}

Expand All @@ -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();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 0 additions & 2 deletions SerialDisk/Interfaces/IDisk.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using AtariST.SerialDisk.Storage;
using System;
using System.IO;

namespace AtariST.SerialDisk.Interfaces
{
Expand Down
6 changes: 1 addition & 5 deletions SerialDisk/Models/AtariDiskSettings.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
34 changes: 17 additions & 17 deletions SerialDisk/SerialDisk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -113,6 +113,18 @@ private static void ConfigureServices(IServiceCollection serviceCollection)
serviceCollection.AddSingleton<ILogger, Logger>();
}

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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
});
}
}
}
}
27 changes: 13 additions & 14 deletions SerialDisk/Storage/Disk.cs
Original file line number Diff line number Diff line change
@@ -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<LocalDirectoryContentInfo> _localDirectoryContentInfos;
private FileSystemWatcher _fileSystemWatcher { get; set; }
private ILogger _logger;
private FileSystemWatcher _fileSystemWatcher;
private readonly ILogger _logger;

public DiskParameters Parameters { get; set; }
public bool FileSystemWatcherEnabled
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions SerialDisk/Storage/DiskParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class DiskParameters
private int _bytesPerSector;
private byte[] _biosParameterBlock;

private ILogger _logger;
private readonly ILogger _logger;

public int DiskTotalBytes
{
Expand All @@ -31,7 +31,7 @@ public int DiskTotalBytes
}
}

catch(ArgumentException argEx)
catch (ArgumentException argEx)
{
_logger.LogException(argEx);
throw argEx;
Expand Down
8 changes: 2 additions & 6 deletions SerialDisk/Utilities/CRC32.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down Expand Up @@ -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)];
}
Expand Down
6 changes: 3 additions & 3 deletions SerialDisk/Utilities/FAT16Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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)
Expand All @@ -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;
}
Expand Down
19 changes: 9 additions & 10 deletions SerialDisk/Utilities/Logger.cs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
{
Expand Down Expand Up @@ -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");
}
}
Expand All @@ -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);
}
}
Expand All @@ -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)
Expand Down
5 changes: 1 addition & 4 deletions SerialDisk/Utilities/OSHelper.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
2 changes: 1 addition & 1 deletion SerialDiskTests/CRC32Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class CRC32Tests
[SetUp]
public void Setup()
{

}

[Test]
Expand Down
10 changes: 5 additions & 5 deletions SerialDiskTests/DiskParameterTests.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
8 changes: 4 additions & 4 deletions SerialDiskTests/FAT16HelperTests.cs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
Expand Down

0 comments on commit e28ed12

Please sign in to comment.