extend Registry handling capabilities in preparation for Registry settings

Enhanced the functionality of Registry handling in preparation for managing Registry settings
This commit is contained in:
Schmitti91
2024-01-23 12:54:43 +01:00
parent 45149d6547
commit 5f5700b948
14 changed files with 1240 additions and 160 deletions

View File

@@ -1,17 +1,21 @@
using Microsoft.Win32; using Microsoft.Win32;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry namespace mRemoteNG.Tools.WindowsRegistry
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
/// <summary>
/// Interface for the Registry class providing methods for interacting with the Windows Registry.
/// </summary>
public interface IRegistry public interface IRegistry
{ {
#region registry reader #region registry reader
string[] GetSubKeyNames(RegistryHive hive, string path); string[] GetSubKeyNames(RegistryHive hive, string path);
string GetPropertyValue(WindowsRegistryKey key);
Optional<string> GetPropertyValue(WindowsRegistryKey key); string GetPropertyValue(RegistryHive hive, string path, string name);
Optional<string> GetPropertyValue(RegistryHive hive, string path, string name); bool GetBoolValue(RegistryHive hive, string path, string propertyName, bool defaultValue = false);
WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name); WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name);
WindowsRegistryKey GetWindowsRegistryKey(WindowsRegistryKey key); WindowsRegistryKey GetWindowsRegistryKey(WindowsRegistryKey key);
@@ -24,12 +28,15 @@ namespace mRemoteNG.Tools.WindowsRegistry
#region registry writer #region registry writer
void SetRegistryValue(WindowsRegistryKey key); void SetRegistryValue(WindowsRegistryKey key);
void SetRegistryValue(RegistryHive hive, string path, string name, object value, RegistryValueKind valueKind); void SetRegistryValue(RegistryHive hive, string path, string name, object value, RegistryValueKind valueKind);
void DeleteRegistryKey(RegistryHive hive, string path, bool ignoreNotFound = false);
#endregion #endregion
#region converter #region registry tools
RegistryHive ConvertStringToRegistryHive(string hiveString); RegistryHive ConvertStringToRegistryHive(string hiveString);
RegistryValueKind ConvertStringToRegistryValueKind(string valueType); RegistryValueKind ConvertStringToRegistryValueKind(string valueType);
RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType);
Type ConvertRegistryValueKindToType(RegistryValueKind valueKind);
#endregion #endregion
} }
} }

View File

@@ -0,0 +1,53 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using static mRemoteNG.Config.Settings.Registry.RegistryController;
namespace mRemoteNG.Tools.WindowsRegistry
{
[SupportedOSPlatform("windows")]
/// <summary>
/// Interface for the RegistryWorker class providing functionality to interact with the Windows Registry to retrieve registry settings.
/// </summary>
public interface IRegistryAdvanced
{
#region WindowsRegistry reader
string[] GetSubKeyNames(RegistryHive hive, string path);
string GetPropertyValue(WindowsRegistryKey key);
string GetPropertyValue(RegistryHive hive, string path, string name);
WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name);
WindowsRegistryKey GetWindowsRegistryKey(WindowsRegistryKey key);
List<WindowsRegistryKey> GetRegistryEntries(RegistryHive hive, string path);
List<WindowsRegistryKey> GetRegistryEntryiesRecursive(RegistryHive hive, string path);
#endregion
#region WindowsRegistry writer
void SetRegistryValue(WindowsRegistryKey key);
void SetRegistryValue(RegistryHive hive, string path, string name, object value, RegistryValueKind valueKind);
void DeleteRegistryKey(RegistryHive hive, string path, bool ignoreNotFound = false);
#endregion
#region WindowsRegistry tools
RegistryHive ConvertStringToRegistryHive(string hiveString);
RegistryValueKind ConvertStringToRegistryValueKind(string valueType);
RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType);
Type ConvertRegistryValueKindToType(RegistryValueKind valueKind);
#endregion
#region WindowsRegistryAdvanced GetInteger
WindowsRegistryKeyInteger GetInteger(RegistryHive hive, string path, string propertyName, int? defaultValue = null);
#endregion
#region WindowsRegistryAdvanced GetString
WindowsRegistryKeyString GetString(RegistryHive hive, string path, string propertyName, string defaultValue = null);
WindowsRegistryKeyString GetStringValidated(RegistryHive hive, string path, string propertyName, string[] allowedValues, bool caseSensitive = false, string defaultValue = null);
#endregion
#region WindowsRegistryAdvanced GetBoolean
WindowsRegistryKeyBoolean GetBoolean(RegistryHive hive, string path, string propertyName, bool? defaultValue = null);
#endregion
}
}

View File

@@ -0,0 +1,47 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using static mRemoteNG.Config.Settings.Registry.RegistryController;
namespace mRemoteNG.Tools.WindowsRegistry
{
[SupportedOSPlatform("windows")]
/// <summary>
/// Interface for the RegistryWorker class providing functionality to interact with the Windows Registry to retrieve registry settings.
/// </summary>
public interface IRegistryAdvancedRead
{
#region WindowsRegistry reader
string[] GetSubKeyNames(RegistryHive hive, string path);
string GetPropertyValue(WindowsRegistryKey key);
string GetPropertyValue(RegistryHive hive, string path, string name);
WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name);
WindowsRegistryKey GetWindowsRegistryKey(WindowsRegistryKey key);
List<WindowsRegistryKey> GetRegistryEntries(RegistryHive hive, string path);
List<WindowsRegistryKey> GetRegistryEntryiesRecursive(RegistryHive hive, string path);
#endregion
#region WindowsRegistry tools
RegistryHive ConvertStringToRegistryHive(string hiveString);
RegistryValueKind ConvertStringToRegistryValueKind(string valueType);
RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType);
Type ConvertRegistryValueKindToType(RegistryValueKind valueKind);
#endregion
#region WindowsRegistryAdvanced GetInteger
WindowsRegistryKeyInteger GetInteger(RegistryHive hive, string path, string propertyName, int? defaultValue = null);
#endregion
#region WindowsRegistryAdvanced GetString
WindowsRegistryKeyString GetString(RegistryHive hive, string path, string propertyName, string defaultValue = null);
WindowsRegistryKeyString GetStringValidated(RegistryHive hive, string path, string propertyName, string[] allowedValues, bool caseSensitive = false, string defaultValue = null);
#endregion
#region WindowsRegistryAdvanced GetBoolean
WindowsRegistryKeyBoolean GetBoolean(RegistryHive hive, string path, string propertyName, bool? defaultValue = null);
#endregion
}
}

View File

@@ -6,13 +6,17 @@ using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry namespace mRemoteNG.Tools.WindowsRegistry
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
/// <summary>
/// Interface for the Registry class providing methods for interacting with read actions in the Windows Registry.
/// </summary>
public interface IRegistryRead public interface IRegistryRead
{ {
#region registry reader #region registry reader
string[] GetSubKeyNames(RegistryHive hive, string path); string[] GetSubKeyNames(RegistryHive hive, string path);
Optional<string> GetPropertyValue(WindowsRegistryKey key); string GetPropertyValue(WindowsRegistryKey key);
Optional<string> GetPropertyValue(RegistryHive hive, string path, string name); string GetPropertyValue(RegistryHive hive, string path, string name);
bool GetBoolValue(RegistryHive hive, string path, string propertyName, bool defaultValue = false);
WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name); WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name);
WindowsRegistryKey GetWindowsRegistryKey(WindowsRegistryKey key); WindowsRegistryKey GetWindowsRegistryKey(WindowsRegistryKey key);
@@ -20,10 +24,12 @@ namespace mRemoteNG.Tools.WindowsRegistry
List<WindowsRegistryKey> GetRegistryEntries(RegistryHive hive, string path); List<WindowsRegistryKey> GetRegistryEntries(RegistryHive hive, string path);
List<WindowsRegistryKey> GetRegistryEntryiesRecursive(RegistryHive hive, string path); List<WindowsRegistryKey> GetRegistryEntryiesRecursive(RegistryHive hive, string path);
#endregion #endregion
#region converter #region registry tools
RegistryHive ConvertStringToRegistryHive(string hiveString); RegistryHive ConvertStringToRegistryHive(string hiveString);
RegistryValueKind ConvertStringToRegistryValueKind(string valueType); RegistryValueKind ConvertStringToRegistryValueKind(string valueType);
RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType);
Type ConvertRegistryValueKindToType(RegistryValueKind valueKind);
#endregion #endregion
} }
} }

View File

@@ -1,9 +1,13 @@
using Microsoft.Win32; using Microsoft.Win32;
using System;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry namespace mRemoteNG.Tools.WindowsRegistry
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
/// <summary>
/// Interface for the Registry class providing methods for interacting with write actions in the Windows Registry.
/// </summary>
public interface IRegistryWrite public interface IRegistryWrite
{ {
#region registry writer #region registry writer
@@ -12,9 +16,11 @@ namespace mRemoteNG.Tools.WindowsRegistry
#endregion #endregion
#region converter #region registry tools
RegistryHive ConvertStringToRegistryHive(string hiveString); RegistryHive ConvertStringToRegistryHive(string hiveString);
RegistryValueKind ConvertStringToRegistryValueKind(string valueType); RegistryValueKind ConvertStringToRegistryValueKind(string valueType);
#endregion} RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType);
Type ConvertRegistryValueKindToType(RegistryValueKind valueKind);
#endregion
} }
} }

View File

@@ -40,7 +40,7 @@ namespace mRemoteNG.Tools.WindowsRegistry
/// </summary> /// </summary>
/// <param name="key">The WindowsRegistryKey containing information about the registry property.</param> /// <param name="key">The WindowsRegistryKey containing information about the registry property.</param>
/// <returns>An Optional<string> containing the property value, or Optional<string>.Empty if the value is not found.</returns> /// <returns>An Optional<string> containing the property value, or Optional<string>.Empty if the value is not found.</returns>
public Optional<string> GetPropertyValue(WindowsRegistryKey key) public string GetPropertyValue(WindowsRegistryKey key)
{ {
if (!key.IsKeyReadable()) if (!key.IsKeyReadable())
throw new InvalidOperationException("The Windows Registry key is not ready for reading."); throw new InvalidOperationException("The Windows Registry key is not ready for reading.");
@@ -55,7 +55,7 @@ namespace mRemoteNG.Tools.WindowsRegistry
/// <param name="path">The path to the registry key containing the property.</param> /// <param name="path">The path to the registry key containing the property.</param>
/// <param name="name">The name of the property to retrieve.</param> /// <param name="name">The name of the property to retrieve.</param>
/// <returns>An Optional<string> containing the property value, or Optional<string>.Empty if the value is not found.</returns> /// <returns>An Optional<string> containing the property value, or Optional<string>.Empty if the value is not found.</returns>
public Optional<string> GetPropertyValue(RegistryHive hive, string path, string name) public string GetPropertyValue(RegistryHive hive, string path, string name)
{ {
if (hive == 0) if (hive == 0)
throw new ArgumentException("Unknown or unsupported RegistryHive value.", nameof(hive)); throw new ArgumentException("Unknown or unsupported RegistryHive value.", nameof(hive));
@@ -65,12 +65,41 @@ namespace mRemoteNG.Tools.WindowsRegistry
using (var key = OpenSubKey(hive, path)) using (var key = OpenSubKey(hive, path))
{ {
if (!key.Any()) if (!key.Any())
return Optional<string>.Empty; return null;
return key.First().GetValue(name) as string; var keyValue = key.First().GetValue(name);
if (keyValue == null)
return null;
return keyValue.ToString();
} }
} }
/// <summary>
/// Gets a boolean value from the Windows Registry based on the specified registry path and property name.
/// If the value is not found or cannot be parsed, it returns a specified default value.
/// </summary>
/// <param name="hive">The Registry hive where the value is located.</param>
/// <param name="path">The registry path to the key containing the property.</param>
/// <param name="propertyName">The name of the property to retrieve.</param>
/// <param name="defaultValue">The default value to return if the property is not found or cannot be parsed. Default is false.</param>
/// <returns>The boolean value of the specified property or the default value if not found or cannot be parsed.</returns>
public bool GetBoolValue(RegistryHive hive, string path, string propertyName, bool defaultValue = false)
{
var value = GetPropertyValue(hive, path, propertyName);
if (!string.IsNullOrEmpty(value))
{
if (int.TryParse(value, out int intValue))
return intValue == 1;
if (bool.TryParse(value, out bool boolValue))
return boolValue;
}
return defaultValue;
}
/// <summary> /// <summary>
/// Retrieves a WindowsRegistryKey object for a specific registry hive, path, and value name. /// Retrieves a WindowsRegistryKey object for a specific registry hive, path, and value name.
/// </summary> /// </summary>
@@ -80,7 +109,7 @@ namespace mRemoteNG.Tools.WindowsRegistry
/// <returns>A WindowsRegistryKey object representing the specified registry key and value.</returns> /// <returns>A WindowsRegistryKey object representing the specified registry key and value.</returns>
public WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name) public WindowsRegistryKey GetWindowsRegistryKey(RegistryHive hive, string path, string name)
{ {
WindowsRegistryKey key = new WindowsRegistryKey WindowsRegistryKey key = new()
{ {
Hive = hive, Hive = hive,
Path = path, Path = path,
@@ -108,8 +137,7 @@ namespace mRemoteNG.Tools.WindowsRegistry
if (value != null) if (value != null)
key.Value = value.ToString(); key.Value = value.ToString();
RegistryValueKind ValueKind; if (TestValueKindExists(subKey, key.Name, out RegistryValueKind ValueKind))
if (TestValueKindExists(subKey, key.Name, out ValueKind))
key.ValueKind = ValueKind; key.ValueKind = ValueKind;
} }
} }
@@ -212,6 +240,32 @@ namespace mRemoteNG.Tools.WindowsRegistry
{ {
CreateOrSetRegistryValue(key); CreateOrSetRegistryValue(key);
} }
/// <summary>
/// Deletes a registry key and its subkeys.
/// </summary>
/// <param name="hive">The registry hive to open.</param>
/// <param name="path">The path of the registry key to delete.</param>
/// <param name="ignoreNotFound">Set to true to ignore if the key is not found.</param>
public void DeleteRegistryKey(RegistryHive hive, string path, bool ignoreNotFound = false)
{
try
{
using (RegistryKey key = RegistryKey.OpenBaseKey(hive, RegistryView.Default))
{
if (key != null)
{
key.DeleteSubKeyTree(path, ignoreNotFound);
}
}
}
catch (Exception ex)
{
// Handle any exceptions according to your requirements
Console.WriteLine($"Error deleting registry key: {ex.Message}");
throw;
}
}
#endregion #endregion
#region public methods #region public methods
@@ -304,6 +358,69 @@ namespace mRemoteNG.Tools.WindowsRegistry
throw new ArgumentException("Invalid RegistryValueKind string representation.", nameof(valueType)); throw new ArgumentException("Invalid RegistryValueKind string representation.", nameof(valueType));
} }
} }
/// <summary>
/// Converts a .NET data type to the corresponding RegistryValueKind.
/// </summary>
/// <param name="valueType">The .NET data type to convert.</param>
/// <returns>The corresponding RegistryValueKind.</returns>
public RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType)
{
switch (Type.GetTypeCode(valueType))
{
case TypeCode.String:
return RegistryValueKind.String;
case TypeCode.Int32:
return RegistryValueKind.DWord;
case TypeCode.Int64:
return RegistryValueKind.QWord;
case TypeCode.Boolean:
return RegistryValueKind.DWord;
case TypeCode.Byte:
return RegistryValueKind.Binary;
/*
case TypeCode.Single:
return RegistryValueKind;
case TypeCode.Double:
return RegistryValueKind.String;
case TypeCode.DateTime:
return RegistryValueKind.String; // DateTime can be stored as a string or other types
case TypeCode.Char:
return RegistryValueKind.String; // Char can be stored as a string or other types
case TypeCode.Decimal:
return RegistryValueKind.String; // Decimal can be stored as a string or other types
*/
default:
return RegistryValueKind.String; // Default to String for unsupported types
}
}
/// <summary>
/// Converts a RegistryValueKind enumeration value to its corresponding .NET Type.
/// </summary>
/// <param name="valueKind">The RegistryValueKind value to be converted.</param>
/// <returns>The .NET Type that corresponds to the given RegistryValueKind.</returns>
public Type ConvertRegistryValueKindToType(RegistryValueKind valueKind)
{
switch (valueKind)
{
case RegistryValueKind.String:
case RegistryValueKind.ExpandString:
return typeof(string);
case RegistryValueKind.DWord:
return typeof(int);
case RegistryValueKind.QWord:
return typeof(long);
case RegistryValueKind.Binary:
return typeof(byte[]);
case RegistryValueKind.MultiString:
return typeof(string[]);
case RegistryValueKind.Unknown:
default:
return typeof(object);
}
}
#endregion #endregion
#region private methods #region private methods
@@ -391,26 +508,18 @@ namespace mRemoteNG.Tools.WindowsRegistry
} }
catch (SecurityException ex) catch (SecurityException ex)
{ {
// Handle or log SecurityException throw ex;
// For example: log ex.Message
throw;
} }
catch (IOException ex) catch (IOException ex)
{ {
// Handle or log IOException throw ex;
// For example: log ex.Message
throw;
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
// Handle or log UnauthorizedAccessException throw ex;
// For example: log ex.Message
throw;
} }
catch (Exception ex) catch (Exception)
{ {
// For all other exceptions, log and rethrow
// For example: log ex.ToString()
throw; throw;
} }
} }

View File

@@ -0,0 +1,116 @@
using Microsoft.Win32;
using mRemoteNG.App.Info;
using mRemoteNG.Security.SymmetricEncryption;
using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry
{
[SupportedOSPlatform("windows")]
/// <summary>
/// Extends the functionality of interacting with the Windows Registry, building upon the base WindowsRegistry class.
/// </summary>
public class WindowsRegistryAdvanced : WindowsRegistry , IRegistryAdvanced, IRegistryAdvancedRead
{
#region dword methods
/// <summary>
/// Retrieves a DWORD (32-bit integer) value from the Windows Registry based on the specified registry information.
/// </summary>
/// <param name="hive">The registry hive.</param>
/// <param name="path">The path to the registry key.</param>
/// <param name="propertyName">The name of the registry property.</param>
/// <param name="defaultValue">Optional default value to be used if the registry key is not present (default is null).</param>
/// <returns>A WindowsRegistryKeyInteger instance representing the retrieved DWORD value.</returns>
public WindowsRegistryKeyInteger GetInteger(RegistryHive hive, string path, string propertyName, int? defaultValue = null)
{
// Retrieve the Windows Registry key
var key = GetWindowsRegistryKey(hive, path, propertyName);
// Create a WindowsRegistryKeyInteger instance and initialize it from the retrieved key
WindowsRegistryKeyInteger IntKey = new();
IntKey.ConvertFromWindowsRegistryKey(key);
return IntKey;
}
#endregion
#region string methods
/// <summary>
/// Retrieves a string value from the Windows Registry based on the specified registry information.
/// </summary>
/// <param name="hive">The registry hive.</param>
/// <param name="path">The path to the registry key.</param>
/// <param name="propertyName">The name of the registry property.</param>
/// <param name="defaultValue">Optional default value to be used if the registry key is not present (default is null).</param>
/// <returns>A WindowsRegistryKeyString instance representing the retrieved string value.</returns>
public WindowsRegistryKeyString GetString(RegistryHive hive, string path, string propertyName, string defaultValue = null)
{
// Retrieve the Windows Registry key
var key = GetWindowsRegistryKey(hive, path, propertyName);
// Create a WindowsRegistryKeyString instance and initialize it from the retrieved key
WindowsRegistryKeyString StrKey = new();
StrKey.ConvertFromWindowsRegistryKey(key, defaultValue);
return StrKey;
}
/// <summary>
/// Retrieves a string value from the Windows Registry based on the specified registry information and validates it against a set of allowed values.
/// </summary>
/// <param name="hive">The registry hive.</param>
/// <param name="path">The path to the registry key.</param>
/// <param name="propertyName">The name of the registry property.</param>
/// <param name="allowedValues">An array of valid values against which the retrieved string is validated.</param>
/// <param name="caseSensitive">Optional parameter indicating whether the validation is case-sensitive (default is false).</param>
/// <returns>A WindowsRegistryKeyString instance representing the retrieved and validated string value.</returns>
public WindowsRegistryKeyString GetStringValidated(RegistryHive hive, string path, string propertyName, string[] allowedValues, bool caseSensitive = false, string defaultValue = null)
{
// Retrieve the Windows Registry key
var key = GetWindowsRegistryKey(hive, path, propertyName);
// Create a WindowsRegistryKeyString instance and initialize it from the retrieved key
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = allowedValues;
StrKey.IsCaseSensitiveValidation = caseSensitive;
StrKey.ConvertFromWindowsRegistryKey(key, defaultValue);
return StrKey;
}
/*public WindowsRegistryKeySecureString GetSecureString(RegistryHive hive, string path, string propertyName)
{
// Retrieve the Windows Registry key, the key should be encrypted
var key = GetWindowsRegistryKey(hive, path, propertyName);
// Create a WindowsRegistryKeyBoolean instance and initialize it from the retrieved key
WindowsRegistryKeySecureString secureKey = new (); // class not exsists
secureKey.ConvertFromWindowsRegistryKey(key); // no default possible!
return secureKey
}*/
#endregion
#region bool methods
/// <summary>
/// Retrieves a boolean value from the Windows Registry based on the specified registry information.
/// </summary>
/// <param name="hive">The registry hive.</param>
/// <param name="path">The path to the registry key.</param>
/// <param name="propertyName">The name of the registry property.</param>
/// <param name="defaultValue">An optional default value to use if the registry key is not present or if the value is not a valid boolean.</param>
/// <returns>A WindowsRegistryKeyBoolean instance representing the retrieved boolean value.</returns>
public WindowsRegistryKeyBoolean GetBoolean(RegistryHive hive, string path, string propertyName, bool? defaultValue = null)
{
// Retrieve the Windows Registry key
var key = GetWindowsRegistryKey(hive, path, propertyName);
// Create a WindowsRegistryKeyBoolean instance and initialize it from the retrieved key
WindowsRegistryKeyBoolean boolKey = new ();
boolKey.ConvertFromWindowsRegistryKey(key, defaultValue);
return boolKey;
}
#endregion
}
}

View File

@@ -6,9 +6,8 @@ using Microsoft.Win32;
namespace mRemoteNG.Tools.WindowsRegistry namespace mRemoteNG.Tools.WindowsRegistry
{ {
/// <summary> /// <summary>
/// This class provides a convenient way to work with Windows Registry keys /// Represents a Windows Registry key with a default string value, providing a flexible abstraction for registry operations.
/// by encapsulating information about a registry key, including its path, /// This class can be extended by inherited classes to customize behavior for specific data types.
/// name, value, and registry hive/type.
/// </summary> /// </summary>
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
public class WindowsRegistryKey public class WindowsRegistryKey
@@ -56,42 +55,22 @@ namespace mRemoteNG.Tools.WindowsRegistry
private string _Name { get; set; } private string _Name { get; set; }
#endregion #endregion
#region Property valueKind #region Property value
public RegistryValueKind ValueKind public virtual string Value
{ {
get { return _ValueKind; } get => _value;
set { set
if (value == 0) {
throw new ArgumentNullException("ValueKind unknown."); _value = value;
UpdateIsProvidedState();
_ValueKind = value;
// Check if Type is uninitialized (null)
if (_Type == null)
// Initialize Type if it's uninitialized
_Type = ConvertRegistryValueKindToType(value);
} }
} }
private RegistryValueKind _ValueKind; private string _value;
#endregion #endregion
#region Property type public RegistryValueKind ValueKind { get; set; } = RegistryValueKind.Unknown;
public Type Type
{
get { return _Type; }
set {
_Type = value;
// Check if ValueKind is uninitialized(0)
if (_ValueKind == 0)
// Initialize ValueKind if it's uninitialized
_ValueKind = ConvertTypeToRegistryValueKind(value);
}
}
private Type _Type;
#endregion
public string Value { get; set; } public bool IsKeyPresent { get; set; } = false;
#endregion #endregion
#region public methods #region public methods
@@ -118,94 +97,20 @@ namespace mRemoteNG.Tools.WindowsRegistry
} }
#endregion #endregion
#region private methods #region protected methods
/// <summary> protected void UpdateIsProvidedState()
/// Converts a .NET data type to the corresponding RegistryValueKind.
/// </summary>
/// <param name="valueType">The .NET data type to convert.</param>
/// <returns>The corresponding RegistryValueKind.</returns>
private RegistryValueKind ConvertTypeToRegistryValueKind(Type valueType)
{ {
switch (Type.GetTypeCode(valueType)) // Key is present when RegistryKey value is not null
{ IsKeyPresent = Value != null;
case TypeCode.String:
return RegistryValueKind.String;
case TypeCode.Int32:
return RegistryValueKind.DWord;
case TypeCode.Int64:
return RegistryValueKind.QWord;
case TypeCode.Boolean:
return RegistryValueKind.DWord;
case TypeCode.Byte:
return RegistryValueKind.Binary;
/*
case TypeCode.Single:
return RegistryValueKind;
case TypeCode.Double:
return RegistryValueKind.String;
case TypeCode.DateTime:
return RegistryValueKind.String; // DateTime can be stored as a string or other types
case TypeCode.Char:
return RegistryValueKind.String; // Char can be stored as a string or other types
case TypeCode.Decimal:
return RegistryValueKind.String; // Decimal can be stored as a string or other types
*/
default:
return RegistryValueKind.String; // Default to String for unsupported types
}
} }
/// <summary> protected bool IsHiveSet() => Hive != 0;
/// Converts a RegistryValueKind enumeration value to its corresponding .NET Type.
/// </summary>
/// <param name="valueKind">The RegistryValueKind value to be converted.</param>
/// <returns>The .NET Type that corresponds to the given RegistryValueKind.</returns>
private Type ConvertRegistryValueKindToType(RegistryValueKind valueKind)
{
switch (valueKind)
{
case RegistryValueKind.String:
case RegistryValueKind.ExpandString:
return typeof(string);
case RegistryValueKind.DWord:
return typeof(int);
case RegistryValueKind.QWord:
return typeof(long);
case RegistryValueKind.Binary:
return typeof(byte[]);
case RegistryValueKind.MultiString:
return typeof(string[]);
case RegistryValueKind.Unknown:
default:
return typeof(object);
}
}
private bool IsHiveSet() protected bool IsValueKindSet() => ValueKind != 0;
{
return Hive != 0;
}
private bool IsValueKindSet() protected bool IsPathSet() => Path != null;
{
return ValueKind != 0;
}
private bool IsPathSet() protected bool IsNameSet() => Name != null;
{
return Path != null; ;
//return !string.IsNullOrEmpty(Path);
}
private bool IsNameSet()
{
return Name != null;
}
private bool IsValueSet()
{
return !string.IsNullOrEmpty(Value);
}
#endregion #endregion
} }
} }

View File

@@ -0,0 +1,75 @@
using System;
using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry
{
/// <summary>
/// Represents a boolean Windows Registry key, extending the base class WindowsRegistryKey.
/// </summary>
[SupportedOSPlatform("windows")]
public class WindowsRegistryKeyBoolean : WindowsRegistryKey
{
/// <summary>
/// Gets or sets the default boolean value for a Windows Registry key.
/// </summary>
/// <remarks>
/// The default value is initially set to `false`.
/// </remarks>
public bool DefaultValue { get; private set; } = false;
/// <summary>
/// Gets or sets the boolean value for a Windows Registry key.
/// </summary>
public new bool Value
{
get => BoolValue;
private set
{
BoolValue = value;
UpdateIsProvidedState();
}
}
private bool BoolValue;
/// <summary>
/// Converts and initializes a WindowsRegistryKeyBoolean from a base WindowsRegistryKey, with an optional default value.
/// </summary>
/// <param name="baseKey">The base WindowsRegistryKey to convert from.</param>
/// <param name="defaultValue">Optional default value to set for the WindowsRegistryKeyBoolean.</param>
public void ConvertFromWindowsRegistryKey(WindowsRegistryKey baseKey, bool? defaultValue = null)
{
SetDefaultValue(defaultValue);
FromBaseKey(baseKey);
}
private void FromBaseKey(WindowsRegistryKey baseKey)
{
if (baseKey == null)
throw new ArgumentNullException(nameof(baseKey));
Hive = baseKey.Hive;
Path = baseKey.Path;
Name = baseKey.Name;
ValueKind = baseKey.ValueKind;
IsKeyPresent = baseKey.IsKeyPresent;
ConvertToBool(baseKey.Value);
}
private void SetDefaultValue(bool? defaultValue)
{
if (defaultValue.HasValue)
DefaultValue = (bool)defaultValue;
}
private void ConvertToBool(string newValue)
{
if (IsKeyPresent && bool.TryParse(newValue, out bool boolValue))
BoolValue = boolValue;
else if (IsKeyPresent && int.TryParse(newValue, out int intValue))
BoolValue = intValue == 1;
else
BoolValue = DefaultValue;
}
}
}

View File

@@ -0,0 +1,78 @@
using Microsoft.Win32;
using System;
using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry
{
/// <summary>
/// Represents a integer Windows Registry key, extending the base class WindowsRegistryKey.
/// </summary>
[SupportedOSPlatform("windows")]
public class WindowsRegistryKeyInteger : WindowsRegistryKey
{
/// <summary>
/// Gets or sets the default integer value for a Windows Registry key.
/// </summary>
/// <remarks>
/// The default value is initially set to `-1`.
/// </remarks>
public int DefaultValue { get; private set; } = -1;
/// <summary>
/// Gets or sets the integer value for a Windows Registry key.
/// </summary>
public new int Value
{
get => IntegerValue;
private set
{
IntegerValue = value;
UpdateIsProvidedState();
}
}
private int IntegerValue;
/// <summary>
/// Converts and initializes a WindowsRegistryKeyInteger from a base WindowsRegistryKey, with an optional default value.
/// </summary>
/// <param name="baseKey">The base WindowsRegistryKey to convert from.</param>
/// <param name="defaultValue">Optional default value to set for the WindowsRegistryKeyBoolean.</param>
public void ConvertFromWindowsRegistryKey(WindowsRegistryKey baseKey, int? defaultValue = null)
{
SetDefaultValue(defaultValue);
FromBaseKey(baseKey);
}
private void FromBaseKey(WindowsRegistryKey baseKey)
{
if (baseKey == null)
throw new ArgumentNullException(nameof(baseKey));
Hive = baseKey.Hive;
Path = baseKey.Path;
Name = baseKey.Name;
ValueKind = baseKey.ValueKind;
IsKeyPresent = baseKey.IsKeyPresent;
ConvertToInteger(baseKey.Value);
}
private void SetDefaultValue (int? defaultValue)
{
if (defaultValue.HasValue)
DefaultValue = (int)defaultValue;
}
private void ConvertToInteger(string newValue)
{
if (ValueKind != RegistryValueKind.DWord)
IsKeyPresent = false;
if (IsKeyPresent && int.TryParse(newValue.ToString(), out int intValue))
IntegerValue = intValue;
else
IntegerValue = DefaultValue;
}
}
}

View File

@@ -0,0 +1,121 @@
using Microsoft.Win32;
using System;
using System.Linq;
using System.Runtime.Versioning;
namespace mRemoteNG.Tools.WindowsRegistry
{
/// <summary>
/// Represents a string Windows Registry key, extending the base class WindowsRegistryKey, can be evaluated with a value set.
/// </summary>
[SupportedOSPlatform("windows")]
public class WindowsRegistryKeyString : WindowsRegistryKey
{
/// <summary>
/// Gets or sets the default integer value for a Windows Registry key.
/// </summary>
public string DefaultValue { get; private set; }
/// <summary>
/// Gets or sets an array of allowed values for validation.
/// </summary>
public string[] AllowedValues { get; set; }
/// <summary>
/// Gets or sets a boolean flag indicating whether validation is case-sensitive.
/// </summary>
public bool IsCaseSensitiveValidation { get; set; } = false;
/// <summary>
/// Gets a boolean indicating whether the value is valid based on the validation rules.
/// </summary>
public bool IsValid { get; private set; } = false;
public new string Value
{
get => StringValue;
private set
{
StringValue = value;
UpdateIsProvidedState();
Validate();
}
}
private string StringValue;
/// <summary>
/// Converts and initializes a WindowsRegistryKeyString from a base WindowsRegistryKey, with an optional default value.
/// </summary>
/// <param name="baseKey">The base WindowsRegistryKey to convert from.</param>
/// <param name="defaultValue">Optional default value to set for the WindowsRegistryKeyBoolean.</param>
public void ConvertFromWindowsRegistryKey(WindowsRegistryKey baseKey, string defaultValue = null)
{
SetDefaultValue(defaultValue);
FromBaseKey(baseKey);
Validate();
}
private void FromBaseKey(WindowsRegistryKey baseKey)
{
if (baseKey == null)
throw new ArgumentNullException(nameof(baseKey));
Hive = baseKey.Hive;
Path = baseKey.Path;
Name = baseKey.Name;
ValueKind = baseKey.ValueKind;
IsKeyPresent = baseKey.IsKeyPresent;
ConvertToString(baseKey.Value);
}
private void SetDefaultValue (string defaultValue)
{
DefaultValue = defaultValue;
}
private void ConvertToString(string newValue)
{
if (IsKeyPresent && newValue != null)
StringValue = newValue;
else
StringValue = DefaultValue;
}
/// <summary>
/// Validates a Windows Registry key value against a set of allowed values, considering case sensitivity.
/// </summary>
/// <param name="allowedValues">Array of allowed values.</param>
/// <param name="caseSensitive">Optional parameter to specify case sensitivity in validation.</param>
public void Validate(string[] allowedValues = null, bool? caseSensitive = null)
{
// Key must be present to evaluate
if (!IsKeyPresent)
return;
if (caseSensitive.HasValue)
IsCaseSensitiveValidation = caseSensitive.Value;
if (allowedValues != null && allowedValues.Length >= 1)
AllowedValues = allowedValues;
// AllowedValues array cannot be null or empty.
if (AllowedValues == null || AllowedValues.Length == 0 || !IsKeyPresent)
return;
if (IsKeyPresent && AllowedValues.Any(v =>
IsCaseSensitiveValidation ? v == Value : v.Equals(Value, StringComparison.OrdinalIgnoreCase)))
{
// Set to true when the value is found in the valid values
IsValid = true;
}
else
{
// Set to false when the value is not found in the valid values
IsValid = false;
StringValue = DefaultValue;
}
}
}
}

View File

@@ -0,0 +1,181 @@
using Microsoft.Win32;
using mRemoteNG.Tools.WindowsRegistry;
using NUnit.Framework;
namespace mRemoteNGTests.Tools.Registry
{
internal class WindowsRegistryAdvancedTests : WindowsRegistryAdvanced
{
private const string _TestRootKey = @"Software\mRemoteNGTest";
private const RegistryHive _TestHive = RegistryHive.CurrentUser;
[SetUp]
public void Setup()
{
// GetBoolean && GetBoolValue (GetBoolValue -> Not Advanced but not tested jet)
SetRegistryValue(_TestHive, _TestRootKey, "TestBoolAsString", "true", RegistryValueKind.String);
SetRegistryValue(_TestHive, _TestRootKey, "TestBoolAsDWord", 0, RegistryValueKind.DWord);
// GetInteger Tests
SetRegistryValue(_TestHive, _TestRootKey, "TestInteger", "4711", RegistryValueKind.DWord);
// GetString Tests
SetRegistryValue(_TestHive, _TestRootKey, "TestString1", "Banane", RegistryValueKind.String);
SetRegistryValue(_TestHive, _TestRootKey, "TestString2", "Hund", RegistryValueKind.String);
}
[TearDown]
public void Cleanup()
{
// Delete the registry keys here
DeleteRegistryKey(_TestHive, _TestRootKey, true);
}
#region GetBoolean() Tests
// Non object returns
[Test]
public void GetBooleanFromString_ReturnsTrue()
{
var key = GetBoolean(_TestHive, _TestRootKey, "TestBoolAsString");
Assert.That(key.Value, Is.EqualTo(true));
}
[Test]
public void GetBooleanFromDword_ReturnsFalse()
{
var key = GetBoolean(_TestHive, _TestRootKey, "TestBoolAsDWord");
Assert.That(key.Value, Is.EqualTo(false));
}
[Test]
public void GetBooleanNotProvided_ReturnsDefaultTrue()
{
var key = GetBoolean(_TestHive, _TestRootKey, "TestBoolNotProvided", true);
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo(true), "Value should be the default (true)");
Assert.That(key.IsKeyPresent, Is.EqualTo(false), "IsProvided should be false");
});
}
#endregion
#region GetBoolValue()___No Object, just bool value returns
[Test]
public void GetBoolValueFromString_ReturnsTrue()
{
var key = GetBoolValue(_TestHive, _TestRootKey, "TestBoolAsString");
Assert.That(key, Is.EqualTo(true));
}
[Test]
public void GetBoolValueFromDword_ReturnsFalse()
{
var key = GetBoolValue(_TestHive, _TestRootKey, "TestBoolAsDWord", true);
Assert.That(key, Is.EqualTo(false));
}
[Test]
public void GetBoolValue_ReturnsDefaultTrue()
{
var key = GetBoolValue(_TestHive, _TestRootKey, "TestBoolNotProvided", true);
Assert.That(key, Is.EqualTo(true));
}
#endregion
#region GetInteger()
[Test]
public void GetInteger()
{
var key = GetInteger(_TestHive, _TestRootKey, "TestInteger");
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo(4711));
Assert.That(key.IsKeyPresent, Is.EqualTo(true));
});
}
[Test]
public void GetInteger_returnObjectDefault()
{
var key = GetInteger(_TestHive, _TestRootKey, "TestIntegerNotProvided");
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo(-1), "Value should be the default (-1)");
Assert.That(key.IsKeyPresent, Is.EqualTo(false));
});
}
[Test]
public void GetInteger_returnSpecifiedDefault()
{
var key = GetInteger(_TestHive, _TestRootKey, "TestIntegerNotProvided", 2096);
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo(-1), "Value should be the default (-1)");
Assert.That(key.IsKeyPresent, Is.EqualTo(false));
});
}
#endregion
#region GetString()
[Test]
public void GetString()
{
var key = GetString(_TestHive, _TestRootKey, "TestString1");
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo("Banane"));
Assert.That(key.IsKeyPresent, Is.EqualTo(true));
});
}
[Test]
public void GetString_ReturnsDefault()
{
var key = GetString(_TestHive, _TestRootKey, "TestStringNotProvided", "Banane");
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo("Banane"));
Assert.That(key.IsKeyPresent, Is.EqualTo(false));
});
}
[Test]
public void GetStringValidated_Valid()
{
string[] fruits = { "Banane", "Erdbeere", "Apfel" };
var key = GetStringValidated(_TestHive, _TestRootKey, "TestString1", fruits);
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo("Banane"));
Assert.That(key.IsKeyPresent, Is.EqualTo(true));
Assert.That(key.IsValid, Is.EqualTo(true));
});
}
[Test]
public void GetStringValidated_NotValidNull()
{
string[] fruits = { "Banane", "Erdbeere", "Apfel" };
var key = GetStringValidated(_TestHive, _TestRootKey, "TestString2", fruits);
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo(null));
Assert.That(key.IsKeyPresent, Is.EqualTo(true));
Assert.That(key.IsValid, Is.EqualTo(false));
});
}
[Test]
public void GetStringValidated_NotValidDefault()
{
string[] fruits = { "Banane", "Erdbeere", "Apfel" };
var key = GetStringValidated(_TestHive, _TestRootKey, "TestString2", fruits, false, "Banane");
Assert.Multiple(() =>
{
Assert.That(key.Value, Is.EqualTo("Banane"));
Assert.That(key.IsKeyPresent, Is.EqualTo(true));
Assert.That(key.IsValid, Is.EqualTo(false));
});
}
#endregion
}
}

View File

@@ -0,0 +1,374 @@
using Microsoft.Win32;
using mRemoteNG.Tools.WindowsRegistry;
using NUnit.Framework;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
namespace mRemoteNGTests.Tools.Registry
{
internal class WindowsRegistryKeyTests
{
private WindowsRegistryKey CompleteRegistryKey { get; set; }
private WindowsRegistryKey PartialRegistryKey { get; set; }
[SetUp]
public void Setup()
{
CompleteRegistryKey = new WindowsRegistryKey()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.String,
Name = "Test",
Path = @"SOFTWARE\TEST\TEST\Test",
Value = "CompleteRegistryKey"
};
PartialRegistryKey = new WindowsRegistryKey()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
};
}
#region WindowsRegistryKey() tests
[Test]
public void WindowsRegistryKeyReadable()
{
Assert.That(CompleteRegistryKey.IsKeyReadable, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyNotReadable()
{
Assert.That(PartialRegistryKey.IsKeyReadable, Is.EqualTo(false));
}
[Test]
public void WindowsRegistryKeyWriteable()
{
Assert.That(CompleteRegistryKey.IsKeyWritable, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyNotWriteable()
{
Assert.That(PartialRegistryKey.IsKeyWritable, Is.EqualTo(false));
}
[Test]
public void WindowsRegistryKeyProvided()
{
Assert.That(CompleteRegistryKey.IsKeyPresent, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyNotProvided()
{
Assert.That(PartialRegistryKey.IsKeyPresent, Is.EqualTo(false));
}
#endregion
#region WindowsRegistryKeyBoolean tests
[Test]
public void WindowsRegistryKeyBoolean_FromStringTrue()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.String,
Name = "TestBoolString",
Path = @"SOFTWARE\Test",
Value = "true"
};
WindowsRegistryKeyBoolean boolKey = new ();
boolKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(boolKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(boolKey.Value, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyBoolean_FromStringFalse()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.String,
Name = "TestBoolString",
Path = @"SOFTWARE\Test",
Value = "false"
};
WindowsRegistryKeyBoolean boolKey = new();
boolKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(boolKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(boolKey.Value, Is.EqualTo(false));
}
[Test]
public void WindowsRegistryKeyBoolean_FromDwordTrue()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestBoolString",
Path = @"SOFTWARE\Test",
Value = "1"
};
WindowsRegistryKeyBoolean boolKey = new();
boolKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(boolKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(boolKey.Value, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyBoolean_FromDwordFalse()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestBoolString",
Path = @"SOFTWARE\Test",
Value = "0"
};
WindowsRegistryKeyBoolean boolKey = new();
boolKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(boolKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(boolKey.Value, Is.EqualTo(false));
}
[Test]
public void WindowsRegistryKeyBoolean_ReturnDefault()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestBoolString",
Path = @"SOFTWARE\Test",
Value = null
};
WindowsRegistryKeyBoolean boolKey = new();
boolKey.ConvertFromWindowsRegistryKey(TestKey, true);
Assert.That(boolKey.IsKeyPresent, Is.EqualTo(false));
Assert.That(boolKey.Value, Is.EqualTo(true));
}
#endregion
#region WindowsRegistryKeyInteger tests
[Test]
public void WindowsRegistryKeyInteger()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestIntigerString",
Path = @"SOFTWARE\Test",
Value = "4711"
};
WindowsRegistryKeyInteger IntKey = new();
IntKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(IntKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(IntKey.Value, Is.EqualTo(4711));
}
[Test]
public void WindowsRegistryKeyInteger_ReturnDefault()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestIntigerString",
Path = @"SOFTWARE\Test",
Value = null
};
WindowsRegistryKeyInteger IntKey = new();
IntKey.ConvertFromWindowsRegistryKey(TestKey, 2096);
Assert.That(IntKey.IsKeyPresent, Is.EqualTo(false));
Assert.That(IntKey.Value, Is.EqualTo(2096));
}
#endregion
#region WindowsRegistryKeyString tests
[Test]
public void WindowsRegistryKeyString()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "The Big Bang Theory"
};
WindowsRegistryKeyString StrKey = new();
StrKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.Value, Is.EqualTo("The Big Bang Theory"));
}
[Test]
public void WindowsRegistryKeyString_ReturnDefault()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = null
};
WindowsRegistryKeyString StrKey = new();
StrKey.ConvertFromWindowsRegistryKey(TestKey, "South Park");
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(false));
Assert.That(StrKey.Value, Is.EqualTo("South Park"));
}
[Test]
public void WindowsRegistryKeyString_ValidateSuccess()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "Big Bang"
};
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" };
StrKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.IsValid, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyString_ValidateNotSuccess()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "ig ang"
};
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" };
StrKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.IsValid, Is.EqualTo(false));
}
[Test]
public void WindowsRegistryKeyString_ValidateSuccessCase()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "BiG BAng"
};
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = new[] { "BiG BAng", "Big Bang Theory", "The Big Bang Theory" };
StrKey.IsCaseSensitiveValidation = true;
StrKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.IsValid, Is.EqualTo(true));
}
[Test]
public void WindowsRegistryKeyString_ValidateNotSuccessCase()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "BiG BAng"
};
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" };
StrKey.IsCaseSensitiveValidation = true;
StrKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.IsValid, Is.EqualTo(false));
}
[Test]
public void WindowsRegistryKeyString_ValidateNotSuccessReturnNull()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "ig ang"
};
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" };
StrKey.ConvertFromWindowsRegistryKey(TestKey);
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.IsValid, Is.EqualTo(false));
Assert.That(StrKey.Value, Is.EqualTo(null));
}
[Test]
public void WindowsRegistryKeyString_ValidateNotSuccessValidValue()
{
WindowsRegistryKey TestKey = new()
{
Hive = RegistryHive.CurrentUser,
ValueKind = RegistryValueKind.DWord,
Name = "TestRegString",
Path = @"SOFTWARE\Test",
Value = "ig ang"
};
WindowsRegistryKeyString StrKey = new();
StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" };
StrKey.ConvertFromWindowsRegistryKey(TestKey, "Big Bang Theory");
Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true));
Assert.That(StrKey.IsValid, Is.EqualTo(false));
Assert.That(StrKey.Value, Is.EqualTo("Big Bang Theory"));
}
#endregion
}
}

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Windows.Forms;
using Microsoft.Win32; using Microsoft.Win32;
using mRemoteNG.Tools.WindowsRegistry; using mRemoteNG.Tools.WindowsRegistry;
using NUnit.Framework; using NUnit.Framework;
@@ -9,14 +10,12 @@ namespace mRemoteNGTests.Tools.Registry
{ {
public class WindowsRegistryTests public class WindowsRegistryTests
{ {
private IRegistry _registry;
private IRegistryRead _registryReader; private IRegistryRead _registryReader;
private IRegistryWrite _registryWriter; private IRegistryWrite _registryWriter;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
_registry = new WindowsRegistry();
_registryReader = new WindowsRegistry(); _registryReader = new WindowsRegistry();
_registryWriter = new WindowsRegistry(); _registryWriter = new WindowsRegistry();
} }
@@ -28,11 +27,13 @@ namespace mRemoteNGTests.Tools.Registry
var subKeyNames = _registryReader.GetSubKeyNames(RegistryHive.CurrentUser, "Software"); var subKeyNames = _registryReader.GetSubKeyNames(RegistryHive.CurrentUser, "Software");
Assert.That(subKeyNames, Does.Contain("Microsoft")); Assert.That(subKeyNames, Does.Contain("Microsoft"));
} }
[Test] [Test]
public void GetSubkeyNamesThrowsIfGivenNullKeyPath() public void GetSubkeyNamesThrowsIfGivenNullKeyPath()
{ {
Assert.Throws<ArgumentNullException>(() => _registryReader.GetSubKeyNames(RegistryHive.CurrentUser, null)); Assert.Throws<ArgumentNullException>(() => _registryReader.GetSubKeyNames(RegistryHive.CurrentUser, null));
} }
[Test] [Test]
public void GetSubkeyNamesThrowsIfGivenUnknownHive() public void GetSubkeyNamesThrowsIfGivenUnknownHive()
{ {
@@ -45,13 +46,13 @@ namespace mRemoteNGTests.Tools.Registry
public void CanGetPropertyValue() public void CanGetPropertyValue()
{ {
var keyValue = _registryReader.GetPropertyValue(RegistryHive.ClassesRoot, @".dll\PersistentHandler", ""); var keyValue = _registryReader.GetPropertyValue(RegistryHive.ClassesRoot, @".dll\PersistentHandler", "");
Assert.That(keyValue.FirstOrDefault(), Is.EqualTo("{098f2470-bae0-11cd-b579-08002b30bfeb}")); Assert.That(keyValue, Is.EqualTo("{098f2470-bae0-11cd-b579-08002b30bfeb}"));
} }
[Test] [Test]
public void CanGetPropertyValueByRegistryKeyObject() public void CanGetPropertyValueByRegistryKeyObject()
{ {
WindowsRegistryKey key = new WindowsRegistryKey WindowsRegistryKey key = new()
{ {
Hive = RegistryHive.ClassesRoot, Hive = RegistryHive.ClassesRoot,
Path = @".dll\PersistentHandler", Path = @".dll\PersistentHandler",
@@ -59,7 +60,7 @@ namespace mRemoteNGTests.Tools.Registry
}; };
var keyValue = _registryReader.GetPropertyValue(key); var keyValue = _registryReader.GetPropertyValue(key);
Assert.That(keyValue.FirstOrDefault(), Is.EqualTo("{098f2470-bae0-11cd-b579-08002b30bfeb}")); Assert.That(keyValue, Is.EqualTo("{098f2470-bae0-11cd-b579-08002b30bfeb}"));
} }
[Test] [Test]
public void GetPropertyValueThrowsIfGivenNullKeyPath() public void GetPropertyValueThrowsIfGivenNullKeyPath()
@@ -85,7 +86,7 @@ namespace mRemoteNGTests.Tools.Registry
[Test] [Test]
public void CanGetWindowsRegistryKeyByObject() public void CanGetWindowsRegistryKeyByObject()
{ {
WindowsRegistryKey key = new WindowsRegistryKey WindowsRegistryKey key = new()
{ {
Hive = RegistryHive.ClassesRoot, Hive = RegistryHive.ClassesRoot,
Path = @".dll\PersistentHandler", Path = @".dll\PersistentHandler",
@@ -107,11 +108,11 @@ namespace mRemoteNGTests.Tools.Registry
[Test] [Test]
public void GetWindowsRegistryThrowNotReadable() public void GetWindowsRegistryThrowNotReadable()
{ {
WindowsRegistryKey key = new WindowsRegistryKey WindowsRegistryKey key = new()
{ {
Hive = RegistryHive.ClassesRoot, Hive = RegistryHive.ClassesRoot,
}; };
Assert.Throws<InvalidOperationException>(() => _registryReader.GetWindowsRegistryKey(key)); Assert.Throws<InvalidOperationException>(() => _registryReader.GetWindowsRegistryKey(key));
} }
#endregion #endregion
@@ -137,7 +138,7 @@ namespace mRemoteNGTests.Tools.Registry
public void IsWindowsRegistryKeyValid() public void IsWindowsRegistryKeyValid()
{ {
// Tests property rules of WindowsRegistryKey // Tests property rules of WindowsRegistryKey
WindowsRegistryKey key = new WindowsRegistryKey(); WindowsRegistryKey key = new();
Assert.Multiple(() => Assert.Multiple(() =>
{ {
@@ -152,26 +153,27 @@ namespace mRemoteNGTests.Tools.Registry
[Test] [Test]
public void WindowsRegistryKeyThrowHiveNullException() public void WindowsRegistryKeyThrowHiveNullException()
{ {
WindowsRegistryKey key = new WindowsRegistryKey(); WindowsRegistryKey key = new();
Assert.Throws<ArgumentNullException>(() => key.Hive = 0, "Expected IsHiveValid to throw ArgumentNullException"); Assert.Throws<ArgumentNullException>(() => key.Hive = 0, "Expected IsHiveValid to throw ArgumentNullException");
} }
[Test] [Test]
public void WindowsRegistryKeyThrowValueKindNullException() public void WindowsRegistryKeyValueKindUnknown()
{ {
WindowsRegistryKey key = new WindowsRegistryKey(); WindowsRegistryKey key = new();
Assert.Throws<ArgumentNullException>(() => key.ValueKind = 0, "Expected IsValueKindValid to throw ArgumentNullException"); Assert.That(key.ValueKind, Is.EqualTo(RegistryValueKind.Unknown));
} }
[Test] [Test]
public void WindowsRegistryKeyThrowPathNullException() public void WindowsRegistryKeyThrowPathNullException()
{ {
WindowsRegistryKey key = new WindowsRegistryKey(); WindowsRegistryKey key = new();
Assert.Throws<ArgumentNullException>(() => key.Path = null, "Expected IsPathValid to throw ArgumentNullException"); Assert.Throws<ArgumentNullException>(() => key.Path = null, "Expected IsPathValid to throw ArgumentNullException");
} }
[Test] [Test]
public void WindowsRegistryKeyThrowNameNullException() public void WindowsRegistryKeyThrowNameNullException()
{ {
WindowsRegistryKey key = new WindowsRegistryKey(); WindowsRegistryKey key = new();
Assert.Throws<ArgumentNullException>(() => key.Name = null, "Expected IsNameValid to throw ArgumentNullException"); Assert.Throws<ArgumentNullException>(() => key.Name = null, "Expected IsNameValid to throw ArgumentNullException");
} }
#endregion #endregion