Skip to content

Commit

Permalink
Added validation for Process Name. (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
Taron-art authored Jan 7, 2025
1 parent 7877773 commit 070799c
Show file tree
Hide file tree
Showing 12 changed files with 260 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
using Affinity_manager.Model;
using Affinity_manager.Model.CRUD;
using Microsoft.Win32;
Expand Down Expand Up @@ -48,18 +50,18 @@ public void OneTimeTearDown()
[Test]
public void CleanWithoutServiceRestart_ThenAllRelatedItemsFromRegistryAreRemoved()
{
ProcessConfiguration configuration = new(TestContext.CurrentContext.Random.GetString())
ProcessConfiguration configuration = new(TestContext.CurrentContext.Random.GetString() + ".exe")
{
IoPriority = IoPriority.High
};

ProcessConfiguration configuration1 = new(TestContext.CurrentContext.Random.GetString())
ProcessConfiguration configuration1 = new(TestContext.CurrentContext.Random.GetString() + ".exe")
{
CpuPriority = CpuPriorityClass.High,
CpuAffinityMask = 1234
};

ProcessConfiguration configuration2 = new(TestContext.CurrentContext.Random.GetString())
ProcessConfiguration configuration2 = new(TestContext.CurrentContext.Random.GetString() + ".exe")
{
CpuAffinityMask = 1U
};
Expand All @@ -71,5 +73,17 @@ public void CleanWithoutServiceRestart_ThenAllRelatedItemsFromRegistryAreRemoved

Assert.That(repository.Get(), Is.Empty);
}

[Test]
public void SaveAndRestartServiceAsync_ThrowsIfInvalid()
{
ProcessConfiguration configuration = new(TestContext.CurrentContext.Random.GetString())
{
CpuAffinityMask = 1U
};

ProcessConfigurationsRepository repository = new();
Assert.ThrowsAsync<ValidationException>(() => repository.SaveAndRestartServiceAsync([configuration]));
}
}
}
45 changes: 40 additions & 5 deletions src/PPM.Application.Tests/ViewModels/MainPageViewModelTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Affinity_manager.Exceptions;
using Affinity_manager.Model;
Expand Down Expand Up @@ -33,7 +32,7 @@ public void SetUp()
public void Add_ShouldAddNewProcessConfigurationView_WhenProcessNameIsValid()
{
// Arrange
_viewModel.NewProcessName = "TestProcess";
_viewModel.NewProcessName = "TestProcess.exe";
ProcessConfiguration processConfiguration = new("TestProcess");
ProcessConfigurationView processConfigurationView = new(processConfiguration, A.Fake<IOptionsProvider>());
A.CallTo(() => _viewFactory.Create(A<ProcessConfiguration>.Ignored)).Returns(processConfigurationView);
Expand All @@ -48,7 +47,7 @@ public void Add_ShouldAddNewProcessConfigurationView_WhenProcessNameIsValid()
}

[Test]
public void Add_ShouldNotAddNewProcessConfigurationView_WhenProcessNameIsInvalid()
public void Add_ShouldNotAddNewProcessConfigurationView_WhenProcessNameIsEmpty()
{
// Arrange
_viewModel.NewProcessName = " ";
Expand All @@ -60,6 +59,23 @@ public void Add_ShouldNotAddNewProcessConfigurationView_WhenProcessNameIsInvalid
Assert.That(_viewModel.ProcessesConfigurations, Is.Empty);
}

[Test]
public void Add_ShouldNotAddNewProcessConfigurationView_WhenProcessNameIsInvalud()
{
// Arrange
_viewModel.NewProcessName = "testexe";

using var monitor = _viewModel.Monitor();

// Act
_viewModel.Add();

// Assert
Assert.That(_viewModel.ProcessesConfigurations, Is.Empty);

monitor.Should().Raise(nameof(_viewModel.ShowMessage));
}

[Test]
public async Task SaveChangesAsync_ShouldSaveDirtyProcessConfigurations()
{
Expand Down Expand Up @@ -157,7 +173,26 @@ public void SaveChangesAsync_ShouldShowMessage_WhenServiceNotInstalledExceptionI
Assert.DoesNotThrowAsync(() => _viewModel.SaveChangesAsync());
A.CallTo(() => _repository.SaveAndRestartServiceAsync(A<IEnumerable<ProcessConfiguration>>.Ignored, A<Func<Task>>.Ignored)).MustHaveHappened();

monitor.Should().Raise(nameof(_viewModel.ShowMessage)).WithArgs<string>((message) => message.Contains("Service"));
monitor.Should().Raise(nameof(_viewModel.ShowMessage))
.WithArgs<string>((message) => message.Equals(Affinity_manager.Strings.PPM.ServiceNotFountErrorMessage));
}

[Test]
[SetUICulture("en-US")]
public void SaveChangesAsync_ShouldShowMessage_WhenValidationExceptionIsThrown()
{
// Arrange
string message = TestContext.CurrentContext.Random.GetString();
A.CallTo(() => _repository.SaveAndRestartServiceAsync(A<IEnumerable<ProcessConfiguration>>.Ignored, A<Func<Task>>.Ignored))
.Throws(new ValidationException(message));
using FluentAssertions.Events.IMonitor<MainPageViewModel> monitor = _viewModel.Monitor();

// Act & Assert
Assert.DoesNotThrowAsync(() => _viewModel.SaveChangesAsync());
A.CallTo(() => _repository.SaveAndRestartServiceAsync(A<IEnumerable<ProcessConfiguration>>.Ignored, A<Func<Task>>.Ignored)).MustHaveHappened();

monitor.Should().Raise(nameof(_viewModel.ShowMessage))
.WithArgs<string>((message) => message.Equals(message));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void DisplayName_ShouldReturnCorrectDisplayName()

string displayName = wrapper.DisplayName;

Assert.That(displayName, Is.EqualTo("Normal"));
Assert.That(displayName, Is.EqualTo(Affinity_manager.Strings.PPM.GetString("IoPriority/Normal")));
}

[Test]
Expand Down
16 changes: 16 additions & 0 deletions src/PPM.Application/Model/CRUD/ProcessConfigurationsRepository.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
using Affinity_manager.Exceptions;
Expand All @@ -23,6 +25,9 @@ public void Save(IEnumerable<ProcessConfiguration> items)

public async Task SaveAndRestartServiceAsync(IEnumerable<ProcessConfiguration> items, Func<Task>? readyToGetCallback = null)
{
ProcessConfiguration[] itemsArray = items.ToArray();
ThrowIfHaveInvalidNonEmptyItems(itemsArray);

await Task.Run(() => _processAffinitiesManager.SaveToRegistry(items));

// We want UI to be responsive, so we restart the service in the background while UI performing a callback.
Expand All @@ -48,6 +53,9 @@ public void CleanWithoutServiceRestart()

private void Save(IEnumerable<ProcessConfiguration> items, bool restartService)
{
ProcessConfiguration[] itemsArray = items.ToArray();
ThrowIfHaveInvalidNonEmptyItems(itemsArray);

_processAffinitiesManager.SaveToRegistry(items);
if (restartService)
{
Expand All @@ -74,5 +82,13 @@ private void RestartService()
ServiceNotInstalledException.ThrowFromInvalidOperationException(e, ServiceName);
}
}

private static void ThrowIfHaveInvalidNonEmptyItems(ProcessConfiguration[] itemsArray)
{
if (itemsArray.Any((item) => item.HasErrors && !item.IsEmpty)) // We are passing empty values since they won't introduce invalid items.
{
throw new ValidationException("At least one of the items is invalid.");
}
}
}
}
5 changes: 4 additions & 1 deletion src/PPM.Application/Model/ProcessConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System.ComponentModel.DataAnnotations;
using CommunityToolkit.Mvvm.ComponentModel;

namespace Affinity_manager.Model
{
public sealed partial class ProcessConfiguration : ObservableObject
public sealed partial class ProcessConfiguration : ObservableValidator
{
public const ulong AffinityDefaultValue = ulong.MaxValue;
public const CpuPriorityClass CpuPriorityDefaultValue = CpuPriorityClass.Normal;
Expand All @@ -21,8 +22,10 @@ public ProcessConfiguration(string name)
{
Name = name;
IoPriority = IoPriority.Normal;
ValidateAllProperties();
}

[FileExtensions(Extensions = ".exe", ErrorMessageResourceType = typeof(Strings.Validation), ErrorMessageResourceName = nameof(Strings.Validation.ProcessNameMustHaveExeExtension))]
public string Name { get; }


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,23 @@
<source>Cancel</source>
<target state="final">Відмінити</target>
</trans-unit>
<trans-unit id="UnknownErrorMessage" translate="yes" xml:space="preserve">
<source>Unknown error.</source>
<target state="final">Невідома помилка.</target>
</trans-unit>
</group>
</body>
</file>
<file datatype="xml" source-language="en-US" target-language="uk-UA" original="PPM.APPLICATION/STRINGS/EN-US/VALIDATION.RESW" tool-id="MultilingualAppToolkit" product-name="n/a" product-version="n/a" build-num="n/a">
<header>
<tool tool-id="MultilingualAppToolkit" tool-name="Multilingual App Toolkit" tool-version="1.0.0.0" tool-company="Microsoft" />
</header>
<body>
<group id="PPM.APPLICATION/STRINGS/EN-US/VALIDATION.RESW" datatype="resx">
<trans-unit id="ProcessNameMustHaveExeExtension" translate="yes" xml:space="preserve">
<source>Process Name must have ".exe" extension.</source>
<target state="final">Назва застосунка мусить мати розширення ".exe".</target>
</trans-unit>
</group>
</body>
</file>
Expand Down
5 changes: 5 additions & 0 deletions src/PPM.Application/PPM.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -353,4 +353,9 @@
<ItemGroup>
<XliffResource Include="MultilingualResources\PPM.Application.uk-UA.xlf" />
</ItemGroup>
<ItemGroup>
<PRIResource Update="Strings\en-us\Validation.resw">
<Generator>ReswPlusAdvancedGenerator</Generator>
</PRIResource>
</ItemGroup>
</Project>
3 changes: 3 additions & 0 deletions src/PPM.Application/Strings/en-us/PPM.resw
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,7 @@
<data name="Cancel" xml:space="preserve">
<value>Cancel</value>
</data>
<data name="UnknownErrorMessage" xml:space="preserve">
<value>Unknown error.</value>
</data>
</root>
123 changes: 123 additions & 0 deletions src/PPM.Application/Strings/en-us/Validation.resw
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ProcessNameMustHaveExeExtension" xml:space="preserve">
<value>Process Name must have ".exe" extension.</value>
</data>
</root>
3 changes: 3 additions & 0 deletions src/PPM.Application/Strings/uk-UA/PPM.resw
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,7 @@
<data name="Cancel" xml:space="preserve">
<value>Відмінити</value>
</data>
<data name="UnknownErrorMessage" xml:space="preserve">
<value>Невідома помилка.</value>
</data>
</root>
18 changes: 18 additions & 0 deletions src/PPM.Application/Strings/uk-UA/Validation.resw
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ProcessNameMustHaveExeExtension" xml:space="preserve">
<value>Назва застосунка мусить мати розширення ".exe".</value>
</data>
</root>
Loading

0 comments on commit 070799c

Please sign in to comment.