From 2dbe387cabae655da3f6fc0403a1f084bbcd4b23 Mon Sep 17 00:00:00 2001 From: Si Carter Date: Wed, 6 Sep 2023 18:18:45 +0200 Subject: [PATCH 1/5] Sonar issues --- .../Analyzers/AnalyzeCoordinateSystemsUsed.cs | 2 +- .../Analyzers/AnalyzeInvalidGCode.cs | 2 +- .../Analyzers/AnalyzeToolChange.cs | 9 ++--- src/GCAAnalyser/Analyzers/BaseAnalyzer.cs | 12 +++---- src/GCAAnalyser/GCodeCommand.cs | 5 --- src/GSendCommon/GCodeProcessor.cs | 33 ++++--------------- src/GSendEditor/GCodeSyntaxHighLighter.cs | 14 ++++---- 7 files changed, 25 insertions(+), 52 deletions(-) diff --git a/src/GCAAnalyser/Analyzers/AnalyzeCoordinateSystemsUsed.cs b/src/GCAAnalyser/Analyzers/AnalyzeCoordinateSystemsUsed.cs index f2be9945..faa12ba2 100644 --- a/src/GCAAnalyser/Analyzers/AnalyzeCoordinateSystemsUsed.cs +++ b/src/GCAAnalyser/Analyzers/AnalyzeCoordinateSystemsUsed.cs @@ -23,7 +23,7 @@ public void Analyze(string fileName, IGCodeAnalyses gCodeAnalyses) }); } - if (gCodeAnalyses.CoordinateSystems.EndsWith(",")) + if (gCodeAnalyses.CoordinateSystems.EndsWith(',')) gCodeAnalyses.CoordinateSystems = gCodeAnalyses.CoordinateSystems[..^1]; } diff --git a/src/GCAAnalyser/Analyzers/AnalyzeInvalidGCode.cs b/src/GCAAnalyser/Analyzers/AnalyzeInvalidGCode.cs index 408dfa81..e2f812af 100644 --- a/src/GCAAnalyser/Analyzers/AnalyzeInvalidGCode.cs +++ b/src/GCAAnalyser/Analyzers/AnalyzeInvalidGCode.cs @@ -9,7 +9,7 @@ internal class AnalyzeInvalidGCode : IGCodeAnalyzer public void Analyze(string fileName, IGCodeAnalyses gCodeAnalyses) { - bool longLine = gCodeAnalyses.AllCommands.Where(c => c.Attributes.HasFlag(CommandAttributes.InvalidLineTooLong)).Any(); + bool longLine = gCodeAnalyses.AllCommands.Any(c => c.Attributes.HasFlag(CommandAttributes.InvalidLineTooLong)); if (longLine) { diff --git a/src/GCAAnalyser/Analyzers/AnalyzeToolChange.cs b/src/GCAAnalyser/Analyzers/AnalyzeToolChange.cs index 792a82fe..cb0423fb 100644 --- a/src/GCAAnalyser/Analyzers/AnalyzeToolChange.cs +++ b/src/GCAAnalyser/Analyzers/AnalyzeToolChange.cs @@ -23,15 +23,12 @@ public void Analyze(string fileName, IGCodeAnalyses gCodeAnalyses) tools.ForEach(t => gCodeAnalyses.Tools += $"{t.CommandValueString},"); } - else if (gCodeAnalyses.AnalysesOptions.HasFlag(AnalysesOptions.ContainsAutomaticToolChanges)) + else if (gCodeAnalyses.AnalysesOptions.HasFlag(AnalysesOptions.ContainsAutomaticToolChanges) && (gCodeAnalyses is GCodeAnalyses codeAnalyses)) { - if (gCodeAnalyses is GCodeAnalyses codeAnalyses) - { - codeAnalyses.AddError(GSend.Language.Resources.AnalyzeError1); - } + codeAnalyses.AddError(GSend.Language.Resources.AnalyzeError1); } - if (gCodeAnalyses.Tools.EndsWith(",")) + if (gCodeAnalyses.Tools.EndsWith(',')) gCodeAnalyses.Tools = gCodeAnalyses.Tools[..^1]; } } diff --git a/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs b/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs index 64e50937..acd12e90 100644 --- a/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs +++ b/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs @@ -8,7 +8,7 @@ protected bool HasCommandsOnSameLine(IGCodeCommand command, char ignoreCommands) { var commandsOnLine = CommandsOnSameLine(command); - return commandsOnLine.Any(c => c.Command != ignoreCommands); + return commandsOnLine.Exists(c => c.Command != ignoreCommands); } protected List CommandsOnSameLine(IGCodeCommand command) @@ -25,7 +25,7 @@ protected List CommandsOnSameLine(IGCodeCommand command) return Result; } - private void LookPrevious(IGCodeCommand command, List commands) + private static void LookPrevious(IGCodeCommand command, List commands) { IGCodeCommand previous = command.PreviousCommand; @@ -43,7 +43,7 @@ private void LookPrevious(IGCodeCommand command, List commands) } } - private void LookNext(IGCodeCommand command, List commands) + private static void LookNext(IGCodeCommand command, List commands) { IGCodeCommand next = command.NextCommand; @@ -61,7 +61,7 @@ private void LookNext(IGCodeCommand command, List commands) } } - protected bool ValidatePreviousNextCommand(IGCodeCommand command, char toFindCommand) + protected static bool ValidatePreviousNextCommand(IGCodeCommand command, char toFindCommand) { if (command == null) return false; @@ -75,7 +75,7 @@ protected bool ValidatePreviousNextCommand(IGCodeCommand command, char toFindCom return false; } - protected bool ValidateNextCommand(IGCodeCommand command, decimal finalNextTo) + protected static bool ValidateNextCommand(IGCodeCommand command, decimal finalNextTo) { if (command == null) return false; @@ -88,7 +88,7 @@ protected bool ValidateNextCommand(IGCodeCommand command, decimal finalNextTo) return false; } - protected bool ValidateNextCommand(IGCodeCommand command, decimal finalNextTo, decimal[] nextTo, char[] ignoreNextCommands, int depth) + protected static bool ValidateNextCommand(IGCodeCommand command, decimal finalNextTo, decimal[] nextTo, char[] ignoreNextCommands, int depth) { if (command == null || command.NextCommand == null || depth == 10) return false; diff --git a/src/GCAAnalyser/GCodeCommand.cs b/src/GCAAnalyser/GCodeCommand.cs index b0e620bd..89e33142 100644 --- a/src/GCAAnalyser/GCodeCommand.cs +++ b/src/GCAAnalyser/GCodeCommand.cs @@ -245,11 +245,6 @@ public override bool Equals(object obj) Comment.Equals(command.Comment); } - public override int GetHashCode() - { - return base.GetHashCode(); - } - public override string ToString() { return $"{Command}{CommandValueString}"; diff --git a/src/GSendCommon/GCodeProcessor.cs b/src/GSendCommon/GCodeProcessor.cs index 851c2f57..155eedd8 100644 --- a/src/GSendCommon/GCodeProcessor.cs +++ b/src/GSendCommon/GCodeProcessor.cs @@ -34,7 +34,6 @@ public class GCodeProcessor : ThreadManager, IGCodeProcessor private const string CommandCoolantOff = "M9"; private const string CommandZero = "G10 P{0} L20"; private const string CommandZeroAxis = " {0}0"; - private const string StatusIdle = "Idle"; private const string CommandGetStatus = "$I"; private const string CommonadGetConfiguration = "$G"; private const string CommandStartResume = "~"; @@ -81,7 +80,6 @@ public class GCodeProcessor : ThreadManager, IGCodeProcessor private bool _initialising = true; private readonly Stopwatch _jobTime = new(); private bool _updateStatusSent = false; - private readonly ProcessGCodeJob _processJobThread; private readonly IGSendSettings _gSendSettings; #region Constructors @@ -110,8 +108,8 @@ public GCodeProcessor(IGSendDataProvider gSendDataProvider, IMachine machine, _machine, _machineStateModel, _commandQueue); ThreadManager.ThreadStart(this, $"{machine.Name} - {machine.ComPort} - Update Status", ThreadPriority.Normal); - _processJobThread = new ProcessGCodeJob(this); - ThreadManager.ThreadStart(_processJobThread, $"{machine.Name} - {machine.ComPort} - Job Processor", ThreadPriority.Normal); + ProcessGCodeJob processJobThread = new ProcessGCodeJob(this); + ThreadManager.ThreadStart(processJobThread, $"{machine.Name} - {machine.ComPort} - Job Processor", ThreadPriority.Normal); } #endregion Constructors @@ -152,7 +150,6 @@ public void ProcessNextCommand() string commandText = peekCommand.GetGCode(); _sendQueue.Enqueue(peekCommand); UpdateMachineStateBufferData(); - //Trace.WriteLine($"From Command Queue: {commandText}"); _port.WriteLine(commandText); _machineStateModel.CommandQueueSize = _commandQueue.Count; @@ -195,7 +192,7 @@ public void ProcessNextCommand() if ((BufferSize + commandText.Length + 1) < _gSendSettings.MaximumBufferSize && IsRunning) { if (!String.IsNullOrEmpty(commandText) || - !commandText.StartsWith("%")) + !commandText.StartsWith('%')) { Trace.WriteLine($"Line {NextCommand} {commandText} added to queue"); commandToSend.Status = LineStatus.Sent; @@ -352,16 +349,7 @@ public bool Stop() { Trace.WriteLine("Stop"); - //if (_isPaused) - //{ - //_port.WriteLine("CTRL-X"); - //InternalWriteByte(new byte[] { 0x85 }); InternalWriteByte(new byte[] { 0x18 }); - //} - //else - //{ - // _port.WriteLine("M2"); - //} _jobTime.Stop(); @@ -1013,8 +1001,6 @@ private void ProcessGrblResponse() if (String.IsNullOrWhiteSpace(response)) continue; - //Trace.WriteLine($"Response: {response}; Queue Size: {_sendQueue.Count}; Buffer: {BufferSize}; Line: {NextCommand}"); - if (!IsRunning) OnResponseReceived?.Invoke(this, response); @@ -1025,24 +1011,20 @@ private void ProcessGrblResponse() { _updateStatusSent = false; ProcessInformationResponse(response[1..^1]); - continue; } else if (response.StartsWith("alarm", StringComparison.InvariantCultureIgnoreCase)) { Trace.WriteLine($"Response: {response}"); ProcessAlarmResponse(response); - continue; } else if (response.StartsWith("error", StringComparison.InvariantCultureIgnoreCase)) { Trace.WriteLine($"Response: {response}"); ProcessErrorResponse(response); - continue; } else if (response.StartsWith('[')) { ProcessMessageResponse(response.Trim()[1..^1]); - continue; } else if (response.Equals(ResultOk, StringComparison.InvariantCultureIgnoreCase)) { @@ -1053,7 +1035,7 @@ private void ProcessGrblResponse() RaiseOnLineStatusUpdated(activeCommand); - if (activeCommand.Commands.Any(c => c.Command.Equals('G') && + if (activeCommand.Commands.Exists(c => c.Command.Equals('G') && ( c.CommandValue.Equals(54) || c.CommandValue.Equals(55) || @@ -1068,7 +1050,6 @@ private void ProcessGrblResponse() } _waitingForResponse = false; - continue; } @@ -1215,9 +1196,9 @@ private void ProcessInformationResponse(string response) break; case OptionAccessoryState: - _machineStateModel.SpindleClockWise = values[0].Contains("S"); - _machineStateModel.SpindleCounterClockWise = values[0].Contains("C"); - _machineStateModel.FloodEnabled = values[0].Contains("F"); + _machineStateModel.SpindleClockWise = values[0].Contains('S'); + _machineStateModel.SpindleCounterClockWise = values[0].Contains('C'); + _machineStateModel.FloodEnabled = values[0].Contains('F'); _machineStateModel.MistEnabled = values[0].Contains(StatusMistEnabled); break; } diff --git a/src/GSendEditor/GCodeSyntaxHighLighter.cs b/src/GSendEditor/GCodeSyntaxHighLighter.cs index 3851635f..00f5e9a3 100644 --- a/src/GSendEditor/GCodeSyntaxHighLighter.cs +++ b/src/GSendEditor/GCodeSyntaxHighLighter.cs @@ -34,13 +34,13 @@ public override void HighlightSyntax(Language language, Range range) private void InitGCodeRegex() { - GCodeCommentRegex1 = new Regex(@"\;.*$", RegexCompiledOption); - GCodeCommentRegex2 = new Regex(@"\(([^\)]+)\)", RegexCompiledOption); - GCodeCommentRegex3 = new Regex(@"\;.*\n", RegexCompiledOption); - GCodeNumberRegex = new Regex(@"[0-9]", RegexCompiledOption); - GCodeVariableRegex = new Regex(@"(#[0-9]*)", RegexCompiledOption); - GCodeVariableGroupRegex = new Regex(@"[\[\]\*\+\=\-\/]", RegexCompiledOption); - GCodeKeywordRegex = new Regex(@"(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)", RegexCompiledOption); + GCodeCommentRegex1 = new Regex(@"\;.*$", RegexCompiledOption, TimeSpan.FromSeconds(2)); + GCodeCommentRegex2 = new Regex(@"\(([^\)]+)\)", RegexCompiledOption, TimeSpan.FromSeconds(2)); + GCodeCommentRegex3 = new Regex(@"\;.*\n", RegexCompiledOption, TimeSpan.FromSeconds(2)); + GCodeNumberRegex = new Regex(@"[0-9]", RegexCompiledOption, TimeSpan.FromSeconds(2)); + GCodeVariableRegex = new Regex(@"(#[0-9]*)", RegexCompiledOption, TimeSpan.FromSeconds(2)); + GCodeVariableGroupRegex = new Regex(@"[\[\]\*\+\=\-\/]", RegexCompiledOption, TimeSpan.FromSeconds(2)); + GCodeKeywordRegex = new Regex(@"(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)", RegexCompiledOption, TimeSpan.FromSeconds(2)); } /// From d3d72048dcf5e52caf8e80b3dc01c411bb7d4d10 Mon Sep 17 00:00:00 2001 From: Si Carter Date: Wed, 6 Sep 2023 18:21:12 +0200 Subject: [PATCH 2/5] Sonar issues --- src/GCAAnalyser/GCodeCommand.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/GCAAnalyser/GCodeCommand.cs b/src/GCAAnalyser/GCodeCommand.cs index 89e33142..b0e620bd 100644 --- a/src/GCAAnalyser/GCodeCommand.cs +++ b/src/GCAAnalyser/GCodeCommand.cs @@ -245,6 +245,11 @@ public override bool Equals(object obj) Comment.Equals(command.Comment); } + public override int GetHashCode() + { + return base.GetHashCode(); + } + public override string ToString() { return $"{Command}{CommandValueString}"; From da405a28fac95db68011830197767a70ad139e13 Mon Sep 17 00:00:00 2001 From: Si Carter Date: Wed, 6 Sep 2023 19:20:59 +0200 Subject: [PATCH 3/5] Sonar issues --- src/GCAAnalyser/Analyzers/BaseAnalyzer.cs | 4 +- src/GCSDesktop/Forms/FrmMachine.cs | 17 +-- .../GSendLicenseGenerator.csproj | 14 -- src/GSendLicenseGenerator/Program.cs | 123 ------------------ .../Properties/launchSettings.json | 8 -- 5 files changed, 6 insertions(+), 160 deletions(-) delete mode 100644 src/GSendLicenseGenerator/GSendLicenseGenerator.csproj delete mode 100644 src/GSendLicenseGenerator/Program.cs delete mode 100644 src/GSendLicenseGenerator/Properties/launchSettings.json diff --git a/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs b/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs index acd12e90..31afac66 100644 --- a/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs +++ b/src/GCAAnalyser/Analyzers/BaseAnalyzer.cs @@ -4,14 +4,14 @@ namespace GSendAnalyzer.Analyzers { public class BaseAnalyzer { - protected bool HasCommandsOnSameLine(IGCodeCommand command, char ignoreCommands) + protected static bool HasCommandsOnSameLine(IGCodeCommand command, char ignoreCommands) { var commandsOnLine = CommandsOnSameLine(command); return commandsOnLine.Exists(c => c.Command != ignoreCommands); } - protected List CommandsOnSameLine(IGCodeCommand command) + protected static List CommandsOnSameLine(IGCodeCommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); diff --git a/src/GCSDesktop/Forms/FrmMachine.cs b/src/GCSDesktop/Forms/FrmMachine.cs index b294ab29..a7fc8551 100644 --- a/src/GCSDesktop/Forms/FrmMachine.cs +++ b/src/GCSDesktop/Forms/FrmMachine.cs @@ -30,8 +30,6 @@ using static GSendShared.Constants; -//using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrayNotify; - namespace GSendDesktop.Forms { public partial class FrmMachine : BaseForm, IUiUpdate, IShortcutImplementation @@ -200,8 +198,6 @@ private void ClientWebSocket_ProcessMessage(string message) if (String.IsNullOrWhiteSpace(message)) return; - //Trace.WriteLine($"Client: {message}"); - ClientBaseMessage clientMessage = null; try { @@ -212,9 +208,6 @@ private void ClientWebSocket_ProcessMessage(string message) return; } - //Trace.WriteLine(String.Format("Machine {0} Socket Message: {1}", _machine.Name, clientMessage.success)); - //Trace.WriteLine(message); - if (clientMessage == null) return; @@ -223,8 +216,6 @@ private void ClientWebSocket_ProcessMessage(string message) ProcessFailedMessage(clientMessage); } - string serverCpu = String.Format(GSend.Language.Resources.ServerCpuStateConnected, clientMessage.ServerCpuStatus.ToString("N2")); - switch (clientMessage.request) { case "Stop": @@ -307,7 +298,7 @@ private void ClientWebSocket_ProcessMessage(string message) case "ResponseReceived": case "MessageReceived": - if (clientMessage.message.ToString().StartsWith("<") || _isJogging) + if (clientMessage.message.ToString().StartsWith('<') || _isJogging) { _lastMessageWasHiddenCommand = true; } @@ -360,7 +351,7 @@ private void ClientWebSocket_ProcessMessage(string message) break; case Constants.MessageLineStatusUpdated: - LineStatusUpdateModel lineStatusUpdateModel = (LineStatusUpdateModel)JsonSerializer.Deserialize(clientMessage.message.ToString(), Constants.DefaultJsonSerializerOptions); + LineStatusUpdateModel lineStatusUpdateModel = JsonSerializer.Deserialize(clientMessage.message.ToString(), Constants.DefaultJsonSerializerOptions); if (lineStatusUpdateModel != null && _gcodeLines != null) { @@ -384,7 +375,7 @@ private void ClientWebSocket_ProcessMessage(string message) break; case Constants.MessageInformationUpdate: - InformationMessageModel informationMessageModel = (InformationMessageModel)JsonSerializer.Deserialize(clientMessage.message.ToString(), Constants.DefaultJsonSerializerOptions); + InformationMessageModel informationMessageModel = JsonSerializer.Deserialize(clientMessage.message.ToString(), Constants.DefaultJsonSerializerOptions); if (informationMessageModel != null) { @@ -397,7 +388,7 @@ private void ClientWebSocket_ProcessMessage(string message) break; case Constants.MessageConfigurationUpdated: - ConfigurationUpdatedMessage updateMessage = (ConfigurationUpdatedMessage)JsonSerializer.Deserialize(clientMessage.message.ToString(), Constants.DefaultJsonSerializerOptions); + ConfigurationUpdatedMessage updateMessage = JsonSerializer.Deserialize(clientMessage.message.ToString(), Constants.DefaultJsonSerializerOptions); if (_machine.Name != updateMessage.Name) { diff --git a/src/GSendLicenseGenerator/GSendLicenseGenerator.csproj b/src/GSendLicenseGenerator/GSendLicenseGenerator.csproj deleted file mode 100644 index 4d3d1bb7..00000000 --- a/src/GSendLicenseGenerator/GSendLicenseGenerator.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - Exe - net7.0 - enable - disable - - - - - - - diff --git a/src/GSendLicenseGenerator/Program.cs b/src/GSendLicenseGenerator/Program.cs deleted file mode 100644 index 02f4d3d3..00000000 --- a/src/GSendLicenseGenerator/Program.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System.Text; - -using GSendShared; -using GSendShared.Providers.Internal.Enc; - -namespace GSendLicenseGenerator -{ - internal class Program - { - private const byte LicenseVersion1 = 1; - private const string headerValue = "GSend Pro"; - private static readonly byte[] Header = Encoding.ASCII.GetBytes(headerValue); - private static readonly byte[] key = new byte[] { 239, 191, 189, 86, 239, 191, 107, 33, 239, 191, 189, 239, 189, 92, 8, 35, 93, 107, 50, 239, 19, 239, 189, 239, 191, 189, 239, 189, 239, 34, 239, 189 }; - - - static int Main(string[] args) - { - Environment.SetEnvironmentVariable("GSendProRootPath", - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), Constants.GSendProAppFolder)); - GenerateUniqueSerialNumberInServiceForClientcomputer(); - - CommandLineArgs cmdLineArgs = new(args); - - return ProcessArgs(cmdLineArgs); - } - - private static int ProcessArgs(CommandLineArgs cmdLineArgs) - { - string userName = cmdLineArgs.Get("user", String.Empty); - string dateTime = cmdLineArgs.Get("date", String.Empty); - string uniqueId = cmdLineArgs.Get("id", String.Empty); - - string file = Path.Combine(Environment.GetEnvironmentVariable("GSendProRootPath"), "SerialNo.dat"); - - uniqueId = AesImpl.Decrypt(File.ReadAllText(file), key); - - - if (String.IsNullOrEmpty(userName) || String.IsNullOrEmpty(dateTime)) - { - Console.WriteLine("Invalid args"); - return 1; - } - - string[] idParts = uniqueId.Replace("\\n", "\n").Split('\n', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); - - if (idParts.Length != 5) - return -100; - - DateTime createdDate = new(Convert.ToInt64(idParts[1]), DateTimeKind.Utc); - - TimeSpan timeDiff = DateTime.UtcNow - createdDate; - - if (timeDiff.TotalSeconds > 5000) - return -101; - - DateTime expires = DateTime.UtcNow.Date.AddDays(30); - string license = CreateLicense(1, userName, expires, uniqueId); - Console.WriteLine(license); - - File.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("GSendProRootPath"), "lic.dat"), license); - - string decrypted = AesImpl.Decrypt(File.ReadAllText(Path.Combine(Environment.GetEnvironmentVariable("GSendProRootPath"), "lic.dat")), key); - - return 0; - } - - private static string CreateLicense(in byte version, in string name, in DateTime expires, - in string id) - { - StringBuilder stringBuilder = new(); - - for (int i = 0; i < Header.Length; i++) - stringBuilder.Append((char)Header[i]); - - stringBuilder.Append('\r'); - stringBuilder.Append(version); - stringBuilder.Append('\r'); - stringBuilder.Append(name.Length); - stringBuilder.Append('\r'); - stringBuilder.Append(name); - stringBuilder.Append('\r'); - stringBuilder.Append(expires.Ticks); - stringBuilder.Append('\r'); - stringBuilder.Append(id.Length); - stringBuilder.Append('\r'); - stringBuilder.Append(id); - stringBuilder.Append('\r'); - - return AesImpl.Encrypt(stringBuilder.ToString(), key); - } - - - - - - - - - private static void GenerateUniqueSerialNumberInServiceForClientcomputer() - { - string file = Path.Combine(Environment.GetEnvironmentVariable("GSendProRootPath"), "SerialNo.dat"); - - if (File.Exists(file)) - return; - - char installDrive = Environment.GetEnvironmentVariable("GSendProRootPath")[0]; - DriveInfo drives = DriveInfo.GetDrives().Where(d => d.Name.StartsWith(installDrive)).First(); - - StringBuilder stringBuilder = new(); - stringBuilder.Append(Guid.NewGuid().ToString("N")); - stringBuilder.Append('\n'); - stringBuilder.Append(DateTime.UtcNow.Ticks); - stringBuilder.Append('\n'); - stringBuilder.Append(drives.DriveFormat); - stringBuilder.Append('\n'); - stringBuilder.Append(drives.TotalSize); - stringBuilder.Append('\n'); - stringBuilder.Append(drives.DriveType); - File.WriteAllText(file, AesImpl.Encrypt(stringBuilder.ToString(), key)); - } - - } -} \ No newline at end of file diff --git a/src/GSendLicenseGenerator/Properties/launchSettings.json b/src/GSendLicenseGenerator/Properties/launchSettings.json deleted file mode 100644 index f9257843..00000000 --- a/src/GSendLicenseGenerator/Properties/launchSettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "profiles": { - "GSendLicenseGenerator": { - "commandName": "Project", - "commandLineArgs": "--user:\"Simon Carter\" --date:\"asdf\" --id:\"696def41790b462a8114a76f7c663ebd\\n638225211222536795\\nNTFS\\n499461910528\\nFixed\"" - } - } -} \ No newline at end of file From 9a62987cf6a5c074588ceed369016e9afa787a07 Mon Sep 17 00:00:00 2001 From: Si Carter Date: Wed, 6 Sep 2023 19:21:25 +0200 Subject: [PATCH 4/5] Sonar issues --- src/GCSDesktop/Forms/FrmMachine.cs | 1 - src/GCSDesktop/Forms/StartJobWizard.cs | 3 --- src/GSend.sln | 6 ------ 3 files changed, 10 deletions(-) diff --git a/src/GCSDesktop/Forms/FrmMachine.cs b/src/GCSDesktop/Forms/FrmMachine.cs index a7fc8551..b571f4f8 100644 --- a/src/GCSDesktop/Forms/FrmMachine.cs +++ b/src/GCSDesktop/Forms/FrmMachine.cs @@ -456,7 +456,6 @@ protected override void UpdateEnabledState() mnuMachineLoadGCode.Enabled = _machineStatusModel?.IsRunning == false; mnuMachineClearGCode.Enabled = _machineStatusModel?.IsRunning == false && _gCodeAnalyses != null; - //tabPageServiceSchedule.Enabled = _machineConnected && _machineStatusModel?.IsRunning == false; tabPageSpindle.Enabled = _machineConnected && _machineStatusModel?.IsRunning == false; } diff --git a/src/GCSDesktop/Forms/StartJobWizard.cs b/src/GCSDesktop/Forms/StartJobWizard.cs index 181d4a74..59dd4440 100644 --- a/src/GCSDesktop/Forms/StartJobWizard.cs +++ b/src/GCSDesktop/Forms/StartJobWizard.cs @@ -48,9 +48,6 @@ public StartJobWizard(MachineStateModel machineStatusModel, IGCodeAnalyses gCode _gCodeAnalyses = gCodeAnalyses ?? throw new ArgumentNullException(nameof(gCodeAnalyses)); _gSendApiWrapper = machineApiWrapper ?? throw new ArgumentNullException(nameof(machineApiWrapper)); - if (machineApiWrapper == null) - throw new ArgumentNullException(nameof(machineApiWrapper)); - string jobName = DesktopSettings.ReadValue(nameof(StartJobWizard), Constants.StartWizardSelectedJob, String.Empty); if (!String.IsNullOrEmpty(gCodeAnalyses.JobName)) diff --git a/src/GSend.sln b/src/GSend.sln index c093fbdd..0e896923 100644 --- a/src/GSend.sln +++ b/src/GSend.sln @@ -32,8 +32,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GSendEditor", "GSendEditor\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GSendControls", "GSendControls\GSendControls.csproj", "{DE225549-B4AA-4A8B-BDEC-496C6B9628D0}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GSendLicenseGenerator", "GSendLicenseGenerator\GSendLicenseGenerator.csproj", "{72B5B9AF-4DF3-406B-87E1-8F3FEFDBB5C4}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wwwroot", "wwwroot", "{862EFEB6-17A5-4BD5-80BD-0E4F16AC2192}" ProjectSection(SolutionItems) = preProject ..\wwwroot\Index.html = ..\wwwroot\Index.html @@ -105,10 +103,6 @@ Global {DE225549-B4AA-4A8B-BDEC-496C6B9628D0}.Debug|Any CPU.Build.0 = Debug|Any CPU {DE225549-B4AA-4A8B-BDEC-496C6B9628D0}.Release|Any CPU.ActiveCfg = Release|Any CPU {DE225549-B4AA-4A8B-BDEC-496C6B9628D0}.Release|Any CPU.Build.0 = Release|Any CPU - {72B5B9AF-4DF3-406B-87E1-8F3FEFDBB5C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {72B5B9AF-4DF3-406B-87E1-8F3FEFDBB5C4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {72B5B9AF-4DF3-406B-87E1-8F3FEFDBB5C4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {72B5B9AF-4DF3-406B-87E1-8F3FEFDBB5C4}.Release|Any CPU.Build.0 = Release|Any CPU {6B1A0717-A7CC-47E9-8DEC-F19DC1C40932}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6B1A0717-A7CC-47E9-8DEC-F19DC1C40932}.Debug|Any CPU.Build.0 = Debug|Any CPU {6B1A0717-A7CC-47E9-8DEC-F19DC1C40932}.Release|Any CPU.ActiveCfg = Release|Any CPU From 707a1465e9465052c123ddc74251ce8573902b2b Mon Sep 17 00:00:00 2001 From: Si Carter Date: Wed, 6 Sep 2023 21:24:00 +0200 Subject: [PATCH 5/5] Sonar issues --- README.md | 6 ------ src/GCAAnalyser/GCodeAnalyses.cs | 4 ++-- src/GCSDesktop/Forms/FrmMachine.cs | 28 ++++++---------------------- src/GSendCommon/ClientBaseMessage.cs | 2 ++ src/GSendCommon/ProcessorMediator.cs | 14 ++++++++++---- 5 files changed, 20 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 1c6b3a54..c3528812 100644 --- a/README.md +++ b/README.md @@ -3,12 +3,6 @@ G Code Analyser, Editor and Sender ## Devops -main: ![Build Status main Branch](https://ci.appveyor.com/api/projects/status/eordnrimxkovdwe2/branch/main?svg=true) - -Latest Branch: ![Build Status Latest Build](https://ci.appveyor.com/api/projects/status/eordnrimxkovdwe2?svg=true) - -main: [![CodeQL](https://github.com/k3ldar/GSendPro/actions/workflows/codeql-analysis.yml/badge.svg?branch=main)](https://github.com/k3ldar/GSendPro/actions/workflows/codeql-analysis.yml) - [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=vulnerabilities)](https://sonarcloud.io/summary/overall?id=k3ldar_GSendPro) [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=bugs)](https://sonarcloud.io/summary/overalloverall?id=k3ldar_GSendPro) [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=code_smells)](https://sonarcloud.io/summary/overall?id=k3ldar_GSendPro) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=reliability_rating)](https://sonarcloud.io/summary/overall?id=k3ldar_GSendPro) [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=sqale_rating)](https://sonarcloud.io/summary/overall?id=k3ldar_GSendPro) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=security_rating)](https://sonarcloud.io/summary/overall?id=k3ldar_GSendPro) [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=k3ldar_GSendPro&metric=sqale_index)](https://sonarcloud.io/summary/overall?id=k3ldar_GSendPro) diff --git a/src/GCAAnalyser/GCodeAnalyses.cs b/src/GCAAnalyser/GCodeAnalyses.cs index 913ec00f..bc460c3e 100644 --- a/src/GCAAnalyser/GCodeAnalyses.cs +++ b/src/GCAAnalyser/GCodeAnalyses.cs @@ -211,7 +211,7 @@ public List Lines(out int lineCount) Result.Add(currentLine); } - currentLine.Commands.Add(command); + currentLine?.Commands.Add(command); } return Result; @@ -233,7 +233,7 @@ public List AllLines(out int lineCount) Result.Add(currentLine); } - currentLine.Commands.Add(command); + currentLine?.Commands.Add(command); } return Result; diff --git a/src/GCSDesktop/Forms/FrmMachine.cs b/src/GCSDesktop/Forms/FrmMachine.cs index b571f4f8..6c16e787 100644 --- a/src/GCSDesktop/Forms/FrmMachine.cs +++ b/src/GCSDesktop/Forms/FrmMachine.cs @@ -499,14 +499,6 @@ private void UpdateMachineStatus(MachineStateModel status) } } - //if (!_updatingRapidOverride && selectionOverrideRapids.Value != (int)status.RapidSpeed) - //{ - // selectionOverrideRapids.ValueChanged -= SelectionOverrideRapids_ValueChanged; - // selectionOverrideRapids.Value = (int)status.RapidSpeed; - // selectionOverrideRapids.LabelValue = HelperMethods.TranslateRapidOverride(status.RapidSpeed); - // selectionOverrideRapids.ValueChanged += SelectionOverrideRapids_ValueChanged; - //} - if (status.IsConnected) { machine2dView1.XPosition = (float)status.WorkX; @@ -572,7 +564,7 @@ private void UpdateMachineStatus(MachineStateModel status) _isRunning = status.IsRunning || status.MachineState == MachineState.Run; _isJogging = status.MachineState == MachineState.Jog; _isAlarm = status.IsLocked; - toolStripProgressBarJob.Visible = status == null ? false : status.IsConnected && status.IsRunning; + toolStripProgressBarJob.Visible = status != null && status.IsConnected && status.IsRunning; toolStripProgressBarJob.Value = status.LineNumber; @@ -916,7 +908,6 @@ private void SelectionOverrideRapids_ValueChanged(object sender, EventArgs e) { if (selectionOverrideRapids.Checked) { - //_updatingRapidOverride = true; _machineUpdateThread.Overrides.Rapids = (RapidsOverride)selectionOverrideRapids.Value; } else @@ -1014,8 +1005,6 @@ private void OverrideAxis_Checked(object sender, EventArgs e) protected override void WndProc(ref Message m) { - //_shortcutHandler.WndProc(ref m); - base.WndProc(ref m); } @@ -1142,7 +1131,7 @@ private void ValidateLaserSpindleMode(MachineStateModel status) switch (_machine.MachineType) { case MachineType.CNC: - if (status.UpdatedGrblConfiguration.Any(s => s.DollarValue.Equals(32) && s.OldValue.Equals("0") && s.NewValue.Equals("1"))) + if (status.UpdatedGrblConfiguration.Exists(s => s.DollarValue.Equals(32) && s.OldValue.Equals("0") && s.NewValue.Equals("1"))) { warningsAndErrors.AddWarningPanel(InformationType.Information, GSend.Language.Resources.AutomaticallySelectedSpindleMode); _machine.Settings.LaserModeEnabled = false; @@ -1154,7 +1143,7 @@ private void ValidateLaserSpindleMode(MachineStateModel status) break; case MachineType.Laser: - if (status.UpdatedGrblConfiguration.Any(s => s.DollarValue.Equals(32) && s.OldValue.Equals("1") && s.NewValue.Equals("2"))) + if (status.UpdatedGrblConfiguration.Exists(s => s.DollarValue.Equals(32) && s.OldValue.Equals("1") && s.NewValue.Equals("2"))) { warningsAndErrors.AddWarningPanel(InformationType.Information, GSend.Language.Resources.AutomaticallySelectedLaserMode); _machine.Settings.LaserModeEnabled = true; @@ -1331,7 +1320,7 @@ private void btnGrblCommandSend_Click(object sender, EventArgs e) string command = txtUserGrblCommand.Text.Replace(":", "\t").Trim(); - if (txtUserGrblCommand.Text.StartsWith("$") || txtUserGrblCommand.Text == "?") + if (txtUserGrblCommand.Text.StartsWith('$') || txtUserGrblCommand.Text == "?") SendMessage(String.Format(Constants.MessageMachineWriteLineR, _machine.Id, command)); else SendMessage(String.Format(Constants.MessageMachineWriteLine, _machine.Id, command)); @@ -1555,7 +1544,6 @@ private void ConfigureMachine() selectionOverrideZDown.EnabledChanged += OverrideAxis_Checked; selectionOverrideSpindle.EnabledChanged += OverrideAxis_Checked; - //trackBarPercent.ValueChanged -= trackBarPercent_ValueChanged; selectionOverrideRapids.ValueChanged -= SelectionOverrideRapids_ValueChanged; selectionOverrideXY.ValueChanged -= SelectionOverride_ValueChanged; selectionOverrideZDown.ValueChanged -= SelectionOverride_ValueChanged; @@ -1576,7 +1564,6 @@ private void ConfigureMachine() cbSoftStart.Checked = _machine.SoftStart; trackBarDelaySpindle.Value = Shared.Utilities.CheckMinMax(_machine.SoftStartSeconds, trackBarDelaySpindle.Minimum, trackBarDelaySpindle.Maximum); - //trackBarPercent.ValueChanged += trackBarPercent_ValueChanged; selectionOverrideRapids.ValueChanged += SelectionOverrideRapids_ValueChanged; selectionOverrideXY.ValueChanged += SelectionOverride_ValueChanged; selectionOverrideZDown.ValueChanged += SelectionOverride_ValueChanged; @@ -1586,7 +1573,6 @@ private void ConfigureMachine() // spindle trackBarSpindleSpeed.Maximum = (int)_machine.Settings.MaxSpindleSpeed; trackBarSpindleSpeed.Minimum = (int)_machine.Settings.MinSpindleSpeed; - //trackBarSpindleSpeed.TickFrequency = trackBarSpindleSpeed.Value = trackBarSpindleSpeed.Maximum; cbSpindleCounterClockwise.Checked = _machine.Options.HasFlag(MachineOptions.SpindleCounterClockWise); cmbSpindleType.SelectedItem = _machine.SpindleType; @@ -1686,7 +1672,6 @@ private void HookUpEvents() mnuViewJog.Click += SelectTabControlMainTab; mnuViewSpindle.Tag = tabPageSpindle; mnuViewSpindle.Click += SelectTabControlMainTab; - //mnuViewServiceSchedule.Tag = tabPageServiceSchedule; mnuViewServiceSchedule.Click += SelectTabControlMainTab; mnuViewMachineSettings.Tag = tabPageMachineSettings; mnuViewMachineSettings.Click += SelectTabControlMainTab; @@ -1724,7 +1709,6 @@ protected override void LoadResources() //tab pages tabPageMain.Text = GSend.Language.Resources.General; tabPageOverrides.Text = GSend.Language.Resources.Overrides; - //tabPageServiceSchedule.Text = GSend.Language.Resources.ServiceSchedule; tabPageMachineSettings.Text = GSend.Language.Resources.GrblSettings; tabPageSpindle.Text = GSend.Language.Resources.Spindle; tabPageSettings.Text = GSend.Language.Resources.Settings; @@ -2430,7 +2414,7 @@ private void UpdateShortcutKeyValues(List Result) } } - if (shortcut != null && shortcut.KeysUpdated != null) + if (shortcut.KeysUpdated != null) shortcut.KeysUpdated(shortcut.DefaultKeys); } } @@ -2439,7 +2423,7 @@ private void RecursivelyRetrieveAllShortcutClasses(Control control, List 25) { - + return; } if (control is IShortcutImplementation shortcutImpl) diff --git a/src/GSendCommon/ClientBaseMessage.cs b/src/GSendCommon/ClientBaseMessage.cs index 14e6bd86..609e2480 100644 --- a/src/GSendCommon/ClientBaseMessage.cs +++ b/src/GSendCommon/ClientBaseMessage.cs @@ -30,7 +30,9 @@ public ClientBaseMessage(string req, object msg) public bool IsConnected { get; set; } +#if __LICENSED__ public bool IsLicensed { get; set; } +#endif public long CombinedHash { get; set; } } diff --git a/src/GSendCommon/ProcessorMediator.cs b/src/GSendCommon/ProcessorMediator.cs index 9995dd81..bdc0c18f 100644 --- a/src/GSendCommon/ProcessorMediator.cs +++ b/src/GSendCommon/ProcessorMediator.cs @@ -19,12 +19,14 @@ namespace GSendCommon { public class ProcessorMediator : IProcessorMediator, INotificationListener { - internal static bool _isLicensed = true; + internal readonly static bool _isLicensed = true; +#if __LICENSED__ private static DateTime _lastLicenseCheck = DateTime.MinValue; + private const int LicenseValidationCheckInterval = 250; +#endif private static readonly List _machines = new(); private const int BufferSize = 8192; private const int DelayBetweenUpdatesSent = 100; - private const int LicenseValidationCheckInterval = 250; private DateTime _lastSendStatus = DateTime.MinValue; private readonly object _lockObject = new(); private readonly ILogger _logger; @@ -481,9 +483,12 @@ private byte[] ProcessRequest(string request) request = request, ServerCpuStatus = ThreadManager.CpuUsage, Identifier = $"{_clientId}:{_messageId++}", +#if __LICENSED__ IsLicensed = _isLicensed, +#endif }; +#if __LICENSED__ TimeSpan timeFromLastLicenseCheck = DateTime.UtcNow - _lastLicenseCheck; if (timeFromLastLicenseCheck.TotalMinutes > 5) @@ -496,6 +501,7 @@ private byte[] ProcessRequest(string request) _lastLicenseCheck = DateTime.UtcNow; } +#endif if (_isLicensed) { @@ -931,7 +937,7 @@ private byte[] ProcessRequest(string request) return json; } - private void UpdateCombinedMachineHash() + private static void UpdateCombinedMachineHash() { long newHash = 0; @@ -947,6 +953,6 @@ private void UpdateCombinedMachineHash() _machineCombinedHash = newHash; } - #endregion Private Methods +#endregion Private Methods } }