diff --git a/ExternalConnectors/DSS/SecretServerInterface.cs b/ExternalConnectors/DSS/SecretServerInterface.cs
index 1a6f3e377..4d9f04935 100644
--- a/ExternalConnectors/DSS/SecretServerInterface.cs
+++ b/ExternalConnectors/DSS/SecretServerInterface.cs
@@ -34,7 +34,7 @@ namespace ExternalConnectors.DSS
try
{
// display gui and ask for data
- SSConnectionForm f = new SSConnectionForm();
+ SSConnectionForm f = new();
string? un = key.GetValue("Username") as string;
f.tbUsername.Text = un ?? "";
f.tbPassword.Text = SSConnectionData.ssPassword; // in OTP refresh cases, this value might already be filled
@@ -212,7 +212,7 @@ namespace ExternalConnectors.DSS
private static string DecodePrivateKey(string encryptedPrivateKey, string password)
{
TextReader textReader = new StringReader(encryptedPrivateKey);
- PemReader pemReader = new PemReader(textReader, new PasswordFinder(password));
+ PemReader pemReader = new(textReader, new PasswordFinder(password));
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
@@ -242,10 +242,10 @@ namespace ExternalConnectors.DSS
// read private key pem string to rsacryptoserviceprovider
public static RSACryptoServiceProvider ImportPrivateKey(string pem)
{
- PemReader pr = new PemReader(new StringReader(pem));
+ PemReader pr = new(new StringReader(pem));
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
- RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
+ RSACryptoServiceProvider rsa = new();
rsa.ImportParameters(rsaParams);
return rsa;
}
diff --git a/ExternalConnectors/ExternalConnectors.csproj b/ExternalConnectors/ExternalConnectors.csproj
index ba51ca931..8d806aee8 100644
--- a/ExternalConnectors/ExternalConnectors.csproj
+++ b/ExternalConnectors/ExternalConnectors.csproj
@@ -15,9 +15,9 @@
-
-
-
+
+
+
diff --git a/mRemoteNG/App/CompatibilityChecker.cs b/mRemoteNG/App/CompatibilityChecker.cs
index 0ef443c91..cbaeeabc4 100644
--- a/mRemoteNG/App/CompatibilityChecker.cs
+++ b/mRemoteNG/App/CompatibilityChecker.cs
@@ -35,13 +35,13 @@ namespace mRemoteNG.App
if (!FipsPolicyEnabledForServer2003() && !FipsPolicyEnabledForServer2008AndNewer()) return;
- var errorText = string.Format(Language.ErrorFipsPolicyIncompatible, GeneralAppInfo.ProductName);
+ string errorText = string.Format(Language.ErrorFipsPolicyIncompatible, GeneralAppInfo.ProductName);
messageCollector.AddMessage(MessageClass.ErrorMsg, errorText, true);
//About to pop up a message, let's not block it...
FrmSplashScreenNew.GetInstance().Close();
- var ShouldIStayOrShouldIGo = CTaskDialog.MessageBox(Application.ProductName, Language.CompatibilityProblemDetected, errorText, "", "", Language.CheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.OkCancel, ESysIcons.Warning, ESysIcons.Warning);
+ DialogResult ShouldIStayOrShouldIGo = CTaskDialog.MessageBox(Application.ProductName, Language.CompatibilityProblemDetected, errorText, "", "", Language.CheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.OkCancel, ESysIcons.Warning, ESysIcons.Warning);
if (CTaskDialog.VerificationChecked && ShouldIStayOrShouldIGo == DialogResult.OK)
{
messageCollector.AddMessage(MessageClass.ErrorMsg, "User requests that FIPS check be overridden", true);
@@ -56,7 +56,7 @@ namespace mRemoteNG.App
private static bool FipsPolicyEnabledForServer2003()
{
- var regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa");
+ RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa");
if (!(regKey?.GetValue("FIPSAlgorithmPolicy") is int fipsPolicy))
return false;
return fipsPolicy != 0;
@@ -64,7 +64,7 @@ namespace mRemoteNG.App
private static bool FipsPolicyEnabledForServer2008AndNewer()
{
- var regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy");
+ RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy");
if (!(regKey?.GetValue("Enabled") is int fipsPolicy))
return false;
return fipsPolicy != 0;
@@ -77,7 +77,7 @@ namespace mRemoteNG.App
if (!Settings.Default.CompatibilityWarnLenovoAutoScrollUtility)
return;
- var proccesses = new Process[] { };
+ Process[] proccesses = new Process[] { };
try
{
proccesses = Process.GetProcessesByName("virtscrl");
diff --git a/mRemoteNG/App/Export.cs b/mRemoteNG/App/Export.cs
index ecf935b8a..490855819 100644
--- a/mRemoteNG/App/Export.cs
+++ b/mRemoteNG/App/Export.cs
@@ -25,9 +25,9 @@ namespace mRemoteNG.App
{
try
{
- var saveFilter = new SaveFilter();
+ SaveFilter saveFilter = new();
- using (var exportForm = new FrmExport())
+ using (FrmExport exportForm = new())
{
if (selectedNode?.GetTreeNodeType() == TreeNodeType.Container)
exportForm.SelectedFolder = selectedNode as ContainerInfo;
@@ -81,9 +81,9 @@ namespace mRemoteNG.App
switch (saveFormat)
{
case SaveFormat.mRXML:
- var cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
- var rootNode = exportTarget.GetRootParent() as RootNodeInfo;
- var connectionNodeSerializer = new XmlConnectionNodeSerializer28(
+ ICryptographyProvider cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
+ RootNodeInfo rootNode = exportTarget.GetRootParent() as RootNodeInfo;
+ XmlConnectionNodeSerializer28 connectionNodeSerializer = new(
cryptographyProvider,
rootNode?.PasswordString
.ConvertToSecureString() ??
@@ -102,8 +102,8 @@ namespace mRemoteNG.App
throw new ArgumentOutOfRangeException(nameof(saveFormat), saveFormat, null);
}
- var serializedData = serializer.Serialize(exportTarget);
- var fileDataProvider = new FileDataProvider(fileName);
+ string serializedData = serializer.Serialize(exportTarget);
+ FileDataProvider fileDataProvider = new(fileName);
fileDataProvider.Save(serializedData);
}
catch (Exception ex)
diff --git a/mRemoteNG/App/Import.cs b/mRemoteNG/App/Import.cs
index d56e7d23b..f25a19d03 100644
--- a/mRemoteNG/App/Import.cs
+++ b/mRemoteNG/App/Import.cs
@@ -19,13 +19,13 @@ namespace mRemoteNG.App
{
try
{
- using (var openFileDialog = new OpenFileDialog())
+ using (OpenFileDialog openFileDialog = new())
{
openFileDialog.CheckFileExists = true;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Multiselect = true;
- var fileTypes = new List();
+ List fileTypes = new();
fileTypes.AddRange(new[] {Language.FilterAllImportable, "*.xml;*.rdp;*.rdg;*.dat;*.csv"});
fileTypes.AddRange(new[] {Language.FiltermRemoteXML, "*.xml"});
fileTypes.AddRange(new[] {Language.FiltermRemoteCSV, "*.csv"});
@@ -60,13 +60,13 @@ namespace mRemoteNG.App
{
using (Runtime.ConnectionsService.BatchedSavingContext())
{
- using (var openFileDialog = new OpenFileDialog())
+ using (OpenFileDialog openFileDialog = new())
{
openFileDialog.CheckFileExists = true;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Multiselect = false;
- var fileTypes = new List();
+ List fileTypes = new();
fileTypes.AddRange(new[] {Language.FiltermRemoteRemoteDesktopManagerCSV, "*.csv"});
openFileDialog.Filter = string.Join("|", fileTypes.ToArray());
@@ -74,7 +74,7 @@ namespace mRemoteNG.App
if (openFileDialog.ShowDialog() != DialogResult.OK)
return;
- var importer = new RemoteDesktopManagerImporter();
+ RemoteDesktopManagerImporter importer = new();
importer.Import(openFileDialog.FileName, importDestinationContainer);
}
}
@@ -93,11 +93,11 @@ namespace mRemoteNG.App
{
using (connectionsService.BatchedSavingContext())
{
- foreach (var fileName in filePaths)
+ foreach (string fileName in filePaths)
{
try
{
- var importer = BuildConnectionImporterFromFileExtension(fileName);
+ IConnectionImporter importer = BuildConnectionImporterFromFileExtension(fileName);
importer.Import(fileName, importDestinationContainer);
}
catch (Exception ex)
@@ -134,7 +134,7 @@ namespace mRemoteNG.App
{
using (Runtime.ConnectionsService.BatchedSavingContext())
{
- var importer = new PortScanImporter(protocol);
+ PortScanImporter importer = new(protocol);
importer.Import(hosts, importDestinationContainer);
}
}
@@ -162,7 +162,7 @@ namespace mRemoteNG.App
private static IConnectionImporter BuildConnectionImporterFromFileExtension(string fileName)
{
// TODO: Use the file contents to determine the file type instead of trusting the extension
- var extension = Path.GetExtension(fileName) ?? "";
+ string extension = Path.GetExtension(fileName) ?? "";
switch (extension.ToLowerInvariant())
{
case ".xml":
diff --git a/mRemoteNG/App/Info/ConnectionsFileInfo.cs b/mRemoteNG/App/Info/ConnectionsFileInfo.cs
index ded493ff5..e5c4efdf9 100644
--- a/mRemoteNG/App/Info/ConnectionsFileInfo.cs
+++ b/mRemoteNG/App/Info/ConnectionsFileInfo.cs
@@ -9,6 +9,6 @@ namespace mRemoteNG.App.Info
public static readonly string DefaultConnectionsPath = SettingsFileInfo.SettingsPath;
public static readonly string DefaultConnectionsFile = "confCons.xml";
public static readonly string DefaultConnectionsFileNew = "confConsNew.xml";
- public static readonly Version ConnectionFileVersion = new Version(3, 0);
+ public static readonly Version ConnectionFileVersion = new(3, 0);
}
}
\ No newline at end of file
diff --git a/mRemoteNG/App/Info/GeneralAppInfo.cs b/mRemoteNG/App/Info/GeneralAppInfo.cs
index 639922e13..1dff82183 100644
--- a/mRemoteNG/App/Info/GeneralAppInfo.cs
+++ b/mRemoteNG/App/Info/GeneralAppInfo.cs
@@ -18,25 +18,25 @@ namespace mRemoteNG.App.Info
public const string UrlForum = "https://www.reddit.com/r/mRemoteNG";
public const string UrlBugs = "https://bugs.mremoteng.org";
public const string UrlDocumentation = "https://mremoteng.readthedocs.io/en/latest/";
- public static string ApplicationVersion = Application.ProductVersion;
+ public static readonly string ApplicationVersion = Application.ProductVersion;
public static readonly string ProductName = Application.ProductName;
public static readonly string Copyright = ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCopyrightAttribute), false))?.Copyright;
public static readonly string HomePath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
//public static string ReportingFilePath = "";
- public static readonly string PuttyPath = HomePath + "\\PuTTYNG.exe";
+ private static readonly string puttyPath = HomePath + "\\PuTTYNG.exe";
public static string UserAgent
{
get
{
- var details = new List
- {
+ List details =
+ [
"compatible",
OSVersion.Platform == PlatformID.Win32NT
? $"Windows NT {OSVersion.Version.Major}.{OSVersion.Version.Minor}"
: OSVersion.VersionString
- };
+ ];
if (Is64BitProcess)
{
details.Add("WOW64");
@@ -44,15 +44,17 @@ namespace mRemoteNG.App.Info
details.Add(Thread.CurrentThread.CurrentUICulture.Name);
details.Add($".NET CLR {Environment.Version}");
- var detailsString = string.Join("; ", details.ToArray());
+ string detailsString = string.Join("; ", [.. details]);
return $"Mozilla/5.0 ({detailsString}) {ProductName}/{ApplicationVersion}";
}
}
+ public static string PuttyPath => puttyPath;
+
public static Version GetApplicationVersion()
{
- System.Version.TryParse(ApplicationVersion, out var v);
+ _ = System.Version.TryParse(ApplicationVersion, out Version v);
return v;
}
}
diff --git a/mRemoteNG/App/Info/UpdateChannelInfo.cs b/mRemoteNG/App/Info/UpdateChannelInfo.cs
index b1fe138f2..8821337dd 100644
--- a/mRemoteNG/App/Info/UpdateChannelInfo.cs
+++ b/mRemoteNG/App/Info/UpdateChannelInfo.cs
@@ -24,7 +24,7 @@ namespace mRemoteNG.App.Info
public static Uri GetUpdateChannelInfo()
{
- var channel = IsValidChannel(Properties.OptionsUpdatesPage.Default.UpdateChannel) ? Properties.OptionsUpdatesPage.Default.UpdateChannel : STABLE;
+ string channel = IsValidChannel(Properties.OptionsUpdatesPage.Default.UpdateChannel) ? Properties.OptionsUpdatesPage.Default.UpdateChannel : STABLE;
return GetUpdateTxtUri(channel);
}
diff --git a/mRemoteNG/App/Initialization/ConnectionIconLoader.cs b/mRemoteNG/App/Initialization/ConnectionIconLoader.cs
index 1f27ba17e..8548252b4 100644
--- a/mRemoteNG/App/Initialization/ConnectionIconLoader.cs
+++ b/mRemoteNG/App/Initialization/ConnectionIconLoader.cs
@@ -24,9 +24,9 @@ namespace mRemoteNG.App.Initialization
if (Directory.Exists(_path) == false)
return;
- foreach (var f in Directory.GetFiles(_path, "*.ico", SearchOption.AllDirectories))
+ foreach (string f in Directory.GetFiles(_path, "*.ico", SearchOption.AllDirectories))
{
- var fInfo = new FileInfo(f);
+ FileInfo fInfo = new(f);
Array.Resize(ref ConnectionIcon.Icons, ConnectionIcon.Icons.Length + 1);
ConnectionIcon.Icons.SetValue(fInfo.Name.Replace(".ico", ""), ConnectionIcon.Icons.Length - 1);
}
diff --git a/mRemoteNG/App/Initialization/MessageCollectorSetup.cs b/mRemoteNG/App/Initialization/MessageCollectorSetup.cs
index 00602649a..38c5215c3 100644
--- a/mRemoteNG/App/Initialization/MessageCollectorSetup.cs
+++ b/mRemoteNG/App/Initialization/MessageCollectorSetup.cs
@@ -19,9 +19,9 @@ namespace mRemoteNG.App.Initialization
IMessage[] messages = args.NewItems.Cast().ToArray();
- foreach (var printer in messageWriterList)
+ foreach (IMessageWriter printer in messageWriterList)
{
- foreach (var message in messages)
+ foreach (IMessage message in messages)
{
printer.Write(message);
}
diff --git a/mRemoteNG/App/Initialization/StartupDataLogger.cs b/mRemoteNG/App/Initialization/StartupDataLogger.cs
index 33faa4ba2..49e211c11 100644
--- a/mRemoteNG/App/Initialization/StartupDataLogger.cs
+++ b/mRemoteNG/App/Initialization/StartupDataLogger.cs
@@ -29,24 +29,24 @@ namespace mRemoteNG.App.Initialization
private void LogSystemData()
{
- var osData = GetOperatingSystemData();
- var architecture = GetArchitectureData();
- var nonEmptyData = Array.FindAll(new[] {osData, architecture}, s => !string.IsNullOrEmpty(s));
- var data = string.Join(" ", nonEmptyData);
+ string osData = GetOperatingSystemData();
+ string architecture = GetArchitectureData();
+ string[] nonEmptyData = Array.FindAll(new[] {osData, architecture}, s => !string.IsNullOrEmpty(s));
+ string data = string.Join(" ", nonEmptyData);
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
private string GetOperatingSystemData()
{
- var osVersion = string.Empty;
- var servicePack = string.Empty;
+ string osVersion = string.Empty;
+ string servicePack = string.Empty;
try
{
- foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary=True")
+ foreach (ManagementBaseObject o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary=True")
.Get())
{
- var managementObject = (ManagementObject)o;
+ ManagementObject managementObject = (ManagementObject)o;
osVersion = Convert.ToString(managementObject.GetPropertyValue("Caption"))?.Trim();
servicePack = GetOSServicePack(servicePack, managementObject);
}
@@ -56,13 +56,13 @@ namespace mRemoteNG.App.Initialization
_messageCollector.AddExceptionMessage("Error retrieving operating system information from WMI.", ex);
}
- var osData = string.Join(" ", osVersion, servicePack);
+ string osData = string.Join(" ", osVersion, servicePack);
return osData;
}
private string GetOSServicePack(string servicePack, ManagementObject managementObject)
{
- var servicePackNumber = Convert.ToInt32(managementObject.GetPropertyValue("ServicePackMajorVersion"));
+ int servicePackNumber = Convert.ToInt32(managementObject.GetPropertyValue("ServicePackMajorVersion"));
if (servicePackNumber != 0)
{
servicePack = $"Service Pack {servicePackNumber}";
@@ -73,13 +73,13 @@ namespace mRemoteNG.App.Initialization
private string GetArchitectureData()
{
- var architecture = string.Empty;
+ string architecture = string.Empty;
try
{
- foreach (var o in new ManagementObjectSearcher("SELECT AddressWidth FROM Win32_Processor WHERE DeviceID=\'CPU0\'").Get())
+ foreach (ManagementBaseObject o in new ManagementObjectSearcher("SELECT AddressWidth FROM Win32_Processor WHERE DeviceID=\'CPU0\'").Get())
{
- var managementObject = (ManagementObject)o;
- var addressWidth = Convert.ToInt32(managementObject.GetPropertyValue("AddressWidth"));
+ ManagementObject managementObject = (ManagementObject)o;
+ int addressWidth = Convert.ToInt32(managementObject.GetPropertyValue("AddressWidth"));
architecture = $"{addressWidth}-bit";
}
}
@@ -93,7 +93,7 @@ namespace mRemoteNG.App.Initialization
private void LogApplicationData()
{
- var data = $"{Application.ProductName} {Application.ProductVersion}";
+ string data = $"{Application.ProductName} {Application.ProductVersion}";
if (Runtime.IsPortableEdition)
data += $" {Language.PortableEdition}";
data += " starting.";
@@ -102,19 +102,19 @@ namespace mRemoteNG.App.Initialization
private void LogCmdLineArgs()
{
- var data = $"Command Line: {string.Join(" ", Environment.GetCommandLineArgs())}";
+ string data = $"Command Line: {string.Join(" ", Environment.GetCommandLineArgs())}";
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
private void LogClrData()
{
- var data = $"Microsoft .NET CLR {Environment.Version}";
+ string data = $"Microsoft .NET CLR {Environment.Version}";
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
private void LogCultureData()
{
- var data = $"System Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}";
+ string data = $"System Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}";
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
}
diff --git a/mRemoteNG/App/Logger.cs b/mRemoteNG/App/Logger.cs
index 5667b04cd..59e9d6a03 100644
--- a/mRemoteNG/App/Logger.cs
+++ b/mRemoteNG/App/Logger.cs
@@ -12,7 +12,7 @@ namespace mRemoteNG.App
[SupportedOSPlatform("windows")]
public class Logger
{
- public static readonly Logger Instance = new Logger();
+ public static readonly Logger Instance = new();
public ILog Log { get; private set; }
@@ -43,7 +43,7 @@ namespace mRemoteNG.App
IAppender[] appenders = repository.GetAppenders();
- foreach (var appender in appenders)
+ foreach (IAppender appender in appenders)
{
RollingFileAppender fileAppender = (RollingFileAppender)appender;
if (fileAppender is not { Name: "LogFileAppender" }) continue;
diff --git a/mRemoteNG/App/ProgramRoot.cs b/mRemoteNG/App/ProgramRoot.cs
index 6b9c57db7..c58918945 100644
--- a/mRemoteNG/App/ProgramRoot.cs
+++ b/mRemoteNG/App/ProgramRoot.cs
@@ -48,7 +48,7 @@ namespace mRemoteNG.App
_frmSplashScreen = FrmSplashScreenNew.GetInstance();
- var targetScreen = Screen.PrimaryScreen;
+ Screen targetScreen = Screen.PrimaryScreen;
Rectangle viewport = targetScreen.WorkingArea;
_frmSplashScreen.Top = viewport.Top;
@@ -70,7 +70,7 @@ namespace mRemoteNG.App
private static void StartApplicationAsSingleInstance()
{
const string mutexID = "mRemoteNG_SingleInstanceMutex";
- _mutex = new Mutex(false, mutexID, out var newInstanceCreated);
+ _mutex = new Mutex(false, mutexID, out bool newInstanceCreated);
if (!newInstanceCreated)
{
SwitchToCurrentInstance();
@@ -83,7 +83,7 @@ namespace mRemoteNG.App
private static void SwitchToCurrentInstance()
{
- var singletonInstanceWindowHandle = GetRunningSingletonInstanceWindowHandle();
+ IntPtr singletonInstanceWindowHandle = GetRunningSingletonInstanceWindowHandle();
if (singletonInstanceWindowHandle == IntPtr.Zero) return;
if (NativeMethods.IsIconic(singletonInstanceWindowHandle) != 0)
_ = NativeMethods.ShowWindow(singletonInstanceWindowHandle, (int)NativeMethods.SW_RESTORE);
@@ -92,9 +92,9 @@ namespace mRemoteNG.App
private static IntPtr GetRunningSingletonInstanceWindowHandle()
{
- var windowHandle = IntPtr.Zero;
- var currentProcess = Process.GetCurrentProcess();
- foreach (var enumeratedProcess in Process.GetProcessesByName(currentProcess.ProcessName))
+ IntPtr windowHandle = IntPtr.Zero;
+ Process currentProcess = Process.GetCurrentProcess();
+ foreach (Process enumeratedProcess in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (enumeratedProcess.Id != currentProcess.Id &&
enumeratedProcess.MainModule.FileName == currentProcess.MainModule.FileName &&
@@ -119,7 +119,7 @@ namespace mRemoteNG.App
if (FrmMain.Default.IsDisposed) return;
- var window = new FrmUnhandledException(e.Exception, false);
+ FrmUnhandledException window = new(e.Exception, false);
window.ShowDialog(FrmMain.Default);
}
@@ -129,7 +129,7 @@ namespace mRemoteNG.App
//if (!FrmSplashScreenNew.GetInstance().IsDisposed)
// FrmSplashScreenNew.GetInstance().Close();
- var window = new FrmUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
+ FrmUnhandledException window = new(e.ExceptionObject as Exception, e.IsTerminating);
window.ShowDialog(FrmMain.Default);
}
}
diff --git a/mRemoteNG/App/Runtime.cs b/mRemoteNG/App/Runtime.cs
index 7b9c4d8e6..8a060acb9 100644
--- a/mRemoteNG/App/Runtime.cs
+++ b/mRemoteNG/App/Runtime.cs
@@ -58,7 +58,7 @@ namespace mRemoteNG.App
public static void LoadConnectionsAsync()
{
- var t = new Thread(LoadConnectionsBGd);
+ Thread t = new(LoadConnectionsBGd);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
@@ -77,7 +77,7 @@ namespace mRemoteNG.App
///
public static void LoadConnections(bool withDialog = false)
{
- var connectionFileName = "";
+ string connectionFileName = "";
try
{
@@ -86,7 +86,7 @@ namespace mRemoteNG.App
if (withDialog)
{
- var loadDialog = DialogFactory.BuildLoadConnectionsDialog();
+ OpenFileDialog loadDialog = DialogFactory.BuildLoadConnectionsDialog();
if (loadDialog.ShowDialog() != DialogResult.OK)
return;
@@ -120,7 +120,7 @@ namespace mRemoteNG.App
if (Properties.OptionsDBsPage.Default.UseSQLServer)
{
MessageCollector.AddExceptionMessage(Language.LoadFromSqlFailed, ex);
- var commandButtons = string.Join("|", Language._TryAgain, Language.CommandOpenConnectionFile, string.Format(Language.CommandExitProgram, Application.ProductName));
+ string commandButtons = string.Join("|", Language._TryAgain, Language.CommandOpenConnectionFile, string.Format(Language.CommandExitProgram, Application.ProductName));
CTaskDialog.ShowCommandBox(Application.ProductName, Language.LoadFromSqlFailed, Language.LoadFromSqlFailedContent, MiscTools.GetExceptionMessageRecursive(ex), "", "", commandButtons, false, ESysIcons.Error, ESysIcons.Error);
switch (CTaskDialog.CommandButtonResult)
{
@@ -152,7 +152,7 @@ namespace mRemoteNG.App
Language.Exit
};
- var answered = false;
+ bool answered = false;
while (!answered)
{
try
diff --git a/mRemoteNG/App/Screens.cs b/mRemoteNG/App/Screens.cs
index 96485717c..04d954c4d 100644
--- a/mRemoteNG/App/Screens.cs
+++ b/mRemoteNG/App/Screens.cs
@@ -10,8 +10,8 @@ namespace mRemoteNG.App
[SupportedOSPlatform("windows")]
public static void SendFormToScreen(Screen screen)
{
- var frmMain = FrmMain.Default;
- var wasMax = false;
+ FrmMain frmMain = FrmMain.Default;
+ bool wasMax = false;
if (frmMain.WindowState == FormWindowState.Maximized)
{
diff --git a/mRemoteNG/App/Startup.cs b/mRemoteNG/App/Startup.cs
index e130c19c4..5ac628251 100644
--- a/mRemoteNG/App/Startup.cs
+++ b/mRemoteNG/App/Startup.cs
@@ -34,14 +34,10 @@ namespace mRemoteNG.App
_connectionIconLoader = new ConnectionIconLoader(GeneralAppInfo.HomePath + "\\Icons\\");
}
- static Startup()
- {
- }
-
public void InitializeProgram(MessageCollector messageCollector)
{
Debug.Print("---------------------------" + Environment.NewLine + "[START] - " + Convert.ToString(DateTime.Now, CultureInfo.InvariantCulture));
- var startupLogger = new StartupDataLogger(messageCollector);
+ StartupDataLogger startupLogger = new(messageCollector);
startupLogger.LogStartupData();
CompatibilityChecker.CheckCompatibility(messageCollector);
ParseCommandLineArgs(messageCollector);
@@ -53,7 +49,7 @@ namespace mRemoteNG.App
private static void ParseCommandLineArgs(MessageCollector messageCollector)
{
- var interpreter = new StartupArgumentsInterpreter(messageCollector);
+ StartupArgumentsInterpreter interpreter = new(messageCollector);
interpreter.ParseArguments(Environment.GetCommandLineArgs());
}
@@ -77,8 +73,7 @@ namespace mRemoteNG.App
return;
}
- var nextUpdateCheck =
- Convert.ToDateTime(Properties.OptionsUpdatesPage.Default.CheckForUpdatesLastCheck.Add(TimeSpan.FromDays(Convert.ToDouble(Properties.OptionsUpdatesPage.Default.CheckForUpdatesFrequencyDays))));
+ DateTime nextUpdateCheck = Convert.ToDateTime(Properties.OptionsUpdatesPage.Default.CheckForUpdatesLastCheck.Add(TimeSpan.FromDays(Convert.ToDouble(Properties.OptionsUpdatesPage.Default.CheckForUpdatesFrequencyDays))));
if (!Properties.OptionsUpdatesPage.Default.UpdatePending && DateTime.UtcNow < nextUpdateCheck)
{
return;
diff --git a/mRemoteNG/App/SupportedCultures.cs b/mRemoteNG/App/SupportedCultures.cs
index 177f52b82..840ad0588 100644
--- a/mRemoteNG/App/SupportedCultures.cs
+++ b/mRemoteNG/App/SupportedCultures.cs
@@ -24,11 +24,11 @@ namespace mRemoteNG.App
private SupportedCultures()
{
- foreach (var CultureName in Properties.AppUI.Default.SupportedUICultures.Split(','))
+ foreach (string CultureName in Properties.AppUI.Default.SupportedUICultures.Split(','))
{
try
{
- var CultureInfo = new CultureInfo(CultureName.Trim());
+ CultureInfo CultureInfo = new(CultureName.Trim());
Add(CultureInfo.Name, CultureInfo.TextInfo.ToTitleCase(CultureInfo.NativeName));
}
catch (Exception ex)
@@ -57,13 +57,13 @@ namespace mRemoteNG.App
public static string get_CultureName(string CultureNativeName)
{
- var Names = new string[SingletonInstance.Count + 1];
- var NativeNames = new string[SingletonInstance.Count + 1];
+ string[] Names = new string[SingletonInstance.Count + 1];
+ string[] NativeNames = new string[SingletonInstance.Count + 1];
SingletonInstance.Keys.CopyTo(Names, 0);
SingletonInstance.Values.CopyTo(NativeNames, 0);
- for (var Index = 0; Index <= SingletonInstance.Count; Index++)
+ for (int Index = 0; Index <= SingletonInstance.Count; Index++)
{
if (NativeNames[Index] == CultureNativeName)
{
@@ -83,8 +83,8 @@ namespace mRemoteNG.App
{
get
{
- var ValueList = new List();
- foreach (var Value in SingletonInstance.Values)
+ List ValueList = new();
+ foreach (string Value in SingletonInstance.Values)
{
ValueList.Add(Value);
}
diff --git a/mRemoteNG/App/Update/AppUpdater.cs b/mRemoteNG/App/Update/AppUpdater.cs
index c33bb1453..93d9a747b 100644
--- a/mRemoteNG/App/Update/AppUpdater.cs
+++ b/mRemoteNG/App/Update/AppUpdater.cs
@@ -60,13 +60,13 @@ namespace mRemoteNG.App.Update
private void SetDefaultProxySettings()
{
- var shouldWeUseProxy = Properties.OptionsUpdatesPage.Default.UpdateUseProxy;
- var proxyAddress = Properties.OptionsUpdatesPage.Default.UpdateProxyAddress;
- var port = Properties.OptionsUpdatesPage.Default.UpdateProxyPort;
- var useAuthentication = Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication;
- var username = Properties.OptionsUpdatesPage.Default.UpdateProxyAuthUser;
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
- var password = cryptographyProvider.Decrypt(Properties.OptionsUpdatesPage.Default.UpdateProxyAuthPass, Runtime.EncryptionKey);
+ bool shouldWeUseProxy = Properties.OptionsUpdatesPage.Default.UpdateUseProxy;
+ string proxyAddress = Properties.OptionsUpdatesPage.Default.UpdateProxyAddress;
+ int port = Properties.OptionsUpdatesPage.Default.UpdateProxyPort;
+ bool useAuthentication = Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication;
+ string username = Properties.OptionsUpdatesPage.Default.UpdateProxyAuthUser;
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
+ string password = cryptographyProvider.Decrypt(Properties.OptionsUpdatesPage.Default.UpdateProxyAuthPass, Runtime.EncryptionKey);
SetProxySettings(shouldWeUseProxy, proxyAddress, port, useAuthentication, username, password);
}
@@ -132,19 +132,19 @@ namespace mRemoteNG.App.Update
try
{
_getUpdateInfoCancelToken = new CancellationTokenSource();
- using var response = await _httpClient.GetAsync(CurrentUpdateInfo.DownloadAddress, HttpCompletionOption.ResponseHeadersRead, _getUpdateInfoCancelToken.Token);
- var buffer = new byte[_bufferLength];
- var totalBytes = response.Content.Headers.ContentLength ?? 0;
- var readBytes = 0L;
+ using HttpResponseMessage response = await _httpClient.GetAsync(CurrentUpdateInfo.DownloadAddress, HttpCompletionOption.ResponseHeadersRead, _getUpdateInfoCancelToken.Token);
+ byte[] buffer = new byte[_bufferLength];
+ long totalBytes = response.Content.Headers.ContentLength ?? 0;
+ long readBytes = 0L;
- await using (var httpStream = await response.Content.ReadAsStreamAsync(_getUpdateInfoCancelToken.Token))
+ await using (Stream httpStream = await response.Content.ReadAsStreamAsync(_getUpdateInfoCancelToken.Token))
{
- await using var fileStream = new FileStream(CurrentUpdateInfo.UpdateFilePath, FileMode.Create,
+ await using FileStream fileStream = new(CurrentUpdateInfo.UpdateFilePath, FileMode.Create,
FileAccess.Write, FileShare.None, _bufferLength, true);
while (readBytes <= totalBytes || !_getUpdateInfoCancelToken.IsCancellationRequested)
{
- var bytesRead =
+ int bytesRead =
await httpStream.ReadAsync(buffer, 0, _bufferLength, _getUpdateInfoCancelToken.Token);
if (bytesRead == 0)
{
@@ -156,13 +156,13 @@ namespace mRemoteNG.App.Update
readBytes += bytesRead;
- var percentComplete = (int)(readBytes * 100 / totalBytes);
+ int percentComplete = (int)(readBytes * 100 / totalBytes);
progress.Report(percentComplete);
}
}
#if !PORTABLE
- var updateAuthenticode = new Authenticode(CurrentUpdateInfo.UpdateFilePath)
+ Authenticode updateAuthenticode = new(CurrentUpdateInfo.UpdateFilePath)
{
RequireThumbprintMatch = true,
ThumbprintToMatch = CurrentUpdateInfo.CertificateThumbprint
@@ -179,10 +179,10 @@ namespace mRemoteNG.App.Update
}
#endif
- using var checksum = SHA512.Create();
- await using var stream = File.OpenRead(CurrentUpdateInfo.UpdateFilePath);
- var hash = await checksum.ComputeHashAsync(stream);
- var hashString = BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
+ using SHA512 checksum = SHA512.Create();
+ await using FileStream stream = File.OpenRead(CurrentUpdateInfo.UpdateFilePath);
+ byte[] hash = await checksum.ComputeHashAsync(stream);
+ string hashString = BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
if (!hashString.Equals(CurrentUpdateInfo.Checksum))
throw new Exception("SHA512 Hashes didn't match!");
} finally{
@@ -202,7 +202,7 @@ namespace mRemoteNG.App.Update
_httpClient.Dispose();
}
- var httpClientHandler = new HttpClientHandler();
+ HttpClientHandler httpClientHandler = new();
if (_webProxy != null)
{
httpClientHandler.UseProxy = true;
@@ -224,7 +224,7 @@ namespace mRemoteNG.App.Update
try
{
_getUpdateInfoCancelToken = new CancellationTokenSource();
- var updateInfo = await _httpClient.GetStringAsync(UpdateChannelInfo.GetUpdateChannelInfo(), _getUpdateInfoCancelToken.Token);
+ string updateInfo = await _httpClient.GetStringAsync(UpdateChannelInfo.GetUpdateChannelInfo(), _getUpdateInfoCancelToken.Token);
CurrentUpdateInfo = UpdateInfo.FromString(updateInfo);
Properties.OptionsUpdatesPage.Default.CheckForUpdatesLastCheck = DateTime.UtcNow;
diff --git a/mRemoteNG/App/Update/UpdateFile.cs b/mRemoteNG/App/Update/UpdateFile.cs
index fae08418b..e4b2f6f5a 100644
--- a/mRemoteNG/App/Update/UpdateFile.cs
+++ b/mRemoteNG/App/Update/UpdateFile.cs
@@ -34,19 +34,19 @@ namespace mRemoteNG.App.Update
// no separators means no valid update data...
if (content.Trim().IndexOfAny(keyValueSeparators) == -1) return;
- using (var sr = new StringReader(content))
+ using (StringReader sr = new(content))
{
string line;
while ((line = sr.ReadLine()) != null)
{
- var trimmedLine = line.Trim();
+ string trimmedLine = line.Trim();
if (trimmedLine.Length == 0)
continue;
if (trimmedLine.Substring(0, 1).IndexOfAny(commentCharacters) != -1)
continue;
- var parts = trimmedLine.Split(keyValueSeparators, 2);
+ string[] parts = trimmedLine.Split(keyValueSeparators, 2);
if (parts.Length != 2)
continue;
@@ -68,13 +68,13 @@ namespace mRemoteNG.App.Update
public Version GetVersion(string key = "Version")
{
- var value = GetString(key);
+ string value = GetString(key);
return string.IsNullOrEmpty(value) ? null : new Version(value);
}
public Uri GetUri(string key)
{
- var value = GetString(key);
+ string value = GetString(key);
return string.IsNullOrEmpty(value) ? null : new Uri(value);
}
@@ -85,8 +85,8 @@ namespace mRemoteNG.App.Update
public string GetFileName()
{
- var value = GetString("dURL");
- var sv = value.Split('/');
+ string value = GetString("dURL");
+ string[] sv = value.Split('/');
return sv[sv.Length - 1];
}
diff --git a/mRemoteNG/App/Update/UpdateInfo.cs b/mRemoteNG/App/Update/UpdateInfo.cs
index 0d2ad4c60..33418b6c6 100644
--- a/mRemoteNG/App/Update/UpdateInfo.cs
+++ b/mRemoteNG/App/Update/UpdateInfo.cs
@@ -22,14 +22,14 @@ namespace mRemoteNG.App.Update
public static UpdateInfo FromString(string input)
{
- var newInfo = new UpdateInfo();
+ UpdateInfo newInfo = new();
if (string.IsNullOrEmpty(input))
{
newInfo.IsValid = false;
}
else
{
- var updateFile = new UpdateFile(input);
+ UpdateFile updateFile = new(input);
newInfo.Version = updateFile.GetVersion();
newInfo.DownloadAddress = updateFile.GetUri("dURL");
newInfo.ChangeLogAddress = updateFile.GetUri("clURL");
diff --git a/mRemoteNG/App/Windows.cs b/mRemoteNG/App/Windows.cs
index 283a17f19..d026d3aff 100644
--- a/mRemoteNG/App/Windows.cs
+++ b/mRemoteNG/App/Windows.cs
@@ -34,7 +34,7 @@ namespace mRemoteNG.App
{
try
{
- var dockPanel = FrmMain.Default.pnlDock;
+ WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel = FrmMain.Default.pnlDock;
// ReSharper disable once SwitchStatementMissingSomeCases
switch (windowType)
{
diff --git a/mRemoteNG/Config/Connections/CsvConnectionsSaver.cs b/mRemoteNG/Config/Connections/CsvConnectionsSaver.cs
index 01790264f..51a922e4b 100644
--- a/mRemoteNG/Config/Connections/CsvConnectionsSaver.cs
+++ b/mRemoteNG/Config/Connections/CsvConnectionsSaver.cs
@@ -27,10 +27,10 @@ namespace mRemoteNG.Config.Connections
public void Save(ConnectionTreeModel connectionTreeModel, string propertyNameTrigger = "")
{
- var csvConnectionsSerializer =
- new CsvConnectionsSerializerMremotengFormat(_saveFilter, Runtime.CredentialProviderCatalog);
- var dataProvider = new FileDataProvider(_connectionFileName);
- var csvContent = csvConnectionsSerializer.Serialize(connectionTreeModel);
+ CsvConnectionsSerializerMremotengFormat csvConnectionsSerializer =
+ new(_saveFilter, Runtime.CredentialProviderCatalog);
+ FileDataProvider dataProvider = new(_connectionFileName);
+ string csvContent = csvConnectionsSerializer.Serialize(connectionTreeModel);
dataProvider.Save(csvContent);
}
}
diff --git a/mRemoteNG/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs b/mRemoteNG/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs
index 15e7c4329..8dad417f1 100644
--- a/mRemoteNG/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs
+++ b/mRemoteNG/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs
@@ -29,7 +29,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
{
RaiseUpdateCheckStartedEvent();
ConnectToSqlDb();
- var updateIsAvailable = DatabaseIsMoreUpToDateThanUs();
+ bool updateIsAvailable = DatabaseIsMoreUpToDateThanUs();
if (updateIsAvailable)
RaiseConnectionsUpdateAvailableEvent();
RaiseUpdateCheckFinishedEvent(updateIsAvailable);
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
public void IsUpdateAvailableAsync()
{
- var thread = new Thread(() => IsUpdateAvailable());
+ Thread thread = new(() => IsUpdateAvailable());
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
@@ -57,14 +57,14 @@ namespace mRemoteNG.Config.Connections.Multiuser
private bool DatabaseIsMoreUpToDateThanUs()
{
- var lastUpdateInDb = GetLastUpdateTimeFromDbResponse();
- var amTheLastoneUpdated = CheckIfIAmTheLastOneUpdated(lastUpdateInDb);
+ DateTime lastUpdateInDb = GetLastUpdateTimeFromDbResponse();
+ bool amTheLastoneUpdated = CheckIfIAmTheLastOneUpdated(lastUpdateInDb);
return (lastUpdateInDb > LastUpdateTime && !amTheLastoneUpdated);
}
private bool CheckIfIAmTheLastOneUpdated(DateTime lastUpdateInDb)
{
- DateTime lastSqlUpdateWithoutMilliseconds = new DateTime(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), LastUpdateTime.Kind);
+ DateTime lastSqlUpdateWithoutMilliseconds = new(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), LastUpdateTime.Kind);
return lastUpdateInDb == lastSqlUpdateWithoutMilliseconds;
}
@@ -104,7 +104,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
private void RaiseUpdateCheckFinishedEvent(bool updateAvailable)
{
- var args = new ConnectionsUpdateCheckFinishedEventArgs {UpdateAvailable = updateAvailable};
+ ConnectionsUpdateCheckFinishedEventArgs args = new() { UpdateAvailable = updateAvailable};
UpdateCheckFinished?.Invoke(this, args);
}
@@ -113,7 +113,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
private void RaiseConnectionsUpdateAvailableEvent()
{
Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, "Remote connection update is available");
- var args = new ConnectionsUpdateAvailableEventArgs(_dbConnector, _lastDatabaseUpdateTime);
+ ConnectionsUpdateAvailableEventArgs args = new(_dbConnector, _lastDatabaseUpdateTime);
ConnectionsUpdateAvailable?.Invoke(this, args);
}
diff --git a/mRemoteNG/Config/Connections/SaveConnectionsOnEdit.cs b/mRemoteNG/Config/Connections/SaveConnectionsOnEdit.cs
index 2e5e1cce6..2112d7e02 100644
--- a/mRemoteNG/Config/Connections/SaveConnectionsOnEdit.cs
+++ b/mRemoteNG/Config/Connections/SaveConnectionsOnEdit.cs
@@ -27,7 +27,7 @@ namespace mRemoteNG.Config.Connections
connectionsLoadedEventArgs.NewConnectionTreeModel.CollectionChanged += ConnectionTreeModelOnCollectionChanged;
connectionsLoadedEventArgs.NewConnectionTreeModel.PropertyChanged += ConnectionTreeModelOnPropertyChanged;
- foreach (var oldTree in connectionsLoadedEventArgs.PreviousConnectionTreeModel)
+ foreach (Tree.ConnectionTreeModel oldTree in connectionsLoadedEventArgs.PreviousConnectionTreeModel)
{
oldTree.CollectionChanged -= ConnectionTreeModelOnCollectionChanged;
oldTree.PropertyChanged -= ConnectionTreeModelOnPropertyChanged;
diff --git a/mRemoteNG/Config/Connections/SqlConnectionsLoader.cs b/mRemoteNG/Config/Connections/SqlConnectionsLoader.cs
index 5a2d5d9b0..5b2936b05 100644
--- a/mRemoteNG/Config/Connections/SqlConnectionsLoader.cs
+++ b/mRemoteNG/Config/Connections/SqlConnectionsLoader.cs
@@ -37,39 +37,39 @@ namespace mRemoteNG.Config.Connections
public ConnectionTreeModel Load()
{
- var connector = DatabaseConnectorFactory.DatabaseConnectorFromSettings();
- var dataProvider = new SqlDataProvider(connector);
- var metaDataRetriever = new SqlDatabaseMetaDataRetriever();
- var databaseVersionVerifier = new SqlDatabaseVersionVerifier(connector);
- var cryptoProvider = new LegacyRijndaelCryptographyProvider();
- var metaData = metaDataRetriever.GetDatabaseMetaData(connector) ?? HandleFirstRun(metaDataRetriever, connector);
- var decryptionKey = GetDecryptionKey(metaData);
+ IDatabaseConnector connector = DatabaseConnectorFactory.DatabaseConnectorFromSettings();
+ SqlDataProvider dataProvider = new(connector);
+ SqlDatabaseMetaDataRetriever metaDataRetriever = new();
+ SqlDatabaseVersionVerifier databaseVersionVerifier = new(connector);
+ LegacyRijndaelCryptographyProvider cryptoProvider = new();
+ SqlConnectionListMetaData metaData = metaDataRetriever.GetDatabaseMetaData(connector) ?? HandleFirstRun(metaDataRetriever, connector);
+ Optional decryptionKey = GetDecryptionKey(metaData);
if (!decryptionKey.Any())
throw new Exception("Could not load SQL connections");
databaseVersionVerifier.VerifyDatabaseVersion(metaData.ConfVersion);
- var dataTable = dataProvider.Load();
- var deserializer = new DataTableDeserializer(cryptoProvider, decryptionKey.First());
- var connectionTree = deserializer.Deserialize(dataTable);
+ System.Data.DataTable dataTable = dataProvider.Load();
+ DataTableDeserializer deserializer = new(cryptoProvider, decryptionKey.First());
+ ConnectionTreeModel connectionTree = deserializer.Deserialize(dataTable);
ApplyLocalConnectionProperties(connectionTree.RootNodes.First(i => i is RootNodeInfo));
return connectionTree;
}
private Optional GetDecryptionKey(SqlConnectionListMetaData metaData)
{
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
- var cipherText = metaData.Protected;
- var authenticator = new PasswordAuthenticator(cryptographyProvider, cipherText, AuthenticationRequestor);
- var authenticated = authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword.ConvertToSecureString());
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
+ string cipherText = metaData.Protected;
+ PasswordAuthenticator authenticator = new(cryptographyProvider, cipherText, AuthenticationRequestor);
+ bool authenticated = authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword.ConvertToSecureString());
return authenticated ? authenticator.LastAuthenticatedPassword : Optional.Empty;
}
private void ApplyLocalConnectionProperties(ContainerInfo rootNode)
{
- var localPropertiesXml = _dataProvider.Load();
- var localConnectionProperties = _localConnectionPropertiesDeserializer.Deserialize(localPropertiesXml);
+ string localPropertiesXml = _dataProvider.Load();
+ IEnumerable localConnectionProperties = _localConnectionPropertiesDeserializer.Deserialize(localPropertiesXml);
rootNode
.GetRecursiveChildList()
diff --git a/mRemoteNG/Config/Connections/SqlConnectionsSaver.cs b/mRemoteNG/Config/Connections/SqlConnectionsSaver.cs
index bb379ccc6..0a0657cf6 100644
--- a/mRemoteNG/Config/Connections/SqlConnectionsSaver.cs
+++ b/mRemoteNG/Config/Connections/SqlConnectionsSaver.cs
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Connections
public void Save(ConnectionTreeModel connectionTreeModel, string propertyNameTrigger = "")
{
- var rootTreeNode = connectionTreeModel.RootNodes.OfType().First();
+ RootNodeInfo rootTreeNode = connectionTreeModel.RootNodes.OfType().First();
UpdateLocalConnectionProperties(rootTreeNode);
@@ -54,12 +54,12 @@ namespace mRemoteNG.Config.Connections
return;
}
- using (var dbConnector = DatabaseConnectorFactory.DatabaseConnectorFromSettings())
+ using (IDatabaseConnector dbConnector = DatabaseConnectorFactory.DatabaseConnectorFromSettings())
{
dbConnector.Connect();
- var databaseVersionVerifier = new SqlDatabaseVersionVerifier(dbConnector);
- var metaDataRetriever = new SqlDatabaseMetaDataRetriever();
- var metaData = metaDataRetriever.GetDatabaseMetaData(dbConnector);
+ SqlDatabaseVersionVerifier databaseVersionVerifier = new(dbConnector);
+ SqlDatabaseMetaDataRetriever metaDataRetriever = new();
+ SqlConnectionListMetaData metaData = metaDataRetriever.GetDatabaseMetaData(dbConnector);
if (!databaseVersionVerifier.VerifyDatabaseVersion(metaData.ConfVersion))
{
@@ -93,7 +93,7 @@ namespace mRemoteNG.Config.Connections
private void UpdateLocalConnectionProperties(ContainerInfo rootNode)
{
- var a = rootNode.GetRecursiveChildList().Select(info => new LocalConnectionPropertiesModel
+ IEnumerable a = rootNode.GetRecursiveChildList().Select(info => new LocalConnectionPropertiesModel
{
ConnectionId = info.ConstantID,
Connected = info.OpenConnections.Count > 0,
@@ -101,7 +101,7 @@ namespace mRemoteNG.Config.Connections
Favorite = info.Favorite,
});
- var serializedProperties = _localPropertiesSerializer.Serialize(a);
+ string serializedProperties = _localPropertiesSerializer.Serialize(a);
_dataProvider.Save(serializedProperties);
Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, "Saved local connection properties");
}
@@ -109,13 +109,13 @@ namespace mRemoteNG.Config.Connections
private void UpdateRootNodeTable(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
// TODO: use transaction, but method not used at all?
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string strProtected;
if (rootTreeNode != null)
{
if (rootTreeNode.Password)
{
- var password = rootTreeNode.PasswordString.ConvertToSecureString();
+ System.Security.SecureString password = rootTreeNode.PasswordString.ConvertToSecureString();
strProtected = cryptographyProvider.Encrypt("ThisIsProtected", password);
}
else
@@ -128,7 +128,7 @@ namespace mRemoteNG.Config.Connections
strProtected = cryptographyProvider.Encrypt("ThisIsNotProtected", Runtime.EncryptionKey);
}
- var dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
+ System.Data.Common.DbCommand dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
dbQuery.ExecuteNonQuery();
if (rootTreeNode != null)
@@ -148,11 +148,11 @@ namespace mRemoteNG.Config.Connections
private void UpdateConnectionsTable(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
- SqlDataProvider dataProvider = new SqlDataProvider(databaseConnector);
+ SqlDataProvider dataProvider = new(databaseConnector);
DataTable currentDataTable = dataProvider.Load();
- LegacyRijndaelCryptographyProvider cryptoProvider = new LegacyRijndaelCryptographyProvider();
- DataTableSerializer serializer = new DataTableSerializer(_saveFilter, cryptoProvider, rootTreeNode.PasswordString.ConvertToSecureString());
+ LegacyRijndaelCryptographyProvider cryptoProvider = new();
+ DataTableSerializer serializer = new(_saveFilter, cryptoProvider, rootTreeNode.PasswordString.ConvertToSecureString());
serializer.SetSourceDataTable(currentDataTable);
DataTable dataTable = serializer.Serialize(rootTreeNode);
@@ -163,7 +163,7 @@ namespace mRemoteNG.Config.Connections
private void UpdateUpdatesTable(IDatabaseConnector databaseConnector)
{
// TODO: use transaction
- var dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblUpdate");
+ System.Data.Common.DbCommand dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblUpdate");
dbQuery.ExecuteNonQuery();
dbQuery = databaseConnector.DbCommand("INSERT INTO tblUpdate (LastUpdate) VALUES('" + MiscTools.DBDate(DateTime.Now.ToUniversalTime()) + "')");
dbQuery.ExecuteNonQuery();
diff --git a/mRemoteNG/Config/Connections/XmlConnectionsLoader.cs b/mRemoteNG/Config/Connections/XmlConnectionsLoader.cs
index 37680c90d..a6aa01702 100644
--- a/mRemoteNG/Config/Connections/XmlConnectionsLoader.cs
+++ b/mRemoteNG/Config/Connections/XmlConnectionsLoader.cs
@@ -27,15 +27,15 @@ namespace mRemoteNG.Config.Connections
public ConnectionTreeModel Load()
{
- var dataProvider = new FileDataProvider(_connectionFilePath);
- var xmlString = dataProvider.Load();
- var deserializer = new XmlConnectionsDeserializer(PromptForPassword);
+ FileDataProvider dataProvider = new(_connectionFilePath);
+ string xmlString = dataProvider.Load();
+ XmlConnectionsDeserializer deserializer = new(PromptForPassword);
return deserializer.Deserialize(xmlString);
}
private Optional PromptForPassword()
{
- var password = MiscTools.PasswordDialog(Path.GetFileName(_connectionFilePath), false);
+ Optional password = MiscTools.PasswordDialog(Path.GetFileName(_connectionFilePath), false);
return password;
}
}
diff --git a/mRemoteNG/Config/Connections/XmlConnectionsSaver.cs b/mRemoteNG/Config/Connections/XmlConnectionsSaver.cs
index af39698f5..c213b28e4 100644
--- a/mRemoteNG/Config/Connections/XmlConnectionsSaver.cs
+++ b/mRemoteNG/Config/Connections/XmlConnectionsSaver.cs
@@ -30,15 +30,15 @@ namespace mRemoteNG.Config.Connections
{
try
{
- var cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
- var serializerFactory = new XmlConnectionSerializerFactory();
-
- var xmlConnectionsSerializer = serializerFactory.Build(cryptographyProvider, connectionTreeModel, _saveFilter, Properties.OptionsSecurityPage.Default.EncryptCompleteConnectionsFile);
+ ICryptographyProvider cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
+ XmlConnectionSerializerFactory serializerFactory = new();
- var rootNode = connectionTreeModel.RootNodes.OfType().First();
- var xml = xmlConnectionsSerializer.Serialize(rootNode);
+ Serializers.ISerializer xmlConnectionsSerializer = serializerFactory.Build(cryptographyProvider, connectionTreeModel, _saveFilter, Properties.OptionsSecurityPage.Default.EncryptCompleteConnectionsFile);
- var fileDataProvider = new FileDataProviderWithRollingBackup(_connectionFileName);
+ RootNodeInfo rootNode = connectionTreeModel.RootNodes.OfType().First();
+ string xml = xmlConnectionsSerializer.Serialize(rootNode);
+
+ FileDataProviderWithRollingBackup fileDataProvider = new(_connectionFileName);
fileDataProvider.Save(xml);
}
catch (Exception ex)
diff --git a/mRemoteNG/Config/CredentialHarvester.cs b/mRemoteNG/Config/CredentialHarvester.cs
index 26a0cd37d..acf56c3ff 100644
--- a/mRemoteNG/Config/CredentialHarvester.cs
+++ b/mRemoteNG/Config/CredentialHarvester.cs
@@ -17,19 +17,19 @@ namespace mRemoteNG.Config
// maps a connectioninfo (by its id) to the credential object that was harvested
public Dictionary ConnectionToCredentialMap { get; } =
- new Dictionary();
+ [];
public IEnumerable Harvest(XDocument xDocument, SecureString decryptionKey)
{
if (xDocument == null)
throw new ArgumentNullException(nameof(xDocument));
- var cryptoProvider = new CryptoProviderFactoryFromXml(xDocument.Root).Build();
+ ICryptographyProvider cryptoProvider = new CryptoProviderFactoryFromXml(xDocument.Root).Build();
- foreach (var element in xDocument.Descendants("Node"))
+ foreach (XElement element in xDocument.Descendants("Node"))
{
if (!EntryHasSomeCredentialData(element)) continue;
- var newCredential = BuildCredential(element, cryptoProvider, decryptionKey);
+ ICredentialRecord newCredential = BuildCredential(element, cryptoProvider, decryptionKey);
Guid connectionId;
Guid.TryParse(element.Attribute("Id")?.Value, out connectionId);
@@ -40,7 +40,7 @@ namespace mRemoteNG.Config
if (ConnectionToCredentialMap.Values.Contains(newCredential, _credentialComparer))
{
- var existingCredential = ConnectionToCredentialMap.Values.First(record => _credentialComparer.Equals(newCredential, record));
+ ICredentialRecord existingCredential = ConnectionToCredentialMap.Values.First(record => _credentialComparer.Equals(newCredential, record));
ConnectionToCredentialMap.Add(connectionId, existingCredential);
}
else
@@ -52,7 +52,7 @@ namespace mRemoteNG.Config
private ICredentialRecord BuildCredential(XElement element, ICryptographyProvider cryptographyProvider, SecureString decryptionKey)
{
- var credential = new CredentialRecord
+ CredentialRecord credential = new()
{
Title = $"{element.Attribute("Username")?.Value}\\{element.Attribute("Domain")?.Value}",
Username = element.Attribute("Username")?.Value,
diff --git a/mRemoteNG/Config/CredentialRecordLoader.cs b/mRemoteNG/Config/CredentialRecordLoader.cs
index f74525bdd..e39ee4b08 100644
--- a/mRemoteNG/Config/CredentialRecordLoader.cs
+++ b/mRemoteNG/Config/CredentialRecordLoader.cs
@@ -27,7 +27,7 @@ namespace mRemoteNG.Config
public IEnumerable Load(SecureString key)
{
- var serializedCredentials = _dataProvider.Load();
+ string serializedCredentials = _dataProvider.Load();
return _deserializer.Deserialize(serializedCredentials, key);
}
}
diff --git a/mRemoteNG/Config/CredentialRecordSaver.cs b/mRemoteNG/Config/CredentialRecordSaver.cs
index 9a9b52d76..6167ba190 100644
--- a/mRemoteNG/Config/CredentialRecordSaver.cs
+++ b/mRemoteNG/Config/CredentialRecordSaver.cs
@@ -26,7 +26,7 @@ namespace mRemoteNG.Config
public void Save(IEnumerable credentialRecords, SecureString key)
{
- var serializedCredentials = _serializer.Serialize(credentialRecords, key);
+ string serializedCredentials = _serializer.Serialize(credentialRecords, key);
_dataProvider.Save(serializedCredentials);
}
}
diff --git a/mRemoteNG/Config/CredentialRepositoryListLoader.cs b/mRemoteNG/Config/CredentialRepositoryListLoader.cs
index c332b195b..54e439324 100644
--- a/mRemoteNG/Config/CredentialRepositoryListLoader.cs
+++ b/mRemoteNG/Config/CredentialRepositoryListLoader.cs
@@ -26,7 +26,7 @@ namespace mRemoteNG.Config
[SupportedOSPlatform("windows")]
public IEnumerable Load()
{
- var data = _dataProvider.Load();
+ string data = _dataProvider.Load();
return _deserializer.Deserialize(data);
}
}
diff --git a/mRemoteNG/Config/CredentialRepositoryListSaver.cs b/mRemoteNG/Config/CredentialRepositoryListSaver.cs
index 6a4a549d7..a10bd534c 100644
--- a/mRemoteNG/Config/CredentialRepositoryListSaver.cs
+++ b/mRemoteNG/Config/CredentialRepositoryListSaver.cs
@@ -20,8 +20,8 @@ namespace mRemoteNG.Config
public void Save(IEnumerable repositories, string propertyNameTrigger = "")
{
- var serializer = new CredentialRepositoryListSerializer();
- var data = serializer.Serialize(repositories);
+ CredentialRepositoryListSerializer serializer = new();
+ string data = serializer.Serialize(repositories);
_dataProvider.Save(data);
}
}
diff --git a/mRemoteNG/Config/DataProviders/FileBackupCreator.cs b/mRemoteNG/Config/DataProviders/FileBackupCreator.cs
index 7cdf54f73..2c1b4a179 100644
--- a/mRemoteNG/Config/DataProviders/FileBackupCreator.cs
+++ b/mRemoteNG/Config/DataProviders/FileBackupCreator.cs
@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.DataProviders
if (WeDontNeedToBackup(fileName))
return;
- var backupFileName =
+ string backupFileName =
string.Format(Properties.OptionsBackupPage.Default.BackupFileNameFormat, fileName, DateTime.Now);
File.Copy(fileName, backupFileName);
}
diff --git a/mRemoteNG/Config/DataProviders/FileBackupPruner.cs b/mRemoteNG/Config/DataProviders/FileBackupPruner.cs
index 7955455d8..8e6c3283a 100644
--- a/mRemoteNG/Config/DataProviders/FileBackupPruner.cs
+++ b/mRemoteNG/Config/DataProviders/FileBackupPruner.cs
@@ -7,23 +7,23 @@ namespace mRemoteNG.Config.DataProviders
{
public void PruneBackupFiles(string filePath, int maxBackupsToKeep)
{
- var fileName = Path.GetFileName(filePath);
- var directoryName = Path.GetDirectoryName(filePath);
+ string fileName = Path.GetFileName(filePath);
+ string directoryName = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(directoryName))
return;
- var searchPattern = string.Format(Properties.OptionsBackupPage.Default.BackupFileNameFormat, fileName, "*");
- var files = Directory.GetFiles(directoryName, searchPattern);
+ string searchPattern = string.Format(Properties.OptionsBackupPage.Default.BackupFileNameFormat, fileName, "*");
+ string[] files = Directory.GetFiles(directoryName, searchPattern);
if (files.Length <= maxBackupsToKeep)
return;
- var filesToDelete = files
+ System.Collections.Generic.IEnumerable filesToDelete = files
.OrderByDescending(s => s)
.Skip(maxBackupsToKeep);
- foreach (var file in filesToDelete)
+ foreach (string file in filesToDelete)
{
File.Delete(file);
}
diff --git a/mRemoteNG/Config/DataProviders/FileDataProvider.cs b/mRemoteNG/Config/DataProviders/FileDataProvider.cs
index dcf0f949a..c741c6038 100644
--- a/mRemoteNG/Config/DataProviders/FileDataProvider.cs
+++ b/mRemoteNG/Config/DataProviders/FileDataProvider.cs
@@ -18,7 +18,7 @@ namespace mRemoteNG.Config.DataProviders
public virtual string Load()
{
- var fileContents = "";
+ string fileContents = "";
try
{
if (!File.Exists(FilePath))
@@ -70,7 +70,7 @@ namespace mRemoteNG.Config.DataProviders
private void CreateMissingDirectories()
{
- var dirname = Path.GetDirectoryName(FilePath);
+ string dirname = Path.GetDirectoryName(FilePath);
if (dirname == null) return;
Directory.CreateDirectory(dirname);
}
diff --git a/mRemoteNG/Config/DataProviders/SqlDataProvider.cs b/mRemoteNG/Config/DataProviders/SqlDataProvider.cs
index 3266b37c6..121c873a0 100644
--- a/mRemoteNG/Config/DataProviders/SqlDataProvider.cs
+++ b/mRemoteNG/Config/DataProviders/SqlDataProvider.cs
@@ -20,12 +20,12 @@ namespace mRemoteNG.Config.DataProviders
public DataTable Load()
{
- var dataTable = new DataTable();
- var dbQuery = DatabaseConnector.DbCommand("SELECT * FROM tblCons ORDER BY PositionID ASC");
+ DataTable dataTable = new();
+ System.Data.Common.DbCommand dbQuery = DatabaseConnector.DbCommand("SELECT * FROM tblCons ORDER BY PositionID ASC");
DatabaseConnector.AssociateItemToThisConnector(dbQuery);
if (!DatabaseConnector.IsConnected)
OpenConnection();
- var dbDataReader = dbQuery.ExecuteReader(CommandBehavior.CloseConnection);
+ System.Data.Common.DbDataReader dbDataReader = dbQuery.ExecuteReader(CommandBehavior.CloseConnection);
if (dbDataReader.HasRows)
dataTable.Load(dbDataReader);
@@ -47,16 +47,18 @@ namespace mRemoteNG.Config.DataProviders
{
SqlConnection sqlConnection = (SqlConnection)DatabaseConnector.DbConnection();
using SqlTransaction transaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.Serializable);
- using SqlCommand sqlCommand = new SqlCommand();
+ using SqlCommand sqlCommand = new();
sqlCommand.Connection = sqlConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
- using SqlDataAdapter dataAdapter = new SqlDataAdapter();
+ using SqlDataAdapter dataAdapter = new();
dataAdapter.SelectCommand = sqlCommand;
- SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
- // Avoid optimistic concurrency, check if it is necessary.
- builder.ConflictOption = ConflictOption.OverwriteChanges;
+ SqlCommandBuilder builder = new(dataAdapter)
+ {
+ // Avoid optimistic concurrency, check if it is necessary.
+ ConflictOption = ConflictOption.OverwriteChanges
+ };
dataAdapter.UpdateCommand = builder.GetUpdateCommand();
dataAdapter.DeleteCommand = builder.GetDeleteCommand();
@@ -66,15 +68,15 @@ namespace mRemoteNG.Config.DataProviders
}
else if (DatabaseConnector.GetType() == typeof(MySqlDatabaseConnector))
{
- var dbConnection = (MySqlConnection) DatabaseConnector.DbConnection();
+ MySqlConnection dbConnection = (MySqlConnection) DatabaseConnector.DbConnection();
using MySqlTransaction transaction = dbConnection.BeginTransaction(System.Data.IsolationLevel.Serializable);
- using MySqlCommand sqlCommand = new MySqlCommand();
+ using MySqlCommand sqlCommand = new();
sqlCommand.Connection = dbConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
- using MySqlDataAdapter dataAdapter = new MySqlDataAdapter(sqlCommand);
+ using MySqlDataAdapter dataAdapter = new(sqlCommand);
dataAdapter.UpdateBatchSize = 1000;
- using MySqlCommandBuilder cb = new MySqlCommandBuilder(dataAdapter);
+ using MySqlCommandBuilder cb = new(dataAdapter);
dataAdapter.Update(dataTable);
transaction.Commit();
}
diff --git a/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectionTester.cs b/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectionTester.cs
index 21562673d..2689834e2 100644
--- a/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectionTester.cs
+++ b/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectionTester.cs
@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.DatabaseConnectors
string username,
string password)
{
- using (var dbConnector = DatabaseConnectorFactory.DatabaseConnector(type, server, database, username, password))
+ using (IDatabaseConnector dbConnector = DatabaseConnectorFactory.DatabaseConnector(type, server, database, username, password))
{
try
{
diff --git a/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectorFactory.cs b/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectorFactory.cs
index 461920077..da82f5019 100644
--- a/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectorFactory.cs
+++ b/mRemoteNG/Config/DatabaseConnectors/DatabaseConnectorFactory.cs
@@ -10,12 +10,12 @@ namespace mRemoteNG.Config.DatabaseConnectors
public static IDatabaseConnector DatabaseConnectorFromSettings()
{
// TODO: add custom port handling?
- var sqlType = Properties.OptionsDBsPage.Default.SQLServerType;
- var sqlHost = Properties.OptionsDBsPage.Default.SQLHost;
- var sqlCatalog = Properties.OptionsDBsPage.Default.SQLDatabaseName;
- var sqlUsername = Properties.OptionsDBsPage.Default.SQLUser;
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
- var sqlPassword = cryptographyProvider.Decrypt(Properties.OptionsDBsPage.Default.SQLPass, Runtime.EncryptionKey);
+ string sqlType = Properties.OptionsDBsPage.Default.SQLServerType;
+ string sqlHost = Properties.OptionsDBsPage.Default.SQLHost;
+ string sqlCatalog = Properties.OptionsDBsPage.Default.SQLDatabaseName;
+ string sqlUsername = Properties.OptionsDBsPage.Default.SQLUser;
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
+ string sqlPassword = cryptographyProvider.Decrypt(Properties.OptionsDBsPage.Default.SQLPass, Runtime.EncryptionKey);
return DatabaseConnector(sqlType, sqlHost, sqlCatalog, sqlUsername, sqlPassword);
}
diff --git a/mRemoteNG/Config/DatabaseConnectors/MSSqlDatabaseConnector.cs b/mRemoteNG/Config/DatabaseConnectors/MSSqlDatabaseConnector.cs
index a93fbfb24..4d72022dd 100644
--- a/mRemoteNG/Config/DatabaseConnectors/MSSqlDatabaseConnector.cs
+++ b/mRemoteNG/Config/DatabaseConnectors/MSSqlDatabaseConnector.cs
@@ -54,7 +54,7 @@ namespace mRemoteNG.Config.DatabaseConnectors
private void BuildDbConnectionStringWithCustomCredentials()
{
string[] hostParts = _dbHost.Split(new char[] { ':' }, 2);
- var _dbPort = (hostParts.Length == 2) ? hostParts[1] : "1433";
+ string _dbPort = (hostParts.Length == 2) ? hostParts[1] : "1433";
_dbConnectionString = new SqlConnectionStringBuilder
{
diff --git a/mRemoteNG/Config/Import/ActiveDirectoryImporter.cs b/mRemoteNG/Config/Import/ActiveDirectoryImporter.cs
index 7cea15ec5..0ed5030ae 100644
--- a/mRemoteNG/Config/Import/ActiveDirectoryImporter.cs
+++ b/mRemoteNG/Config/Import/ActiveDirectoryImporter.cs
@@ -21,11 +21,11 @@ namespace mRemoteNG.Config.Import
try
{
ldapPath.ThrowIfNullOrEmpty(nameof(ldapPath));
- var deserializer = new ActiveDirectoryDeserializer(ldapPath, importSubOu);
- var connectionTreeModel = deserializer.Deserialize();
- var importedRootNode = connectionTreeModel.RootNodes.First();
+ ActiveDirectoryDeserializer deserializer = new(ldapPath, importSubOu);
+ Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize();
+ ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
- var childrenToAdd = importedRootNode.Children.ToArray();
+ Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
catch (Exception ex)
diff --git a/mRemoteNG/Config/Import/MRemoteNGCsvImporter.cs b/mRemoteNG/Config/Import/MRemoteNGCsvImporter.cs
index 550a0f8d4..0c3138cb8 100644
--- a/mRemoteNG/Config/Import/MRemoteNGCsvImporter.cs
+++ b/mRemoteNG/Config/Import/MRemoteNGCsvImporter.cs
@@ -24,12 +24,12 @@ namespace mRemoteNG.Config.Import
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
$"Unable to import file. File does not exist. Path: {filePath}");
- var dataProvider = new FileDataProvider(filePath);
- var xmlString = dataProvider.Load();
- var xmlConnectionsDeserializer = new CsvConnectionsDeserializerMremotengFormat();
- var connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString);
+ FileDataProvider dataProvider = new(filePath);
+ string xmlString = dataProvider.Load();
+ CsvConnectionsDeserializerMremotengFormat xmlConnectionsDeserializer = new();
+ Tree.ConnectionTreeModel connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString);
- var rootImportContainer = new ContainerInfo {Name = Path.GetFileNameWithoutExtension(filePath)};
+ ContainerInfo rootImportContainer = new() { Name = Path.GetFileNameWithoutExtension(filePath)};
rootImportContainer.AddChildRange(connectionTreeModel.RootNodes.First().Children.ToArray());
destinationContainer.AddChild(rootImportContainer);
}
diff --git a/mRemoteNG/Config/Import/MRemoteNGXmlImporter.cs b/mRemoteNG/Config/Import/MRemoteNGXmlImporter.cs
index 328924b5c..a034df090 100644
--- a/mRemoteNG/Config/Import/MRemoteNGXmlImporter.cs
+++ b/mRemoteNG/Config/Import/MRemoteNGXmlImporter.cs
@@ -26,12 +26,12 @@ namespace mRemoteNG.Config.Import
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
$"Unable to import file. File does not exist. Path: {fileName}");
- var dataProvider = new FileDataProvider(fileName);
- var xmlString = dataProvider.Load();
- var xmlConnectionsDeserializer = new XmlConnectionsDeserializer();
- var connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString, true);
+ FileDataProvider dataProvider = new(fileName);
+ string xmlString = dataProvider.Load();
+ XmlConnectionsDeserializer xmlConnectionsDeserializer = new();
+ Tree.ConnectionTreeModel connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString, true);
- var rootImportContainer = new ContainerInfo {Name = Path.GetFileNameWithoutExtension(fileName)};
+ ContainerInfo rootImportContainer = new() { Name = Path.GetFileNameWithoutExtension(fileName)};
rootImportContainer.AddChildRange(connectionTreeModel.RootNodes.First().Children.ToArray());
destinationContainer.AddChild(rootImportContainer);
}
diff --git a/mRemoteNG/Config/Import/PortScanImporter.cs b/mRemoteNG/Config/Import/PortScanImporter.cs
index d76f931d3..0021f9aa4 100644
--- a/mRemoteNG/Config/Import/PortScanImporter.cs
+++ b/mRemoteNG/Config/Import/PortScanImporter.cs
@@ -21,12 +21,12 @@ namespace mRemoteNG.Config.Import
public void Import(IEnumerable hosts, ContainerInfo destinationContainer)
{
- var deserializer = new PortScanDeserializer(_targetProtocolType);
- var connectionTreeModel = deserializer.Deserialize(hosts);
+ PortScanDeserializer deserializer = new(_targetProtocolType);
+ Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(hosts);
- var importedRootNode = connectionTreeModel.RootNodes.First();
+ ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
- var childrenToAdd = importedRootNode.Children.ToArray();
+ Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
}
diff --git a/mRemoteNG/Config/Import/PuttyConnectionManagerImporter.cs b/mRemoteNG/Config/Import/PuttyConnectionManagerImporter.cs
index f04a5bffa..26bff6edc 100644
--- a/mRemoteNG/Config/Import/PuttyConnectionManagerImporter.cs
+++ b/mRemoteNG/Config/Import/PuttyConnectionManagerImporter.cs
@@ -12,15 +12,15 @@ namespace mRemoteNG.Config.Import
{
public void Import(string filePath, ContainerInfo destinationContainer)
{
- var dataProvider = new FileDataProvider(filePath);
- var xmlContent = dataProvider.Load();
+ FileDataProvider dataProvider = new(filePath);
+ string xmlContent = dataProvider.Load();
- var deserializer = new PuttyConnectionManagerDeserializer();
- var connectionTreeModel = deserializer.Deserialize(xmlContent);
+ PuttyConnectionManagerDeserializer deserializer = new();
+ Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(xmlContent);
- var importedRootNode = connectionTreeModel.RootNodes.First();
+ ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
- var childrenToAdd = importedRootNode.Children.ToArray();
+ Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
}
diff --git a/mRemoteNG/Config/Import/RemoteDesktopConnectionImporter.cs b/mRemoteNG/Config/Import/RemoteDesktopConnectionImporter.cs
index e0ee66a9b..ab45962e2 100644
--- a/mRemoteNG/Config/Import/RemoteDesktopConnectionImporter.cs
+++ b/mRemoteNG/Config/Import/RemoteDesktopConnectionImporter.cs
@@ -13,13 +13,13 @@ namespace mRemoteNG.Config.Import
{
public void Import(string fileName, ContainerInfo destinationContainer)
{
- var dataProvider = new FileDataProvider(fileName);
- var content = dataProvider.Load();
+ FileDataProvider dataProvider = new(fileName);
+ string content = dataProvider.Load();
- var deserializer = new RemoteDesktopConnectionDeserializer();
- var connectionTreeModel = deserializer.Deserialize(content);
+ RemoteDesktopConnectionDeserializer deserializer = new();
+ Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(content);
- var importedConnection = connectionTreeModel.RootNodes.First().Children.First();
+ Connection.ConnectionInfo importedConnection = connectionTreeModel.RootNodes.First().Children.First();
if (importedConnection == null) return;
importedConnection.Name = Path.GetFileNameWithoutExtension(fileName);
diff --git a/mRemoteNG/Config/Import/RemoteDesktopConnectionManagerImporter.cs b/mRemoteNG/Config/Import/RemoteDesktopConnectionManagerImporter.cs
index f13b5e7de..1cc40d076 100644
--- a/mRemoteNG/Config/Import/RemoteDesktopConnectionManagerImporter.cs
+++ b/mRemoteNG/Config/Import/RemoteDesktopConnectionManagerImporter.cs
@@ -12,15 +12,15 @@ namespace mRemoteNG.Config.Import
{
public void Import(string filePath, ContainerInfo destinationContainer)
{
- var dataProvider = new FileDataProvider(filePath);
- var fileContent = dataProvider.Load();
+ FileDataProvider dataProvider = new(filePath);
+ string fileContent = dataProvider.Load();
- var deserializer = new RemoteDesktopConnectionManagerDeserializer();
- var connectionTreeModel = deserializer.Deserialize(fileContent);
+ RemoteDesktopConnectionManagerDeserializer deserializer = new();
+ Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(fileContent);
- var importedRootNode = connectionTreeModel.RootNodes.First();
+ ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
- var childrenToAdd = importedRootNode.Children.ToArray();
+ Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
}
diff --git a/mRemoteNG/Config/Import/RemoteDesktopManagerImporter.cs b/mRemoteNG/Config/Import/RemoteDesktopManagerImporter.cs
index 1190132c1..94aac8e9a 100644
--- a/mRemoteNG/Config/Import/RemoteDesktopManagerImporter.cs
+++ b/mRemoteNG/Config/Import/RemoteDesktopManagerImporter.cs
@@ -27,15 +27,15 @@ namespace mRemoteNG.Config.Import
if (!File.Exists(filePath))
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"Unable to import file. File does not exist. Path: {filePath}");
- var dataProvider = new FileDataProvider(filePath);
- var csvString = dataProvider.Load();
+ FileDataProvider dataProvider = new(filePath);
+ string csvString = dataProvider.Load();
if (!string.IsNullOrEmpty(csvString))
{
- var csvDeserializer = new CsvConnectionsDeserializerRdmFormat();
- var connectionTreeModel = csvDeserializer.Deserialize(csvString);
+ CsvConnectionsDeserializerRdmFormat csvDeserializer = new();
+ Tree.ConnectionTreeModel connectionTreeModel = csvDeserializer.Deserialize(csvString);
- var rootContainer = new ContainerInfo { Name = Path.GetFileNameWithoutExtension(filePath) };
+ ContainerInfo rootContainer = new() { Name = Path.GetFileNameWithoutExtension(filePath) };
rootContainer.AddChildRange(connectionTreeModel.RootNodes);
destinationContainer.AddChild(rootContainer);
}
diff --git a/mRemoteNG/Config/Import/SecureCRTImporter.cs b/mRemoteNG/Config/Import/SecureCRTImporter.cs
index c200c2cf8..eae48b773 100644
--- a/mRemoteNG/Config/Import/SecureCRTImporter.cs
+++ b/mRemoteNG/Config/Import/SecureCRTImporter.cs
@@ -31,12 +31,12 @@ namespace mRemoteNG.Config.Import
$"Unable to import file. File does not exist. Path: {fileName}");
- var dataProvider = new FileDataProvider(fileName);
- var content = dataProvider.Load();
- var deserializer = new SecureCRTFileDeserializer();
- var connectionTreeModel = deserializer.Deserialize(content);
+ FileDataProvider dataProvider = new(fileName);
+ string content = dataProvider.Load();
+ SecureCRTFileDeserializer deserializer = new();
+ ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(content);
- var rootImportContainer = new ContainerInfo { Name = Path.GetFileNameWithoutExtension(fileName) };
+ ContainerInfo rootImportContainer = new() { Name = Path.GetFileNameWithoutExtension(fileName) };
rootImportContainer.AddChildRange(connectionTreeModel.RootNodes.First().Children.ToArray());
destinationContainer.AddChild(rootImportContainer);
}
diff --git a/mRemoteNG/Config/Putty/AbstractPuttySessionsProvider.cs b/mRemoteNG/Config/Putty/AbstractPuttySessionsProvider.cs
index e4529455d..da18622d3 100644
--- a/mRemoteNG/Config/Putty/AbstractPuttySessionsProvider.cs
+++ b/mRemoteNG/Config/Putty/AbstractPuttySessionsProvider.cs
@@ -24,15 +24,15 @@ namespace mRemoteNG.Config.Putty
public virtual IEnumerable GetSessions()
{
- var sessionNamesFromProvider = GetSessionNames(true);
+ string[] sessionNamesFromProvider = GetSessionNames(true);
- foreach (var sessionName in GetSessionNamesToAdd(sessionNamesFromProvider))
+ foreach (string sessionName in GetSessionNamesToAdd(sessionNamesFromProvider))
{
- var sessionInfo = GetSession(sessionName);
+ PuttySessionInfo sessionInfo = GetSession(sessionName);
AddSession(sessionInfo);
}
- foreach (var session in GetSessionToRemove(sessionNamesFromProvider))
+ foreach (PuttySessionInfo session in GetSessionToRemove(sessionNamesFromProvider))
{
RemoveSession(session);
}
@@ -44,18 +44,18 @@ namespace mRemoteNG.Config.Putty
private IEnumerable GetSessionNamesToAdd(IEnumerable sessionNamesFromProvider)
{
if (sessionNamesFromProvider == null) { return Enumerable.Empty(); }
- var currentlyKnownSessionNames = Sessions.Select(session => session.Name);
- var sessionNamesToAdd = sessionNamesFromProvider.Except(currentlyKnownSessionNames);
+ IEnumerable currentlyKnownSessionNames = Sessions.Select(session => session.Name);
+ IEnumerable sessionNamesToAdd = sessionNamesFromProvider.Except(currentlyKnownSessionNames);
return sessionNamesToAdd;
}
private IEnumerable GetSessionToRemove(IEnumerable sessionNamesFromProvider)
{
if (sessionNamesFromProvider == null) return Enumerable.Empty();
- var currentlyKnownSessionNames = Sessions.Select(session => session.Name);
- var normalizedSessionNames =
+ IEnumerable currentlyKnownSessionNames = Sessions.Select(session => session.Name);
+ IEnumerable normalizedSessionNames =
sessionNamesFromProvider.Select(name => WebUtility.UrlDecode(name));
- var sessionNamesToRemove = currentlyKnownSessionNames.Except(normalizedSessionNames);
+ IEnumerable sessionNamesToRemove = currentlyKnownSessionNames.Except(normalizedSessionNames);
return Sessions.Where(session => sessionNamesToRemove.Contains(session.Name));
}
diff --git a/mRemoteNG/Config/Putty/PuttySessionsManager.cs b/mRemoteNG/Config/Putty/PuttySessionsManager.cs
index 32154881b..0793b30f1 100644
--- a/mRemoteNG/Config/Putty/PuttySessionsManager.cs
+++ b/mRemoteNG/Config/Putty/PuttySessionsManager.cs
@@ -14,11 +14,11 @@ namespace mRemoteNG.Config.Putty
{
public static PuttySessionsManager Instance { get; } = new PuttySessionsManager();
- private readonly List _providers = new List();
+ private readonly List _providers = [];
public IEnumerable Providers => _providers;
- public List RootPuttySessionsNodes { get; } = new List();
+ public List RootPuttySessionsNodes { get; } = [];
private PuttySessionsManager()
{
@@ -30,7 +30,7 @@ namespace mRemoteNG.Config.Putty
public void AddSessions()
{
- foreach (var provider in Providers)
+ foreach (AbstractPuttySessionsProvider provider in Providers)
{
AddSessionsFromProvider(provider);
}
@@ -40,7 +40,7 @@ namespace mRemoteNG.Config.Putty
{
puttySessionProvider.ThrowIfNull(nameof(puttySessionProvider));
- var rootTreeNode = puttySessionProvider.RootInfo;
+ RootPuttySessionsNodeInfo rootTreeNode = puttySessionProvider.RootInfo;
puttySessionProvider.GetSessions();
if (!RootPuttySessionsNodes.Contains(rootTreeNode) && rootTreeNode.HasChildren())
@@ -50,7 +50,7 @@ namespace mRemoteNG.Config.Putty
public void StartWatcher()
{
- foreach (var provider in Providers)
+ foreach (AbstractPuttySessionsProvider provider in Providers)
{
provider.StartWatcher();
provider.PuttySessionChanged += PuttySessionChanged;
@@ -59,7 +59,7 @@ namespace mRemoteNG.Config.Putty
public void StopWatcher()
{
- foreach (var provider in Providers)
+ foreach (AbstractPuttySessionsProvider provider in Providers)
{
provider.StopWatcher();
provider.PuttySessionChanged -= PuttySessionChanged;
@@ -79,7 +79,7 @@ namespace mRemoteNG.Config.Putty
public void AddProviders(IEnumerable newProviders)
{
- foreach (var provider in newProviders)
+ foreach (AbstractPuttySessionsProvider provider in newProviders)
AddProvider(provider);
}
@@ -105,8 +105,8 @@ namespace mRemoteNG.Config.Putty
private string[] GetSessionNames(bool raw = false)
{
- var sessionNames = new List();
- foreach (var provider in Providers)
+ List sessionNames = new();
+ foreach (AbstractPuttySessionsProvider provider in Providers)
{
if (!IsProviderEnabled(provider))
{
@@ -121,7 +121,7 @@ namespace mRemoteNG.Config.Putty
private bool IsProviderEnabled(AbstractPuttySessionsProvider puttySessionsProvider)
{
- var enabled = true;
+ bool enabled = true;
if (!(puttySessionsProvider is PuttySessionsRegistryProvider)) enabled = false;
return enabled;
diff --git a/mRemoteNG/Config/Putty/PuttySessionsRegistryProvider.cs b/mRemoteNG/Config/Putty/PuttySessionsRegistryProvider.cs
index e079d5622..e8eb6bb2a 100644
--- a/mRemoteNG/Config/Putty/PuttySessionsRegistryProvider.cs
+++ b/mRemoteNG/Config/Putty/PuttySessionsRegistryProvider.cs
@@ -24,11 +24,11 @@ namespace mRemoteNG.Config.Putty
public override string[] GetSessionNames(bool raw = false)
{
- var sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
+ RegistryKey sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
if (sessionsKey == null) return Array.Empty();
- var sessionNames = new List();
- foreach (var sessionName in sessionsKey.GetSubKeyNames())
+ List sessionNames = new();
+ foreach (string sessionName in sessionsKey.GetSubKeyNames())
{
sessionNames.Add(raw ? sessionName
: WebUtility.UrlDecode(sessionName.Replace("+", "%2B")));
@@ -47,13 +47,13 @@ namespace mRemoteNG.Config.Putty
if (string.IsNullOrEmpty(sessionName))
return null;
- var sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
- var sessionKey = sessionsKey?.OpenSubKey(sessionName);
+ RegistryKey sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
+ RegistryKey sessionKey = sessionsKey?.OpenSubKey(sessionName);
if (sessionKey == null) return null;
sessionName = WebUtility.UrlDecode(sessionName.Replace("+", "%2B"));
- var sessionInfo = new PuttySessionInfo
+ PuttySessionInfo sessionInfo = new()
{
PuttySession = sessionName,
Name = sessionName,
@@ -62,7 +62,7 @@ namespace mRemoteNG.Config.Putty
};
- var protocol = string.IsNullOrEmpty(sessionKey.GetValue("Protocol")?.ToString())
+ string protocol = string.IsNullOrEmpty(sessionKey.GetValue("Protocol")?.ToString())
? "ssh"
: sessionKey.GetValue("Protocol").ToString();
@@ -77,7 +77,7 @@ namespace mRemoteNG.Config.Putty
case "serial":
return null;
case "ssh":
- int.TryParse(sessionKey.GetValue("SshProt")?.ToString(), out var sshVersion);
+ int.TryParse(sessionKey.GetValue("SshProt")?.ToString(), out int sshVersion);
/* Per PUTTY.H in PuTTYNG & PuTTYNG Upstream (PuTTY proper currently)
* expect 0 for SSH1, 3 for SSH2 ONLY
* 1 for SSH1 with a 2 fallback
@@ -94,7 +94,7 @@ namespace mRemoteNG.Config.Putty
return null;
}
- int.TryParse(sessionKey.GetValue("PortNumber")?.ToString(), out var portNumber);
+ int.TryParse(sessionKey.GetValue("PortNumber")?.ToString(), out int portNumber);
if (portNumber == default(int))
sessionInfo.SetDefaultPort();
else
@@ -109,13 +109,13 @@ namespace mRemoteNG.Config.Putty
try
{
- var keyName = string.Join("\\", CurrentUserSid, PuttySessionsKey).Replace("\\", "\\\\");
- var sessionsKey = Registry.Users.OpenSubKey(keyName);
+ string keyName = string.Join("\\", CurrentUserSid, PuttySessionsKey).Replace("\\", "\\\\");
+ RegistryKey sessionsKey = Registry.Users.OpenSubKey(keyName);
if (sessionsKey == null)
{
Registry.Users.CreateSubKey(keyName);
}
- var query = new WqlEventQuery($"SELECT * FROM RegistryTreeChangeEvent WHERE Hive = \'HKEY_USERS\' AND RootPath = \'{keyName}\'");
+ WqlEventQuery query = new($"SELECT * FROM RegistryTreeChangeEvent WHERE Hive = \'HKEY_USERS\' AND RootPath = \'{keyName}\'");
_eventWatcher = new ManagementEventWatcher(query);
_eventWatcher.EventArrived += OnManagementEventArrived;
_eventWatcher.Start();
diff --git a/mRemoteNG/Config/Serializers/ConfConsEnsureConnectionsHaveIds.cs b/mRemoteNG/Config/Serializers/ConfConsEnsureConnectionsHaveIds.cs
index 085d948ab..8ece7c949 100644
--- a/mRemoteNG/Config/Serializers/ConfConsEnsureConnectionsHaveIds.cs
+++ b/mRemoteNG/Config/Serializers/ConfConsEnsureConnectionsHaveIds.cs
@@ -8,10 +8,10 @@ namespace mRemoteNG.Config.Serializers
{
public void EnsureElementsHaveIds(XDocument xdoc)
{
- foreach (var element in xdoc.Descendants("Node"))
+ foreach (XElement element in xdoc.Descendants("Node"))
{
if (element.Attribute("Id") != null) continue;
- var id = Guid.NewGuid();
+ Guid id = Guid.NewGuid();
element.Add(new XAttribute("Id", id));
}
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs
index a3a269a28..f7416c8aa 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs
@@ -18,34 +18,34 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
{
public ConnectionTreeModel Deserialize(string serializedData)
{
- var lines = serializedData.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries);
- var csvHeaders = new List();
+ string[] lines = serializedData.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries);
+ List csvHeaders = new();
// used to map a connectioninfo to it's parent's GUID
- var parentMapping = new Dictionary();
+ Dictionary parentMapping = new();
- for (var lineNumber = 0; lineNumber < lines.Length; lineNumber++)
+ for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
- var line = lines[lineNumber].Split(';');
+ string[] line = lines[lineNumber].Split(';');
if (lineNumber == 0)
csvHeaders = line.ToList();
else
{
- var connectionInfo = ParseConnectionInfo(csvHeaders, line);
+ ConnectionInfo connectionInfo = ParseConnectionInfo(csvHeaders, line);
parentMapping.Add(connectionInfo, line[csvHeaders.IndexOf("Parent")]);
}
}
- var root = CreateTreeStructure(parentMapping);
- var connectionTreeModel = new ConnectionTreeModel();
+ RootNodeInfo root = CreateTreeStructure(parentMapping);
+ ConnectionTreeModel connectionTreeModel = new();
connectionTreeModel.AddRootNode(root);
return connectionTreeModel;
}
private RootNodeInfo CreateTreeStructure(Dictionary parentMapping)
{
- var root = new RootNodeInfo(RootNodeType.Connection);
+ RootNodeInfo root = new(RootNodeType.Connection);
- foreach (var node in parentMapping)
+ foreach (KeyValuePair node in parentMapping)
{
// no parent mapped, add to root
if (string.IsNullOrEmpty(node.Value))
@@ -55,7 +55,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
}
// search for parent in the list by GUID
- var parent = parentMapping
+ ContainerInfo parent = parentMapping
.Keys
.OfType()
.FirstOrDefault(info => info.ConstantID == node.Value);
@@ -75,15 +75,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
private ConnectionInfo ParseConnectionInfo(IList headers, string[] connectionCsv)
{
- var nodeType = headers.Contains("NodeType")
+ TreeNodeType nodeType = headers.Contains("NodeType")
? (TreeNodeType)Enum.Parse(typeof(TreeNodeType), connectionCsv[headers.IndexOf("NodeType")], true)
: TreeNodeType.Connection;
- var nodeId = headers.Contains("Id")
+ string nodeId = headers.Contains("Id")
? connectionCsv[headers.IndexOf("Id")]
: Guid.NewGuid().ToString();
- var connectionRecord = nodeType == TreeNodeType.Connection
+ ConnectionInfo connectionRecord = nodeType == TreeNodeType.Connection
? new ConnectionInfo(nodeId)
: new ContainerInfo(nodeId);
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs
index ee56c475e..c3cdba5e5 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs
@@ -34,14 +34,14 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
{
connectionTreeModel.ThrowIfNull(nameof(connectionTreeModel));
- var rootNode = connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
+ ContainerInfo rootNode = connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
return Serialize(rootNode);
}
public string Serialize(ConnectionInfo serializationTarget)
{
serializationTarget.ThrowIfNull(nameof(serializationTarget));
- var sb = new StringBuilder();
+ StringBuilder sb = new();
WriteCsvHeader(sb);
SerializeNodesRecursive(serializationTarget, sb);
@@ -81,10 +81,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
private void SerializeNodesRecursive(ConnectionInfo node, StringBuilder sb)
{
- var nodeAsContainer = node as ContainerInfo;
+ ContainerInfo nodeAsContainer = node as ContainerInfo;
if (nodeAsContainer != null)
{
- foreach (var child in nodeAsContainer.Children)
+ foreach (ConnectionInfo child in nodeAsContainer.Children)
{
SerializeNodesRecursive(child, sb);
}
@@ -272,7 +272,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
private string FormatForCsv(object value)
{
- var cleanedString = value.ToString().Replace(";", "");
+ string cleanedString = value.ToString().Replace(";", "");
return cleanedString + ";";
}
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/RemoteDesktopManager/CsvConnectionsDeserializerRdmFormat.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/RemoteDesktopManager/CsvConnectionsDeserializerRdmFormat.cs
index 99aca4f13..15b813dae 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/RemoteDesktopManager/CsvConnectionsDeserializerRdmFormat.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Csv/RemoteDesktopManager/CsvConnectionsDeserializerRdmFormat.cs
@@ -24,15 +24,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
public CsvConnectionsDeserializerRdmFormat()
{
- _connectionTypes = new List
- {
+ _connectionTypes =
+ [
new(ProtocolType.RDP, "RDP (Microsoft Remote Desktop)", 3389, "Remote Desktop"),
new(ProtocolType.SSH2, "SSH Shell", 22, "SSH")
- };
+ ];
- _groups = new HashSet();
+ _groups = [];
- Containers = new List();
+ Containers = [];
}
private List Containers { get; }
@@ -44,42 +44,42 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
///
public ConnectionTreeModel Deserialize(string serializedData)
{
- var lines = serializedData.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
- var csvHeaders = new List();
+ string[] lines = serializedData.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
+ List csvHeaders = new();
- var connections = new List<(ConnectionInfo, string)>(); // (ConnectionInfo, group)
+ List<(ConnectionInfo, string)> connections = new(); // (ConnectionInfo, group)
- for (var lineNumber = 0; lineNumber < lines.Length; lineNumber++)
+ for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
- var line = lines[lineNumber].Split(',');
+ string[] line = lines[lineNumber].Split(',');
if (lineNumber == 0)
{
csvHeaders = line.ToList();
}
else
{
- var (connectionInfo, group) = ParseConnectionInfo(csvHeaders, line);
+ (ConnectionInfo connectionInfo, string group) = ParseConnectionInfo(csvHeaders, line);
if (connectionInfo == default) continue;
connections.Add((connectionInfo, group));
}
}
- var connectionTreeModel = new ConnectionTreeModel();
- var unsortedConnections = new ContainerInfo { Name = "Unsorted" };
+ ConnectionTreeModel connectionTreeModel = new();
+ ContainerInfo unsortedConnections = new() { Name = "Unsorted" };
- foreach (var containerInfo in Containers) connectionTreeModel.AddRootNode(containerInfo);
+ foreach (ContainerInfo containerInfo in Containers) connectionTreeModel.AddRootNode(containerInfo);
- var allChildren = Containers.SelectMany(x => x.GetRecursiveChildList().Select(y => (ContainerInfo)y)).ToList();
+ List allChildren = Containers.SelectMany(x => x.GetRecursiveChildList().Select(y => (ContainerInfo)y)).ToList();
- foreach (var (connection, path) in connections)
+ foreach ((ConnectionInfo connection, string path) in connections)
if (string.IsNullOrEmpty(path))
{
unsortedConnections.AddChild(connection);
}
else
{
- var container = allChildren.FirstOrDefault(x => x.ConstantID == path);
+ ContainerInfo container = allChildren.FirstOrDefault(x => x.ConstantID == path);
if (container == default) continue;
container.AddChild(connection);
@@ -101,30 +101,30 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
{
if (headers.Count != connectionCsv.Count) return default;
- var hostString = connectionCsv[headers.IndexOf("Host")].Trim();
+ string hostString = connectionCsv[headers.IndexOf("Host")].Trim();
if (string.IsNullOrEmpty(hostString)) return default;
- var hostType = Uri.CheckHostName(hostString);
+ UriHostNameType hostType = Uri.CheckHostName(hostString);
if (hostType == UriHostNameType.Unknown) return default;
- var connectionTypeString = connectionCsv[headers.IndexOf("ConnectionType")];
+ string connectionTypeString = connectionCsv[headers.IndexOf("ConnectionType")];
if (string.IsNullOrEmpty(connectionTypeString)) return default;
- var connectionType = _connectionTypes.FirstOrDefault(x => x.Name == connectionTypeString);
+ RemoteDesktopManagerConnectionInfo connectionType = _connectionTypes.FirstOrDefault(x => x.Name == connectionTypeString);
if (connectionType == default) return default;
- var portString = connectionCsv[headers.IndexOf("Port")] ?? connectionType.Port.ToString();
- if (!int.TryParse(portString, out var port)) port = connectionType.Port;
+ string portString = connectionCsv[headers.IndexOf("Port")] ?? connectionType.Port.ToString();
+ if (!int.TryParse(portString, out int port)) port = connectionType.Port;
- var name = connectionCsv[headers.IndexOf("Name")];
- var description = connectionCsv[headers.IndexOf("Description")];
- var group = connectionCsv[headers.IndexOf("Group")];
+ string name = connectionCsv[headers.IndexOf("Name")];
+ string description = connectionCsv[headers.IndexOf("Description")];
+ string group = connectionCsv[headers.IndexOf("Group")];
- var username = connectionCsv[headers.IndexOf("CredentialUserName")];
- var domain = connectionCsv[headers.IndexOf("CredentialDomain")];
- var password = connectionCsv[headers.IndexOf("CredentialPassword")];
+ string username = connectionCsv[headers.IndexOf("CredentialUserName")];
+ string domain = connectionCsv[headers.IndexOf("CredentialDomain")];
+ string password = connectionCsv[headers.IndexOf("CredentialPassword")];
- var connectionInfo = new ConnectionInfo(Guid.NewGuid().ToString())
+ ConnectionInfo connectionInfo = new(Guid.NewGuid().ToString())
{
Name = name,
Hostname = hostString,
@@ -140,10 +140,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
if (!string.IsNullOrEmpty(group))
if (group.Contains('\\'))
{
- var groupParts = group.Split('\\').ToList();
- var parentContainerName = groupParts[0];
+ List groupParts = group.Split('\\').ToList();
+ string parentContainerName = groupParts[0];
- var parentContainer = Containers.FirstOrDefault(x => x.Name == parentContainerName);
+ ContainerInfo parentContainer = Containers.FirstOrDefault(x => x.Name == parentContainerName);
if (parentContainer == default)
{
parentContainer = new ContainerInfo(group) { Name = parentContainerName };
@@ -168,13 +168,13 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
{
if (_groups.Contains(group)) return;
- var groupCount = groupParts.Count;
+ int groupCount = groupParts.Count;
while (groupCount > 0)
{
- var childName = groupParts[0];
- var newContainer = new ContainerInfo(group) { Name = childName };
+ string childName = groupParts[0];
+ ContainerInfo newContainer = new(group) { Name = childName };
- var childrenNames = parentContainer.GetRecursiveChildList().Select(x => x.Name).ToList();
+ List childrenNames = parentContainer.GetRecursiveChildList().Select(x => x.Name).ToList();
if (!childrenNames.Any())
{
groupCount = AddChild(parentContainer, newContainer, groupCount);
@@ -184,7 +184,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
if (groupParts.Count > 1)
{
- var childContainer = (ContainerInfo)parentContainer.Children.FirstOrDefault(x => x.Name == childName);
+ ContainerInfo childContainer = (ContainerInfo)parentContainer.Children.FirstOrDefault(x => x.Name == childName);
if (childContainer == default)
{
groupCount = AddChild(parentContainer, newContainer, groupCount);
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableDeserializer.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableDeserializer.cs
index f2f92b079..e664c7f38 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableDeserializer.cs
@@ -33,15 +33,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
public ConnectionTreeModel Deserialize(DataTable table)
{
- var connectionList = CreateNodesFromTable(table);
- var connectionTreeModel = CreateNodeHierarchy(connectionList, table);
+ List connectionList = CreateNodesFromTable(table);
+ ConnectionTreeModel connectionTreeModel = CreateNodeHierarchy(connectionList, table);
Runtime.ConnectionsService.IsConnectionsFileLoaded = true;
return connectionTreeModel;
}
private List CreateNodesFromTable(DataTable table)
{
- var nodeList = new List();
+ List nodeList = new();
foreach (DataRow row in table.Rows)
{
// ReSharper disable once SwitchStatementMissingSomeCases
@@ -61,16 +61,16 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private ConnectionInfo DeserializeConnectionInfo(DataRow row)
{
- var connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
- var connectionInfo = new ConnectionInfo(connectionId);
+ string connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
+ ConnectionInfo connectionInfo = new(connectionId);
PopulateConnectionInfoFromDatarow(row, connectionInfo);
return connectionInfo;
}
private ContainerInfo DeserializeContainerInfo(DataRow row)
{
- var containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
- var containerInfo = new ContainerInfo(containerId);
+ string containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
+ ContainerInfo containerInfo = new(containerId);
PopulateConnectionInfoFromDatarow(row, containerInfo);
return containerInfo;
}
@@ -258,8 +258,8 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private ConnectionTreeModel CreateNodeHierarchy(List connectionList, DataTable dataTable)
{
- var connectionTreeModel = new ConnectionTreeModel();
- var rootNode = new RootNodeInfo(RootNodeType.Connection, "0")
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo rootNode = new(RootNodeType.Connection, "0")
{
PasswordString = _decryptionKey.ConvertToUnsecureString()
};
@@ -267,9 +267,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
foreach (DataRow row in dataTable.Rows)
{
- var id = (string)row["ConstantID"];
- var connectionInfo = connectionList.First(node => node.ConstantID == id);
- var parentId = (string)row["ParentID"];
+ string id = (string)row["ConstantID"];
+ ConnectionInfo connectionInfo = connectionList.First(node => node.ConstantID == id);
+ string parentId = (string)row["ParentID"];
if (parentId == "0" || connectionList.All(node => node.ConstantID != parentId))
rootNode.AddChild(connectionInfo);
else
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableSerializer.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableSerializer.cs
index 1c9096e35..d96e89f33 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableSerializer.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/DataTableSerializer.cs
@@ -21,7 +21,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private readonly SecureString _encryptionKey;
private DataTable _dataTable;
private DataTable _sourceDataTable;
- private readonly Dictionary _sourcePrimaryKeyDict = new Dictionary();
+ private readonly Dictionary _sourcePrimaryKeyDict = [];
private const string TABLE_NAME = "tblCons";
private readonly SaveFilter _saveFilter;
private int _currentNodeIndex;
@@ -69,7 +69,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
List entryToDelete = _sourcePrimaryKeyDict.Keys.ToList();
- foreach (var entry in entryToDelete)
+ foreach (string entry in entryToDelete)
{
_dataTable.Rows.Find(entry)?.Delete();
}
@@ -277,7 +277,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
SerializeConnectionInfo(connectionInfo);
}
- var containerInfo = connectionInfo as ContainerInfo;
+ ContainerInfo containerInfo = connectionInfo as ContainerInfo;
if (containerInfo == null) return;
foreach (ConnectionInfo child in containerInfo.Children)
@@ -288,7 +288,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private bool IsRowUpdated(ConnectionInfo connectionInfo, DataRow dataRow)
{
- var isFieldNotChange = dataRow["Name"].Equals(connectionInfo.Name) &&
+ bool isFieldNotChange = dataRow["Name"].Equals(connectionInfo.Name) &&
dataRow["Type"].Equals(connectionInfo.GetTreeNodeType().ToString()) &&
dataRow["ParentID"].Equals(connectionInfo.Parent?.ConstantID ?? "") &&
dataRow["PositionID"].Equals(_currentNodeIndex) &&
@@ -370,7 +370,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
isFieldNotChange = isFieldNotChange && dataRow["VNCViewOnly"].Equals(connectionInfo.VNCViewOnly);
isFieldNotChange = isFieldNotChange && dataRow["VmId"].Equals(connectionInfo.VmId);
- var isInheritanceFieldNotChange = false;
+ bool isInheritanceFieldNotChange = false;
if (_saveFilter.SaveInheritance)
{
isInheritanceFieldNotChange =
@@ -519,7 +519,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
dataRow["InheritVNCViewOnly"].Equals(false);
}
- var pwd = dataRow["Password"].Equals(_saveFilter.SavePassword ? _cryptographyProvider.Encrypt(connectionInfo.Password, _encryptionKey) : "") &&
+ bool pwd = dataRow["Password"].Equals(_saveFilter.SavePassword ? _cryptographyProvider.Encrypt(connectionInfo.Password, _encryptionKey) : "") &&
dataRow["VNCProxyPassword"].Equals(_cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, _encryptionKey)) &&
dataRow["RDGatewayPassword"].Equals(_cryptographyProvider.Encrypt(connectionInfo.RDGatewayPassword, _encryptionKey));
return !(pwd && isFieldNotChange && isInheritanceFieldNotChange);
@@ -528,7 +528,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private void SerializeConnectionInfo(ConnectionInfo connectionInfo)
{
_currentNodeIndex++;
- var isNewRow = false;
+ bool isNewRow = false;
DataRow dataRow = _dataTable.Rows.Find(connectionInfo.ConstantID);
if (dataRow == null)
{
@@ -540,7 +540,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
_sourcePrimaryKeyDict.Remove(connectionInfo.ConstantID);
}
- var tmp = IsRowUpdated(connectionInfo, dataRow);
+ bool tmp = IsRowUpdated(connectionInfo, dataRow);
if (!tmp)
{
return;
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/LocalConnectionPropertiesXmlSerializer.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/LocalConnectionPropertiesXmlSerializer.cs
index 83dd9cd14..fa689a228 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/LocalConnectionPropertiesXmlSerializer.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/LocalConnectionPropertiesXmlSerializer.cs
@@ -16,15 +16,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
public string Serialize(IEnumerable models)
{
- var localConnections = models
+ IEnumerable localConnections = models
.Select(m => new XElement("Node",
new XAttribute("ConnectionId", m.ConnectionId),
new XAttribute("Connected", m.Connected),
new XAttribute("Expanded", m.Expanded),
new XAttribute("Favorite", m.Favorite)));
- var root = new XElement("LocalConnections", localConnections);
- var xdoc = new XDocument(new XDeclaration("1.0", "utf-8", null), root);
+ XElement root = new("LocalConnections", localConnections);
+ XDocument xdoc = new(new XDeclaration("1.0", "utf-8", null), root);
return WriteXmlToString(xdoc);
}
@@ -33,7 +33,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
if (string.IsNullOrWhiteSpace(serializedData))
return Enumerable.Empty();
- var xdoc = XDocument.Parse(serializedData);
+ XDocument xdoc = XDocument.Parse(serializedData);
return xdoc
.Descendants("Node")
.Where(e => e.Attribute("ConnectionId") != null)
@@ -49,14 +49,13 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private static string WriteXmlToString(XNode xmlDocument)
{
string xmlString;
- var xmlWriterSettings = new XmlWriterSettings
- {Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
- var memoryStream = new MemoryStream();
- using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
+ XmlWriterSettings xmlWriterSettings = new() { Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
+ MemoryStream memoryStream = new();
+ using (XmlWriter xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xmlDocument.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
- var streamReader = new StreamReader(memoryStream, Encoding.UTF8, true);
+ StreamReader streamReader = new(memoryStream, Encoding.UTF8, true);
memoryStream.Seek(0, SeekOrigin.Begin);
xmlString = streamReader.ReadToEnd();
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/SqlDatabaseMetaDataRetriever.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/SqlDatabaseMetaDataRetriever.cs
index 41d52f775..d900a9594 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/SqlDatabaseMetaDataRetriever.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Sql/SqlDatabaseMetaDataRetriever.cs
@@ -71,7 +71,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
// TODO: use transaction
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string strProtected;
@@ -93,7 +93,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
strProtected = cryptographyProvider.Encrypt("ThisIsNotProtected", Runtime.EncryptionKey);
}
- var cmd = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
+ DbCommand cmd = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
cmd.ExecuteNonQuery();
if (rootTreeNode != null)
@@ -118,9 +118,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
try
{
// ANSI SQL way. Works in PostgreSQL, MSSQL, MySQL.
- var database_name = Properties.OptionsDBsPage.Default.SQLDatabaseName;
- var cmd = databaseConnector.DbCommand("select case when exists((select * from information_schema.tables where table_name = '" + tableName + "' and table_schema='"+ database_name + "')) then 1 else 0 end");
- var cmdResult = Convert.ToInt16(cmd.ExecuteScalar());
+ string database_name = Properties.OptionsDBsPage.Default.SQLDatabaseName;
+ DbCommand cmd = databaseConnector.DbCommand("select case when exists((select * from information_schema.tables where table_name = '" + tableName + "' and table_schema='"+ database_name + "')) then 1 else 0 end");
+ short cmdResult = Convert.ToInt16(cmd.ExecuteScalar());
exists = (cmdResult == 1);
}
catch
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs
index 184d1a743..42a15cf1e 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs
@@ -34,7 +34,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement Serialize(ConnectionInfo connectionInfo)
{
- var element = new XElement(XName.Get("Node", ""));
+ XElement element = new(XName.Get("Node", ""));
SetElementAttributes(element, connectionInfo);
SetInheritanceAttributes(element, connectionInfo);
return element;
@@ -42,7 +42,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void SetElementAttributes(XContainer element, ConnectionInfo connectionInfo)
{
- var nodeAsContainer = connectionInfo as ContainerInfo;
+ ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo;
element.Add(new XAttribute("Name", connectionInfo.Name));
element.Add(new XAttribute("Type", connectionInfo.GetTreeNodeType().ToString()));
if (nodeAsContainer != null)
@@ -141,7 +141,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (_saveFilter.SaveInheritance)
{
- var inheritance = connectionInfo.Inheritance;
+ ConnectionInfoInheritance inheritance = connectionInfo.Inheritance;
if (inheritance.CacheBitmaps)
element.Add(new XAttribute("InheritCacheBitmaps", inheritance.CacheBitmaps.ToString().ToLowerInvariant()));
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs
index 2a2d59f52..2c35b27b3 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs
@@ -30,7 +30,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement Serialize(ConnectionInfo connectionInfo)
{
- var element = new XElement(XName.Get("Node", ""));
+ XElement element = new(XName.Get("Node", ""));
SetElementAttributes(element, connectionInfo);
SetInheritanceAttributes(element, connectionInfo);
return element;
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void SetElementAttributes(XContainer element, ConnectionInfo connectionInfo)
{
- var nodeAsContainer = connectionInfo as ContainerInfo;
+ ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo;
element.Add(new XAttribute("Name", connectionInfo.Name));
element.Add(new XAttribute("VmId", connectionInfo.VmId));
element.Add(new XAttribute("UseVmId", connectionInfo.UseVmId));
@@ -162,7 +162,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (_saveFilter.SaveInheritance)
{
- var inheritance = connectionInfo.Inheritance;
+ ConnectionInfoInheritance inheritance = connectionInfo.Inheritance;
if (inheritance.CacheBitmaps)
element.Add(new XAttribute("InheritCacheBitmaps", inheritance.CacheBitmaps.ToString().ToLowerInvariant()));
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer28.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer28.cs
index 76f845adb..4fa111f90 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer28.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer28.cs
@@ -30,7 +30,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement Serialize(ConnectionInfo connectionInfo)
{
- var element = new XElement(XName.Get("Node", ""));
+ XElement element = new(XName.Get("Node", ""));
SetElementAttributes(element, connectionInfo);
SetInheritanceAttributes(element, connectionInfo);
return element;
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void SetElementAttributes(XContainer element, ConnectionInfo connectionInfo)
{
- var nodeAsContainer = connectionInfo as ContainerInfo;
+ ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo;
element.Add(new XAttribute("Name", connectionInfo.Name));
element.Add(new XAttribute("VmId", connectionInfo.VmId));
element.Add(new XAttribute("UseVmId", connectionInfo.UseVmId));
@@ -163,7 +163,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (!_saveFilter.SaveInheritance) return;
- var inheritance = connectionInfo.Inheritance;
+ ConnectionInfoInheritance inheritance = connectionInfo.Inheritance;
if (inheritance.CacheBitmaps)
element.Add(new XAttribute("InheritCacheBitmaps", inheritance.CacheBitmaps.ToString().ToLowerInvariant()));
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionSerializerFactory.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionSerializerFactory.cs
index 9c6119b31..7556ef315 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionSerializerFactory.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionSerializerFactory.cs
@@ -16,12 +16,12 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
SaveFilter saveFilter = null,
bool useFullEncryption = false)
{
- var encryptionKey = connectionTreeModel
+ System.Security.SecureString encryptionKey = connectionTreeModel
.RootNodes.OfType()
.First().PasswordString
.ConvertToSecureString();
- var connectionNodeSerializer = new XmlConnectionNodeSerializer28(
+ XmlConnectionNodeSerializer28 connectionNodeSerializer = new(
cryptographyProvider,
encryptionKey,
saveFilter ?? new SaveFilter());
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs
index bb51fac8c..2a19f4d4c 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs
@@ -23,7 +23,7 @@ using System.Runtime.Versioning;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
[SupportedOSPlatform("windows")]
- public class XmlConnectionsDeserializer : IDeserializer
+ public class XmlConnectionsDeserializer(Func> authenticationRequestor = null) : IDeserializer
{
private XmlDocument _xmlDocument;
private double _confVersion;
@@ -32,12 +32,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private const double MaxSupportedConfVersion = 2.8;
private readonly RootNodeInfo _rootNodeInfo = new(RootNodeType.Connection);
- public Func> AuthenticationRequestor { get; set; }
-
- public XmlConnectionsDeserializer(Func> authenticationRequestor = null)
- {
- AuthenticationRequestor = authenticationRequestor;
- }
+ public Func> AuthenticationRequestor { get; set; } = authenticationRequestor;
public ConnectionTreeModel Deserialize(string xml)
{
@@ -52,16 +47,16 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
LoadXmlConnectionData(xml);
ValidateConnectionFileVersion();
- var rootXmlElement = _xmlDocument.DocumentElement;
+ XmlElement rootXmlElement = _xmlDocument.DocumentElement;
InitializeRootNode(rootXmlElement);
CreateDecryptor(_rootNodeInfo, rootXmlElement);
- var connectionTreeModel = new ConnectionTreeModel();
+ ConnectionTreeModel connectionTreeModel = new();
connectionTreeModel.AddRootNode(_rootNodeInfo);
if (_confVersion > 1.3)
{
- var protectedString = _xmlDocument.DocumentElement?.Attributes["Protected"]?.Value;
+ string protectedString = _xmlDocument.DocumentElement?.Attributes["Protected"]?.Value;
if (!_decryptor.ConnectionsFileIsAuthentic(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()))
{
return null;
@@ -70,10 +65,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (_confVersion >= 2.6)
{
- var fullFileEncryptionValue = rootXmlElement.GetAttributeAsBool("FullFileEncryption");
+ bool fullFileEncryptionValue = rootXmlElement.GetAttributeAsBool("FullFileEncryption");
if (fullFileEncryptionValue)
{
- var decryptedContent = _decryptor.Decrypt(rootXmlElement.InnerText);
+ string decryptedContent = _decryptor.Decrypt(rootXmlElement.InnerText);
rootXmlElement.InnerXml = decryptedContent;
}
}
@@ -118,28 +113,14 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void ShowIncompatibleVersionDialogBox()
{
- CTaskDialog.ShowTaskDialogBox(
- FrmMain.Default,
- Application.ProductName,
- "Incompatible connection file format",
- $"The format of this connection file is not supported. Please upgrade to a newer version of {Application.ProductName}.",
- string
- .Format("{1}{0}File Format Version: {2}{0}Highest Supported Version: {3}",
- Environment.NewLine,
- ConnectionFileName, _confVersion, MaxSupportedConfVersion),
- "",
- "",
- "",
- "",
- ETaskDialogButtons.Ok,
- ESysIcons.Error,
- ESysIcons.Error
- );
+ CTaskDialog.ShowTaskDialogBox(FrmMain.Default, Application.ProductName, "Incompatible connection file format", $"The format of this connection file is not supported. Please upgrade to a newer version of {Application.ProductName}.",
+ string .Format("{1}{0}File Format Version: {2}{0}Highest Supported Version: {3}", Environment.NewLine, ConnectionFileName, _confVersion, MaxSupportedConfVersion),
+ "", "", "", "", ETaskDialogButtons.Ok, ESysIcons.Error, ESysIcons.Error);
}
private void InitializeRootNode(XmlElement connectionsRootElement)
{
- var rootNodeName = connectionsRootElement?.Attributes["Name"]?.Value.Trim();
+ string rootNodeName = connectionsRootElement?.Attributes["Name"]?.Value.Trim();
_rootNodeInfo.Name = rootNodeName;
}
@@ -147,9 +128,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (_confVersion >= 2.6)
{
- var engine = connectionsRootElement.GetAttributeAsEnum("EncryptionEngine");
- var mode = connectionsRootElement.GetAttributeAsEnum("BlockCipherMode");
- var keyDerivationIterations = connectionsRootElement.GetAttributeAsInt("KdfIterations");
+ BlockCipherEngines engine = connectionsRootElement.GetAttributeAsEnum("EncryptionEngine");
+ BlockCipherModes mode = connectionsRootElement.GetAttributeAsEnum("BlockCipherMode");
+ int keyDerivationIterations = connectionsRootElement.GetAttributeAsInt("KdfIterations");
_decryptor = new XmlConnectionsDecryptor(engine, mode, rootNodeInfo)
{
@@ -173,17 +154,17 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (!parentXmlNode.HasChildNodes) return;
foreach (XmlNode xmlNode in parentXmlNode.ChildNodes)
{
- var nodeType = xmlNode.GetAttributeAsEnum("Type", TreeNodeType.Connection);
+ TreeNodeType nodeType = xmlNode.GetAttributeAsEnum("Type", TreeNodeType.Connection);
// ReSharper disable once SwitchStatementMissingSomeCases
switch (nodeType)
{
case TreeNodeType.Connection:
- var connectionInfo = GetConnectionInfoFromXml(xmlNode);
+ ConnectionInfo connectionInfo = GetConnectionInfoFromXml(xmlNode);
parentContainer.AddChild(connectionInfo);
break;
case TreeNodeType.Container:
- var containerInfo = new ContainerInfo();
+ ContainerInfo containerInfo = new();
if (_confVersion >= 0.9)
containerInfo.CopyFrom(GetConnectionInfoFromXml(xmlNode));
@@ -210,10 +191,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (xmlnode?.Attributes == null)
return null;
- var connectionId = xmlnode.GetAttributeAsString("Id");
+ string connectionId = xmlnode.GetAttributeAsString("Id");
if (string.IsNullOrWhiteSpace(connectionId))
connectionId = Guid.NewGuid().ToString();
- var connectionInfo = new ConnectionInfo(connectionId);
+ ConnectionInfo connectionInfo = new(connectionId);
try
{
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs
index 50569261e..1444ee8ec 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs
@@ -26,19 +26,19 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XDocument CompileDocument(ConnectionTreeModel connectionTreeModel, bool fullFileEncryption)
{
- var rootNodeInfo = GetRootNodeFromConnectionTreeModel(connectionTreeModel);
+ RootNodeInfo rootNodeInfo = GetRootNodeFromConnectionTreeModel(connectionTreeModel);
return CompileDocument(rootNodeInfo, fullFileEncryption);
}
public XDocument CompileDocument(ConnectionInfo serializationTarget, bool fullFileEncryption)
{
- var rootNodeInfo = GetRootNodeFromConnectionInfo(serializationTarget);
+ RootNodeInfo rootNodeInfo = GetRootNodeFromConnectionInfo(serializationTarget);
_encryptionKey = rootNodeInfo.PasswordString.ConvertToSecureString();
- var rootElement = CompileRootNode(rootNodeInfo, fullFileEncryption);
+ XElement rootElement = CompileRootNode(rootNodeInfo, fullFileEncryption);
CompileRecursive(serializationTarget, rootElement);
- var xmlDeclaration = new XDeclaration("1.0", "utf-8", null);
- var xmlDocument = new XDocument(xmlDeclaration, rootElement);
+ XDeclaration xmlDeclaration = new("1.0", "utf-8", null);
+ XDocument xmlDocument = new(xmlDeclaration, rootElement);
if (fullFileEncryption)
xmlDocument = new XmlConnectionsDocumentEncryptor(_cryptographyProvider).EncryptDocument(xmlDocument, _encryptionKey);
return xmlDocument;
@@ -46,7 +46,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void CompileRecursive(ConnectionInfo serializationTarget, XContainer parentElement)
{
- var newElement = parentElement;
+ XContainer newElement = parentElement;
if (serializationTarget is not RootNodeInfo)
{
newElement = CompileConnectionInfoNode(serializationTarget);
@@ -54,7 +54,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
}
if (serializationTarget is not ContainerInfo serializationTargetAsContainer) return;
- foreach (var child in serializationTargetAsContainer.Children.ToArray())
+ foreach (ConnectionInfo child in serializationTargetAsContainer.Children.ToArray())
CompileRecursive(child, newElement);
}
@@ -74,7 +74,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private XElement CompileRootNode(RootNodeInfo rootNodeInfo, bool fullFileEncryption)
{
- var rootNodeSerializer = new XmlRootNodeSerializer();
+ XmlRootNodeSerializer rootNodeSerializer = new();
return rootNodeSerializer.SerializeRootNodeInfo(rootNodeInfo, _cryptographyProvider, _connectionNodeSerializer.Version, fullFileEncryption);
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentEncryptor.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentEncryptor.cs
index c254a6744..fbdcab1ab 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentEncryptor.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentEncryptor.cs
@@ -15,30 +15,30 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XDocument EncryptDocument(XDocument documentToEncrypt, SecureString encryptionKey)
{
- var contentToEncrypt = GetContentToEncrypt(documentToEncrypt.Root);
- var encryptedContent = _cryptographyProvider.Encrypt(contentToEncrypt, encryptionKey);
- var encryptedDocument = ReplaceInnerXml(documentToEncrypt, encryptedContent);
+ string contentToEncrypt = GetContentToEncrypt(documentToEncrypt.Root);
+ string encryptedContent = _cryptographyProvider.Encrypt(contentToEncrypt, encryptionKey);
+ XDocument encryptedDocument = ReplaceInnerXml(documentToEncrypt, encryptedContent);
return encryptedDocument;
}
private string GetContentToEncrypt(XNode element)
{
- var reader = element.CreateReader();
+ System.Xml.XmlReader reader = element.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
private XDocument ReplaceInnerXml(XDocument originalDocument, string newContent)
{
- var newRootElement = ShallowCloneRootNode(originalDocument.Root);
+ XElement newRootElement = ShallowCloneRootNode(originalDocument.Root);
newRootElement.SetValue(newContent);
return new XDocument(newRootElement);
}
private XElement ShallowCloneRootNode(XElement originalElement)
{
- var newElement = new XElement(originalElement.Name);
- foreach (var attribute in originalElement.Attributes())
+ XElement newElement = new(originalElement.Name);
+ foreach (XAttribute attribute in originalElement.Attributes())
newElement.Add(new XAttribute(attribute));
return newElement;
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs
index 94bdd1c18..7823e0911 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs
@@ -32,7 +32,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public string Serialize(ConnectionTreeModel connectionTreeModel)
{
- var rootNode = (RootNodeInfo)connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
+ RootNodeInfo rootNode = (RootNodeInfo)connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
return SerializeConnectionsData(rootNode);
}
@@ -43,12 +43,12 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private string SerializeConnectionsData(ConnectionInfo serializationTarget)
{
- var xml = "";
+ string xml = "";
try
{
- var documentCompiler =
- new XmlConnectionsDocumentCompiler(_cryptographyProvider, _connectionNodeSerializer);
- var xmlDocument = documentCompiler.CompileDocument(serializationTarget, UseFullEncryption);
+ XmlConnectionsDocumentCompiler documentCompiler =
+ new(_cryptographyProvider, _connectionNodeSerializer);
+ XDocument xmlDocument = documentCompiler.CompileDocument(serializationTarget, UseFullEncryption);
xml = WriteXmlToString(xmlDocument);
}
catch (Exception ex)
@@ -62,14 +62,13 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private static string WriteXmlToString(XNode xmlDocument)
{
string xmlString;
- var xmlWriterSettings = new XmlWriterSettings
- {Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
- var memoryStream = new MemoryStream();
- using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
+ XmlWriterSettings xmlWriterSettings = new() { Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
+ MemoryStream memoryStream = new();
+ using (XmlWriter xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xmlDocument.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
- var streamReader = new StreamReader(memoryStream, Encoding.UTF8, true);
+ StreamReader streamReader = new(memoryStream, Encoding.UTF8, true);
memoryStream.Seek(0, SeekOrigin.Begin);
xmlString = streamReader.ReadToEnd();
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs
index 55e2411ad..1ea6b4159 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs
@@ -7,28 +7,28 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
public static string GetAttributeAsString(this XmlNode xmlNode, string attribute, string defaultValue = "")
{
- var value = xmlNode?.Attributes?[attribute]?.Value;
+ string value = xmlNode?.Attributes?[attribute]?.Value;
return value ?? defaultValue;
}
public static bool GetAttributeAsBool(this XmlNode xmlNode, string attribute, bool defaultValue = false)
{
- var value = xmlNode?.Attributes?[attribute]?.Value;
+ string value = xmlNode?.Attributes?[attribute]?.Value;
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
- return bool.TryParse(value, out var valueAsBool)
+ return bool.TryParse(value, out bool valueAsBool)
? valueAsBool
: defaultValue;
}
public static int GetAttributeAsInt(this XmlNode xmlNode, string attribute, int defaultValue = 0)
{
- var value = xmlNode?.Attributes?[attribute]?.Value;
+ string value = xmlNode?.Attributes?[attribute]?.Value;
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
- return int.TryParse(value, out var valueAsBool)
+ return int.TryParse(value, out int valueAsBool)
? valueAsBool
: defaultValue;
}
@@ -36,11 +36,11 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public static T GetAttributeAsEnum(this XmlNode xmlNode, string attribute, T defaultValue = default)
where T : struct
{
- var value = xmlNode?.Attributes?[attribute]?.Value;
+ string value = xmlNode?.Attributes?[attribute]?.Value;
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
- return Enum.TryParse(value, true, out var valueAsEnum)
+ return Enum.TryParse(value, true, out T valueAsEnum)
? valueAsEnum
: defaultValue;
}
diff --git a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs
index 8c6e4d397..12dc94158 100644
--- a/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs
+++ b/mRemoteNG/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs
@@ -12,7 +12,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement SerializeRootNodeInfo(RootNodeInfo rootNodeInfo, ICryptographyProvider cryptographyProvider, Version version, bool fullFileEncryption = false)
{
XNamespace xmlNamespace = "http://mremoteng.org";
- var element = new XElement(xmlNamespace + "Connections");
+ XElement element = new(xmlNamespace + "Connections");
element.Add(new XAttribute(XNamespace.Xmlns + "mrng", xmlNamespace));
element.Add(new XAttribute(XName.Get("Name"), rootNodeInfo.Name));
element.Add(new XAttribute(XName.Get("Export"), "false"));
@@ -27,9 +27,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private XAttribute CreateProtectedAttribute(RootNodeInfo rootNodeInfo, ICryptographyProvider cryptographyProvider)
{
- var attribute = new XAttribute(XName.Get("Protected"), "");
- var plainText = rootNodeInfo.Password ? "ThisIsProtected" : "ThisIsNotProtected";
- var encryptionPassword = rootNodeInfo.PasswordString.ConvertToSecureString();
+ XAttribute attribute = new(XName.Get("Protected"), "");
+ string plainText = rootNodeInfo.Password ? "ThisIsProtected" : "ThisIsNotProtected";
+ System.Security.SecureString encryptionPassword = rootNodeInfo.PasswordString.ConvertToSecureString();
attribute.Value = cryptographyProvider.Encrypt(plainText, encryptionPassword);
return attribute;
}
diff --git a/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListDeserializer.cs b/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListDeserializer.cs
index d97d2789f..077307e88 100644
--- a/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListDeserializer.cs
@@ -30,9 +30,9 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer
public IEnumerable Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml)) return new ICredentialRepository[0];
- var xdoc = XDocument.Parse(xml);
- var repoEntries = xdoc.Descendants("CredentialRepository");
- var xmlRepoFactory = new XmlCredentialRepositoryFactory(_serializer, _deserializer);
+ XDocument xdoc = XDocument.Parse(xml);
+ IEnumerable repoEntries = xdoc.Descendants("CredentialRepository");
+ XmlCredentialRepositoryFactory xmlRepoFactory = new(_serializer, _deserializer);
return repoEntries.Select(xmlRepoFactory.Build);
}
}
diff --git a/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs b/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs
index ea755999c..d1ee7009a 100644
--- a/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs
+++ b/mRemoteNG/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs
@@ -11,8 +11,8 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer
{
public string Serialize(IEnumerable credentialProviderCatalog)
{
- var xmlDocument = new XDocument(new XDeclaration("1.0", "utf-8", null));
- var rootElement = new XElement("CredentialRepositories",
+ XDocument xmlDocument = new(new XDeclaration("1.0", "utf-8", null));
+ XElement rootElement = new("CredentialRepositories",
from provider in credentialProviderCatalog
select new XElement("CredentialRepository",
new XAttribute("Id", provider.Config.Id),
@@ -22,8 +22,8 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer
)
);
xmlDocument.Add(rootElement);
- var declaration = xmlDocument.Declaration.ToString();
- var documentBody = xmlDocument.ToString();
+ string declaration = xmlDocument.Declaration.ToString();
+ string documentBody = xmlDocument.ToString();
return string.Concat(declaration, Environment.NewLine, documentBody);
}
}
diff --git a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs
index 73e13d600..540be8cf2 100644
--- a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs
+++ b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs
@@ -25,21 +25,21 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
public IEnumerable Deserialize(string xml, SecureString key)
{
- var decryptedXml = DecryptPasswords(xml, key);
+ string decryptedXml = DecryptPasswords(xml, key);
return _baseDeserializer.Deserialize(decryptedXml);
}
private string DecryptPasswords(string xml, SecureString key)
{
if (string.IsNullOrEmpty(xml)) return xml;
- var xdoc = XDocument.Parse(xml);
- var cryptoProvider = new CryptoProviderFactoryFromXml(xdoc.Root).Build();
+ XDocument xdoc = XDocument.Parse(xml);
+ ICryptographyProvider cryptoProvider = new CryptoProviderFactoryFromXml(xdoc.Root).Build();
DecryptAuthHeader(xdoc.Root, cryptoProvider, key);
- foreach (var credentialElement in xdoc.Descendants())
+ foreach (XElement credentialElement in xdoc.Descendants())
{
- var passwordAttribute = credentialElement.Attribute("Password");
+ XAttribute passwordAttribute = credentialElement.Attribute("Password");
if (passwordAttribute == null) continue;
- var decryptedPassword = cryptoProvider.Decrypt(passwordAttribute.Value, key);
+ string decryptedPassword = cryptoProvider.Decrypt(passwordAttribute.Value, key);
passwordAttribute.SetValue(decryptedPassword);
}
@@ -48,7 +48,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
private void DecryptAuthHeader(XElement rootElement, ICryptographyProvider cryptographyProvider, SecureString key)
{
- var authAttribute = rootElement.Attribute("Auth");
+ XAttribute authAttribute = rootElement.Attribute("Auth");
if (authAttribute == null)
throw new EncryptionException("Could not find Auth header in the XML repository root element.");
cryptographyProvider.Decrypt(authAttribute.Value, key);
diff --git a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs
index 1719e94d3..700ce535d 100644
--- a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs
+++ b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs
@@ -29,20 +29,20 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
if (credentialRecords == null)
throw new ArgumentNullException(nameof(credentialRecords));
- var baseReturn = _baseSerializer.Serialize(credentialRecords);
- var encryptedReturn = EncryptPasswordAttributes(baseReturn, key);
+ string baseReturn = _baseSerializer.Serialize(credentialRecords);
+ string encryptedReturn = EncryptPasswordAttributes(baseReturn, key);
return encryptedReturn;
}
private string EncryptPasswordAttributes(string xml, SecureString encryptionKey)
{
- var xdoc = XDocument.Parse(xml);
+ XDocument xdoc = XDocument.Parse(xml);
SetEncryptionAttributes(xdoc, encryptionKey);
- foreach (var element in xdoc.Descendants())
+ foreach (XElement element in xdoc.Descendants())
{
- var passwordAttribute = element.Attribute("Password");
+ XAttribute passwordAttribute = element.Attribute("Password");
if (passwordAttribute == null) continue;
- var encryptedPassword = _cryptographyProvider.Encrypt(passwordAttribute.Value, encryptionKey);
+ string encryptedPassword = _cryptographyProvider.Encrypt(passwordAttribute.Value, encryptionKey);
passwordAttribute.Value = encryptedPassword;
}
diff --git a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs
index a2a45ce15..cd4d521b8 100644
--- a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs
@@ -14,11 +14,11 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
public IEnumerable Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml)) return new ICredentialRecord[0];
- var xdoc = XDocument.Parse(xml);
- var rootElement = xdoc.Root;
+ XDocument xdoc = XDocument.Parse(xml);
+ XElement rootElement = xdoc.Root;
ValidateSchemaVersion(rootElement);
- var credentials = from element in xdoc.Descendants("Credential")
+ IEnumerable credentials = from element in xdoc.Descendants("Credential")
select new CredentialRecord(Guid.Parse(element.Attribute("Id")?.Value ??
Guid.NewGuid().ToString()))
{
@@ -32,7 +32,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
private void ValidateSchemaVersion(XElement rootElement)
{
- var docSchemaVersion = rootElement?.Attribute("SchemaVersion")?.Value;
+ string docSchemaVersion = rootElement?.Attribute("SchemaVersion")?.Value;
if (docSchemaVersion != SchemaVersion)
throw new Exception($"The schema version of this document is not supported by this class. Document Version: {docSchemaVersion} Supported Version: {SchemaVersion}");
}
diff --git a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs
index 77319073f..7a21c3a81 100644
--- a/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs
+++ b/mRemoteNG/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs
@@ -13,7 +13,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
public string Serialize(IEnumerable credentialRecords)
{
- var xdoc = new XDocument(
+ XDocument xdoc = new(
new XElement("Credentials",
new XAttribute("SchemaVersion", Version.ToString(2)),
from r in credentialRecords
diff --git a/mRemoteNG/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs b/mRemoteNG/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs
index 345a46103..d7d53824f 100644
--- a/mRemoteNG/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs
@@ -28,8 +28,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize()
{
- var connectionTreeModel = new ConnectionTreeModel();
- var root = new RootNodeInfo(RootNodeType.Connection);
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
ImportContainers(_ldapPath, root);
@@ -39,10 +39,10 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportContainers(string ldapPath, ContainerInfo parentContainer)
{
- var match = Regex.Match(ldapPath, "ou=([^,]*)", RegexOptions.IgnoreCase);
- var name = match.Success ? match.Groups[1].Captures[0].Value : Language.ActiveDirectory;
+ Match match = Regex.Match(ldapPath, "ou=([^,]*)", RegexOptions.IgnoreCase);
+ string name = match.Success ? match.Groups[1].Captures[0].Value : Language.ActiveDirectory;
- var newContainer = new ContainerInfo {Name = name};
+ ContainerInfo newContainer = new() { Name = name};
parentContainer.AddChild(newContainer);
ImportComputers(ldapPath, newContainer);
@@ -53,17 +53,17 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
try
{
const string ldapFilter = "(|(objectClass=computer)(objectClass=organizationalUnit))";
- using (var ldapSearcher = new DirectorySearcher())
+ using (DirectorySearcher ldapSearcher = new())
{
ldapSearcher.SearchRoot = new DirectoryEntry(ldapPath);
ldapSearcher.Filter = ldapFilter;
ldapSearcher.SearchScope = SearchScope.OneLevel;
ldapSearcher.PropertiesToLoad.AddRange(new[] {"securityEquals", "cn", "objectClass"});
- var ldapResults = ldapSearcher.FindAll();
+ SearchResultCollection ldapResults = ldapSearcher.FindAll();
foreach (SearchResult ldapResult in ldapResults)
{
- using (var directoryEntry = ldapResult.GetDirectoryEntry())
+ using (DirectoryEntry directoryEntry = ldapResult.GetDirectoryEntry())
{
if (directoryEntry.Properties["objectClass"].Contains("organizationalUnit"))
{
@@ -88,11 +88,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void DeserializeConnection(DirectoryEntry directoryEntry, ContainerInfo parentContainer)
{
- var displayName = Convert.ToString(directoryEntry.Properties["cn"].Value);
- var description = Convert.ToString(directoryEntry.Properties["Description"].Value);
- var hostName = Convert.ToString(directoryEntry.Properties["dNSHostName"].Value);
+ string displayName = Convert.ToString(directoryEntry.Properties["cn"].Value);
+ string description = Convert.ToString(directoryEntry.Properties["Description"].Value);
+ string hostName = Convert.ToString(directoryEntry.Properties["dNSHostName"].Value);
- var newConnectionInfo = new ConnectionInfo
+ ConnectionInfo newConnectionInfo = new()
{
Name = displayName,
Hostname = hostName,
diff --git a/mRemoteNG/Config/Serializers/MiscSerializers/PortScanDeserializer.cs b/mRemoteNG/Config/Serializers/MiscSerializers/PortScanDeserializer.cs
index 0628ce6fb..2fce4105e 100644
--- a/mRemoteNG/Config/Serializers/MiscSerializers/PortScanDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/MiscSerializers/PortScanDeserializer.cs
@@ -21,11 +21,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(IEnumerable scannedHosts)
{
- var connectionTreeModel = new ConnectionTreeModel();
- var root = new RootNodeInfo(RootNodeType.Connection);
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
- foreach (var host in scannedHosts)
+ foreach (ScanHost host in scannedHosts)
ImportScannedHost(host, root);
return connectionTreeModel;
@@ -33,8 +33,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportScannedHost(ScanHost host, ContainerInfo parentContainer)
{
- var finalProtocol = default(ProtocolType);
- var protocolValid = true;
+ ProtocolType finalProtocol = default(ProtocolType);
+ bool protocolValid = true;
switch (_targetProtocolType)
{
@@ -72,7 +72,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
}
if (!protocolValid) return;
- var newConnectionInfo = new ConnectionInfo
+ ConnectionInfo newConnectionInfo = new()
{
Name = host.HostNameWithoutDomain,
Hostname = host.HostName,
diff --git a/mRemoteNG/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs b/mRemoteNG/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs
index bb55a58bd..495c370c3 100644
--- a/mRemoteNG/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs
@@ -15,16 +15,16 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
{
public ConnectionTreeModel Deserialize(string puttycmConnectionsXml)
{
- var connectionTreeModel = new ConnectionTreeModel();
- var root = new RootNodeInfo(RootNodeType.Connection);
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
- var xmlDocument = new XmlDocument();
+ XmlDocument xmlDocument = new();
xmlDocument.LoadXml(puttycmConnectionsXml);
- var configurationNode = xmlDocument.SelectSingleNode("/configuration");
+ XmlNode configurationNode = xmlDocument.SelectSingleNode("/configuration");
- var rootNodes = configurationNode?.SelectNodes("./root");
+ XmlNodeList rootNodes = configurationNode?.SelectNodes("./root");
if (rootNodes == null) return connectionTreeModel;
foreach (XmlNode rootNode in rootNodes)
{
@@ -38,9 +38,9 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
{
VerifyNodeType(xmlNode);
- var newContainer = ImportContainer(xmlNode, parentContainer);
+ ContainerInfo newContainer = ImportContainer(xmlNode, parentContainer);
- var childNodes = xmlNode.SelectNodes("./*");
+ XmlNodeList childNodes = xmlNode.SelectNodes("./*");
if (childNodes == null) return;
foreach (XmlNode childNode in childNodes)
{
@@ -60,7 +60,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void VerifyNodeType(XmlNode xmlNode)
{
- var xmlNodeType = xmlNode?.Attributes?["type"].Value;
+ string xmlNodeType = xmlNode?.Attributes?["type"].Value;
switch (xmlNode?.Name)
{
case "root":
@@ -86,7 +86,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ContainerInfo ImportContainer(XmlNode containerNode, ContainerInfo parentContainer)
{
- var containerInfo = new ContainerInfo
+ ContainerInfo containerInfo = new()
{
Name = containerNode.Attributes?["name"].Value,
IsExpanded = bool.Parse(containerNode.Attributes?["expanded"].InnerText ?? "false")
@@ -97,22 +97,22 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportConnection(XmlNode connectionNode, ContainerInfo parentContainer)
{
- var connectionNodeType = connectionNode.Attributes?["type"].Value;
+ string connectionNodeType = connectionNode.Attributes?["type"].Value;
if (string.Compare(connectionNodeType, "PuTTY", StringComparison.OrdinalIgnoreCase) != 0)
throw (new FileFormatException($"Unrecognized connection node type ({connectionNodeType})."));
- var connectionInfo = ConnectionInfoFromXml(connectionNode);
+ ConnectionInfo connectionInfo = ConnectionInfoFromXml(connectionNode);
parentContainer.AddChild(connectionInfo);
}
private ConnectionInfo ConnectionInfoFromXml(XmlNode xmlNode)
{
- var connectionInfoNode = xmlNode.SelectSingleNode("./connection_info");
+ XmlNode connectionInfoNode = xmlNode.SelectSingleNode("./connection_info");
- var name = connectionInfoNode?.SelectSingleNode("./name")?.InnerText;
- var connectionInfo = new ConnectionInfo {Name = name};
+ string name = connectionInfoNode?.SelectSingleNode("./name")?.InnerText;
+ ConnectionInfo connectionInfo = new() { Name = name};
- var protocol = connectionInfoNode?.SelectSingleNode("./protocol")?.InnerText;
+ string protocol = connectionInfoNode?.SelectSingleNode("./protocol")?.InnerText;
switch (protocol?.ToLowerInvariant())
{
case "telnet":
@@ -131,7 +131,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
// ./commandline
connectionInfo.Description = connectionInfoNode.SelectSingleNode("./description")?.InnerText;
- var loginNode = xmlNode.SelectSingleNode("./login");
+ XmlNode loginNode = xmlNode.SelectSingleNode("./login");
connectionInfo.Username = loginNode?.SelectSingleNode("login")?.InnerText;
connectionInfo.Password = loginNode?.SelectSingleNode("password")?.InnerText;
// ./prompt
diff --git a/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs b/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs
index 95c9734fe..be3950feb 100644
--- a/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs
@@ -14,20 +14,20 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(string rdcFileContent)
{
- var connectionTreeModel = new ConnectionTreeModel();
- var root = new RootNodeInfo(RootNodeType.Connection);
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
- var connectionInfo = new ConnectionInfo();
- foreach (var line in rdcFileContent.Split(Environment.NewLine.ToCharArray()))
+ ConnectionInfo connectionInfo = new();
+ foreach (string line in rdcFileContent.Split(Environment.NewLine.ToCharArray()))
{
- var parts = line.Split(new[] { ':' }, 3);
+ string[] parts = line.Split(new[] { ':' }, 3);
if (parts.Length < 3)
{
continue;
}
- var key = parts[0].Trim();
- var value = parts[2].Trim();
+ string key = parts[0].Trim();
+ string value = parts[2].Trim();
SetConnectionInfoParameter(connectionInfo, key, value);
}
@@ -43,7 +43,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
switch (key.ToLower())
{
case "full address":
- var uri = new Uri("dummyscheme" + Uri.SchemeDelimiter + value);
+ Uri uri = new("dummyscheme" + Uri.SchemeDelimiter + value);
if (!string.IsNullOrEmpty(uri.Host))
connectionInfo.Hostname = uri.Host;
if (uri.Port != -1)
diff --git a/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs b/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs
index 45af0013a..e6c569702 100644
--- a/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs
@@ -22,18 +22,18 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(string rdcmConnectionsXml)
{
- var connectionTreeModel = new ConnectionTreeModel();
- var root = new RootNodeInfo(RootNodeType.Connection);
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo root = new(RootNodeType.Connection);
- var xmlDocument = new XmlDocument();
+ XmlDocument xmlDocument = new();
xmlDocument.LoadXml(rdcmConnectionsXml);
- var rdcManNode = xmlDocument.SelectSingleNode("/RDCMan");
+ XmlNode rdcManNode = xmlDocument.SelectSingleNode("/RDCMan");
VerifySchemaVersion(rdcManNode);
VerifyFileVersion(rdcManNode);
- var fileNode = rdcManNode?.SelectSingleNode("./file");
+ XmlNode fileNode = rdcManNode?.SelectSingleNode("./file");
ImportFileOrGroup(fileNode, root);
connectionTreeModel.AddRootNode(root);
@@ -42,7 +42,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void VerifySchemaVersion(XmlNode rdcManNode)
{
- if (!int.TryParse(rdcManNode?.Attributes?["schemaVersion"]?.Value, out var version))
+ if (!int.TryParse(rdcManNode?.Attributes?["schemaVersion"]?.Value, out int version))
throw new FileFormatException("Could not find schema version attribute.");
if (version != 1 && version != 3)
@@ -55,10 +55,10 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void VerifyFileVersion(XmlNode rdcManNode)
{
- var versionAttribute = rdcManNode?.Attributes?["programVersion"]?.Value;
+ string versionAttribute = rdcManNode?.Attributes?["programVersion"]?.Value;
if (versionAttribute != null)
{
- var version = new Version(versionAttribute);
+ Version version = new(versionAttribute);
if (!(version == new Version(2, 7)) && !(version == new Version(2, 83)))
{
throw new FileFormatException($"Unsupported file version ({version}).");
@@ -66,10 +66,10 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
}
else
{
- var versionNode = rdcManNode?.SelectSingleNode("./version")?.InnerText;
+ string versionNode = rdcManNode?.SelectSingleNode("./version")?.InnerText;
if (versionNode != null)
{
- var version = new Version(versionNode);
+ Version version = new(versionNode);
if (!(version == new Version(2, 2)))
{
throw new FileFormatException($"Unsupported file version ({version}).");
@@ -84,9 +84,9 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void ImportFileOrGroup(XmlNode xmlNode, ContainerInfo parentContainer)
{
- var newContainer = ImportContainer(xmlNode, parentContainer);
+ ContainerInfo newContainer = ImportContainer(xmlNode, parentContainer);
- var childNodes = xmlNode.SelectNodes("./group|./server");
+ XmlNodeList childNodes = xmlNode.SelectNodes("./group|./server");
if (childNodes == null) return;
foreach (XmlNode childNode in childNodes)
{
@@ -111,8 +111,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
containerPropertiesNode = containerPropertiesNode.SelectSingleNode("./properties");
}
- var newContainer = new ContainerInfo();
- var connectionInfo = ConnectionInfoFromXml(containerPropertiesNode);
+ ContainerInfo newContainer = new();
+ ConnectionInfo connectionInfo = ConnectionInfoFromXml(containerPropertiesNode);
newContainer.CopyFrom(connectionInfo);
if (_schemaVersion == 3)
@@ -121,7 +121,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
containerPropertiesNode = containerPropertiesNode.SelectSingleNode("./properties");
}
newContainer.Name = containerPropertiesNode?.SelectSingleNode("./name")?.InnerText ?? Language.NewFolder;
- if (bool.TryParse(containerPropertiesNode?.SelectSingleNode("./expanded")?.InnerText, out var expanded))
+ if (bool.TryParse(containerPropertiesNode?.SelectSingleNode("./expanded")?.InnerText, out bool expanded))
newContainer.IsExpanded = expanded;
parentContainer.AddChild(newContainer);
return newContainer;
@@ -129,15 +129,15 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void ImportServer(XmlNode serverNode, ContainerInfo parentContainer)
{
- var newConnectionInfo = ConnectionInfoFromXml(serverNode);
+ ConnectionInfo newConnectionInfo = ConnectionInfoFromXml(serverNode);
parentContainer.AddChild(newConnectionInfo);
}
private static ConnectionInfo ConnectionInfoFromXml(XmlNode xmlNode)
{
- var connectionInfo = new ConnectionInfo {Protocol = ProtocolType.RDP};
+ ConnectionInfo connectionInfo = new() { Protocol = ProtocolType.RDP};
- var propertiesNode = xmlNode.SelectSingleNode("./properties");
+ XmlNode propertiesNode = xmlNode.SelectSingleNode("./properties");
if (_schemaVersion == 1)
propertiesNode = xmlNode; // Version 2.2 defines the container name at the root instead
@@ -145,7 +145,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Hostname = propertiesNode?.SelectSingleNode("./name")?.InnerText ?? "";
- var connectionDisplayName = propertiesNode?.SelectSingleNode("./displayName")?.InnerText;
+ string connectionDisplayName = propertiesNode?.SelectSingleNode("./displayName")?.InnerText;
connectionInfo.Name = !string.IsNullOrWhiteSpace(connectionDisplayName)
? connectionDisplayName
: string.IsNullOrWhiteSpace(connectionInfo.Hostname)
@@ -154,12 +154,12 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Description = propertiesNode?.SelectSingleNode("./comment")?.InnerText ?? string.Empty;
- var logonCredentialsNode = xmlNode.SelectSingleNode("./logonCredentials");
+ XmlNode logonCredentialsNode = xmlNode.SelectSingleNode("./logonCredentials");
if (logonCredentialsNode?.Attributes?["inherit"]?.Value == "None")
{
connectionInfo.Username = logonCredentialsNode.SelectSingleNode("userName")?.InnerText ?? string.Empty;
- var passwordNode = logonCredentialsNode.SelectSingleNode("./password");
+ XmlNode passwordNode = logonCredentialsNode.SelectSingleNode("./password");
if (_schemaVersion == 1) // Version 2.2 allows clear text passwords
{
connectionInfo.Password = passwordNode?.Attributes?["storeAsClearText"]?.Value == "True"
@@ -180,14 +180,14 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.Domain = true;
}
- var connectionSettingsNode = xmlNode.SelectSingleNode("./connectionSettings");
+ XmlNode connectionSettingsNode = xmlNode.SelectSingleNode("./connectionSettings");
if (connectionSettingsNode?.Attributes?["inherit"]?.Value == "None")
{
- if (bool.TryParse(connectionSettingsNode.SelectSingleNode("./connectToConsole")?.InnerText, out var useConsole))
+ if (bool.TryParse(connectionSettingsNode.SelectSingleNode("./connectToConsole")?.InnerText, out bool useConsole))
connectionInfo.UseConsoleSession = useConsole;
connectionInfo.RDPStartProgram = connectionSettingsNode.SelectSingleNode("./startProgram")?.InnerText ?? string.Empty;
connectionInfo.RDPStartProgramWorkDir = connectionSettingsNode.SelectSingleNode("./startProgramWorkDir")?.InnerText ?? string.Empty;
- if (int.TryParse(connectionSettingsNode.SelectSingleNode("./port")?.InnerText, out var port))
+ if (int.TryParse(connectionSettingsNode.SelectSingleNode("./port")?.InnerText, out int port))
connectionInfo.Port = port;
}
else
@@ -196,7 +196,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.Port = true;
}
- var gatewaySettingsNode = xmlNode.SelectSingleNode("./gatewaySettings");
+ XmlNode gatewaySettingsNode = xmlNode.SelectSingleNode("./gatewaySettings");
if (gatewaySettingsNode?.Attributes?["inherit"]?.Value == "None")
{
connectionInfo.RDGatewayUsageMethod =
@@ -206,7 +206,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.RDGatewayHostname = gatewaySettingsNode.SelectSingleNode("./hostName")?.InnerText ?? string.Empty;
connectionInfo.RDGatewayUsername = gatewaySettingsNode.SelectSingleNode("./userName")?.InnerText ?? string.Empty;
- var passwordNode = gatewaySettingsNode.SelectSingleNode("./password");
+ XmlNode passwordNode = gatewaySettingsNode.SelectSingleNode("./password");
connectionInfo.RDGatewayPassword = passwordNode?.Attributes?["storeAsClearText"]?.Value == "True"
? passwordNode.InnerText
: DecryptRdcManPassword(passwordNode?.InnerText);
@@ -225,11 +225,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.RDGatewayDomain = true;
}
- var remoteDesktopNode = xmlNode.SelectSingleNode("./remoteDesktop");
+ XmlNode remoteDesktopNode = xmlNode.SelectSingleNode("./remoteDesktop");
if (remoteDesktopNode?.Attributes?["inherit"]?.Value == "None")
{
connectionInfo.Resolution =
- Enum.TryParse(remoteDesktopNode.SelectSingleNode("./size")?.InnerText.Replace(" ", ""), true, out var rdpResolution)
+ Enum.TryParse(remoteDesktopNode.SelectSingleNode("./size")?.InnerText.Replace(" ", ""), true, out RDPResolutions rdpResolution)
? rdpResolution
: RDPResolutions.FitToWindow;
@@ -243,7 +243,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Resolution = RDPResolutions.Fullscreen;
}
- if (Enum.TryParse(remoteDesktopNode.SelectSingleNode("./colorDepth")?.InnerText, true, out var rdpColors))
+ if (Enum.TryParse(remoteDesktopNode.SelectSingleNode("./colorDepth")?.InnerText, true, out RDPColors rdpColors))
connectionInfo.Colors = rdpColors;
}
else
@@ -252,7 +252,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.Colors = true;
}
- var localResourcesNode = xmlNode.SelectSingleNode("./localResources");
+ XmlNode localResourcesNode = xmlNode.SelectSingleNode("./localResources");
if (localResourcesNode?.Attributes?["inherit"]?.Value == "None")
{
// ReSharper disable once SwitchStatementMissingSomeCases
@@ -293,19 +293,19 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
}
// ./redirectClipboard
- if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectDrives")?.InnerText, out var redirectDisks))
+ if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectDrives")?.InnerText, out bool redirectDisks))
connectionInfo.RedirectDiskDrives = redirectDisks ? RDPDiskDrives.Local : RDPDiskDrives.None;
- if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPorts")?.InnerText, out var redirectPorts))
+ if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPorts")?.InnerText, out bool redirectPorts))
connectionInfo.RedirectPorts = redirectPorts;
- if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPrinters")?.InnerText, out var redirectPrinters))
+ if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPrinters")?.InnerText, out bool redirectPrinters))
connectionInfo.RedirectPrinters = redirectPrinters;
- if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectSmartCards")?.InnerText, out var redirectSmartCards))
+ if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectSmartCards")?.InnerText, out bool redirectSmartCards))
connectionInfo.RedirectSmartCards = redirectSmartCards;
- if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectClipboard")?.InnerText, out var redirectClipboard))
+ if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectClipboard")?.InnerText, out bool redirectClipboard))
connectionInfo.RedirectClipboard = redirectClipboard;
}
else
@@ -319,7 +319,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.RedirectClipboard = true;
}
- var securitySettingsNode = xmlNode.SelectSingleNode("./securitySettings");
+ XmlNode securitySettingsNode = xmlNode.SelectSingleNode("./securitySettings");
if (securitySettingsNode?.Attributes?["inherit"]?.Value == "None")
{
// ReSharper disable once SwitchStatementMissingSomeCases
@@ -358,9 +358,9 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
try
{
- var plaintextData = ProtectedData.Unprotect(Convert.FromBase64String(ciphertext), new byte[] { },
+ byte[] plaintextData = ProtectedData.Unprotect(Convert.FromBase64String(ciphertext), new byte[] { },
DataProtectionScope.LocalMachine);
- var charArray = Encoding.Unicode.GetChars(plaintextData);
+ char[] charArray = Encoding.Unicode.GetChars(plaintextData);
return new string(charArray);
}
catch (Exception /*ex*/)
diff --git a/mRemoteNG/Config/Serializers/MiscSerializers/SecureCRTFileDeserializer.cs b/mRemoteNG/Config/Serializers/MiscSerializers/SecureCRTFileDeserializer.cs
index ae9f54e9e..6aa4a74de 100644
--- a/mRemoteNG/Config/Serializers/MiscSerializers/SecureCRTFileDeserializer.cs
+++ b/mRemoteNG/Config/Serializers/MiscSerializers/SecureCRTFileDeserializer.cs
@@ -18,14 +18,14 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(string content)
{
- var connectionTreeModel = new ConnectionTreeModel();
- var root = new RootNodeInfo(RootNodeType.Connection);
+ ConnectionTreeModel connectionTreeModel = new();
+ RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
- var xmlDocument = new XmlDocument();
+ XmlDocument xmlDocument = new();
xmlDocument.LoadXml(content);
- var sessionsNode = xmlDocument.SelectSingleNode("/VanDyke/key[@name=\"Sessions\"]");
+ XmlNode sessionsNode = xmlDocument.SelectSingleNode("/VanDyke/key[@name=\"Sessions\"]");
ImportRootOrContainer(sessionsNode, root);
@@ -34,17 +34,17 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportRootOrContainer(XmlNode rootNode, ContainerInfo parentContainer)
{
- var newContainer = ImportContainer(rootNode, parentContainer);
+ ContainerInfo newContainer = ImportContainer(rootNode, parentContainer);
if (rootNode.ChildNodes.Count == 0)
return;
foreach (XmlNode child in rootNode.ChildNodes)
{
- var name = child.Attributes["name"].Value;
+ string name = child.Attributes["name"].Value;
if (name == "Default" || name == "Default_LocalShell")
continue;
- var nodeType = GetFolderOrSession(child);
+ SecureCRTNodeType nodeType = GetFolderOrSession(child);
switch (nodeType)
{
case SecureCRTNodeType.folder:
@@ -59,7 +59,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportConnection(XmlNode childNode, ContainerInfo parentContainer)
{
- var connectionInfo = ConnectionInfoFromXml(childNode);
+ ConnectionInfo connectionInfo = ConnectionInfoFromXml(childNode);
if (connectionInfo == null)
return;
@@ -68,7 +68,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ContainerInfo ImportContainer(XmlNode containerNode, ContainerInfo parentContainer)
{
- var containerInfo = new ContainerInfo
+ ContainerInfo containerInfo = new()
{
Name = containerNode.Attributes["name"].InnerText
};
@@ -86,7 +86,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ConnectionInfo ConnectionInfoFromXml(XmlNode xmlNode)
{
- var connectionInfo = new ConnectionInfo();
+ ConnectionInfo connectionInfo = new();
try
{
connectionInfo.Name = xmlNode.Attributes["name"].InnerText;
@@ -131,11 +131,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ProtocolType GetProtocolFromNode(XmlNode xmlNode)
{
- var protocolNode = xmlNode.SelectSingleNode("string[@name=\"Protocol Name\"]");
+ XmlNode protocolNode = xmlNode.SelectSingleNode("string[@name=\"Protocol Name\"]");
if (protocolNode == null)
throw new FileFormatException($"Protocol node not found");
- var protocolText = protocolNode.InnerText.ToUpper();
+ string protocolText = protocolNode.InnerText.ToUpper();
switch (protocolText)
{
case "RDP":
@@ -157,8 +157,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private string GetDescriptionFromNode(XmlNode xmlNode)
{
- var description = string.Empty;
- var descNode = xmlNode.SelectSingleNode("array[@name=\"Description\"]");
+ string description = string.Empty;
+ XmlNode descNode = xmlNode.SelectSingleNode("array[@name=\"Description\"]");
foreach(XmlNode n in descNode.ChildNodes)
{
description += n.InnerText + " ";
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs b/mRemoteNG/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs
index 78581383a..8d883fc43 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs
@@ -11,7 +11,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlDatabaseVersionVerifier
{
- private readonly Version _currentSupportedVersion = new Version(3, 0);
+ private readonly Version _currentSupportedVersion = new(3, 0);
private readonly IDatabaseConnector _databaseConnector;
@@ -31,7 +31,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
return true;
}
- var dbUpgraders = new IVersionUpgrader[]
+ IVersionUpgrader[] dbUpgraders = new IVersionUpgrader[]
{
new SqlVersion22To23Upgrader(_databaseConnector),
new SqlVersion23To24Upgrader(_databaseConnector),
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs
index 591417a0d..c161ab96c 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs
@@ -32,7 +32,7 @@ ADD EnableFontSmoothing bit NOT NULL DEFAULT 0,
InheritEnableFontSmoothing bit NOT NULL DEFAULT 0,
InheritEnableDesktopComposition bit NOT NULL DEFAULT 0;";
- var dbCommand = _databaseConnector.DbCommand(sqlText);
+ System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs
index 874806950..ea4e5be2b 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs
@@ -30,7 +30,7 @@ ALTER TABLE tblCons
ADD UseCredSsp bit NOT NULL DEFAULT 1,
InheritUseCredSsp bit NOT NULL DEFAULT 0;";
- var dbCommand = _databaseConnector.DbCommand(sqlText);
+ System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs
index 6d2e234d6..e4de34c13 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs
@@ -31,7 +31,7 @@ ADD LoadBalanceInfo varchar (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
AutomaticResize bit NOT NULL DEFAULT 1,
InheritLoadBalanceInfo bit NOT NULL DEFAULT 0,
InheritAutomaticResize bit NOT NULL DEFAULT 0;";
- var dbCommand = _databaseConnector.DbCommand(sqlText);
+ System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
return new Version(2, 5);
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs
index 2a71d6250..59af69030 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs
@@ -35,7 +35,7 @@ ADD RDPMinutesToIdleTimeout int NOT NULL DEFAULT 0,
InheritSoundQuality bit NOT NULL DEFAULT 0;
UPDATE tblRoot
SET ConfVersion='2.6'";
- var dbCommand = _databaseConnector.DbCommand(sqlText);
+ System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
return new Version(2, 6);
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs
index 34e6a5e0d..4ae9b8c7d 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs
@@ -44,7 +44,7 @@ ADD RedirectClipboard bit NOT NULL,
InheritUseEnhancedMode bit NOT NULL;
UPDATE tblRoot
SET ConfVersion='2.7'";
- var dbCommand = _databaseConnector.DbCommand(sqlText);
+ System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
}
catch (SqlException)
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion28To29Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion28To29Upgrader.cs
index f7fe8a967..32eae44b8 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion28To29Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion28To29Upgrader.cs
@@ -10,7 +10,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlVersion28To29Upgrader : IVersionUpgrader
{
- private readonly Version _version = new Version(2, 9);
+ private readonly Version _version = new(2, 9);
private readonly IDatabaseConnector _databaseConnector;
public SqlVersion28To29Upgrader(IDatabaseConnector databaseConnector)
@@ -91,7 +91,7 @@ ALTER TABLE tblRoot ALTER COLUMN [ConfVersion] VARCHAR(15) NOT NULL;
const string msSqlUpdate = @"UPDATE tblRoot SET ConfVersion=@confVersion;";
- using (var sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
+ using (DbTransaction sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
{
DbCommand dbCommand;
if (_databaseConnector.GetType() == typeof(MSSqlDatabaseConnector))
@@ -114,7 +114,7 @@ ALTER TABLE tblRoot ALTER COLUMN [ConfVersion] VARCHAR(15) NOT NULL;
{
throw new Exception("Unknown database back-end");
}
- var pConfVersion = dbCommand.CreateParameter();
+ DbParameter pConfVersion = dbCommand.CreateParameter();
pConfVersion.ParameterName = "confVersion";
pConfVersion.Value = _version.ToString();
pConfVersion.DbType = System.Data.DbType.String;
diff --git a/mRemoteNG/Config/Serializers/Versioning/SqlVersion29To30Upgrader.cs b/mRemoteNG/Config/Serializers/Versioning/SqlVersion29To30Upgrader.cs
index b06f03bcd..185fb08aa 100644
--- a/mRemoteNG/Config/Serializers/Versioning/SqlVersion29To30Upgrader.cs
+++ b/mRemoteNG/Config/Serializers/Versioning/SqlVersion29To30Upgrader.cs
@@ -10,7 +10,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlVersion29To30Upgrader : IVersionUpgrader
{
- private readonly Version _version = new Version(3, 0);
+ private readonly Version _version = new(3, 0);
private readonly IDatabaseConnector _databaseConnector;
public SqlVersion29To30Upgrader(IDatabaseConnector databaseConnector)
@@ -157,7 +157,7 @@ ALTER TABLE tblCons ADD `UserViaAPI` varchar(512) NOT NULL;
const string msSqlUpdate = @"UPDATE tblRoot SET ConfVersion=@confVersion;";
- using (var sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
+ using (DbTransaction sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
{
DbCommand dbCommand;
if (_databaseConnector.GetType() == typeof(MSSqlDatabaseConnector))
@@ -180,7 +180,7 @@ ALTER TABLE tblCons ADD `UserViaAPI` varchar(512) NOT NULL;
{
throw new Exception("Unknown database back-end");
}
- var pConfVersion = dbCommand.CreateParameter();
+ DbParameter pConfVersion = dbCommand.CreateParameter();
pConfVersion.ParameterName = "confVersion";
pConfVersion.Value = _version.ToString();
pConfVersion.DbType = System.Data.DbType.String;
diff --git a/mRemoteNG/Config/Serializers/XmlConnectionsDecryptor.cs b/mRemoteNG/Config/Serializers/XmlConnectionsDecryptor.cs
index 6a613a93d..1c9b47acb 100644
--- a/mRemoteNG/Config/Serializers/XmlConnectionsDecryptor.cs
+++ b/mRemoteNG/Config/Serializers/XmlConnectionsDecryptor.cs
@@ -49,7 +49,7 @@ namespace mRemoteNG.Config.Serializers
if (string.IsNullOrEmpty(xml)) return "";
if (xml.Contains("")) return xml;
- var decryptedContent = "";
+ string decryptedContent = "";
bool notDecr;
try
@@ -84,7 +84,7 @@ namespace mRemoteNG.Config.Serializers
public bool ConnectionsFileIsAuthentic(string protectedString, SecureString password)
{
- var connectionsFileIsNotEncrypted = false;
+ bool connectionsFileIsNotEncrypted = false;
try
{
connectionsFileIsNotEncrypted = _cryptographyProvider.Decrypt(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()) == "ThisIsNotProtected";
@@ -98,8 +98,8 @@ namespace mRemoteNG.Config.Serializers
private bool Authenticate(string cipherText, SecureString password)
{
- var authenticator = new PasswordAuthenticator(_cryptographyProvider, cipherText, AuthenticationRequestor);
- var authenticated = authenticator.Authenticate(password);
+ PasswordAuthenticator authenticator = new(_cryptographyProvider, cipherText, AuthenticationRequestor);
+ bool authenticated = authenticator.Authenticate(password);
if (!authenticated)
return false;
diff --git a/mRemoteNG/Config/Settings/DockPanelLayoutLoader.cs b/mRemoteNG/Config/Settings/DockPanelLayoutLoader.cs
index 9318244c8..c775aab4e 100644
--- a/mRemoteNG/Config/Settings/DockPanelLayoutLoader.cs
+++ b/mRemoteNG/Config/Settings/DockPanelLayoutLoader.cs
@@ -33,15 +33,15 @@ namespace mRemoteNG.Config.Settings
{
while (_mainForm.pnlDock.Contents.Count > 0)
{
- var dc = (DockContent)_mainForm.pnlDock.Contents[0];
+ DockContent dc = (DockContent)_mainForm.pnlDock.Contents[0];
dc.Close();
}
#if !PORTABLE
- var oldPath =
+ string oldPath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\" + GeneralAppInfo.ProductName + "\\" + SettingsFileInfo.LayoutFileName;
#endif
- var newPath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
+ string newPath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
if (File.Exists(newPath))
{
_mainForm.pnlDock.LoadFromXml(newPath, GetContentFromPersistString);
diff --git a/mRemoteNG/Config/Settings/DockPanelLayoutSaver.cs b/mRemoteNG/Config/Settings/DockPanelLayoutSaver.cs
index e2f949c85..55cc4e7be 100644
--- a/mRemoteNG/Config/Settings/DockPanelLayoutSaver.cs
+++ b/mRemoteNG/Config/Settings/DockPanelLayoutSaver.cs
@@ -37,7 +37,7 @@ namespace mRemoteNG.Config.Settings
Directory.CreateDirectory(SettingsFileInfo.SettingsPath);
}
- var serializedLayout = _dockPanelSerializer.Serialize(FrmMain.Default.pnlDock);
+ string serializedLayout = _dockPanelSerializer.Serialize(FrmMain.Default.pnlDock);
_dataProvider.Save(serializedLayout);
}
catch (Exception ex)
diff --git a/mRemoteNG/Config/Settings/DockPanelLayoutSerializer.cs b/mRemoteNG/Config/Settings/DockPanelLayoutSerializer.cs
index e8e4be847..1d8f563ed 100644
--- a/mRemoteNG/Config/Settings/DockPanelLayoutSerializer.cs
+++ b/mRemoteNG/Config/Settings/DockPanelLayoutSerializer.cs
@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.Settings
throw new ArgumentNullException(nameof(dockPanel));
XDocument xdoc;
- using (var memoryStream = new MemoryStream())
+ using (MemoryStream memoryStream = new())
{
dockPanel.SaveAsXml(memoryStream, Encoding.UTF8);
memoryStream.Position = 0;
diff --git a/mRemoteNG/Config/Settings/ExternalAppsLoader.cs b/mRemoteNG/Config/Settings/ExternalAppsLoader.cs
index c403cfed7..eaa6d11e5 100644
--- a/mRemoteNG/Config/Settings/ExternalAppsLoader.cs
+++ b/mRemoteNG/Config/Settings/ExternalAppsLoader.cs
@@ -36,11 +36,11 @@ namespace mRemoteNG.Config.Settings
public void LoadExternalAppsFromXML()
{
#if !PORTABLE
- var oldPath =
+ string oldPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GeneralAppInfo.ProductName, SettingsFileInfo.ExtAppsFilesName);
#endif
- var newPath = Path.Combine(SettingsFileInfo.SettingsPath, SettingsFileInfo.ExtAppsFilesName);
- var xDom = new XmlDocument();
+ string newPath = Path.Combine(SettingsFileInfo.SettingsPath, SettingsFileInfo.ExtAppsFilesName);
+ XmlDocument xDom = new();
if (File.Exists(newPath))
{
_messageCollector.AddMessage(MessageClass.InformationMsg, $"Loading External Apps from: {newPath}",
@@ -69,7 +69,7 @@ namespace mRemoteNG.Config.Settings
foreach (XmlElement xEl in xDom.DocumentElement.ChildNodes)
{
- var extA = new ExternalTool
+ ExternalTool extA = new()
{
DisplayName = xEl.Attributes["DisplayName"].Value,
FileName = xEl.Attributes["FileName"].Value,
diff --git a/mRemoteNG/Config/Settings/ExternalAppsSaver.cs b/mRemoteNG/Config/Settings/ExternalAppsSaver.cs
index 5acc00df3..07c5d792f 100644
--- a/mRemoteNG/Config/Settings/ExternalAppsSaver.cs
+++ b/mRemoteNG/Config/Settings/ExternalAppsSaver.cs
@@ -22,8 +22,8 @@ namespace mRemoteNG.Config.Settings
Directory.CreateDirectory(SettingsFileInfo.SettingsPath);
}
- var xmlTextWriter =
- new XmlTextWriter(SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.ExtAppsFilesName,
+ XmlTextWriter xmlTextWriter =
+ new(SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.ExtAppsFilesName,
Encoding.UTF8)
{
Formatting = Formatting.Indented,
@@ -33,7 +33,7 @@ namespace mRemoteNG.Config.Settings
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("Apps");
- foreach (var extA in externalTools)
+ foreach (ExternalTool extA in externalTools)
{
xmlTextWriter.WriteStartElement("App");
xmlTextWriter.WriteAttributeString("DisplayName", "", extA.DisplayName);
diff --git a/mRemoteNG/Config/Settings/Providers/PortableSettingsProvider.cs b/mRemoteNG/Config/Settings/Providers/PortableSettingsProvider.cs
index fa79921fa..ec29bf76b 100644
--- a/mRemoteNG/Config/Settings/Providers/PortableSettingsProvider.cs
+++ b/mRemoteNG/Config/Settings/Providers/PortableSettingsProvider.cs
@@ -115,7 +115,7 @@ namespace mRemoteNG.Config.Settings.Providers
public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context,
SettingsPropertyCollection collection)
{
- var values = new SettingsPropertyValueCollection();
+ SettingsPropertyValueCollection values = new();
foreach (SettingsProperty property in collection)
{
@@ -130,9 +130,9 @@ namespace mRemoteNG.Config.Settings.Providers
private void SetValue(SettingsPropertyValue propertyValue)
{
- var targetNode = IsGlobal(propertyValue.Property) ? _globalSettingsNode : _localSettingsNode;
+ XmlNode targetNode = IsGlobal(propertyValue.Property) ? _globalSettingsNode : _localSettingsNode;
- var settingNode = targetNode.SelectSingleNode($"setting[@name='{propertyValue.Name}']");
+ XmlNode settingNode = targetNode.SelectSingleNode($"setting[@name='{propertyValue.Name}']");
if (settingNode != null)
settingNode.InnerText = propertyValue.SerializedValue.ToString();
@@ -140,7 +140,7 @@ namespace mRemoteNG.Config.Settings.Providers
{
settingNode = _rootDocument.CreateElement("setting");
- var nameAttribute = _rootDocument.CreateAttribute("name");
+ XmlAttribute nameAttribute = _rootDocument.CreateAttribute("name");
nameAttribute.Value = propertyValue.Name;
settingNode.Attributes?.Append(nameAttribute);
@@ -152,8 +152,8 @@ namespace mRemoteNG.Config.Settings.Providers
private string GetValue(SettingsProperty property)
{
- var targetNode = IsGlobal(property) ? _globalSettingsNode : _localSettingsNode;
- var settingNode = targetNode.SelectSingleNode($"setting[@name='{property.Name}']");
+ XmlNode targetNode = IsGlobal(property) ? _globalSettingsNode : _localSettingsNode;
+ XmlNode settingNode = targetNode.SelectSingleNode($"setting[@name='{property.Name}']");
if (settingNode == null)
return property.DefaultValue != null ? property.DefaultValue.ToString() : string.Empty;
@@ -174,7 +174,7 @@ namespace mRemoteNG.Config.Settings.Providers
private XmlNode GetSettingsNode(string name)
{
- var settingsNode = _rootNode.SelectSingleNode(name);
+ XmlNode settingsNode = _rootNode.SelectSingleNode(name);
if (settingsNode != null) return settingsNode;
settingsNode = _rootDocument.CreateElement(name);
@@ -185,7 +185,7 @@ namespace mRemoteNG.Config.Settings.Providers
private static XmlDocument GetBlankXmlDocument()
{
- var blankXmlDocument = new XmlDocument();
+ XmlDocument blankXmlDocument = new();
blankXmlDocument.AppendChild(blankXmlDocument.CreateXmlDeclaration("1.0", "utf-8", string.Empty));
blankXmlDocument.AppendChild(blankXmlDocument.CreateElement(_rootNodeName));
diff --git a/mRemoteNG/Config/Settings/SettingsLoader.cs b/mRemoteNG/Config/Settings/SettingsLoader.cs
index 13e35dde3..29e3ae0ae 100644
--- a/mRemoteNG/Config/Settings/SettingsLoader.cs
+++ b/mRemoteNG/Config/Settings/SettingsLoader.cs
@@ -108,8 +108,8 @@ namespace mRemoteNG.Config.Settings
// Make sure the form is visible on the screen
const int minHorizontal = 300;
const int minVertical = 150;
- var screenBounds = Screen.FromHandle(MainForm.Handle).Bounds;
- var newBounds = MainForm.Bounds;
+ Rectangle screenBounds = Screen.FromHandle(MainForm.Handle).Bounds;
+ Rectangle newBounds = MainForm.Bounds;
if (newBounds.Right < screenBounds.Left + minHorizontal)
newBounds.X = screenBounds.Left + minHorizontal - newBounds.Width;
@@ -198,7 +198,7 @@ namespace mRemoteNG.Config.Settings
///
private void ResetAllToolbarLocations()
{
- var tempToolStrip = new ToolStripPanel();
+ ToolStripPanel tempToolStrip = new();
tempToolStrip.Join(_mainMenu);
tempToolStrip.Join(_quickConnectToolStrip);
tempToolStrip.Join(_externalToolsToolStrip);
@@ -208,7 +208,7 @@ namespace mRemoteNG.Config.Settings
private void AddMainMenuPanel()
{
SetToolstripGripStyle(_mainMenu);
- var toolStripPanel = ToolStripPanelFromString("top");
+ ToolStripPanel toolStripPanel = ToolStripPanelFromString("top");
toolStripPanel.Join(_mainMenu, new Point(3, 0));
}
@@ -216,7 +216,7 @@ namespace mRemoteNG.Config.Settings
{
SetToolstripGripStyle(_quickConnectToolStrip);
_quickConnectToolStrip.Visible = Properties.Settings.Default.QuickyTBVisible;
- var toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.QuickyTBParentDock);
+ ToolStripPanel toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.QuickyTBParentDock);
toolStripPanel.Join(_quickConnectToolStrip, Properties.Settings.Default.QuickyTBLocation);
}
@@ -224,7 +224,7 @@ namespace mRemoteNG.Config.Settings
{
SetToolstripGripStyle(_externalToolsToolStrip);
_externalToolsToolStrip.Visible = Properties.Settings.Default.ExtAppsTBVisible;
- var toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.ExtAppsTBParentDock);
+ ToolStripPanel toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.ExtAppsTBParentDock);
toolStripPanel.Join(_externalToolsToolStrip, Properties.Settings.Default.ExtAppsTBLocation);
}
@@ -232,7 +232,7 @@ namespace mRemoteNG.Config.Settings
{
SetToolstripGripStyle(_multiSshToolStrip);
_multiSshToolStrip.Visible = Properties.Settings.Default.MultiSshToolbarVisible;
- var toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.MultiSshToolbarParentDock);
+ ToolStripPanel toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.MultiSshToolbarParentDock);
toolStripPanel.Join(_multiSshToolStrip, Properties.Settings.Default.MultiSshToolbarLocation);
}
diff --git a/mRemoteNG/Config/Settings/SettingsSaver.cs b/mRemoteNG/Config/Settings/SettingsSaver.cs
index b4ce61735..56e87aed1 100644
--- a/mRemoteNG/Config/Settings/SettingsSaver.cs
+++ b/mRemoteNG/Config/Settings/SettingsSaver.cs
@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.Settings
{
try
{
- var windowPlacement = new WindowPlacement(FrmMain.Default);
+ WindowPlacement windowPlacement = new(FrmMain.Default);
if (frmMain.WindowState == FormWindowState.Minimized & windowPlacement.RestoreToMaximized)
{
frmMain.Opacity = 0;
@@ -110,8 +110,8 @@ namespace mRemoteNG.Config.Settings
private static void SaveDockPanelLayout()
{
- var panelLayoutXmlFilePath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
- var panelLayoutSaver = new DockPanelLayoutSaver(
+ string panelLayoutXmlFilePath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
+ DockPanelLayoutSaver panelLayoutSaver = new(
new DockPanelLayoutSerializer(),
new FileDataProvider(panelLayoutXmlFilePath)
);
@@ -120,7 +120,7 @@ namespace mRemoteNG.Config.Settings
private static void SaveExternalApps()
{
- var externalAppsSaver = new ExternalAppsSaver();
+ ExternalAppsSaver externalAppsSaver = new();
externalAppsSaver.Save(Runtime.ExternalToolsService.ExternalTools);
}
}
diff --git a/mRemoteNG/Connection/AbstractConnectionRecord.cs b/mRemoteNG/Connection/AbstractConnectionRecord.cs
index 7d3dd58e5..5d0240298 100644
--- a/mRemoteNG/Connection/AbstractConnectionRecord.cs
+++ b/mRemoteNG/Connection/AbstractConnectionRecord.cs
@@ -128,8 +128,8 @@ namespace mRemoteNG.Connection
LocalizedAttributes.LocalizedDescription(nameof(Language.PropertyDescriptionDescription))]
public virtual string Description
{
- get => GetPropertyValue("Description", _description);
- set => SetField(ref _description, value, "Description");
+ get => GetPropertyValue(nameof(Description), _description);
+ set => SetField(ref _description, value, nameof(Description));
}
[LocalizedAttributes.LocalizedCategory(nameof(Language.Display)),
diff --git a/mRemoteNG/Connection/ConnectionIcon.cs b/mRemoteNG/Connection/ConnectionIcon.cs
index bbaa0d487..9d41e738a 100644
--- a/mRemoteNG/Connection/ConnectionIcon.cs
+++ b/mRemoteNG/Connection/ConnectionIcon.cs
@@ -31,11 +31,11 @@ namespace mRemoteNG.Connection
{
try
{
- var iconPath = $"{GeneralAppInfo.HomePath}\\Icons\\{iconName}.ico";
+ string iconPath = $"{GeneralAppInfo.HomePath}\\Icons\\{iconName}.ico";
if (System.IO.File.Exists(iconPath))
{
- var nI = new System.Drawing.Icon(iconPath);
+ System.Drawing.Icon nI = new(iconPath);
return nI;
}
}
diff --git a/mRemoteNG/Connection/ConnectionInfo.cs b/mRemoteNG/Connection/ConnectionInfo.cs
index 33bc5b9de..f65384368 100644
--- a/mRemoteNG/Connection/ConnectionInfo.cs
+++ b/mRemoteNG/Connection/ConnectionInfo.cs
@@ -84,7 +84,7 @@ namespace mRemoteNG.Connection
public virtual ConnectionInfo Clone()
{
- var newConnectionInfo = new ConnectionInfo();
+ ConnectionInfo newConnectionInfo = new();
newConnectionInfo.CopyFrom(this);
return newConnectionInfo;
}
@@ -96,16 +96,16 @@ namespace mRemoteNG.Connection
///
public void CopyFrom(ConnectionInfo sourceConnectionInfo)
{
- var properties = GetType().BaseType?.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
+ IEnumerable properties = GetType().BaseType?.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
if (properties == null) return;
- foreach (var property in properties)
+ foreach (PropertyInfo property in properties)
{
if (property.Name == nameof(Parent)) continue;
- var remotePropertyValue = property.GetValue(sourceConnectionInfo, null);
+ object remotePropertyValue = property.GetValue(sourceConnectionInfo, null);
property.SetValue(this, remotePropertyValue, null);
}
- var clonedInheritance = sourceConnectionInfo.Inheritance.Clone(this);
+ ConnectionInfoInheritance clonedInheritance = sourceConnectionInfo.Inheritance.Clone(this);
Inheritance = clonedInheritance;
}
@@ -134,14 +134,14 @@ namespace mRemoteNG.Connection
protected virtual IEnumerable GetProperties(string[] excludedPropertyNames)
{
- var properties = typeof(ConnectionInfo).GetProperties();
- var filteredProperties = properties.Where((prop) => !excludedPropertyNames.Contains(prop.Name));
+ PropertyInfo[] properties = typeof(ConnectionInfo).GetProperties();
+ IEnumerable filteredProperties = properties.Where((prop) => !excludedPropertyNames.Contains(prop.Name));
return filteredProperties;
}
public virtual IEnumerable GetSerializableProperties()
{
- var excludedProperties = new[]
+ string[] excludedProperties = new[]
{
"Parent", "Name", "Hostname", "Port", "Inheritance", "OpenConnections",
"IsContainer", "IsDefault", "PositionID", "ConstantID", "TreeNode", "IsQuickConnect", "PleaseConnect"
@@ -192,8 +192,8 @@ namespace mRemoteNG.Connection
if (!ShouldThisPropertyBeInherited(propertyName))
return value;
- var couldGetInheritedValue =
- TryGetInheritedPropertyValue(propertyName, out var inheritedValue);
+ bool couldGetInheritedValue =
+ TryGetInheritedPropertyValue(propertyName, out TPropertyType inheritedValue);
return couldGetInheritedValue
? inheritedValue
@@ -215,9 +215,9 @@ namespace mRemoteNG.Connection
private bool IsInheritanceTurnedOnForThisProperty(string propertyName)
{
- var inheritType = Inheritance.GetType();
- var inheritPropertyInfo = inheritType.GetProperty(propertyName);
- var inheritPropertyValue = inheritPropertyInfo != null && Convert.ToBoolean(inheritPropertyInfo.GetValue(Inheritance, null));
+ Type inheritType = Inheritance.GetType();
+ PropertyInfo inheritPropertyInfo = inheritType.GetProperty(propertyName);
+ bool inheritPropertyValue = inheritPropertyInfo != null && Convert.ToBoolean(inheritPropertyInfo.GetValue(Inheritance, null));
return inheritPropertyValue;
}
@@ -225,8 +225,8 @@ namespace mRemoteNG.Connection
{
try
{
- var connectionInfoType = Parent.GetType();
- var parentPropertyInfo = connectionInfoType.GetProperty(propertyName);
+ Type connectionInfoType = Parent.GetType();
+ PropertyInfo parentPropertyInfo = connectionInfoType.GetProperty(propertyName);
if (parentPropertyInfo == null)
throw new NullReferenceException(
$"Could not retrieve property data for property '{propertyName}' on parent node '{Parent?.Name}'"
@@ -402,7 +402,7 @@ namespace mRemoteNG.Connection
private void SetNewOpenConnectionList()
{
- OpenConnections = new ProtocolList();
+ OpenConnections = [];
OpenConnections.CollectionChanged += (sender, args) => RaisePropertyChangedEvent(this, new PropertyChangedEventArgs("OpenConnections"));
}
diff --git a/mRemoteNG/Connection/ConnectionInfoInheritance.cs b/mRemoteNG/Connection/ConnectionInfoInheritance.cs
index 617f28d51..1c0e2281f 100644
--- a/mRemoteNG/Connection/ConnectionInfoInheritance.cs
+++ b/mRemoteNG/Connection/ConnectionInfoInheritance.cs
@@ -527,7 +527,7 @@ namespace mRemoteNG.Connection
public ConnectionInfoInheritance Clone(ConnectionInfo parent)
{
- var newInheritance = (ConnectionInfoInheritance)MemberwiseClone();
+ ConnectionInfoInheritance newInheritance = (ConnectionInfoInheritance)MemberwiseClone();
newInheritance.Parent = parent;
return newInheritance;
}
@@ -567,15 +567,15 @@ namespace mRemoteNG.Connection
private bool EverythingIsInherited()
{
- var inheritanceProperties = GetProperties();
- var everythingInherited = inheritanceProperties.All((p) => (bool)p.GetValue(this, null));
+ IEnumerable inheritanceProperties = GetProperties();
+ bool everythingInherited = inheritanceProperties.All((p) => (bool)p.GetValue(this, null));
return everythingInherited;
}
public IEnumerable GetProperties()
{
- var properties = typeof(ConnectionInfoInheritance).GetProperties();
- var filteredProperties = properties.Where(FilterProperty);
+ PropertyInfo[] properties = typeof(ConnectionInfoInheritance).GetProperties();
+ IEnumerable filteredProperties = properties.Where(FilterProperty);
return filteredProperties;
}
@@ -596,20 +596,20 @@ namespace mRemoteNG.Connection
private bool FilterProperty(PropertyInfo propertyInfo)
{
- var exclusions = new[]
+ string[] exclusions = new[]
{
nameof(EverythingInherited),
nameof(Parent),
nameof(InheritanceActive)
};
- var valueShouldNotBeFiltered = !exclusions.Contains(propertyInfo.Name);
+ bool valueShouldNotBeFiltered = !exclusions.Contains(propertyInfo.Name);
return valueShouldNotBeFiltered;
}
private void SetAllValues(bool value)
{
- var properties = GetProperties();
- foreach (var property in properties)
+ IEnumerable properties = GetProperties();
+ foreach (PropertyInfo property in properties)
{
if (property.PropertyType.Name == typeof(bool).Name)
property.SetValue(this, value, null);
@@ -618,10 +618,10 @@ namespace mRemoteNG.Connection
private void SetAllValues(ConnectionInfoInheritance otherInheritanceObject)
{
- var properties = GetProperties();
- foreach (var property in properties)
+ IEnumerable properties = GetProperties();
+ foreach (PropertyInfo property in properties)
{
- var newPropertyValue = property.GetValue(otherInheritanceObject, null);
+ object newPropertyValue = property.GetValue(otherInheritanceObject, null);
property.SetValue(this, newPropertyValue, null);
}
}
diff --git a/mRemoteNG/Connection/ConnectionInitiator.cs b/mRemoteNG/Connection/ConnectionInitiator.cs
index b13823730..ef3aa102c 100644
--- a/mRemoteNG/Connection/ConnectionInitiator.cs
+++ b/mRemoteNG/Connection/ConnectionInitiator.cs
@@ -19,18 +19,18 @@ namespace mRemoteNG.Connection
[SupportedOSPlatform("windows")]
public class ConnectionInitiator : IConnectionInitiator
{
- private readonly PanelAdder _panelAdder = new PanelAdder();
- private readonly List _activeConnections = new List();
+ private readonly PanelAdder _panelAdder = new();
+ private readonly List _activeConnections = [];
public IEnumerable ActiveConnections => _activeConnections;
public bool SwitchToOpenConnection(ConnectionInfo connectionInfo)
{
- var interfaceControl = FindConnectionContainer(connectionInfo);
+ InterfaceControl interfaceControl = FindConnectionContainer(connectionInfo);
if (interfaceControl == null) return false;
- var connT = (ConnectionTab)interfaceControl.FindForm();
+ ConnectionTab connT = (ConnectionTab)interfaceControl.FindForm();
connT?.Focus();
- var findForm = (ConnectionTab)interfaceControl.FindForm();
+ ConnectionTab findForm = (ConnectionTab)interfaceControl.FindForm();
findForm?.Show(findForm.DockPanel);
return true;
}
@@ -43,7 +43,7 @@ namespace mRemoteNG.Connection
if (containerInfo == null || containerInfo.Children.Count == 0)
return;
- foreach (var child in containerInfo.Children)
+ foreach (ConnectionInfo child in containerInfo.Children)
{
if (child is ContainerInfo childAsContainer)
OpenConnection(childAsContainer, force, conForm);
@@ -98,16 +98,16 @@ namespace mRemoteNG.Connection
return;
}
- var protocolFactory = new ProtocolFactory();
- var connectionPanel = SetConnectionPanel(connectionInfo, force);
+ ProtocolFactory protocolFactory = new();
+ string connectionPanel = SetConnectionPanel(connectionInfo, force);
if (string.IsNullOrEmpty(connectionPanel)) return;
- var connectionForm = SetConnectionForm(conForm, connectionPanel);
+ ConnectionWindow connectionForm = SetConnectionForm(conForm, connectionPanel);
Control connectionContainer = null;
// Handle connection through SSH tunnel:
// in case of connection through SSH tunnel, connectionInfo gets cloned, so that modification of its name, hostname and port do not modify the original connection info
// connectionInfoOriginal points to the original connection info in either case, for where its needed later on.
- var connectionInfoOriginal = connectionInfo;
+ ConnectionInfo connectionInfoOriginal = connectionInfo;
ConnectionInfo connectionInfoSshTunnel = null; // SSH tunnel connection info will be set if SSH tunnel connection is configured, can be found and connected.
if (!string.IsNullOrEmpty(connectionInfoOriginal.SSHTunnelConnectionName))
{
@@ -121,9 +121,9 @@ namespace mRemoteNG.Connection
Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg,
$"SSH Tunnel connection '{connectionInfoOriginal.SSHTunnelConnectionName}' configured for '{connectionInfoOriginal.Name}' found. Finding free local port for use as local tunnel port ...");
// determine a free local port to use as local tunnel port
- var l = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
+ System.Net.Sockets.TcpListener l = new(System.Net.IPAddress.Loopback, 0);
l.Start();
- var localSshTunnelPort = ((System.Net.IPEndPoint)l.LocalEndpoint).Port;
+ int localSshTunnelPort = ((System.Net.IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg,
$"{localSshTunnelPort} will be used as local tunnel port. Establishing SSH connection to '{connectionInfoSshTunnel.Hostname}' with additional tunnel options for target connection ...");
@@ -139,7 +139,7 @@ namespace mRemoteNG.Connection
connectionInfo.Port = localSshTunnelPort;
// connect the SSH connection to setup the tunnel
- var protocolSshTunnel = protocolFactory.CreateProtocol(connectionInfoSshTunnel);
+ ProtocolBase protocolSshTunnel = protocolFactory.CreateProtocol(connectionInfoSshTunnel);
if (!(protocolSshTunnel is PuttyBase puttyBaseSshTunnel))
{
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg,
@@ -173,8 +173,8 @@ namespace mRemoteNG.Connection
"Putty started for SSH connection for tunnel. Waiting for local tunnel port to become available ...");
// wait until SSH tunnel connection is ready, by checking if local port can be connected to, but max 60 sec.
- var testsock = new System.Net.Sockets.Socket(System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
- var stopwatch = System.Diagnostics.Stopwatch.StartNew();
+ System.Net.Sockets.Socket testsock = new(System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
+ System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < 60000)
{
// confirm that SSH connection is still active
@@ -218,7 +218,7 @@ namespace mRemoteNG.Connection
protocolSshTunnel.InterfaceControl.Hide();
}
- var newProtocol = protocolFactory.CreateProtocol(connectionInfo);
+ ProtocolBase newProtocol = protocolFactory.CreateProtocol(connectionInfo);
SetConnectionFormEventHandlers(newProtocol, connectionForm);
SetConnectionEventHandlers(newProtocol);
// in case of connection through SSH tunnel the container is already defined and must be use, else it needs to be created here
@@ -258,7 +258,7 @@ namespace mRemoteNG.Connection
private ConnectionInfo getSSHConnectionInfoByName(IEnumerable rootnodes, string SSHTunnelConnectionName)
{
ConnectionInfo result = null;
- foreach (var node in rootnodes)
+ foreach (ConnectionInfo node in rootnodes)
{
if (node is ContainerInfo container)
{
@@ -277,24 +277,24 @@ namespace mRemoteNG.Connection
private static void StartPreConnectionExternalApp(ConnectionInfo connectionInfo)
{
if (connectionInfo.PreExtApp == "") return;
- var extA = Runtime.ExternalToolsService.GetExtAppByName(connectionInfo.PreExtApp);
+ Tools.ExternalTool extA = Runtime.ExternalToolsService.GetExtAppByName(connectionInfo.PreExtApp);
extA?.Start(connectionInfo);
}
private static InterfaceControl FindConnectionContainer(ConnectionInfo connectionInfo)
{
if (connectionInfo.OpenConnections.Count <= 0) return null;
- for (var i = 0; i <= Runtime.WindowList.Count - 1; i++)
+ for (int i = 0; i <= Runtime.WindowList.Count - 1; i++)
{
// the new structure is ConnectionWindow.Controls[0].ActiveDocument.Controls[0]
// DockPanel InterfaceControl
if (!(Runtime.WindowList[i] is ConnectionWindow connectionWindow)) continue;
if (connectionWindow.Controls.Count < 1) continue;
if (!(connectionWindow.Controls[0] is DockPanel cwDp)) continue;
- foreach (var dockContent in cwDp.Documents)
+ foreach (IDockContent dockContent in cwDp.Documents)
{
- var tab = (ConnectionTab)dockContent;
- var ic = InterfaceControl.FindInterfaceControl(tab);
+ ConnectionTab tab = (ConnectionTab)dockContent;
+ InterfaceControl ic = InterfaceControl.FindInterfaceControl(tab);
if (ic == null) continue;
if (ic.Info == connectionInfo || ic.OriginalInfo == connectionInfo)
return ic;
@@ -309,7 +309,7 @@ namespace mRemoteNG.Connection
if (connectionInfo.Panel != "" && !force.HasFlag(ConnectionInfo.Force.OverridePanel) && !Properties.OptionsTabsPanelsPage.Default.AlwaysShowPanelSelectionDlg)
return connectionInfo.Panel;
- var frmPnl = new FrmChoosePanel();
+ FrmChoosePanel frmPnl = new();
return frmPnl.ShowDialog() == DialogResult.OK
? frmPnl.Panel
: null;
@@ -317,7 +317,7 @@ namespace mRemoteNG.Connection
private ConnectionWindow SetConnectionForm(ConnectionWindow conForm, string connectionPanel)
{
- var connectionForm = conForm ?? Runtime.WindowList.FromString(connectionPanel) as ConnectionWindow;
+ ConnectionWindow connectionForm = conForm ?? Runtime.WindowList.FromString(connectionPanel) as ConnectionWindow;
if (connectionForm == null)
connectionForm = _panelAdder.AddPanel(connectionPanel);
@@ -334,7 +334,7 @@ namespace mRemoteNG.Connection
if (connectionInfo.Protocol != ProtocolType.IntApp) return connectionContainer;
- var extT = Runtime.ExternalToolsService.GetExtAppByName(connectionInfo.ExtApp);
+ Tools.ExternalTool extT = Runtime.ExternalToolsService.GetExtAppByName(connectionInfo.ExtApp);
if (extT == null) return connectionContainer;
@@ -372,8 +372,8 @@ namespace mRemoteNG.Connection
{
try
{
- var prot = (ProtocolBase)sender;
- var msgClass = MessageClass.InformationMsg;
+ ProtocolBase prot = (ProtocolBase)sender;
+ MessageClass msgClass = MessageClass.InformationMsg;
if (prot.InterfaceControl.Info.Protocol == ProtocolType.RDP)
{
@@ -383,7 +383,7 @@ namespace mRemoteNG.Connection
}
}
- var strHostname = prot.InterfaceControl.OriginalInfo.Hostname;
+ string strHostname = prot.InterfaceControl.OriginalInfo.Hostname;
if (prot.InterfaceControl.SSHTunnelInfo != null)
{
strHostname += " via SSH Tunnel " + prot.InterfaceControl.SSHTunnelInfo.Name;
@@ -405,7 +405,7 @@ namespace mRemoteNG.Connection
{
try
{
- var prot = (ProtocolBase)sender;
+ ProtocolBase prot = (ProtocolBase)sender;
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.ConnenctionCloseEvent,
true);
string connDetail;
@@ -426,7 +426,7 @@ namespace mRemoteNG.Connection
_activeConnections.Remove(prot.InterfaceControl.Info.ConstantID);
if (prot.InterfaceControl.Info.PostExtApp == "") return;
- var extA = Runtime.ExternalToolsService.GetExtAppByName(prot.InterfaceControl.Info.PostExtApp);
+ Tools.ExternalTool extA = Runtime.ExternalToolsService.GetExtAppByName(prot.InterfaceControl.Info.PostExtApp);
extA?.Start(prot.InterfaceControl.OriginalInfo);
}
catch (Exception ex)
@@ -437,7 +437,7 @@ namespace mRemoteNG.Connection
private static void Prot_Event_Connected(object sender)
{
- var prot = (ProtocolBase)sender;
+ ProtocolBase prot = (ProtocolBase)sender;
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.ConnectionEventConnected,
true);
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg,
@@ -452,9 +452,9 @@ namespace mRemoteNG.Connection
{
try
{
- var prot = (ProtocolBase)sender;
+ ProtocolBase prot = (ProtocolBase)sender;
- var msg = string.Format(
+ string msg = string.Format(
Language.ConnectionEventErrorOccured,
errorMessage,
prot.InterfaceControl.OriginalInfo.Hostname,
diff --git a/mRemoteNG/Connection/ConnectionsService.cs b/mRemoteNG/Connection/ConnectionsService.cs
index 915189ba8..3439a91e2 100644
--- a/mRemoteNG/Connection/ConnectionsService.cs
+++ b/mRemoteNG/Connection/ConnectionsService.cs
@@ -25,7 +25,7 @@ namespace mRemoteNG.Connection
[SupportedOSPlatform("windows")]
public class ConnectionsService
{
- private static readonly object SaveLock = new object();
+ private static readonly object SaveLock = new();
private readonly PuttySessionsManager _puttySessionsManager;
private readonly IDataProvider _localConnectionPropertiesDataProvider;
private readonly LocalConnectionPropertiesXmlSerializer _localConnectionPropertiesSerializer;
@@ -54,7 +54,7 @@ namespace mRemoteNG.Connection
try
{
filename.ThrowIfNullOrEmpty(nameof(filename));
- var newConnectionsModel = new ConnectionTreeModel();
+ ConnectionTreeModel newConnectionsModel = new();
newConnectionsModel.AddRootNode(new RootNodeInfo(RootNodeType.Connection));
SaveConnections(newConnectionsModel, false, new SaveFilter(), filename, true);
LoadConnections(false, false, filename);
@@ -69,27 +69,27 @@ namespace mRemoteNG.Connection
{
try
{
- var uriBuilder = new UriBuilder
+ UriBuilder uriBuilder = new()
{
Scheme = "dummyscheme"
};
if (connectionString.Contains("@"))
{
- var x = connectionString.Split('@');
+ string[] x = connectionString.Split('@');
uriBuilder.UserName = x[0];
connectionString = x[1];
}
if (connectionString.Contains(":"))
{
- var x = connectionString.Split(':');
+ string[] x = connectionString.Split(':');
connectionString = x[0];
uriBuilder.Port = Convert.ToInt32(x[1]);
}
uriBuilder.Host = connectionString;
- var newConnectionInfo = new ConnectionInfo();
+ ConnectionInfo newConnectionInfo = new();
newConnectionInfo.CopyFrom(DefaultConnectionInfo.Instance);
newConnectionInfo.Name = Properties.OptionsTabsPanelsPage.Default.IdentifyQuickConnectTabs
@@ -132,14 +132,14 @@ namespace mRemoteNG.Connection
///
public void LoadConnections(bool useDatabase, bool import, string connectionFileName)
{
- var oldConnectionTreeModel = ConnectionTreeModel;
- var oldIsUsingDatabaseValue = UsingDatabase;
+ ConnectionTreeModel oldConnectionTreeModel = ConnectionTreeModel;
+ bool oldIsUsingDatabaseValue = UsingDatabase;
- var connectionLoader = useDatabase
+ IConnectionsLoader connectionLoader = useDatabase
? (IConnectionsLoader)new SqlConnectionsLoader(_localConnectionPropertiesSerializer, _localConnectionPropertiesDataProvider)
: new XmlConnectionsLoader(connectionFileName);
- var newConnectionTreeModel = connectionLoader.Load();
+ ConnectionTreeModel newConnectionTreeModel = connectionLoader.Load();
if (useDatabase)
LastSqlUpdate = DateTime.Now.ToUniversalTime();
@@ -248,7 +248,7 @@ namespace mRemoteNG.Connection
bool previouslyUsingDatabase = UsingDatabase;
- var saver = useDatabase
+ ISaver saver = useDatabase
? (ISaver)new SqlConnectionsSaver(saveFilter, _localConnectionPropertiesSerializer, _localConnectionPropertiesDataProvider)
: new XmlConnectionsSaver(connectionFileName, saveFilter);
@@ -287,7 +287,7 @@ namespace mRemoteNG.Connection
return;
}
- var t = new Thread(() =>
+ Thread t = new(() =>
{
lock (SaveLock)
{
@@ -338,7 +338,7 @@ namespace mRemoteNG.Connection
private string GetDefaultStartupConnectionFileNameNormalEdition()
{
- var appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Application.ProductName, ConnectionsFileInfo.DefaultConnectionsFile);
+ string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Application.ProductName, ConnectionsFileInfo.DefaultConnectionsFile);
return File.Exists(appDataPath) ? appDataPath : GetDefaultStartupConnectionFileNamePortableEdition();
}
diff --git a/mRemoteNG/Connection/DefaultConnectionInfo.cs b/mRemoteNG/Connection/DefaultConnectionInfo.cs
index ebe86d79c..30c425cc5 100644
--- a/mRemoteNG/Connection/DefaultConnectionInfo.cs
+++ b/mRemoteNG/Connection/DefaultConnectionInfo.cs
@@ -24,17 +24,17 @@ namespace mRemoteNG.Connection
if (propertyNameMutator == null)
propertyNameMutator = a => a;
- var connectionProperties = GetSerializableProperties();
- foreach (var property in connectionProperties)
+ System.Collections.Generic.IEnumerable connectionProperties = GetSerializableProperties();
+ foreach (System.Reflection.PropertyInfo property in connectionProperties)
{
try
{
- var expectedPropertyName = propertyNameMutator(property.Name);
- var propertyFromSource = typeof(TSource).GetProperty(expectedPropertyName);
+ string expectedPropertyName = propertyNameMutator(property.Name);
+ System.Reflection.PropertyInfo propertyFromSource = typeof(TSource).GetProperty(expectedPropertyName);
if (propertyFromSource == null)
throw new SettingsPropertyNotFoundException($"No property with name '{expectedPropertyName}' found.");
- var valueFromSource = propertyFromSource.GetValue(sourceInstance, null);
+ object valueFromSource = propertyFromSource.GetValue(sourceInstance, null);
if (property.PropertyType.IsEnum)
{
@@ -56,20 +56,20 @@ namespace mRemoteNG.Connection
if (propertyNameMutator == null)
propertyNameMutator = (a) => a;
- var connectionProperties = GetSerializableProperties();
+ System.Collections.Generic.IEnumerable connectionProperties = GetSerializableProperties();
- foreach (var property in connectionProperties)
+ foreach (System.Reflection.PropertyInfo property in connectionProperties)
{
try
{
- var expectedPropertyName = propertyNameMutator(property.Name);
- var propertyFromDestination = typeof(TDestination).GetProperty(expectedPropertyName);
+ string expectedPropertyName = propertyNameMutator(property.Name);
+ System.Reflection.PropertyInfo propertyFromDestination = typeof(TDestination).GetProperty(expectedPropertyName);
if (propertyFromDestination == null)
throw new SettingsPropertyNotFoundException($"No property with name '{expectedPropertyName}' found.");
// ensure value is of correct type
- var value = Convert.ChangeType(property.GetValue(Instance, null), propertyFromDestination.PropertyType);
+ object value = Convert.ChangeType(property.GetValue(Instance, null), propertyFromDestination.PropertyType);
propertyFromDestination.SetValue(destinationInstance, value, null);
}
diff --git a/mRemoteNG/Connection/DefaultConnectionInheritance.cs b/mRemoteNG/Connection/DefaultConnectionInheritance.cs
index acd08f591..13ce8b870 100644
--- a/mRemoteNG/Connection/DefaultConnectionInheritance.cs
+++ b/mRemoteNG/Connection/DefaultConnectionInheritance.cs
@@ -24,17 +24,17 @@ namespace mRemoteNG.Connection
public void LoadFrom(TSource sourceInstance, Func propertyNameMutator = null)
{
if (propertyNameMutator == null) propertyNameMutator = a => a;
- var inheritanceProperties = GetProperties();
- foreach (var property in inheritanceProperties)
+ System.Collections.Generic.IEnumerable inheritanceProperties = GetProperties();
+ foreach (System.Reflection.PropertyInfo property in inheritanceProperties)
{
- var propertyFromSettings = typeof(TSource).GetProperty(propertyNameMutator(property.Name));
+ System.Reflection.PropertyInfo propertyFromSettings = typeof(TSource).GetProperty(propertyNameMutator(property.Name));
if (propertyFromSettings == null)
{
Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, $"DefaultConInherit-LoadFrom: Could not load {property.Name}", true);
continue;
}
- var valueFromSettings = propertyFromSettings.GetValue(sourceInstance, null);
+ object valueFromSettings = propertyFromSettings.GetValue(sourceInstance, null);
property.SetValue(Instance, valueFromSettings, null);
}
}
@@ -43,11 +43,11 @@ namespace mRemoteNG.Connection
Func propertyNameMutator = null)
{
if (propertyNameMutator == null) propertyNameMutator = a => a;
- var inheritanceProperties = GetProperties();
- foreach (var property in inheritanceProperties)
+ System.Collections.Generic.IEnumerable inheritanceProperties = GetProperties();
+ foreach (System.Reflection.PropertyInfo property in inheritanceProperties)
{
- var propertyFromSettings = typeof(TDestination).GetProperty(propertyNameMutator(property.Name));
- var localValue = property.GetValue(Instance, null);
+ System.Reflection.PropertyInfo propertyFromSettings = typeof(TDestination).GetProperty(propertyNameMutator(property.Name));
+ object localValue = property.GetValue(Instance, null);
if (propertyFromSettings == null)
{
Runtime.MessageCollector?.AddMessage(Messages.MessageClass.ErrorMsg, $"DefaultConInherit-SaveTo: Could not load {property.Name}", true);
diff --git a/mRemoteNG/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs b/mRemoteNG/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs
index 103c94e6c..7e2ee4e86 100644
--- a/mRemoteNG/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs
+++ b/mRemoteNG/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs
@@ -1,11 +1,14 @@
using System;
using System.Windows.Forms;
using Microsoft.Web.WebView2.WinForms;
+using Microsoft.Web.WebView2.Core;
using mRemoteNG.Tools;
using mRemoteNG.App;
using mRemoteNG.UI.Tabs;
using mRemoteNG.Resources.Language;
using System.Runtime.Versioning;
+using System.Windows.Forms.VisualStyles;
+
namespace mRemoteNG.Connection.Protocol.Http
{
@@ -29,7 +32,7 @@ namespace mRemoteNG.Connection.Protocol.Http
{
if (renderingEngine == RenderingEngine.EdgeChromium)
{
- Control = new WebView2()
+ Control = new Microsoft.Web.WebView2.WinForms.WebView2()
{
Dock = DockStyle.Fill,
};
@@ -64,13 +67,12 @@ namespace mRemoteNG.Connection.Protocol.Http
if (InterfaceControl.Info.RenderingEngine == RenderingEngine.EdgeChromium)
{
- var edge = (WebView2)_wBrowser;
-
+ Microsoft.Web.WebView2.WinForms.WebView2 edge = (Microsoft.Web.WebView2.WinForms.WebView2)_wBrowser;
edge.CoreWebView2InitializationCompleted += Edge_CoreWebView2InitializationCompleted;
}
else
{
- var objWebBrowser = (WebBrowser)_wBrowser;
+ WebBrowser objWebBrowser = (WebBrowser)_wBrowser;
objWebBrowser.ScrollBarsEnabled = true;
// http://stackoverflow.com/questions/4655662/how-to-ignore-script-errors-in-webbrowser
@@ -95,11 +97,12 @@ namespace mRemoteNG.Connection.Protocol.Http
{
if (InterfaceControl.Info.RenderingEngine == RenderingEngine.EdgeChromium)
{
- ((WebView2)_wBrowser).Source = new Uri(GetUrl());
+ ((Microsoft.Web.WebView2.WinForms.WebView2)_wBrowser).Source = new Uri(GetUrl());
}
else
{
((WebBrowser)_wBrowser).Navigate(GetUrl());
+
}
base.Connect();
@@ -112,6 +115,12 @@ namespace mRemoteNG.Connection.Protocol.Http
}
}
+ private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
+ {
+ // Suppress the popup (prevent it from opening in a new window)
+ e.Handled = true;
+ }
+
#endregion
#region Private Methods
@@ -120,15 +129,19 @@ namespace mRemoteNG.Connection.Protocol.Http
{
try
{
- var strHost = InterfaceControl.Info.Hostname;
+ string strHost = InterfaceControl.Info.Hostname;
if (InterfaceControl.Info.Port != defaultPort)
{
if (strHost.EndsWith("/"))
- strHost = strHost.Substring(0, strHost.Length - 1);
+ {
+ strHost = strHost[..^1];
+ }
if (strHost.Contains(httpOrS + "://") == false)
+ {
strHost = httpOrS + "://" + strHost;
+ }
strHost = strHost + ":" + InterfaceControl.Info.Port;
}
@@ -161,7 +174,7 @@ namespace mRemoteNG.Connection.Protocol.Http
private void WBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
- if (!(_wBrowser is WebBrowser objWebBrowser)) return;
+ if (_wBrowser is not WebBrowser objWebBrowser) return;
// This can only be set once the WebBrowser control is shown, it will throw a COM exception otherwise.
objWebBrowser.AllowWebBrowserDrop = false;
@@ -173,11 +186,11 @@ namespace mRemoteNG.Connection.Protocol.Http
{
try
{
- if (!(InterfaceControl.Parent is ConnectionTab tabP)) return;
+ if (InterfaceControl.Parent is not ConnectionTab tabP) return;
string shortTitle;
if (((WebBrowser)_wBrowser).DocumentTitle.Length >= 15)
{
- shortTitle = ((WebBrowser)_wBrowser).DocumentTitle.Substring(0, 10) + "...";
+ shortTitle = ((WebBrowser)_wBrowser).DocumentTitle[..10] + "...";
}
else
{
diff --git a/mRemoteNG/Connection/Protocol/IntegratedProgram.cs b/mRemoteNG/Connection/Protocol/IntegratedProgram.cs
index 3a291408d..26243bf47 100644
--- a/mRemoteNG/Connection/Protocol/IntegratedProgram.cs
+++ b/mRemoteNG/Connection/Protocol/IntegratedProgram.cs
@@ -66,7 +66,7 @@ namespace mRemoteNG.Connection.Protocol
return false;
}
- var argParser = new ExternalToolArgumentParser(_externalTool.ConnectionInfo);
+ ExternalToolArgumentParser argParser = new(_externalTool.ConnectionInfo);
_process = new Process
{
StartInfo =
@@ -84,7 +84,7 @@ namespace mRemoteNG.Connection.Protocol
_process.Start();
_process.WaitForInputIdle(Properties.OptionsAdvancedPage.Default.MaxPuttyWaitTime * 1000);
- var startTicks = Environment.TickCount;
+ int startTicks = Environment.TickCount;
while (_handle.ToInt32() == 0 &
Environment.TickCount < startTicks + Properties.OptionsAdvancedPage.Default.MaxPuttyWaitTime * 1000)
{
diff --git a/mRemoteNG/Connection/Protocol/PowerShell/Connection.Protocol.PowerShell.cs b/mRemoteNG/Connection/Protocol/PowerShell/Connection.Protocol.PowerShell.cs
index 52ad93ded..9cc822e95 100644
--- a/mRemoteNG/Connection/Protocol/PowerShell/Connection.Protocol.PowerShell.cs
+++ b/mRemoteNG/Connection/Protocol/PowerShell/Connection.Protocol.PowerShell.cs
@@ -191,9 +191,9 @@ namespace mRemoteNG.Connection.Protocol.PowerShell
// Setup process for script with arguments
//* The -NoProfile parameter would be a valuable addition but should be able to be deactivated.
- var arguments = $@"-NoExit -Command ""& {{ {psScriptBlock} }}"" -Hostname ""'{_connectionInfo.Hostname}'"" -Username ""'{psUsername}'"" -Password ""'{_connectionInfo.Password}'"" -LoginAttempts {psLoginAttempts}";
- var hostname = _connectionInfo.Hostname.Trim().ToLower();
- var useLocalHost = hostname == "" || hostname.Equals("localhost");
+ string arguments = $@"-NoExit -Command ""& {{ {psScriptBlock} }}"" -Hostname ""'{_connectionInfo.Hostname}'"" -Username ""'{psUsername}'"" -Password ""'{_connectionInfo.Password}'"" -LoginAttempts {psLoginAttempts}";
+ string hostname = _connectionInfo.Hostname.Trim().ToLower();
+ bool useLocalHost = hostname == "" || hostname.Equals("localhost");
if (useLocalHost)
{
arguments = $@"-NoExit";
diff --git a/mRemoteNG/Connection/Protocol/ProtocolBase.cs b/mRemoteNG/Connection/Protocol/ProtocolBase.cs
index cf63bc0e3..49d0fafe8 100644
--- a/mRemoteNG/Connection/Protocol/ProtocolBase.cs
+++ b/mRemoteNG/Connection/Protocol/ProtocolBase.cs
@@ -62,7 +62,7 @@ namespace mRemoteNG.Connection.Protocol
public ConnectionInfo.Force Force { get; set; }
- protected readonly System.Timers.Timer tmrReconnect = new System.Timers.Timer(5000);
+ protected readonly System.Timers.Timer tmrReconnect = new(5000);
protected ReconnectGroup ReconnectGroup;
protected ProtocolBase(string name)
@@ -145,7 +145,7 @@ namespace mRemoteNG.Connection.Protocol
public virtual void Close()
{
- var t = new Thread(CloseBG);
+ Thread t = new(CloseBG);
t.SetApartmentState(ApartmentState.STA);
t.IsBackground = true;
t.Start();
@@ -208,7 +208,7 @@ namespace mRemoteNG.Connection.Protocol
}
if (_interfaceControl.InvokeRequired)
{
- var s = new DisposeInterfaceCB(DisposeInterface);
+ DisposeInterfaceCB s = new(DisposeInterface);
_interfaceControl.Invoke(s);
}
else
@@ -227,7 +227,7 @@ namespace mRemoteNG.Connection.Protocol
if (_interfaceControl.Parent.InvokeRequired)
{
- var s = new SetTagToNothingCB(SetTagToNothing);
+ SetTagToNothingCB s = new(SetTagToNothing);
_interfaceControl.Parent.Invoke(s);
}
else
@@ -245,7 +245,7 @@ namespace mRemoteNG.Connection.Protocol
if (Control.InvokeRequired)
{
- var s = new DisposeControlCB(DisposeControl);
+ DisposeControlCB s = new(DisposeControl);
Control.Invoke(s);
}
else
diff --git a/mRemoteNG/Connection/Protocol/ProtocolFactory.cs b/mRemoteNG/Connection/Protocol/ProtocolFactory.cs
index 165bef1c7..820724f89 100644
--- a/mRemoteNG/Connection/Protocol/ProtocolFactory.cs
+++ b/mRemoteNG/Connection/Protocol/ProtocolFactory.cs
@@ -15,7 +15,7 @@ namespace mRemoteNG.Connection.Protocol
[SupportedOSPlatform("windows")]
public class ProtocolFactory
{
- private readonly RdpProtocolFactory _rdpProtocolFactory = new RdpProtocolFactory();
+ private readonly RdpProtocolFactory _rdpProtocolFactory = new();
public ProtocolBase CreateProtocol(ConnectionInfo connectionInfo)
{
@@ -23,7 +23,7 @@ namespace mRemoteNG.Connection.Protocol
switch (connectionInfo.Protocol)
{
case ProtocolType.RDP:
- var rdp = _rdpProtocolFactory.Build(connectionInfo.RdpVersion);
+ RdpProtocol rdp = _rdpProtocolFactory.Build(connectionInfo.RdpVersion);
rdp.LoadBalanceInfoUseUtf8 = Properties.OptionsAdvancedPage.Default.RdpLoadBalanceInfoUseUtf8;
return rdp;
case ProtocolType.VNC:
diff --git a/mRemoteNG/Connection/Protocol/ProtocolList.cs b/mRemoteNG/Connection/Protocol/ProtocolList.cs
index 4acba4ec2..4b49eedca 100644
--- a/mRemoteNG/Connection/Protocol/ProtocolList.cs
+++ b/mRemoteNG/Connection/Protocol/ProtocolList.cs
@@ -12,7 +12,7 @@ namespace mRemoteNG.Connection.Protocol
{
get
{
- var @base = index as ProtocolBase;
+ ProtocolBase @base = index as ProtocolBase;
if (@base != null)
return @base;
if (index is int)
@@ -32,7 +32,7 @@ namespace mRemoteNG.Connection.Protocol
public void AddRange(ProtocolBase[] cProt)
{
- foreach (var cP in cProt)
+ foreach (ProtocolBase cP in cProt)
{
List.Add(cP);
}
diff --git a/mRemoteNG/Connection/Protocol/PuttyBase.cs b/mRemoteNG/Connection/Protocol/PuttyBase.cs
index cb139161e..2de964135 100644
--- a/mRemoteNG/Connection/Protocol/PuttyBase.cs
+++ b/mRemoteNG/Connection/Protocol/PuttyBase.cs
@@ -24,7 +24,7 @@ namespace mRemoteNG.Connection.Protocol
{
private const int IDM_RECONF = 0x50; // PuTTY Settings Menu ID
private bool _isPuttyNg;
- private readonly DisplayProperties _display = new DisplayProperties();
+ private readonly DisplayProperties _display = new();
#region Public Properties
@@ -63,7 +63,7 @@ namespace mRemoteNG.Connection.Protocol
string data = (string)oData;
string random = data[..8];
string password = data[8..];
- var server = new NamedPipeServerStream($"mRemoteNGSecretPipe{random}");
+ NamedPipeServerStream server = new($"mRemoteNGSecretPipe{random}");
server.WaitForConnection();
StreamWriter writer = new(server);
writer.Write(password);
@@ -88,7 +88,7 @@ namespace mRemoteNG.Connection.Protocol
}
};
- var arguments = new CommandLineArguments { EscapeForShell = false };
+ CommandLineArguments arguments = new() { EscapeForShell = false };
arguments.Add("-load", InterfaceControl.Info.PuttySession);
@@ -99,10 +99,10 @@ namespace mRemoteNG.Connection.Protocol
if (PuttyProtocol == Putty_Protocol.ssh)
{
- var username = InterfaceControl.Info?.Username ?? "";
- var password = InterfaceControl.Info?.Password ?? "";
- var domain = InterfaceControl.Info?.Domain ?? "";
- var UserViaAPI = InterfaceControl.Info?.UserViaAPI ?? "";
+ string username = InterfaceControl.Info?.Username ?? "";
+ string password = InterfaceControl.Info?.Password ?? "";
+ string domain = InterfaceControl.Info?.Domain ?? "";
+ string UserViaAPI = InterfaceControl.Info?.UserViaAPI ?? "";
string privatekey = "";
// access secret server api if necessary
@@ -116,8 +116,10 @@ namespace mRemoteNG.Connection.Protocol
{
optionalTemporaryPrivateKeyPath = Path.GetTempFileName();
File.WriteAllText(optionalTemporaryPrivateKeyPath, privatekey);
- FileInfo fileInfo = new FileInfo(optionalTemporaryPrivateKeyPath);
- fileInfo.Attributes = FileAttributes.Temporary;
+ FileInfo fileInfo = new(optionalTemporaryPrivateKeyPath)
+ {
+ Attributes = FileAttributes.Temporary
+ };
}
}
catch (Exception ex)
@@ -160,7 +162,7 @@ namespace mRemoteNG.Connection.Protocol
{
if (Properties.OptionsCredentialsPage.Default.EmptyCredentials == "custom")
{
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
password = cryptographyProvider.Decrypt(Properties.OptionsCredentialsPage.Default.DefaultPassword, Runtime.EncryptionKey);
}
}
@@ -178,7 +180,7 @@ namespace mRemoteNG.Connection.Protocol
{
string random = string.Join("", Guid.NewGuid().ToString("n").Take(8).Select(o => o));
// write data to pipe
- var thread = new Thread(new ParameterizedThreadStart(CreatePipe));
+ Thread thread = new(new ParameterizedThreadStart(CreatePipe));
thread.Start($"{random}{password}");
// start putty with piped password
arguments.Add("-pwfile", $"\\\\.\\PIPE\\mRemoteNGSecretPipe{random}");
@@ -216,7 +218,7 @@ namespace mRemoteNG.Connection.Protocol
PuttyProcess.Start();
PuttyProcess.WaitForInputIdle(Properties.OptionsAdvancedPage.Default.MaxPuttyWaitTime * 1000);
- var startTicks = Environment.TickCount;
+ int startTicks = Environment.TickCount;
while (PuttyHandle.ToInt32() == 0 &
Environment.TickCount < startTicks + Properties.OptionsAdvancedPage.Default.MaxPuttyWaitTime * 1000)
{
@@ -249,7 +251,7 @@ namespace mRemoteNG.Connection.Protocol
if (!string.IsNullOrEmpty(InterfaceControl.Info?.OpeningCommand))
{
NativeMethods.SetForegroundWindow(PuttyHandle);
- var finalCommand = InterfaceControl.Info.OpeningCommand.TrimEnd() + "\n";
+ string finalCommand = InterfaceControl.Info.OpeningCommand.TrimEnd() + "\n";
SendKeys.SendWait(finalCommand);
}
@@ -299,8 +301,8 @@ namespace mRemoteNG.Connection.Protocol
}
else
{
- var scaledFrameBorderHeight = _display.ScaleHeight(SystemInformation.FrameBorderSize.Height);
- var scaledFrameBorderWidth = _display.ScaleWidth(SystemInformation.FrameBorderSize.Width);
+ int scaledFrameBorderHeight = _display.ScaleHeight(SystemInformation.FrameBorderSize.Height);
+ int scaledFrameBorderWidth = _display.ScaleWidth(SystemInformation.FrameBorderSize.Width);
NativeMethods.MoveWindow(PuttyHandle, -scaledFrameBorderWidth,
-(SystemInformation.CaptionHeight + scaledFrameBorderHeight),
diff --git a/mRemoteNG/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs b/mRemoteNG/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs
index 1f7a2e38f..7605a4682 100644
--- a/mRemoteNG/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs
+++ b/mRemoteNG/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs
@@ -33,7 +33,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
loadBalanceInfo += " ";
loadBalanceInfo += "\r\n";
- var bytes = Encoding.UTF8.GetBytes(loadBalanceInfo);
+ byte[] bytes = Encoding.UTF8.GetBytes(loadBalanceInfo);
return Encoding.Unicode.GetString(bytes);
}
}
diff --git a/mRemoteNG/Connection/Protocol/RDP/RdpProtocol.cs b/mRemoteNG/Connection/Protocol/RDP/RdpProtocol.cs
index e660256d1..ffcea2372 100644
--- a/mRemoteNG/Connection/Protocol/RDP/RdpProtocol.cs
+++ b/mRemoteNG/Connection/Protocol/RDP/RdpProtocol.cs
@@ -292,7 +292,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
{
try
{
- using var control = CreateActiveXRdpClientControl();
+ using AxHost control = CreateActiveXRdpClientControl();
control.CreateControl();
return true;
}
@@ -308,12 +308,12 @@ namespace mRemoteNG.Connection.Protocol.RDP
protected static class Versions
{
// https://en.wikipedia.org/wiki/Remote_Desktop_Protocol
- public static readonly Version RDC60 = new Version(6, 0, 6000);
- public static readonly Version RDC61 = new Version(6, 0, 6001);
- public static readonly Version RDC70 = new Version(6, 1, 7600);
- public static readonly Version RDC80 = new Version(6, 2, 9200);
- public static readonly Version RDC81 = new Version(6, 3, 9600);
- public static readonly Version RDC100 = new Version(10, 0, 0);
+ public static readonly Version RDC60 = new(6, 0, 6000);
+ public static readonly Version RDC61 = new(6, 0, 6001);
+ public static readonly Version RDC70 = new(6, 1, 7600);
+ public static readonly Version RDC80 = new(6, 2, 9200);
+ public static readonly Version RDC81 = new(6, 3, 9600);
+ public static readonly Version RDC100 = new(10, 0, 0);
}
private void SetRdpClientProperties()
@@ -433,10 +433,10 @@ namespace mRemoteNG.Connection.Protocol.RDP
{
_rdpClient.TransportSettings2.GatewayCredSharing = 0;
- var gwu = connectionInfo.RDGatewayUsername;
- var gwp = connectionInfo.RDGatewayPassword;
- var gwd = connectionInfo.RDGatewayDomain;
- var pkey = "";
+ string gwu = connectionInfo.RDGatewayUsername;
+ string gwp = connectionInfo.RDGatewayPassword;
+ string gwd = connectionInfo.RDGatewayDomain;
+ string pkey = "";
// access secret server api if necessary
if (InterfaceControl.Info.RDGatewayExternalCredentialProvider == ExternalCredentialProvider.DelineaSecretServer)
@@ -521,11 +521,11 @@ namespace mRemoteNG.Connection.Protocol.RDP
return;
}
- var userName = connectionInfo?.Username ?? "";
- var password = connectionInfo?.Password ?? "";
- var domain = connectionInfo?.Domain ?? "";
- var userViaApi = connectionInfo?.UserViaAPI ?? "";
- var pkey = "";
+ string userName = connectionInfo?.Username ?? "";
+ string password = connectionInfo?.Password ?? "";
+ string domain = connectionInfo?.Domain ?? "";
+ string userViaApi = connectionInfo?.UserViaAPI ?? "";
+ string pkey = "";
// access secret server api if necessary
if (InterfaceControl.Info.ExternalCredentialProvider == ExternalCredentialProvider.DelineaSecretServer)
@@ -576,7 +576,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
{
if (Properties.OptionsCredentialsPage.Default.DefaultPassword != "")
{
- var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
+ LegacyRijndaelCryptographyProvider cryptographyProvider = new();
_rdpClient.AdvancedSettings2.ClearTextPassword = cryptographyProvider.Decrypt(Properties.OptionsCredentialsPage.Default.DefaultPassword, Runtime.EncryptionKey);
}
}
@@ -644,7 +644,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
break;
default:
{
- var resolution = connectionInfo.Resolution.GetResolutionRectangle();
+ System.Drawing.Rectangle resolution = connectionInfo.Resolution.GetResolutionRectangle();
_rdpClient.DesktopWidth = resolution.Width;
_rdpClient.DesktopHeight = resolution.Height;
break;
@@ -697,7 +697,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
_rdpClient.AdvancedSettings2.RedirectDrives = true;
else if (RDPDiskDrives.Custom == connectionInfo.RedirectDiskDrives)
{
- var rdpNS5 = (IMsRdpClientNonScriptable5)((AxHost)Control).GetOcx();
+ IMsRdpClientNonScriptable5 rdpNS5 = (IMsRdpClientNonScriptable5)((AxHost)Control).GetOcx();
for (uint i = 0; i < rdpNS5.DriveCollection.DriveCount; i++)
{
IMsRdpDrive drive = rdpNS5.DriveCollection.DriveByIndex[i];
@@ -707,7 +707,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
else
{
// Local Drives
- var rdpNS5 = (IMsRdpClientNonScriptable5)((AxHost)Control).GetOcx();
+ IMsRdpClientNonScriptable5 rdpNS5 = (IMsRdpClientNonScriptable5)((AxHost)Control).GetOcx();
for (uint i = 0; i < rdpNS5.DriveCollection.DriveCount; i++)
{
IMsRdpDrive drive = rdpNS5.DriveCollection.DriveByIndex[i];
@@ -733,7 +733,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
{
try
{
- var pFlags = 0;
+ int pFlags = 0;
if (connectionInfo.DisplayThemes == false)
pFlags += (int)RDPPerformanceFlags.DisableThemes;
@@ -829,7 +829,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
private void RDPEvent_OnFatalError(int errorCode)
{
- var errorMsg = RdpErrorCodes.GetError(errorCode);
+ string errorMsg = RdpErrorCodes.GetError(errorCode);
Event_ErrorOccured(this, errorMsg, errorCode);
}
@@ -838,7 +838,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
const int UI_ERR_NORMAL_DISCONNECT = 0xB08;
if (discReason != UI_ERR_NORMAL_DISCONNECT)
{
- var reason = _rdpClient.GetErrorDescription((uint)discReason, (uint)_rdpClient.ExtendedDisconnectReason);
+ string reason = _rdpClient.GetErrorDescription((uint)discReason, (uint)_rdpClient.ExtendedDisconnectReason);
Event_Disconnected(this, reason, discReason);
}
@@ -917,7 +917,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
{
try
{
- var srvReady = PortScanner.IsPortOpen(connectionInfo.Hostname, Convert.ToString(connectionInfo.Port));
+ bool srvReady = PortScanner.IsPortOpen(connectionInfo.Hostname, Convert.ToString(connectionInfo.Port));
ReconnectGroup.ServerReady = srvReady;
diff --git a/mRemoteNG/Connection/Protocol/RDP/RdpProtocol7.cs b/mRemoteNG/Connection/Protocol/RDP/RdpProtocol7.cs
index d08c13267..06d1362f0 100644
--- a/mRemoteNG/Connection/Protocol/RDP/RdpProtocol7.cs
+++ b/mRemoteNG/Connection/Protocol/RDP/RdpProtocol7.cs
@@ -40,8 +40,8 @@ namespace mRemoteNG.Connection.Protocol.RDP
if (connectionInfo.RDGatewayUseConnectionCredentials == RDGatewayUseConnectionCredentials.AccessToken)
{
- var authToken = connectionInfo.RDGatewayAccessToken;
- var encryptedAuthToken = RdGatewayAccessTokenHelper.EncryptAuthCookieString(authToken);
+ string authToken = connectionInfo.RDGatewayAccessToken;
+ string encryptedAuthToken = RdGatewayAccessTokenHelper.EncryptAuthCookieString(authToken);
RdpClient7.TransportSettings3.GatewayEncryptedAuthCookie = encryptedAuthToken;
RdpClient7.TransportSettings3.GatewayEncryptedAuthCookieSize = (uint)encryptedAuthToken.Length;
RdpClient7.TransportSettings3.GatewayCredsSource = 5;
diff --git a/mRemoteNG/Connection/Protocol/RDP/RdpProtocol8.cs b/mRemoteNG/Connection/Protocol/RDP/RdpProtocol8.cs
index 5890fae02..001eb30af 100644
--- a/mRemoteNG/Connection/Protocol/RDP/RdpProtocol8.cs
+++ b/mRemoteNG/Connection/Protocol/RDP/RdpProtocol8.cs
@@ -96,7 +96,7 @@ namespace mRemoteNG.Connection.Protocol.RDP
try
{
- var size = Fullscreen
+ Size size = Fullscreen
? Screen.FromControl(Control).Bounds.Size
: Control.Size;
diff --git a/mRemoteNG/Connection/Protocol/RDP/RdpProtocolFactory.cs b/mRemoteNG/Connection/Protocol/RDP/RdpProtocolFactory.cs
index b9c3142a9..93abeeb2d 100644
--- a/mRemoteNG/Connection/Protocol/RDP/RdpProtocolFactory.cs
+++ b/mRemoteNG/Connection/Protocol/RDP/RdpProtocolFactory.cs
@@ -33,14 +33,14 @@ namespace mRemoteNG.Connection.Protocol.RDP
private RdpProtocol BuildHighestSupportedVersion()
{
- var versions = Enum.GetValues(typeof(RdpVersion))
+ IEnumerable versions = Enum.GetValues(typeof(RdpVersion))
.OfType()
.Except(new[] { RdpVersion.Highest })
.Reverse();
- foreach (var version in versions)
+ foreach (RdpVersion version in versions)
{
- var rdp = Build(version);
+ RdpProtocol rdp = Build(version);
if (rdp.RdpVersionSupported())
return rdp;
}
@@ -50,12 +50,12 @@ namespace mRemoteNG.Connection.Protocol.RDP
public List GetSupportedVersions()
{
- var versions = Enum.GetValues(typeof(RdpVersion))
+ IEnumerable versions = Enum.GetValues(typeof(RdpVersion))
.OfType()
.Except(new[] { RdpVersion.Highest });
- var supportedVersions = new List();
- foreach (var version in versions)
+ List supportedVersions = new();
+ foreach (RdpVersion version in versions)
{
if (Build(version).RdpVersionSupported())
supportedVersions.Add(version);
diff --git a/mRemoteNG/Connection/Protocol/VNC/Connection.Protocol.VNC.cs b/mRemoteNG/Connection/Protocol/VNC/Connection.Protocol.VNC.cs
index 971e2d93c..dc75dc4c1 100644
--- a/mRemoteNG/Connection/Protocol/VNC/Connection.Protocol.VNC.cs
+++ b/mRemoteNG/Connection/Protocol/VNC/Connection.Protocol.VNC.cs
@@ -22,7 +22,7 @@ namespace mRemoteNG.Connection.Protocol.VNC
private ConnectionInfo _info;
private static bool _isConnectionSuccessful;
private static Exception _socketexception;
- private static readonly ManualResetEvent TimeoutObject = new ManualResetEvent(false);
+ private static readonly ManualResetEvent TimeoutObject = new(false);
#endregion
@@ -160,7 +160,7 @@ namespace mRemoteNG.Connection.Protocol.VNC
private static bool TestConnect(string hostName, int port, int timeoutMSec)
{
- var tcpclient = new TcpClient();
+ TcpClient tcpclient = new();
TimeoutObject.Reset();
tcpclient.BeginConnect(hostName, port, CallBackMethod, tcpclient);
@@ -183,7 +183,7 @@ namespace mRemoteNG.Connection.Protocol.VNC
try
{
_isConnectionSuccessful = false;
- var tcpclient = asyncresult.AsyncState as TcpClient;
+ TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
if (tcpclient?.Client == null) return;
diff --git a/mRemoteNG/Connection/PuttySessionInfo.cs b/mRemoteNG/Connection/PuttySessionInfo.cs
index cdab5428a..ffcf8ed37 100644
--- a/mRemoteNG/Connection/PuttySessionInfo.cs
+++ b/mRemoteNG/Connection/PuttySessionInfo.cs
@@ -63,7 +63,7 @@ namespace mRemoteNG.Connection
{
try
{
- var puttyProcess = new PuttyProcessController();
+ PuttyProcessController puttyProcess = new();
if (!puttyProcess.Start())
{
return;
diff --git a/mRemoteNG/Connection/WebHelper.cs b/mRemoteNG/Connection/WebHelper.cs
index 5b6ae7998..9da9d12ec 100644
--- a/mRemoteNG/Connection/WebHelper.cs
+++ b/mRemoteNG/Connection/WebHelper.cs
@@ -10,7 +10,7 @@ namespace mRemoteNG.Connection
{
public static void GoToUrl(string url)
{
- var connectionInfo = new ConnectionInfo();
+ ConnectionInfo connectionInfo = new();
connectionInfo.CopyFrom(DefaultConnectionInfo.Instance);
connectionInfo.Name = "";
diff --git a/mRemoteNG/Container/ContainerInfo.cs b/mRemoteNG/Container/ContainerInfo.cs
index 473f98334..5ed0f2a8f 100644
--- a/mRemoteNG/Container/ContainerInfo.cs
+++ b/mRemoteNG/Container/ContainerInfo.cs
@@ -16,7 +16,7 @@ namespace mRemoteNG.Container
{
private bool _isExpanded;
- [Browsable(false)] public List Children { get; } = new List();
+ [Browsable(false)] public List Children { get; } = [];
[Category(""), Browsable(false), ReadOnly(false), Bindable(false), DefaultValue(""), DesignOnly(false)]
public bool IsExpanded
@@ -60,7 +60,7 @@ namespace mRemoteNG.Container
public void AddChildAbove(ConnectionInfo newChildItem, ConnectionInfo reference)
{
- var newChildIndex = Children.IndexOf(reference);
+ int newChildIndex = Children.IndexOf(reference);
if (newChildIndex < 0)
newChildIndex = Children.Count;
AddChildAt(newChildItem, newChildIndex);
@@ -68,7 +68,7 @@ namespace mRemoteNG.Container
public void AddChildBelow(ConnectionInfo newChildItem, ConnectionInfo reference)
{
- var newChildIndex = Children.IndexOf(reference) + 1;
+ int newChildIndex = Children.IndexOf(reference) + 1;
if (newChildIndex > Children.Count || newChildIndex < 1)
newChildIndex = Children.Count;
AddChildAt(newChildItem, newChildIndex);
@@ -86,7 +86,7 @@ namespace mRemoteNG.Container
public void AddChildRange(IEnumerable newChildren)
{
- foreach (var child in newChildren)
+ foreach (ConnectionInfo child in newChildren)
{
AddChild(child);
}
@@ -103,7 +103,7 @@ namespace mRemoteNG.Container
public void RemoveChildRange(IEnumerable removalTargets)
{
- foreach (var child in removalTargets)
+ foreach (ConnectionInfo child in removalTargets)
{
RemoveChild(child);
}
@@ -111,7 +111,7 @@ namespace mRemoteNG.Container
public void SetChildPosition(ConnectionInfo child, int newIndex)
{
- var originalIndex = Children.IndexOf(child);
+ int originalIndex = Children.IndexOf(child);
if (originalIndex < 0 || originalIndex == newIndex || newIndex < 0) return;
Children.Remove(child);
if (newIndex > Children.Count) newIndex = Children.Count;
@@ -121,14 +121,14 @@ namespace mRemoteNG.Container
public void SetChildAbove(ConnectionInfo childToPromote, ConnectionInfo reference)
{
- var newIndex = GetNewChildIndexAboveReference(childToPromote, reference);
+ int newIndex = GetNewChildIndexAboveReference(childToPromote, reference);
SetChildPosition(childToPromote, newIndex);
}
private int GetNewChildIndexAboveReference(ConnectionInfo childToPromote, ConnectionInfo reference)
{
- var originalIndex = Children.IndexOf(childToPromote);
- var newIndex = Children.IndexOf(reference);
+ int originalIndex = Children.IndexOf(childToPromote);
+ int newIndex = Children.IndexOf(reference);
if (originalIndex < newIndex)
newIndex -= 1;
return newIndex < 0 ? 0 : newIndex;
@@ -136,14 +136,14 @@ namespace mRemoteNG.Container
public void SetChildBelow(ConnectionInfo childToPromote, ConnectionInfo reference)
{
- var newIndex = GetNewChildIndexBelowReference(childToPromote, reference);
+ int newIndex = GetNewChildIndexBelowReference(childToPromote, reference);
SetChildPosition(childToPromote, newIndex);
}
private int GetNewChildIndexBelowReference(ConnectionInfo childToPromote, ConnectionInfo reference)
{
- var originalIndex = Children.IndexOf(childToPromote);
- var newIndex = Children.IndexOf(reference);
+ int originalIndex = Children.IndexOf(childToPromote);
+ int newIndex = Children.IndexOf(reference);
if (originalIndex > newIndex)
newIndex += 1;
return newIndex < 0 ? 0 : newIndex;
@@ -151,13 +151,13 @@ namespace mRemoteNG.Container
public void PromoteChild(ConnectionInfo child)
{
- var originalIndex = Children.IndexOf(child);
+ int originalIndex = Children.IndexOf(child);
SetChildPosition(child, originalIndex - 1);
}
public void DemoteChild(ConnectionInfo child)
{
- var originalIndex = Children.IndexOf(child);
+ int originalIndex = Children.IndexOf(child);
SetChildPosition(child, originalIndex + 1);
}
@@ -169,7 +169,7 @@ namespace mRemoteNG.Container
public void SortOn(Func propertyToCompare, ListSortDirection sortDirection = ListSortDirection.Ascending)
where TProperty : IComparable
{
- var connectionComparer = new ConnectionInfoComparer(propertyToCompare)
+ ConnectionInfoComparer connectionComparer = new(propertyToCompare)
{
SortDirection = sortDirection
};
@@ -185,7 +185,7 @@ namespace mRemoteNG.Container
public void SortOnRecursive(Func propertyToCompare, ListSortDirection sortDirection = ListSortDirection.Ascending)
where TProperty : IComparable
{
- foreach (var child in Children.OfType())
+ foreach (ContainerInfo child in Children.OfType())
child.SortOnRecursive(propertyToCompare, sortDirection);
SortOn(propertyToCompare, sortDirection);
}
@@ -193,13 +193,13 @@ namespace mRemoteNG.Container
// Deep clone, recursive
public override ConnectionInfo Clone()
{
- var newContainer = new ContainerInfo();
+ ContainerInfo newContainer = new();
newContainer.CopyFrom(this);
- newContainer.OpenConnections = new ProtocolList();
+ newContainer.OpenConnections = [];
newContainer.Inheritance = Inheritance.Clone(newContainer);
- foreach (var child in Children.ToArray())
+ foreach (ConnectionInfo child in Children.ToArray())
{
- var newChild = child.Clone();
+ ConnectionInfo newChild = child.Clone();
newChild.RemoveParent();
newContainer.AddChild(newChild);
}
@@ -215,11 +215,11 @@ namespace mRemoteNG.Container
public IEnumerable GetRecursiveChildList()
{
- var childList = new List();
- foreach (var child in Children)
+ List childList = new();
+ foreach (ConnectionInfo child in Children)
{
childList.Add(child);
- var childContainer = child as ContainerInfo;
+ ContainerInfo childContainer = child as ContainerInfo;
if (childContainer != null)
childList.AddRange(GetRecursiveChildList(childContainer));
}
@@ -229,11 +229,11 @@ namespace mRemoteNG.Container
private IEnumerable GetRecursiveChildList(ContainerInfo container)
{
- var childList = new List();
- foreach (var child in container.Children)
+ List childList = new();
+ foreach (ConnectionInfo child in container.Children)
{
childList.Add(child);
- var childContainer = child as ContainerInfo;
+ ContainerInfo childContainer = child as ContainerInfo;
if (childContainer != null)
childList.AddRange(GetRecursiveChildList(childContainer));
}
@@ -243,12 +243,12 @@ namespace mRemoteNG.Container
public IEnumerable GetRecursiveFavoriteChildList()
{
- var childList = new List();
- foreach (var child in Children)
+ List childList = new();
+ foreach (ConnectionInfo child in Children)
{
if (child.Favorite && child.GetTreeNodeType() == TreeNodeType.Connection)
childList.Add(child);
- var childContainer = child as ContainerInfo;
+ ContainerInfo childContainer = child as ContainerInfo;
if (childContainer != null)
childList.AddRange(GetRecursiveFavoritChildList(childContainer));
}
@@ -261,9 +261,9 @@ namespace mRemoteNG.Container
///
public void ApplyConnectionPropertiesToChildren()
{
- var children = GetRecursiveChildList();
+ IEnumerable children = GetRecursiveChildList();
- foreach (var child in children)
+ foreach (ConnectionInfo child in children)
{
child.CopyFrom(this);
}
@@ -275,9 +275,9 @@ namespace mRemoteNG.Container
///
public void ApplyInheritancePropertiesToChildren()
{
- var children = GetRecursiveChildList();
+ IEnumerable children = GetRecursiveChildList();
- foreach (var child in children)
+ foreach (ConnectionInfo child in children)
{
child.Inheritance = Inheritance.Clone(child);
}
@@ -285,12 +285,12 @@ namespace mRemoteNG.Container
private IEnumerable GetRecursiveFavoritChildList(ContainerInfo container)
{
- var childList = new List();
- foreach (var child in container.Children)
+ List childList = new();
+ foreach (ConnectionInfo child in container.Children)
{
if (child.Favorite && child.GetTreeNodeType() == TreeNodeType.Connection)
childList.Add(child);
- var childContainer = child as ContainerInfo;
+ ContainerInfo childContainer = child as ContainerInfo;
if (childContainer != null)
childList.AddRange(GetRecursiveFavoritChildList(childContainer));
}
@@ -300,7 +300,7 @@ namespace mRemoteNG.Container
protected virtual void SubscribeToChildEvents(ConnectionInfo child)
{
child.PropertyChanged += RaisePropertyChangedEvent;
- var childAsContainer = child as ContainerInfo;
+ ContainerInfo childAsContainer = child as ContainerInfo;
if (childAsContainer == null) return;
childAsContainer.CollectionChanged += RaiseCollectionChangedEvent;
}
@@ -308,7 +308,7 @@ namespace mRemoteNG.Container
protected virtual void UnsubscribeToChildEvents(ConnectionInfo child)
{
child.PropertyChanged -= RaisePropertyChangedEvent;
- var childAsContainer = child as ContainerInfo;
+ ContainerInfo childAsContainer = child as ContainerInfo;
if (childAsContainer == null) return;
childAsContainer.CollectionChanged -= RaiseCollectionChangedEvent;
}
diff --git a/mRemoteNG/Credential/CredentialDeletionMsgBoxConfirmer.cs b/mRemoteNG/Credential/CredentialDeletionMsgBoxConfirmer.cs
index eaad2edfe..366423d14 100644
--- a/mRemoteNG/Credential/CredentialDeletionMsgBoxConfirmer.cs
+++ b/mRemoteNG/Credential/CredentialDeletionMsgBoxConfirmer.cs
@@ -23,7 +23,7 @@ namespace mRemoteNG.Credential
public bool Confirm(IEnumerable confirmationTargets)
{
- var targetsArray = confirmationTargets.ToArray();
+ ICredentialRecord[] targetsArray = confirmationTargets.ToArray();
if (targetsArray.Length == 0) return false;
if (targetsArray.Length > 1)
return PromptUser(string.Format("Are you sure you want to delete these {0} selected credentials?", targetsArray.Length));
@@ -32,7 +32,7 @@ namespace mRemoteNG.Credential
private bool PromptUser(string promptMessage)
{
- var msgBoxResponse = _confirmationFunc.Invoke(promptMessage, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
+ DialogResult msgBoxResponse = _confirmationFunc.Invoke(promptMessage, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
return msgBoxResponse == DialogResult.Yes;
}
}
diff --git a/mRemoteNG/Credential/CredentialDomainUserComparer.cs b/mRemoteNG/Credential/CredentialDomainUserComparer.cs
index f0c21d2f3..436b3687e 100644
--- a/mRemoteNG/Credential/CredentialDomainUserComparer.cs
+++ b/mRemoteNG/Credential/CredentialDomainUserComparer.cs
@@ -8,7 +8,7 @@ namespace mRemoteNG.Credential
{
public int Compare(ICredentialRecord x, ICredentialRecord y)
{
- var comparer = new CaseInsensitiveComparer();
+ CaseInsensitiveComparer comparer = new();
return comparer.Compare($"{x.Domain}\\{x.Username}", $"{y.Domain}\\{y.Username}");
}
diff --git a/mRemoteNG/Credential/CredentialRecord.cs b/mRemoteNG/Credential/CredentialRecord.cs
index e0e77edbc..60773ba07 100644
--- a/mRemoteNG/Credential/CredentialRecord.cs
+++ b/mRemoteNG/Credential/CredentialRecord.cs
@@ -9,7 +9,7 @@ namespace mRemoteNG.Credential
{
private string _title = "New Credential";
private string _username = "";
- private SecureString _password = new SecureString();
+ private SecureString _password = new();
private string _domain = "";
public Guid Id { get; } = Guid.NewGuid();
diff --git a/mRemoteNG/Credential/CredentialRecordTypeConverter.cs b/mRemoteNG/Credential/CredentialRecordTypeConverter.cs
index dca247a70..50d32b2ba 100644
--- a/mRemoteNG/Credential/CredentialRecordTypeConverter.cs
+++ b/mRemoteNG/Credential/CredentialRecordTypeConverter.cs
@@ -33,7 +33,7 @@ namespace mRemoteNG.Credential
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (!(value is Guid)) return base.ConvertFrom(context, culture, value);
- var matchedCredentials = Runtime.CredentialProviderCatalog.GetCredentialRecords()
+ ICredentialRecord[] matchedCredentials = Runtime.CredentialProviderCatalog.GetCredentialRecords()
.Where(record => record.Id.Equals(value)).ToArray();
return matchedCredentials.Any() ? matchedCredentials.First() : null;
}
diff --git a/mRemoteNG/Credential/CredentialServiceFacade.cs b/mRemoteNG/Credential/CredentialServiceFacade.cs
index af8ae83ca..aeba2a0c7 100644
--- a/mRemoteNG/Credential/CredentialServiceFacade.cs
+++ b/mRemoteNG/Credential/CredentialServiceFacade.cs
@@ -35,7 +35,7 @@ namespace mRemoteNG.Credential
public void LoadRepositoryList()
{
- foreach (var repository in _loader.Load())
+ foreach (ICredentialRepository repository in _loader.Load())
{
_repositoryList.AddProvider(repository);
}
@@ -80,7 +80,7 @@ namespace mRemoteNG.Credential
CollectionUpdatedEventArgs
collectionUpdatedEventArgs)
{
- var repo = sender as ICredentialRepository;
+ ICredentialRepository repo = sender as ICredentialRepository;
repo?.SaveCredentials(repo.Config.Key);
}
diff --git a/mRemoteNG/Credential/CredentialServiceFactory.cs b/mRemoteNG/Credential/CredentialServiceFactory.cs
index 671c4c518..f6ef147ce 100644
--- a/mRemoteNG/Credential/CredentialServiceFactory.cs
+++ b/mRemoteNG/Credential/CredentialServiceFactory.cs
@@ -16,14 +16,14 @@ namespace mRemoteNG.Credential
// When we get a true CompositionRoot we can move this to that class. We should only require 1 instance of this service at a time
public CredentialServiceFacade Build()
{
- var cryptoFromSettings = new CryptoProviderFactoryFromSettings();
- var credRepoSerializer = new XmlCredentialPasswordEncryptorDecorator(cryptoFromSettings.Build(), new XmlCredentialRecordSerializer());
- var credRepoDeserializer = new XmlCredentialPasswordDecryptorDecorator(new XmlCredentialRecordDeserializer());
+ CryptoProviderFactoryFromSettings cryptoFromSettings = new();
+ XmlCredentialPasswordEncryptorDecorator credRepoSerializer = new(cryptoFromSettings.Build(), new XmlCredentialRecordSerializer());
+ XmlCredentialPasswordDecryptorDecorator credRepoDeserializer = new(new XmlCredentialRecordDeserializer());
- var credentialRepoListPath = Path.Combine(SettingsFileInfo.SettingsPath, "credentialRepositories.xml");
- var repoListDataProvider = new FileDataProvider(credentialRepoListPath);
- var repoListLoader = new CredentialRepositoryListLoader(repoListDataProvider, new CredentialRepositoryListDeserializer(credRepoSerializer, credRepoDeserializer));
- var repoListSaver = new CredentialRepositoryListSaver(repoListDataProvider);
+ string credentialRepoListPath = Path.Combine(SettingsFileInfo.SettingsPath, "credentialRepositories.xml");
+ FileDataProvider repoListDataProvider = new(credentialRepoListPath);
+ CredentialRepositoryListLoader repoListLoader = new(repoListDataProvider, new CredentialRepositoryListDeserializer(credRepoSerializer, credRepoDeserializer));
+ CredentialRepositoryListSaver repoListSaver = new(repoListDataProvider);
return new CredentialServiceFacade(Runtime.CredentialProviderCatalog, repoListLoader, repoListSaver);
}
diff --git a/mRemoteNG/Credential/PlaceholderCredentialRecord.cs b/mRemoteNG/Credential/PlaceholderCredentialRecord.cs
index 7a7710b0f..18d5eb2c4 100644
--- a/mRemoteNG/Credential/PlaceholderCredentialRecord.cs
+++ b/mRemoteNG/Credential/PlaceholderCredentialRecord.cs
@@ -9,11 +9,11 @@ using mRemoteNG.Resources.Language;
namespace mRemoteNG.Credential
{
[SupportedOSPlatform("windows")]
- public class PlaceholderCredentialRecord : ICredentialRecord
+ public class PlaceholderCredentialRecord(IEnumerable id) : ICredentialRecord
{
public event PropertyChangedEventHandler PropertyChanged;
- public Guid Id { get; }
+ public Guid Id { get; } = id.FirstOrDefault();
[ReadOnly(true)] public string Title { get; set; } = Language.CredentialUnavailable;
@@ -23,11 +23,6 @@ namespace mRemoteNG.Credential
[ReadOnly(true)] public string Domain { get; set; } = Language.CredentialUnavailable;
- public PlaceholderCredentialRecord(IEnumerable id)
- {
- Id = id.FirstOrDefault();
- }
-
public override string ToString() => Language.CredentialUnavailable;
}
}
\ No newline at end of file
diff --git a/mRemoteNG/Credential/Repositories/CompositeRepositoryUnlocker.cs b/mRemoteNG/Credential/Repositories/CompositeRepositoryUnlocker.cs
index 79dd9572e..9f4a58712 100644
--- a/mRemoteNG/Credential/Repositories/CompositeRepositoryUnlocker.cs
+++ b/mRemoteNG/Credential/Repositories/CompositeRepositoryUnlocker.cs
@@ -7,7 +7,7 @@ namespace mRemoteNG.Credential.Repositories
{
public class CompositeRepositoryUnlocker
{
- private readonly List _repositories = new List();
+ private readonly List _repositories = [];
public IEnumerable Repositories => _repositories;
public ICredentialRepository SelectedRepository { get; set; }
@@ -33,7 +33,7 @@ namespace mRemoteNG.Credential.Repositories
private ICredentialRepository GetNextLockedRepo()
{
- var newOrder = OrderListForNextLockedRepo();
+ IList newOrder = OrderListForNextLockedRepo();
return newOrder.Any() ? newOrder.First() : null;
}
@@ -41,9 +41,9 @@ namespace mRemoteNG.Credential.Repositories
{
if (_repositories.Count == 0)
return new List();
- var reorderedList = new List();
- var itemsAfterCurrent = BuildListOfItemsAfterCurrent();
- var itemsBeforeAndIncludingCurrent = BuildListOfItemsBeforeAndIncludingCurrent();
+ List reorderedList = new();
+ IList itemsAfterCurrent = BuildListOfItemsAfterCurrent();
+ IList itemsBeforeAndIncludingCurrent = BuildListOfItemsBeforeAndIncludingCurrent();
reorderedList.AddRange(itemsAfterCurrent.Where(repository => !repository.IsLoaded));
reorderedList.AddRange(itemsBeforeAndIncludingCurrent.Where(repository => !repository.IsLoaded));
return reorderedList;
@@ -51,23 +51,23 @@ namespace mRemoteNG.Credential.Repositories
private IList BuildListOfItemsAfterCurrent()
{
- var lastListIndex = _repositories.Count - 1;
- var newListStartIndex = GetNewListStartIndex();
+ int lastListIndex = _repositories.Count - 1;
+ int newListStartIndex = GetNewListStartIndex();
if (newListStartIndex > lastListIndex) newListStartIndex--;
- var countToEndOfList = _repositories.Count - newListStartIndex;
+ int countToEndOfList = _repositories.Count - newListStartIndex;
return _repositories.GetRange(newListStartIndex, countToEndOfList);
}
private IList BuildListOfItemsBeforeAndIncludingCurrent()
{
- var newListStartIndex = GetNewListStartIndex();
+ int newListStartIndex = GetNewListStartIndex();
return _repositories.GetRange(0, newListStartIndex);
}
private int GetNewListStartIndex()
{
- var currentItemIndex = _repositories.IndexOf(SelectedRepository);
+ int currentItemIndex = _repositories.IndexOf(SelectedRepository);
return currentItemIndex + 1;
}
}
diff --git a/mRemoteNG/Credential/Repositories/CredentialRepositoryConfig.cs b/mRemoteNG/Credential/Repositories/CredentialRepositoryConfig.cs
index a2e6703d5..c4981b39b 100644
--- a/mRemoteNG/Credential/Repositories/CredentialRepositoryConfig.cs
+++ b/mRemoteNG/Credential/Repositories/CredentialRepositoryConfig.cs
@@ -8,7 +8,7 @@ namespace mRemoteNG.Credential.Repositories
{
private string _title = "New Credential Repository";
private string _source = "";
- private SecureString _key = new SecureString();
+ private SecureString _key = new();
private string _typeName = "";
private bool _loaded;
diff --git a/mRemoteNG/Credential/Repositories/CredentialRepositoryList.cs b/mRemoteNG/Credential/Repositories/CredentialRepositoryList.cs
index a3305d2e4..6d82601e6 100644
--- a/mRemoteNG/Credential/Repositories/CredentialRepositoryList.cs
+++ b/mRemoteNG/Credential/Repositories/CredentialRepositoryList.cs
@@ -8,7 +8,7 @@ namespace mRemoteNG.Credential.Repositories
{
public class CredentialRepositoryList : ICredentialRepositoryList
{
- private readonly List _credentialProviders = new List();
+ private readonly List _credentialProviders = [];
public IEnumerable CredentialProviders => _credentialProviders;
@@ -38,8 +38,8 @@ namespace mRemoteNG.Credential.Repositories
public IEnumerable GetCredentialRecords()
{
- var list = new List();
- foreach (var repository in CredentialProviders)
+ List list = new();
+ foreach (ICredentialRepository repository in CredentialProviders)
{
list.AddRange(repository.CredentialRecords);
}
@@ -79,7 +79,7 @@ namespace mRemoteNG.Credential.Repositories
private void OnRepoConfigChanged(object sender, EventArgs args)
{
- var repo = sender as ICredentialRepository;
+ ICredentialRepository repo = sender as ICredentialRepository;
if (repo == null) return;
RaiseRepositoriesUpdatedEvent(ActionType.Updated, new[] {repo});
}
diff --git a/mRemoteNG/Credential/Repositories/XmlCredentialRepository.cs b/mRemoteNG/Credential/Repositories/XmlCredentialRepository.cs
index ebb20073b..7836e3f9e 100644
--- a/mRemoteNG/Credential/Repositories/XmlCredentialRepository.cs
+++ b/mRemoteNG/Credential/Repositories/XmlCredentialRepository.cs
@@ -39,8 +39,8 @@ namespace mRemoteNG.Credential.Repositories
public void LoadCredentials(SecureString key)
{
- var credentials = _credentialRecordLoader.Load(key);
- foreach (var newCredential in credentials)
+ IEnumerable credentials = _credentialRecordLoader.Load(key);
+ foreach (ICredentialRecord newCredential in credentials)
{
if (ThisIsADuplicateCredentialRecord(newCredential)) continue;
CredentialRecords.Add(newCredential);
diff --git a/mRemoteNG/Credential/Repositories/XmlCredentialRepositoryFactory.cs b/mRemoteNG/Credential/Repositories/XmlCredentialRepositoryFactory.cs
index 3ea4c44f4..2d8d41878 100644
--- a/mRemoteNG/Credential/Repositories/XmlCredentialRepositoryFactory.cs
+++ b/mRemoteNG/Credential/Repositories/XmlCredentialRepositoryFactory.cs
@@ -33,11 +33,11 @@ namespace mRemoteNG.Credential.Repositories
public ICredentialRepository Build(XElement repositoryXElement)
{
- var stringId = repositoryXElement.Attribute("Id")?.Value;
+ string stringId = repositoryXElement.Attribute("Id")?.Value;
Guid id;
Guid.TryParse(stringId, out id);
if (id.Equals(Guid.Empty)) id = Guid.NewGuid();
- var config = new CredentialRepositoryConfig(id)
+ CredentialRepositoryConfig config = new(id)
{
TypeName = repositoryXElement.Attribute("TypeName")?.Value,
Title = repositoryXElement.Attribute("Title")?.Value,
@@ -48,9 +48,9 @@ namespace mRemoteNG.Credential.Repositories
private ICredentialRepository BuildXmlRepo(ICredentialRepositoryConfig config)
{
- var dataProvider = new FileDataProvider(config.Source);
- var saver = new CredentialRecordSaver(dataProvider, _serializer);
- var loader = new CredentialRecordLoader(dataProvider, _deserializer);
+ FileDataProvider dataProvider = new(config.Source);
+ CredentialRecordSaver saver = new(dataProvider, _serializer);
+ CredentialRecordLoader loader = new(dataProvider, _deserializer);
return new XmlCredentialRepository(config, saver, loader);
}
}
diff --git a/mRemoteNG/Messages/MessageCollector.cs b/mRemoteNG/Messages/MessageCollector.cs
index 6840845e0..488f4b39c 100644
--- a/mRemoteNG/Messages/MessageCollector.cs
+++ b/mRemoteNG/Messages/MessageCollector.cs
@@ -23,7 +23,7 @@ namespace mRemoteNG.Messages
public void AddMessage(MessageClass messageClass, string messageText, bool onlyLog = false)
{
- var message = new Message(messageClass, messageText, onlyLog);
+ Message message = new(messageClass, messageText, onlyLog);
AddMessage(message);
}
@@ -34,8 +34,8 @@ namespace mRemoteNG.Messages
public void AddMessages(IEnumerable messages)
{
- var newMessages = new List();
- foreach (var message in messages)
+ List newMessages = new();
+ foreach (IMessage message in messages)
{
if (_messageList.Contains(message)) continue;
_messageList.Add(message);
diff --git a/mRemoteNG/Messages/MessageWriters/DebugConsoleMessageWriter.cs b/mRemoteNG/Messages/MessageWriters/DebugConsoleMessageWriter.cs
index c168e39f8..15523ee67 100644
--- a/mRemoteNG/Messages/MessageWriters/DebugConsoleMessageWriter.cs
+++ b/mRemoteNG/Messages/MessageWriters/DebugConsoleMessageWriter.cs
@@ -6,7 +6,7 @@ namespace mRemoteNG.Messages.MessageWriters
{
public void Write(IMessage message)
{
- var textToPrint = $"{message.Class}: {message.Text}";
+ string textToPrint = $"{message.Class}: {message.Text}";
Debug.Print(textToPrint);
}
}
diff --git a/mRemoteNG/Messages/MessageWriters/NotificationPanelMessageWriter.cs b/mRemoteNG/Messages/MessageWriters/NotificationPanelMessageWriter.cs
index a1cf6d039..8395cde93 100644
--- a/mRemoteNG/Messages/MessageWriters/NotificationPanelMessageWriter.cs
+++ b/mRemoteNG/Messages/MessageWriters/NotificationPanelMessageWriter.cs
@@ -18,7 +18,7 @@ namespace mRemoteNG.Messages.MessageWriters
public void Write(IMessage message)
{
- var lvItem = new NotificationMessageListViewItem(message);
+ NotificationMessageListViewItem lvItem = new(message);
AddToList(lvItem);
}
diff --git a/mRemoteNG/Properties/AssemblyInfo.cs b/mRemoteNG/Properties/AssemblyInfo.cs
index ff71434cc..47c81ac64 100644
--- a/mRemoteNG/Properties/AssemblyInfo.cs
+++ b/mRemoteNG/Properties/AssemblyInfo.cs
@@ -1,7 +1,10 @@
+//
+// This code was generated by a script. Any changes made manually will be lost
+// the next time this code is regenerated.
+//
+
using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Resources;
// General Information
@@ -15,10 +18,10 @@ using System.Resources;
[assembly: AssemblyCulture("")]
// Version information
-[assembly: AssemblyVersion("1.77.3.1829")]
-[assembly: AssemblyFileVersion("1.77.3.1829")]
+[assembly: AssemblyVersion("1.77.3.1749")]
+[assembly: AssemblyFileVersion("1.77.3.1749")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
-[assembly: AssemblyInformationalVersion("1.77.3 (Nightly Build 1829)")]
+[assembly: AssemblyInformationalVersion("1.77.3 (Nightly Build 1749)")]
// Logging
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]
diff --git a/mRemoteNG/Properties/AssemblyInfo.tt b/mRemoteNG/Properties/AssemblyInfo.tt
index 99b07ca09..599dc568a 100644
--- a/mRemoteNG/Properties/AssemblyInfo.tt
+++ b/mRemoteNG/Properties/AssemblyInfo.tt
@@ -1,25 +1,12 @@
<#@ template debug="true" hostspecific="true" language="C#" #>
+
<#@ output extension=".cs" #>
-<#@ import namespace="System.IO" #>
-<#@ import namespace="System.Text.RegularExpressions" #>
-<#
- string output = File.ReadAllText(this.Host.ResolvePath("AssemblyInfo.cs"));
- Regex pattern = new Regex("AssemblyVersion\\(\"(?\\d+)\\.(?\\d+)\\.(?\\d+)\\.(?\\d+)\"\\)");
- MatchCollection matches = pattern.Matches(output);
- if( matches.Count == 1 )
- {
- major = Convert.ToInt32(matches[0].Groups["major"].Value);
- minor = Convert.ToInt32(matches[0].Groups["minor"].Value);
- revision = Convert.ToInt32(matches[0].Groups["revision"].Value);
- build = Convert.ToInt32(matches[0].Groups["build"].Value);
- if( this.Host.ResolveParameterValue("-","-","BuildConfiguration") == "Release" || this.Host.ResolveParameterValue("-","-","BuildConfiguration") == "Release Installer" )
- build++;
- }
-#>
+//
+// This code was generated by a script. Any changes made manually will be lost
+// the next time this code is regenerated.
+//
using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Resources;
// General Information
@@ -42,9 +29,10 @@ using System.Resources;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]
<#+
+ //build is a days from date of last release + curent hour + curent minute of build
int major = 1;
int minor = 77;
int revision = 3;
- int build = 0;
string channel = "Nightly Build";
+ int build = (int)(DateTime.UtcNow - new DateTime(2019, 9, 2)).TotalDays + DateTime.UtcNow.Hour + DateTime.UtcNow.Minute;
#>
\ No newline at end of file
diff --git a/mRemoteNG/PuTTYNG.exe b/mRemoteNG/PuTTYNG.exe
index 7a4033708..a45bc9b0d 100644
Binary files a/mRemoteNG/PuTTYNG.exe and b/mRemoteNG/PuTTYNG.exe differ
diff --git a/mRemoteNG/Resources/ImageConverter.cs b/mRemoteNG/Resources/ImageConverter.cs
index a32043930..3f8ca056c 100644
--- a/mRemoteNG/Resources/ImageConverter.cs
+++ b/mRemoteNG/Resources/ImageConverter.cs
@@ -13,7 +13,7 @@ namespace mRemoteNG.Resources
///
internal static Icon GetImageAsIcon(Bitmap bitmap)
{
- var icon = Icon.FromHandle(bitmap.GetHicon());
+ Icon icon = Icon.FromHandle(bitmap.GetHicon());
return icon;
}
diff --git a/mRemoteNG/Security/Authentication/PasswordAuthenticator.cs b/mRemoteNG/Security/Authentication/PasswordAuthenticator.cs
index 8c105cd71..be15b1faf 100644
--- a/mRemoteNG/Security/Authentication/PasswordAuthenticator.cs
+++ b/mRemoteNG/Security/Authentication/PasswordAuthenticator.cs
@@ -25,8 +25,8 @@ namespace mRemoteNG.Security.Authentication
public bool Authenticate(SecureString password)
{
- var authenticated = false;
- var attempts = 0;
+ bool authenticated = false;
+ int attempts = 0;
while (!authenticated && attempts < MaxAttempts)
{
try
@@ -37,7 +37,7 @@ namespace mRemoteNG.Security.Authentication
}
catch
{
- var providedPassword = _authenticationRequestor();
+ Optional providedPassword = _authenticationRequestor();
if (!providedPassword.Any())
return false;
diff --git a/mRemoteNG/Security/EncryptedSecureString.cs b/mRemoteNG/Security/EncryptedSecureString.cs
index 1bf59ea97..f2350b6ba 100644
--- a/mRemoteNG/Security/EncryptedSecureString.cs
+++ b/mRemoteNG/Security/EncryptedSecureString.cs
@@ -32,24 +32,24 @@ namespace mRemoteNG.Security
public string GetClearTextValue()
{
- var encryptedText = _secureString.ConvertToUnsecureString();
- var clearText = _cryptographyProvider.Decrypt(encryptedText, MachineKey);
+ string encryptedText = _secureString.ConvertToUnsecureString();
+ string clearText = _cryptographyProvider.Decrypt(encryptedText, MachineKey);
return clearText;
}
public void SetValue(string value)
{
- var cipherText = _cryptographyProvider.Encrypt(value, MachineKey);
+ string cipherText = _cryptographyProvider.Encrypt(value, MachineKey);
_secureString = cipherText.ConvertToSecureString();
}
private static SecureString GenerateNewMachineKey(int keySize)
{
- var random = new SecureRandom();
+ SecureRandom random = new();
random.SetSeed(random.GenerateSeed(128));
- var machineKeyString = "";
- for (var x = 0; x < keySize; x++)
+ string machineKeyString = "";
+ for (int x = 0; x < keySize; x++)
{
machineKeyString += (char)random.Next(33, 126);
}
diff --git a/mRemoteNG/Security/Factories/CryptoProviderFactory.cs b/mRemoteNG/Security/Factories/CryptoProviderFactory.cs
index 4dfd9bdbd..8382969b9 100644
--- a/mRemoteNG/Security/Factories/CryptoProviderFactory.cs
+++ b/mRemoteNG/Security/Factories/CryptoProviderFactory.cs
@@ -12,7 +12,7 @@ namespace mRemoteNG.Security.Factories
public CryptoProviderFactory(BlockCipherEngines engine, BlockCipherModes mode)
{
- var cipherEngine = ChooseBlockCipherEngine(engine);
+ IBlockCipher cipherEngine = ChooseBlockCipherEngine(engine);
_aeadBlockCipher = ChooseBlockCipherMode(mode, cipherEngine);
}
@@ -21,34 +21,26 @@ namespace mRemoteNG.Security.Factories
return new AeadCryptographyProvider(_aeadBlockCipher);
}
- private IBlockCipher ChooseBlockCipherEngine(BlockCipherEngines engine)
+ private static IBlockCipher ChooseBlockCipherEngine(BlockCipherEngines engine)
{
- switch (engine)
+ return engine switch
{
- case BlockCipherEngines.AES:
- return new AesEngine();
- case BlockCipherEngines.Twofish:
- return new TwofishEngine();
- case BlockCipherEngines.Serpent:
- return new SerpentEngine();
- default:
- throw new ArgumentOutOfRangeException(nameof(engine), engine, null);
- }
+ BlockCipherEngines.AES => new AesEngine(),
+ BlockCipherEngines.Twofish => new TwofishEngine(),
+ BlockCipherEngines.Serpent => new SerpentEngine(),
+ _ => throw new ArgumentOutOfRangeException(nameof(engine), engine, null),
+ };
}
- private IAeadBlockCipher ChooseBlockCipherMode(BlockCipherModes mode, IBlockCipher blockCipher)
+ private static IAeadBlockCipher ChooseBlockCipherMode(BlockCipherModes mode, IBlockCipher blockCipher)
{
- switch (mode)
+ return mode switch
{
- case BlockCipherModes.GCM:
- return new GcmBlockCipher(blockCipher);
- case BlockCipherModes.CCM:
- return new CcmBlockCipher(blockCipher);
- case BlockCipherModes.EAX:
- return new EaxBlockCipher(blockCipher);
- default:
- throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
- }
+ BlockCipherModes.GCM => new GcmBlockCipher(blockCipher),
+ BlockCipherModes.CCM => new CcmBlockCipher(blockCipher),
+ BlockCipherModes.EAX => new EaxBlockCipher(blockCipher),
+ _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null),
+ };
}
}
}
\ No newline at end of file
diff --git a/mRemoteNG/Security/Factories/CryptoProviderFactoryFromSettings.cs b/mRemoteNG/Security/Factories/CryptoProviderFactoryFromSettings.cs
index a291e8780..4199a7fb2 100644
--- a/mRemoteNG/Security/Factories/CryptoProviderFactoryFromSettings.cs
+++ b/mRemoteNG/Security/Factories/CryptoProviderFactoryFromSettings.cs
@@ -6,7 +6,7 @@ namespace mRemoteNG.Security.Factories
{
public ICryptographyProvider Build()
{
- var provider =
+ ICryptographyProvider provider =
new CryptoProviderFactory(Properties.OptionsSecurityPage.Default.EncryptionEngine, Properties.OptionsSecurityPage.Default.EncryptionBlockCipherMode).Build();
provider.KeyDerivationIterations = Properties.OptionsSecurityPage.Default.EncryptionKeyDerivationIterations;
return provider;
diff --git a/mRemoteNG/Security/Factories/CryptoProviderFactoryFromXml.cs b/mRemoteNG/Security/Factories/CryptoProviderFactoryFromXml.cs
index 2241627e4..bb9b3e3bc 100644
--- a/mRemoteNG/Security/Factories/CryptoProviderFactoryFromXml.cs
+++ b/mRemoteNG/Security/Factories/CryptoProviderFactoryFromXml.cs
@@ -23,13 +23,13 @@ namespace mRemoteNG.Security.Factories
ICryptographyProvider cryptoProvider;
try
{
- var engine = (BlockCipherEngines)Enum.Parse(typeof(BlockCipherEngines),
+ BlockCipherEngines engine = (BlockCipherEngines)Enum.Parse(typeof(BlockCipherEngines),
_element?.Attribute("EncryptionEngine")?.Value ?? "");
- var mode = (BlockCipherModes)Enum.Parse(typeof(BlockCipherModes),
+ BlockCipherModes mode = (BlockCipherModes)Enum.Parse(typeof(BlockCipherModes),
_element?.Attribute("BlockCipherMode")?.Value ?? "");
cryptoProvider = new CryptoProviderFactory(engine, mode).Build();
- var keyDerivationIterations = int.Parse(_element?.Attribute("KdfIterations")?.Value ?? "");
+ int keyDerivationIterations = int.Parse(_element?.Attribute("KdfIterations")?.Value ?? "");
cryptoProvider.KeyDerivationIterations = keyDerivationIterations;
}
catch (Exception)
diff --git a/mRemoteNG/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs b/mRemoteNG/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs
index c34bfc3e5..85ff6efb9 100644
--- a/mRemoteNG/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs
+++ b/mRemoteNG/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs
@@ -23,13 +23,13 @@ namespace mRemoteNG.Security.KeyDerivation
public byte[] DeriveKey(string password, byte[] salt)
{
- var passwordInBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray());
+ byte[] passwordInBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray());
- var keyGenerator = new Pkcs5S2ParametersGenerator();
+ Pkcs5S2ParametersGenerator keyGenerator = new();
keyGenerator.Init(passwordInBytes, salt, _iterations);
- var keyParameter = (KeyParameter)keyGenerator.GenerateDerivedMacParameters(_keyBitSize);
- var keyBytes = keyParameter.GetKey();
+ KeyParameter keyParameter = (KeyParameter)keyGenerator.GenerateDerivedMacParameters(_keyBitSize);
+ byte[] keyBytes = keyParameter.GetKey();
return keyBytes;
}
}
diff --git a/mRemoteNG/Security/PasswordCreation/PasswordIncludesLowerCaseConstraint.cs b/mRemoteNG/Security/PasswordCreation/PasswordIncludesLowerCaseConstraint.cs
index e1f769782..d7d8c98b8 100644
--- a/mRemoteNG/Security/PasswordCreation/PasswordIncludesLowerCaseConstraint.cs
+++ b/mRemoteNG/Security/PasswordCreation/PasswordIncludesLowerCaseConstraint.cs
@@ -22,7 +22,7 @@ namespace mRemoteNG.Security.PasswordCreation
public bool Validate(SecureString password)
{
- var regex = new Regex(@"[a-z]");
+ Regex regex = new(@"[a-z]");
return regex.Matches(password.ConvertToUnsecureString()).Count >= _minimumCount;
}
}
diff --git a/mRemoteNG/Security/PasswordCreation/PasswordIncludesNumbersConstraint.cs b/mRemoteNG/Security/PasswordCreation/PasswordIncludesNumbersConstraint.cs
index f3ddee22c..09911f863 100644
--- a/mRemoteNG/Security/PasswordCreation/PasswordIncludesNumbersConstraint.cs
+++ b/mRemoteNG/Security/PasswordCreation/PasswordIncludesNumbersConstraint.cs
@@ -22,7 +22,7 @@ namespace mRemoteNG.Security.PasswordCreation
public bool Validate(SecureString password)
{
- var regex = new Regex(@"\d");
+ Regex regex = new(@"\d");
return regex.Matches(password.ConvertToUnsecureString()).Count >= _minimumCount;
}
}
diff --git a/mRemoteNG/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs b/mRemoteNG/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs
index ea8161318..bc9b965d9 100644
--- a/mRemoteNG/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs
+++ b/mRemoteNG/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs
@@ -36,7 +36,7 @@ namespace mRemoteNG.Security.PasswordCreation
public bool Validate(SecureString password)
{
- var regex = new Regex($"[{string.Concat(SpecialCharacters)}]");
+ Regex regex = new($"[{string.Concat(SpecialCharacters)}]");
return regex.Matches(password.ConvertToUnsecureString()).Count >= _minimumCount;
}
}
diff --git a/mRemoteNG/Security/PasswordCreation/PasswordIncludesUpperCaseConstraint.cs b/mRemoteNG/Security/PasswordCreation/PasswordIncludesUpperCaseConstraint.cs
index 0e45c71d7..5db42fd5e 100644
--- a/mRemoteNG/Security/PasswordCreation/PasswordIncludesUpperCaseConstraint.cs
+++ b/mRemoteNG/Security/PasswordCreation/PasswordIncludesUpperCaseConstraint.cs
@@ -22,7 +22,7 @@ namespace mRemoteNG.Security.PasswordCreation
public bool Validate(SecureString password)
{
- var regex = new Regex(@"[A-Z]");
+ Regex regex = new(@"[A-Z]");
return regex.Matches(password.ConvertToUnsecureString()).Count >= _minimumCount;
}
}
diff --git a/mRemoteNG/Security/RandomGenerator.cs b/mRemoteNG/Security/RandomGenerator.cs
index 7687080a8..75530b813 100644
--- a/mRemoteNG/Security/RandomGenerator.cs
+++ b/mRemoteNG/Security/RandomGenerator.cs
@@ -11,13 +11,13 @@ namespace mRemoteNG.Security
if (length < 0)
throw new ArgumentException($"{nameof(length)} must be a positive integer");
- var randomGen = new SecureRandom();
- var stringBuilder = new StringBuilder();
+ SecureRandom randomGen = new();
+ StringBuilder stringBuilder = new();
const string availableChars =
@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+|[]{};:',./<>?";
- for (var x = 0; x < length; x++)
+ for (int x = 0; x < length; x++)
{
- var randomIndex = randomGen.Next(availableChars.Length - 1);
+ int randomIndex = randomGen.Next(availableChars.Length - 1);
stringBuilder.Append(availableChars[randomIndex]);
}
diff --git a/mRemoteNG/Security/SecureStringExtensions.cs b/mRemoteNG/Security/SecureStringExtensions.cs
index 122aee244..b8c08d815 100644
--- a/mRemoteNG/Security/SecureStringExtensions.cs
+++ b/mRemoteNG/Security/SecureStringExtensions.cs
@@ -19,7 +19,7 @@ namespace mRemoteNG.Security
if (securePassword == null)
throw new ArgumentNullException(nameof(securePassword));
- var unmanagedString = IntPtr.Zero;
+ IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
@@ -36,8 +36,8 @@ namespace mRemoteNG.Security
if (unsecuredPassword == null)
throw new ArgumentNullException(nameof(unsecuredPassword));
- var secureString = new SecureString();
- foreach (var character in unsecuredPassword.ToCharArray())
+ SecureString secureString = new();
+ foreach (char character in unsecuredPassword.ToCharArray())
secureString.AppendChar(character);
// ReSharper disable once RedundantAssignment
unsecuredPassword = null;
diff --git a/mRemoteNG/Security/SymmetricEncryption/AeadCryptographyProvider.cs b/mRemoteNG/Security/SymmetricEncryption/AeadCryptographyProvider.cs
index d536f317a..0838562da 100644
--- a/mRemoteNG/Security/SymmetricEncryption/AeadCryptographyProvider.cs
+++ b/mRemoteNG/Security/SymmetricEncryption/AeadCryptographyProvider.cs
@@ -48,7 +48,7 @@ namespace mRemoteNG.Security.SymmetricEncryption
{
get
{
- var cipherEngine = _aeadBlockCipher.AlgorithmName.Split('/')[0];
+ string cipherEngine = _aeadBlockCipher.AlgorithmName.Split('/')[0];
return (BlockCipherEngines)Enum.Parse(typeof(BlockCipherEngines), cipherEngine);
}
}
@@ -57,7 +57,7 @@ namespace mRemoteNG.Security.SymmetricEncryption
{
get
{
- var cipherMode = _aeadBlockCipher.AlgorithmName.Split('/')[1];
+ string cipherMode = _aeadBlockCipher.AlgorithmName.Split('/')[1];
return (BlockCipherModes)Enum.Parse(typeof(BlockCipherModes), cipherMode);
}
}
@@ -96,7 +96,7 @@ namespace mRemoteNG.Security.SymmetricEncryption
public string Encrypt(string plainText, SecureString encryptionKey)
{
- var encryptedText = SimpleEncryptWithPassword(plainText, encryptionKey.ConvertToUnsecureString());
+ string encryptedText = SimpleEncryptWithPassword(plainText, encryptionKey.ConvertToUnsecureString());
return encryptedText;
}
@@ -105,8 +105,8 @@ namespace mRemoteNG.Security.SymmetricEncryption
if (string.IsNullOrEmpty(secretMessage))
return ""; //throw new ArgumentException(@"Secret Message Required!", nameof(secretMessage));
- var plainText = _encoding.GetBytes(secretMessage);
- var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
+ byte[] plainText = _encoding.GetBytes(secretMessage);
+ byte[] cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
@@ -123,14 +123,14 @@ namespace mRemoteNG.Security.SymmetricEncryption
throw new ArgumentException(@"Secret Message Required!", nameof(secretMessage));
//Use Random Salt to minimize pre-generated weak password attacks.
- var salt = GenerateSalt();
+ byte[] salt = GenerateSalt();
//Generate Key
- var keyDerivationFunction = new Pkcs5S2KeyGenerator(KeyBitSize, KeyDerivationIterations);
- var key = keyDerivationFunction.DeriveKey(password, salt);
+ Pkcs5S2KeyGenerator keyDerivationFunction = new(KeyBitSize, KeyDerivationIterations);
+ byte[] key = keyDerivationFunction.DeriveKey(password, salt);
//Create Full Non Secret Payload
- var payload = new byte[salt.Length + nonSecretPayload.Length];
+ byte[] payload = new byte[salt.Length + nonSecretPayload.Length];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length);
@@ -150,20 +150,20 @@ namespace mRemoteNG.Security.SymmetricEncryption
nonSecretPayload ??= ""u8.ToArray();
//Using random nonce large enough not to repeat
- var nonce = new byte[NonceBitSize / 8];
+ byte[] nonce = new byte[NonceBitSize / 8];
_random.NextBytes(nonce, 0, nonce.Length);
- var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
+ AeadParameters parameters = new(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
_aeadBlockCipher.Init(true, parameters);
//Generate Cipher Text With Auth Tag
- var cipherText = new byte[_aeadBlockCipher.GetOutputSize(secretMessage.Length)];
- var len = _aeadBlockCipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
+ byte[] cipherText = new byte[_aeadBlockCipher.GetOutputSize(secretMessage.Length)];
+ int len = _aeadBlockCipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
_aeadBlockCipher.DoFinal(cipherText, len);
//Assemble Message
- var combinedStream = new MemoryStream();
- using (var binaryWriter = new BinaryWriter(combinedStream))
+ MemoryStream combinedStream = new();
+ using (BinaryWriter binaryWriter = new(combinedStream))
{
//Prepend Authenticated Payload
binaryWriter.Write(nonSecretPayload);
@@ -179,7 +179,7 @@ namespace mRemoteNG.Security.SymmetricEncryption
public string Decrypt(string cipherText, SecureString decryptionKey)
{
- var decryptedText = SimpleDecryptWithPassword(cipherText, decryptionKey);
+ string decryptedText = SimpleDecryptWithPassword(cipherText, decryptionKey);
return decryptedText;
}
@@ -188,8 +188,8 @@ namespace mRemoteNG.Security.SymmetricEncryption
if (string.IsNullOrWhiteSpace(encryptedMessage))
return ""; //throw new ArgumentException(@"Encrypted Message Required!", nameof(encryptedMessage));
- var cipherText = Convert.FromBase64String(encryptedMessage);
- var plainText = SimpleDecryptWithPassword(cipherText, decryptionKey.ConvertToUnsecureString(), nonSecretPayloadLength);
+ byte[] cipherText = Convert.FromBase64String(encryptedMessage);
+ byte[] plainText = SimpleDecryptWithPassword(cipherText, decryptionKey.ConvertToUnsecureString(), nonSecretPayloadLength);
return plainText == null ? null : _encoding.GetString(plainText);
}
@@ -203,12 +203,12 @@ namespace mRemoteNG.Security.SymmetricEncryption
throw new ArgumentException(@"Encrypted Message Required!", nameof(encryptedMessage));
//Grab Salt from Payload
- var salt = new byte[SaltBitSize / 8];
+ byte[] salt = new byte[SaltBitSize / 8];
Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);
//Generate Key
- var keyDerivationFunction = new Pkcs5S2KeyGenerator(KeyBitSize, KeyDerivationIterations);
- var key = keyDerivationFunction.DeriveKey(password, salt);
+ Pkcs5S2KeyGenerator keyDerivationFunction = new(KeyBitSize, KeyDerivationIterations);
+ byte[] key = keyDerivationFunction.DeriveKey(password, salt);
return SimpleDecrypt(encryptedMessage, key, salt.Length + nonSecretPayloadLength);
}
@@ -222,25 +222,25 @@ namespace mRemoteNG.Security.SymmetricEncryption
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException(@"Encrypted Message Required!", nameof(encryptedMessage));
- var cipherStream = new MemoryStream(encryptedMessage);
- using var cipherReader = new BinaryReader(cipherStream);
+ MemoryStream cipherStream = new(encryptedMessage);
+ using BinaryReader cipherReader = new(cipherStream);
//Grab Payload
- var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
+ byte[] nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
//Grab Nonce
- var nonce = cipherReader.ReadBytes(NonceBitSize / 8);
+ byte[] nonce = cipherReader.ReadBytes(NonceBitSize / 8);
- var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
+ AeadParameters parameters = new(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
_aeadBlockCipher.Init(false, parameters);
//Decrypt Cipher Text
- var cipherText =
+ byte[] cipherText =
cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
- var plainText = new byte[_aeadBlockCipher.GetOutputSize(cipherText.Length)];
+ byte[] plainText = new byte[_aeadBlockCipher.GetOutputSize(cipherText.Length)];
try
{
- var len = _aeadBlockCipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
+ int len = _aeadBlockCipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
_aeadBlockCipher.DoFinal(plainText, len);
}
catch (InvalidCipherTextException e)
@@ -253,7 +253,7 @@ namespace mRemoteNG.Security.SymmetricEncryption
private byte[] GenerateSalt()
{
- var salt = new byte[SaltBitSize / 8];
+ byte[] salt = new byte[SaltBitSize / 8];
_random.NextBytes(salt);
return salt;
}
diff --git a/mRemoteNG/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs b/mRemoteNG/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs
index 220c97eeb..2c08f8022 100644
--- a/mRemoteNG/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs
+++ b/mRemoteNG/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs
@@ -33,26 +33,26 @@ namespace mRemoteNG.Security.SymmetricEncryption
try
{
- using var aes = Aes.Create();
+ using Aes aes = Aes.Create();
aes.BlockSize = BlockSizeInBytes * 8;
- using (var md5 = MD5.Create())
+ using (MD5 md5 = MD5.Create())
{
- var key = md5.ComputeHash(Encoding.UTF8.GetBytes(strSecret.ConvertToUnsecureString()));
+ byte[] key = md5.ComputeHash(Encoding.UTF8.GetBytes(strSecret.ConvertToUnsecureString()));
aes.Key = key;
aes.GenerateIV();
}
- using var ms = new MemoryStream();
+ using MemoryStream ms = new();
ms.Write(aes.IV, 0, BlockSizeInBytes);
- using var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
- var data = Encoding.UTF8.GetBytes(strToEncrypt);
+ using CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
+ byte[] data = Encoding.UTF8.GetBytes(strToEncrypt);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
- var encdata = ms.ToArray();
+ byte[] encdata = ms.ToArray();
return Convert.ToBase64String(encdata);
}
@@ -71,26 +71,26 @@ namespace mRemoteNG.Security.SymmetricEncryption
try
{
- using var aes = Aes.Create();
+ using Aes aes = Aes.Create();
aes.BlockSize = BlockSizeInBytes * 8;
- using (var md5 = MD5.Create())
+ using (MD5 md5 = MD5.Create())
{
- var key = md5.ComputeHash(Encoding.UTF8.GetBytes(password.ConvertToUnsecureString()));
+ byte[] key = md5.ComputeHash(Encoding.UTF8.GetBytes(password.ConvertToUnsecureString()));
aes.Key = key;
}
- var ciphertext = Convert.FromBase64String(ciphertextBase64);
+ byte[] ciphertext = Convert.FromBase64String(ciphertextBase64);
- using var ms = new MemoryStream(ciphertext);
+ using MemoryStream ms = new(ciphertext);
- var iv = new byte[BlockSizeInBytes];
+ byte[] iv = new byte[BlockSizeInBytes];
ms.Read(iv, 0, iv.Length);
aes.IV = iv;
- using var cryptoStream = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read);
- using var streamReader = new StreamReader(cryptoStream, Encoding.UTF8, true);
- var plaintext = streamReader.ReadToEnd();
+ using CryptoStream cryptoStream = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read);
+ using StreamReader streamReader = new(cryptoStream, Encoding.UTF8, true);
+ string plaintext = streamReader.ReadToEnd();
return plaintext;
}
diff --git a/mRemoteNG/Themes/ExtendedColorPalette.cs b/mRemoteNG/Themes/ExtendedColorPalette.cs
index f8bbe1d70..dbb420045 100644
--- a/mRemoteNG/Themes/ExtendedColorPalette.cs
+++ b/mRemoteNG/Themes/ExtendedColorPalette.cs
@@ -35,9 +35,9 @@ namespace mRemoteNG.Themes
public ExtendedColorPalette()
{
- ExtColorPalette = new Dictionary();
+ ExtColorPalette = [];
DefaultColorPalette =
- new Dictionary(); // If this is the default palette, it will not have a default-default palette
+ []; // If this is the default palette, it will not have a default-default palette
}
#endregion
@@ -59,7 +59,7 @@ namespace mRemoteNG.Themes
///
public Color getColor(string colorKey)
{
- var retColor = ExtColorPalette.ContainsKey(colorKey) ? ExtColorPalette[colorKey] : Color.Empty;
+ Color retColor = ExtColorPalette.ContainsKey(colorKey) ? ExtColorPalette[colorKey] : Color.Empty;
//Invisible colors are not good, might indicate missing color from the palette as is represented by 00000000
if (retColor != Color.Empty && retColor.A != 0) return retColor;
if (DefaultColorPalette != null)
diff --git a/mRemoteNG/Themes/MremoteNGPaletteManipulator.cs b/mRemoteNG/Themes/MremoteNGPaletteManipulator.cs
index 13a8e1c13..7ada852e2 100644
--- a/mRemoteNG/Themes/MremoteNGPaletteManipulator.cs
+++ b/mRemoteNG/Themes/MremoteNGPaletteManipulator.cs
@@ -26,17 +26,17 @@ namespace mRemoteNG.Themes
//Load the colors for the mRemoteNG own components as Dockpanel only have a menus and docks palette
public ExtendedColorPalette getColors()
{
- var newPalette = new ExtendedColorPalette();
+ ExtendedColorPalette newPalette = new();
newPalette.setDefault(_defaultPalette);
- var resourceSet = ColorMapTheme.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
+ System.Resources.ResourceSet resourceSet = ColorMapTheme.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
//
foreach (DictionaryEntry entry in resourceSet)
{
- var colorName = entry.Key.ToString();
- var xmlQueryPath = entry.Value.ToString();
+ string colorName = entry.Key.ToString();
+ string xmlQueryPath = entry.Value.ToString();
if (_xml.DocumentElement == null) continue;
- var colorNodeList = _xml.DocumentElement.FirstChild.SelectNodes(xmlQueryPath);
- var color = colorNodeList != null && colorNodeList.Count > 0 ? colorNodeList[0].Value : null;
+ XmlNodeList colorNodeList = _xml.DocumentElement.FirstChild.SelectNodes(xmlQueryPath);
+ string color = colorNodeList != null && colorNodeList.Count > 0 ? colorNodeList[0].Value : null;
if (color != null)
{
newPalette.addColor(colorName, ColorTranslator.FromHtml($"#{color}"));
@@ -54,21 +54,21 @@ namespace mRemoteNG.Themes
///
public byte[] mergePalette(ExtendedColorPalette colorPalette)
{
- var resourceSet = ColorMapTheme.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
+ System.Resources.ResourceSet resourceSet = ColorMapTheme.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
- var colorName = entry.Key.ToString();
- var xmlQueryPath = entry.Value.ToString();
- var colorNodeList = _xml.DocumentElement?.FirstChild.SelectNodes(xmlQueryPath);
+ string colorName = entry.Key.ToString();
+ string xmlQueryPath = entry.Value.ToString();
+ XmlNodeList colorNodeList = _xml.DocumentElement?.FirstChild.SelectNodes(xmlQueryPath);
if (colorNodeList == null || colorNodeList.Count <= 0) continue;
- var paletteColor = colorPalette.getColor(colorName);
+ Color paletteColor = colorPalette.getColor(colorName);
colorNodeList[0].Value = $"FF{paletteColor.R:X2}{paletteColor.G:X2}{paletteColor.B:X2}";
}
- var ms = new MemoryStream();
+ MemoryStream ms = new();
_xml.Save(ms);
- var bytes = ms.ToArray();
+ byte[] bytes = ms.ToArray();
return bytes;
}
diff --git a/mRemoteNG/Themes/MremoteNGThemeBase.cs b/mRemoteNG/Themes/MremoteNGThemeBase.cs
index 5ed16477c..c948498ef 100644
--- a/mRemoteNG/Themes/MremoteNGThemeBase.cs
+++ b/mRemoteNG/Themes/MremoteNGThemeBase.cs
@@ -33,7 +33,7 @@ namespace mRemoteNG.Themes
{
public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds)
{
- var activeDocumentBounds = (dockPanel?.ActiveDocument as ConnectionTab)?.Bounds;
+ Rectangle? activeDocumentBounds = (dockPanel?.ActiveDocument as ConnectionTab)?.Bounds;
return new FloatWindowNG(dockPanel, pane, activeDocumentBounds ?? bounds);
}
diff --git a/mRemoteNG/Themes/ThemeInfo.cs b/mRemoteNG/Themes/ThemeInfo.cs
index 41e55aadf..e6326dffe 100644
--- a/mRemoteNG/Themes/ThemeInfo.cs
+++ b/mRemoteNG/Themes/ThemeInfo.cs
@@ -60,13 +60,13 @@ namespace mRemoteNG.Themes
public object Clone()
{
- var extPalette = new ExtendedColorPalette
+ ExtendedColorPalette extPalette = new()
{
ExtColorPalette =
_extendedPalette.ExtColorPalette.ToDictionary(entry => entry.Key, entry => entry.Value),
DefaultColorPalette = _extendedPalette.DefaultColorPalette
};
- var clonedObj = new ThemeInfo(_name, _theme, _URI, _version, extPalette)
+ ThemeInfo clonedObj = new(_name, _theme, _URI, _version, extPalette)
{
IsExtendable = IsExtendable,
IsThemeBase = IsThemeBase
diff --git a/mRemoteNG/Themes/ThemeManager.cs b/mRemoteNG/Themes/ThemeManager.cs
index de273d89d..adef43f1a 100644
--- a/mRemoteNG/Themes/ThemeManager.cs
+++ b/mRemoteNG/Themes/ThemeManager.cs
@@ -85,9 +85,9 @@ namespace mRemoteNG.Themes
Directory.CreateDirectory(themePath);
}
- var orig = new DirectoryInfo(App.Info.SettingsFileInfo.InstalledThemeFolder);
- var files = orig.GetFiles();
- foreach (var file in files)
+ DirectoryInfo orig = new(App.Info.SettingsFileInfo.InstalledThemeFolder);
+ FileInfo[] files = orig.GetFiles();
+ foreach (FileInfo file in files)
{
if (!File.Exists(Path.Combine(themePath, file.Name)))
file.CopyTo(Path.Combine(themePath, file.Name), true);
@@ -109,7 +109,7 @@ namespace mRemoteNG.Themes
{
if (ThemeDirExists())
{
- var defaultThemeURL = $"{themePath}\\vs2015light.vstheme";
+ string defaultThemeURL = $"{themePath}\\vs2015light.vstheme";
if (!File.Exists($"{themePath}\\vs2015light.vstheme"))
{
@@ -121,7 +121,7 @@ namespace mRemoteNG.Themes
//First we load the default base theme, its vs2015lightNG
//the true "default" in DockPanelSuite built-in VS2015LightTheme named "vs2015Light"
//hence the *NG suffix for this one...
- var defaultTheme = ThemeSerializer.LoadFromXmlFile(defaultThemeURL);
+ ThemeInfo defaultTheme = ThemeSerializer.LoadFromXmlFile(defaultThemeURL);
defaultTheme.Name = $"{defaultTheme.Name}NG";
return defaultTheme;
}
@@ -138,7 +138,7 @@ namespace mRemoteNG.Themes
public List LoadThemes()
{
if (themes != null) return themes.Values.OfType().ToList();
- themes = new Hashtable();
+ themes = [];
if (themePath == null) return themes.Values.OfType().ToList();
try
@@ -146,18 +146,18 @@ namespace mRemoteNG.Themes
//Check that theme folder exist before trying to load themes
if (ThemeDirExists())
{
- var themeFiles = Directory.GetFiles(themePath, "*.vstheme");
+ string[] themeFiles = Directory.GetFiles(themePath, "*.vstheme");
//First we load the default base theme, its vs2015lightNG
- var defaultTheme = LoadDefaultTheme();
+ ThemeInfo defaultTheme = LoadDefaultTheme();
themes.Add(defaultTheme.Name, defaultTheme);
//Then the rest
- foreach (var themeFile in themeFiles)
+ foreach (string themeFile in themeFiles)
{
// Skip the default theme here, since it will get loaded again without the *NG below...
if (themeFile.Contains("vs2015light.vstheme")) continue;
//filter default one
- var extTheme = ThemeSerializer.LoadFromXmlFile(themeFile, defaultTheme);
+ ThemeInfo extTheme = ThemeSerializer.LoadFromXmlFile(themeFile, defaultTheme);
if (extTheme.Theme == null || themes.ContainsKey(extTheme.Name)) continue;
if (extTheme.Name.Equals("darcula") || extTheme.Name.Equals("vs2015blue") ||
@@ -170,27 +170,27 @@ namespace mRemoteNG.Themes
//Load the embedded themes, extended palettes are taken from the vs2015 themes, trying to match the color theme
// 2012
- var vs2012Light = new ThemeInfo("vs2012Light", new VS2012LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette);
+ ThemeInfo vs2012Light = new("vs2012Light", new VS2012LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette);
themes.Add(vs2012Light.Name, vs2012Light);
- var vs2012Dark = new ThemeInfo("vs2012Dark", new VS2012DarkTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015darkNG"]).ExtendedPalette);
+ ThemeInfo vs2012Dark = new("vs2012Dark", new VS2012DarkTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015darkNG"]).ExtendedPalette);
themes.Add(vs2012Dark.Name, vs2012Dark);
- var vs2012Blue = new ThemeInfo("vs2012Blue", new VS2012BlueTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette);
+ ThemeInfo vs2012Blue = new("vs2012Blue", new VS2012BlueTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette);
themes.Add(vs2012Blue.Name, vs2012Blue);
// 2013
- var vs2013Light = new ThemeInfo("vs2013Light", new VS2013LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette);
+ ThemeInfo vs2013Light = new("vs2013Light", new VS2013LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette);
themes.Add(vs2013Light.Name, vs2013Light);
- var vs2013Dark = new ThemeInfo("vs2013Dark", new VS2013DarkTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015darkNG"]).ExtendedPalette);
+ ThemeInfo vs2013Dark = new("vs2013Dark", new VS2013DarkTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015darkNG"]).ExtendedPalette);
themes.Add(vs2013Dark.Name, vs2013Dark);
- var vs2013Blue = new ThemeInfo("vs2013Blue", new VS2013BlueTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette);
+ ThemeInfo vs2013Blue = new("vs2013Blue", new VS2013BlueTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette);
themes.Add(vs2013Blue.Name, vs2013Blue);
// 2015
- var vs2015Light = new ThemeInfo("vs2015Light", new VS2015LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2015, ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette);
+ ThemeInfo vs2015Light = new("vs2015Light", new VS2015LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2015, ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette);
themes.Add(vs2015Light.Name, vs2015Light);
- var vs2015Dark = new ThemeInfo("vs2015Dark", new VS2015DarkTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2015, ((ThemeInfo)themes["vs2015darkNG"]).ExtendedPalette);
+ ThemeInfo vs2015Dark = new("vs2015Dark", new VS2015DarkTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2015, ((ThemeInfo)themes["vs2015darkNG"]).ExtendedPalette);
themes.Add(vs2015Dark.Name, vs2015Dark);
- var vs2015Blue = new ThemeInfo("vs2015Blue", new VS2015BlueTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2015, ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette);
+ ThemeInfo vs2015Blue = new("vs2015Blue", new VS2015BlueTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2015, ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette);
themes.Add(vs2015Blue.Name, vs2015Blue);
}
}
@@ -211,7 +211,7 @@ namespace mRemoteNG.Themes
public ThemeInfo addTheme(ThemeInfo baseTheme, string newThemeName)
{
if (themes.Contains(newThemeName)) return null;
- var modifiedTheme = (ThemeInfo)baseTheme.Clone();
+ ThemeInfo modifiedTheme = (ThemeInfo)baseTheme.Clone();
modifiedTheme.Name = newThemeName;
modifiedTheme.IsExtendable = true;
modifiedTheme.IsThemeBase = false;
@@ -247,7 +247,7 @@ namespace mRemoteNG.Themes
{
if (themes.Contains(name))
return false;
- var badChars = Path.GetInvalidFileNameChars();
+ char[] badChars = Path.GetInvalidFileNameChars();
return name.IndexOfAny(badChars) == -1;
}
@@ -308,7 +308,7 @@ namespace mRemoteNG.Themes
// Default accordingly...
if (value == null)
{
- var changed = !Properties.OptionsThemePage.Default.ThemeName.Equals(DefaultTheme.Name);
+ bool changed = !Properties.OptionsThemePage.Default.ThemeName.Equals(DefaultTheme.Name);
Properties.OptionsThemePage.Default.ThemeName = DefaultTheme.Name;
_activeTheme = DefaultTheme;
diff --git a/mRemoteNG/Themes/ThemeSerializer.cs b/mRemoteNG/Themes/ThemeSerializer.cs
index d86f8fea1..b483e2f13 100644
--- a/mRemoteNG/Themes/ThemeSerializer.cs
+++ b/mRemoteNG/Themes/ThemeSerializer.cs
@@ -16,9 +16,9 @@ namespace mRemoteNG.Themes
///
public static void SaveToXmlFile(ThemeInfo themeToSave, ThemeInfo baseTheme)
{
- var oldURI = baseTheme.URI;
- var directoryName = Path.GetDirectoryName(oldURI);
- var toSaveURI = directoryName + Path.DirectorySeparatorChar + themeToSave.Name + ".vstheme";
+ string oldURI = baseTheme.URI;
+ string directoryName = Path.GetDirectoryName(oldURI);
+ string toSaveURI = directoryName + Path.DirectorySeparatorChar + themeToSave.Name + ".vstheme";
File.Copy(baseTheme.URI, toSaveURI);
themeToSave.URI = toSaveURI;
}
@@ -34,9 +34,9 @@ namespace mRemoteNG.Themes
///
public static void UpdateThemeXMLValues(ThemeInfo themeToUpdate)
{
- var bytesIn = File.ReadAllBytes(themeToUpdate.URI);
- var manipulator = new MremoteNGPaletteManipulator(bytesIn, themeToUpdate.ExtendedPalette);
- var bytesOut = manipulator.mergePalette(themeToUpdate.ExtendedPalette);
+ byte[] bytesIn = File.ReadAllBytes(themeToUpdate.URI);
+ MremoteNGPaletteManipulator manipulator = new(bytesIn, themeToUpdate.ExtendedPalette);
+ byte[] bytesOut = manipulator.mergePalette(themeToUpdate.ExtendedPalette);
File.WriteAllBytes(themeToUpdate.URI, bytesOut);
}
@@ -48,13 +48,13 @@ namespace mRemoteNG.Themes
///
public static ThemeInfo LoadFromXmlFile(string filename, ThemeInfo defaultTheme = null)
{
- var bytes = File.ReadAllBytes(filename);
+ byte[] bytes = File.ReadAllBytes(filename);
//Load the dockpanel part
- var themeBaseLoad = new MremoteNGThemeBase(bytes);
+ MremoteNGThemeBase themeBaseLoad = new(bytes);
//Load the mremote part
//Cause we cannot default the theme for the default theme
- var extColorLoader = new MremoteNGPaletteManipulator(bytes, defaultTheme?.ExtendedPalette);
- var loadedTheme = new ThemeInfo(Path.GetFileNameWithoutExtension(filename), themeBaseLoad, filename,
+ MremoteNGPaletteManipulator extColorLoader = new(bytes, defaultTheme?.ExtendedPalette);
+ ThemeInfo loadedTheme = new(Path.GetFileNameWithoutExtension(filename), themeBaseLoad, filename,
VisualStudioToolStripExtender.VsVersion.Vs2015, extColorLoader.getColors());
if (new[] {"darcula", "vs2015blue", "vs2015dark", "vs2015light"}.Contains(
Path
diff --git a/mRemoteNG/Tools/ADhelper.cs b/mRemoteNG/Tools/ADhelper.cs
index a623d5b44..a9e572b00 100644
--- a/mRemoteNG/Tools/ADhelper.cs
+++ b/mRemoteNG/Tools/ADhelper.cs
@@ -13,7 +13,7 @@ namespace mRemoteNG.Tools
public AdHelper(string domain)
{
- Children = new Hashtable();
+ Children = [];
Domain = domain;
}
diff --git a/mRemoteNG/Tools/Authenticode.cs b/mRemoteNG/Tools/Authenticode.cs
index 0a29a56fb..f6f904cf9 100644
--- a/mRemoteNG/Tools/Authenticode.cs
+++ b/mRemoteNG/Tools/Authenticode.cs
@@ -26,11 +26,11 @@ namespace mRemoteNG.Tools
public StatusValue Verify()
{
- var trustFileInfoPointer = default(IntPtr);
- var trustDataPointer = default(IntPtr);
+ IntPtr trustFileInfoPointer = default(IntPtr);
+ IntPtr trustDataPointer = default(IntPtr);
try
{
- var fileInfo = new FileInfo(FilePath);
+ FileInfo fileInfo = new(FilePath);
if (!fileInfo.Exists)
{
Status = StatusValue.FileNotExist;
@@ -49,8 +49,8 @@ namespace mRemoteNG.Tools
Status = StatusValue.NoThumbprintToMatch;
return Status;
}
-
- var certificate2 = new X509Certificate2(X509Certificate.CreateFromSignedFile(FilePath));
+
+ X509Certificate2 certificate2 = new(X509Certificate.CreateFromSignedFile(FilePath));
_thumbprint = certificate2.Thumbprint;
if (_thumbprint != ThumbprintToMatch)
{
@@ -59,12 +59,12 @@ namespace mRemoteNG.Tools
}
}
- var trustFileInfo = new NativeMethods.WINTRUST_FILE_INFO {pcwszFilePath = FilePath};
+ NativeMethods.WINTRUST_FILE_INFO trustFileInfo = new() { pcwszFilePath = FilePath};
trustFileInfoPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(trustFileInfo));
Marshal.StructureToPtr(trustFileInfo, trustFileInfoPointer, false);
- var trustData = new NativeMethods.WINTRUST_DATA
- {
+ NativeMethods.WINTRUST_DATA trustData = new()
+ {
dwUIChoice = (uint) Display,
fdwRevocationChecks = NativeMethods.WTD_REVOKE_WHOLECHAIN,
dwUnionChoice = NativeMethods.WTD_CHOICE_FILE,
@@ -76,7 +76,7 @@ namespace mRemoteNG.Tools
trustDataPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(trustData));
Marshal.StructureToPtr(trustData, trustDataPointer, false);
- var windowHandle = DisplayParentForm?.Handle ?? IntPtr.Zero;
+ IntPtr windowHandle = DisplayParentForm?.Handle ?? IntPtr.Zero;
_trustProviderErrorCode =
NativeMethods.WinVerifyTrust(windowHandle, NativeMethods.WINTRUST_ACTION_GENERIC_VERIFY_V2, trustDataPointer);
@@ -104,11 +104,11 @@ namespace mRemoteNG.Tools
if (ex is CryptographicException)
{
- var hResultProperty =
+ PropertyInfo hResultProperty =
ex.GetType().GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance);
if (hResultProperty != null)
{
- var hResult = Convert.ToInt32(hResultProperty.GetValue(ex, null));
+ int hResult = Convert.ToInt32(hResultProperty.GetValue(ex, null));
if (hResult == NativeMethods.CRYPT_E_NO_MATCH)
{
Status = StatusValue.NoSignature;
@@ -175,7 +175,7 @@ namespace mRemoteNG.Tools
*/
return $"The thumbprint does not match. {_thumbprint} {(char) 0x2260} {ThumbprintToMatch}.";
case StatusValue.TrustProviderError:
- var ex = new Win32Exception(_trustProviderErrorCode);
+ Win32Exception ex = new(_trustProviderErrorCode);
return $"The trust provider returned an error. {ex.Message}";
case StatusValue.UnhandledException:
return $"An unhandled exception occurred. {Exception.Message}";
@@ -273,7 +273,7 @@ namespace mRemoteNG.Tools
public const int TRUST_E_NOSIGNATURE = unchecked ((int) 0x800B0100);
public static readonly Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 =
- new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
+ new("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
public const uint WTD_CHOICE_FILE = 1;
public const uint WTD_DISABLE_MD2_MD4 = 0x2000;
diff --git a/mRemoteNG/Tools/Cmdline/CmdArgumentsInterpreter.cs b/mRemoteNG/Tools/Cmdline/CmdArgumentsInterpreter.cs
index 3800105b6..09f6c4586 100644
--- a/mRemoteNG/Tools/Cmdline/CmdArgumentsInterpreter.cs
+++ b/mRemoteNG/Tools/Cmdline/CmdArgumentsInterpreter.cs
@@ -29,9 +29,9 @@ namespace mRemoteNG.Tools.Cmdline
public CmdArgumentsInterpreter(IEnumerable args)
{
- _parameters = new StringDictionary();
- var spliter = new Regex("^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled);
- var remover = new Regex("^[\'\"]?(.*?)[\'\"]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ _parameters = [];
+ Regex spliter = new("^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ Regex remover = new("^[\'\"]?(.*?)[\'\"]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
string parameter = null;
// Valid parameters forms:
@@ -40,10 +40,10 @@ namespace mRemoteNG.Tools.Cmdline
try
{
- foreach (var txt in args)
+ foreach (string txt in args)
{
// Look for new parameters (-,/ or --) and a possible enclosed value (=,:)
- var Parts = spliter.Split(txt, 3);
+ string[] Parts = spliter.Split(txt, 3);
switch (Parts.Length)
{
case 1:
diff --git a/mRemoteNG/Tools/Cmdline/CommandLineArguments.cs b/mRemoteNG/Tools/Cmdline/CommandLineArguments.cs
index 43d5589e4..a380291d9 100644
--- a/mRemoteNG/Tools/Cmdline/CommandLineArguments.cs
+++ b/mRemoteNG/Tools/Cmdline/CommandLineArguments.cs
@@ -7,7 +7,7 @@ namespace mRemoteNG.Tools.Cmdline
// Adapted from http://qntm.org/cmd
public class CommandLineArguments
{
- protected List Arguments = new List();
+ protected List Arguments = [];
public bool EscapeForShell { get; set; }
@@ -20,7 +20,7 @@ namespace mRemoteNG.Tools.Cmdline
public void Add(params string[] argumentArray)
{
- foreach (var argument in argumentArray)
+ foreach (string argument in argumentArray)
{
Add(argument);
}
@@ -33,7 +33,7 @@ namespace mRemoteNG.Tools.Cmdline
public override string ToString()
{
- var argList = Arguments.Select(argument => ProcessArgument(argument, EscapeForShell));
+ IEnumerable argList = Arguments.Select(argument => ProcessArgument(argument, EscapeForShell));
return string.Join(" ", argList.ToArray());
}
@@ -94,7 +94,7 @@ namespace mRemoteNG.Tools.Cmdline
protected static string ProcessArgument(Argument argument, bool escapeForShell = false)
{
- var text = argument.Text;
+ string text = argument.Text;
if (argument.IsFileName)
{
diff --git a/mRemoteNG/Tools/Cmdline/StartupArgumentsInterpreter.cs b/mRemoteNG/Tools/Cmdline/StartupArgumentsInterpreter.cs
index 16b5ebf7a..2b7984d50 100644
--- a/mRemoteNG/Tools/Cmdline/StartupArgumentsInterpreter.cs
+++ b/mRemoteNG/Tools/Cmdline/StartupArgumentsInterpreter.cs
@@ -32,7 +32,7 @@ namespace mRemoteNG.Tools.Cmdline
try
{
- var args = new CmdArgumentsInterpreter(cmdlineArgs);
+ CmdArgumentsInterpreter args = new(cmdlineArgs);
ParseResetPositionArg(args);
ParseResetPanelsArg(args);
@@ -51,10 +51,10 @@ namespace mRemoteNG.Tools.Cmdline
if (args["resetpos"] == null && args["rp"] == null && args["reset"] == null) return;
_messageCollector.AddMessage(MessageClass.DebugMsg, "Cmdline arg: Resetting window positions.");
Properties.App.Default.MainFormKiosk = false;
- var newWidth = 900;
- var newHeight = 600;
- var newX = Screen.PrimaryScreen.WorkingArea.Width / 2 - newWidth / 2;
- var newY = Screen.PrimaryScreen.WorkingArea.Height / 2 - newHeight / 2;
+ int newWidth = 900;
+ int newHeight = 600;
+ int newX = Screen.PrimaryScreen.WorkingArea.Width / 2 - newWidth / 2;
+ int newY = Screen.PrimaryScreen.WorkingArea.Height / 2 - newHeight / 2;
Properties.App.Default.MainFormLocation = new Point(newX, newY);
Properties.App.Default.MainFormSize = new Size(newWidth, newHeight);
Properties.App.Default.MainFormState = FormWindowState.Normal;
@@ -84,7 +84,7 @@ namespace mRemoteNG.Tools.Cmdline
private void ParseCustomConnectionPathArg(CmdArgumentsInterpreter args)
{
- var consParam = "";
+ string consParam = "";
if (args["cons"] != null)
consParam = "cons";
if (args["c"] != null)
diff --git a/mRemoteNG/Tools/ConnectionsTreeToMenuItemsConverter.cs b/mRemoteNG/Tools/ConnectionsTreeToMenuItemsConverter.cs
index a72bb30ea..fd07ba5bc 100644
--- a/mRemoteNG/Tools/ConnectionsTreeToMenuItemsConverter.cs
+++ b/mRemoteNG/Tools/ConnectionsTreeToMenuItemsConverter.cs
@@ -19,13 +19,13 @@ namespace mRemoteNG.Tools
public IEnumerable CreateToolStripDropDownItems(ConnectionTreeModel connectionTreeModel)
{
- var rootNodes = connectionTreeModel.RootNodes;
+ List rootNodes = connectionTreeModel.RootNodes;
return CreateToolStripDropDownItems(rootNodes);
}
public IEnumerable CreateToolStripDropDownItems(IEnumerable nodes)
{
- var dropDownList = new List();
+ List dropDownList = new();
try
{
dropDownList.AddRange(nodes.Select(CreateMenuItem));
@@ -40,22 +40,22 @@ namespace mRemoteNG.Tools
private void AddSubMenuNodes(IEnumerable nodes, ToolStripDropDownItem toolStripMenuItem)
{
- foreach (var connectionInfo in nodes)
+ foreach (ConnectionInfo connectionInfo in nodes)
{
- var newItem = CreateMenuItem(connectionInfo);
+ ToolStripDropDownItem newItem = CreateMenuItem(connectionInfo);
toolStripMenuItem.DropDownItems.Add(newItem);
}
}
private ToolStripDropDownItem CreateMenuItem(ConnectionInfo node)
{
- var menuItem = new ToolStripMenuItem
+ ToolStripMenuItem menuItem = new()
{
Text = node.Name,
Tag = node
};
- var nodeAsContainer = node as ContainerInfo;
+ ContainerInfo nodeAsContainer = node as ContainerInfo;
if (nodeAsContainer != null)
{
menuItem.Image = Properties.Resources.FolderClosed_16x;
diff --git a/mRemoteNG/Tools/CustomCollections/FullyObservableCollection.cs b/mRemoteNG/Tools/CustomCollections/FullyObservableCollection.cs
index c1b44ce4c..230585e22 100644
--- a/mRemoteNG/Tools/CustomCollections/FullyObservableCollection.cs
+++ b/mRemoteNG/Tools/CustomCollections/FullyObservableCollection.cs
@@ -46,10 +46,10 @@ namespace mRemoteNG.Tools.CustomCollections
///
public void AddRange(IEnumerable items)
{
- var itemsAsList = items.ToList();
+ List itemsAsList = items.ToList();
_eventsAllowed = false;
- foreach (var item in itemsAsList)
+ foreach (T item in itemsAsList)
Add(item);
_eventsAllowed = true;
@@ -65,7 +65,7 @@ namespace mRemoteNG.Tools.CustomCollections
public bool Remove(T item)
{
- var worked = _list.Remove(item);
+ bool worked = _list.Remove(item);
if (!worked) return worked;
UnsubscribeFromChildEvents(item);
RaiseCollectionChangedEvent(ActionType.Removed, new[] {item});
@@ -74,7 +74,7 @@ namespace mRemoteNG.Tools.CustomCollections
public void RemoveAt(int index)
{
- var item = _list[index];
+ T item = _list[index];
_list.RemoveAt(index);
UnsubscribeFromChildEvents(item);
RaiseCollectionChangedEvent(ActionType.Removed, new[] {item});
@@ -82,9 +82,9 @@ namespace mRemoteNG.Tools.CustomCollections
public void Clear()
{
- var oldItems = _list.ToArray();
+ T[] oldItems = _list.ToArray();
_list.Clear();
- foreach (var item in oldItems)
+ foreach (T item in oldItems)
UnsubscribeFromChildEvents(item);
RaiseCollectionChangedEvent(ActionType.Removed, oldItems);
}
diff --git a/mRemoteNG/Tools/EnumWindows.cs b/mRemoteNG/Tools/EnumWindows.cs
index d550fe130..19ab7f362 100644
--- a/mRemoteNG/Tools/EnumWindows.cs
+++ b/mRemoteNG/Tools/EnumWindows.cs
@@ -8,10 +8,10 @@ namespace mRemoteNG.Tools
{
public List EnumWindows_Renamed()
{
- var handleList = new List();
+ List handleList = new();
HandleLists.Add(handleList);
- var handleIndex = (IntPtr)HandleLists.IndexOf(handleList);
+ IntPtr handleIndex = (IntPtr)HandleLists.IndexOf(handleList);
NativeMethods.EnumWindows(EnumCallback, handleIndex);
HandleLists.Remove(handleList);
@@ -20,17 +20,17 @@ namespace mRemoteNG.Tools
public List EnumChildWindows(IntPtr hWndParent)
{
- var handleList = new List();
+ List handleList = new();
HandleLists.Add(handleList);
- var handleIndex = (IntPtr)HandleLists.IndexOf(handleList);
+ IntPtr handleIndex = (IntPtr)HandleLists.IndexOf(handleList);
NativeMethods.EnumChildWindows(hWndParent, EnumCallback, handleIndex);
HandleLists.Remove(handleList);
return handleList;
}
- private readonly List> HandleLists = new List>();
+ private readonly List> HandleLists = [];
private bool EnumCallback(int hwnd, int lParam)
{
diff --git a/mRemoteNG/Tools/Extensions.cs b/mRemoteNG/Tools/Extensions.cs
index 8f13b29ab..27628dc9b 100644
--- a/mRemoteNG/Tools/Extensions.cs
+++ b/mRemoteNG/Tools/Extensions.cs
@@ -64,7 +64,7 @@ namespace mRemoteNG.Tools
{
collection = collection.ToList();
- foreach (var item in collection)
+ foreach (T item in collection)
action(item);
return collection;
diff --git a/mRemoteNG/Tools/ExternalTool.cs b/mRemoteNG/Tools/ExternalTool.cs
index efb157722..8c86eea8f 100644
--- a/mRemoteNG/Tools/ExternalTool.cs
+++ b/mRemoteNG/Tools/ExternalTool.cs
@@ -142,7 +142,7 @@ namespace mRemoteNG.Tools
private void StartExternalProcess()
{
- var process = new Process();
+ Process process = new();
SetProcessProperties(process, ConnectionInfo);
process.Start();
@@ -154,7 +154,7 @@ namespace mRemoteNG.Tools
private void SetProcessProperties(Process process, ConnectionInfo startConnectionInfo)
{
- var argParser = new ExternalToolArgumentParser(startConnectionInfo);
+ ExternalToolArgumentParser argParser = new(startConnectionInfo);
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = argParser.ParseArguments(FileName);
process.StartInfo.Arguments = argParser.ParseArguments(Arguments);
@@ -166,7 +166,7 @@ namespace mRemoteNG.Tools
{
try
{
- var newConnectionInfo = BuildConnectionInfoForIntegratedApp();
+ ConnectionInfo newConnectionInfo = BuildConnectionInfoForIntegratedApp();
Runtime.ConnectionInitiator.OpenConnection(newConnectionInfo);
}
catch (Exception ex)
@@ -177,14 +177,14 @@ namespace mRemoteNG.Tools
private ConnectionInfo BuildConnectionInfoForIntegratedApp()
{
- var newConnectionInfo = GetAppropriateInstanceOfConnectionInfo();
+ ConnectionInfo newConnectionInfo = GetAppropriateInstanceOfConnectionInfo();
SetConnectionInfoFields(newConnectionInfo);
return newConnectionInfo;
}
private ConnectionInfo GetAppropriateInstanceOfConnectionInfo()
{
- var newConnectionInfo = ConnectionInfo == null ? new ConnectionInfo() : ConnectionInfo.Clone();
+ ConnectionInfo newConnectionInfo = ConnectionInfo == null ? new ConnectionInfo() : ConnectionInfo.Clone();
return newConnectionInfo;
}
diff --git a/mRemoteNG/Tools/ExternalToolArgumentParser.cs b/mRemoteNG/Tools/ExternalToolArgumentParser.cs
index fe96c3927..253c5360a 100644
--- a/mRemoteNG/Tools/ExternalToolArgumentParser.cs
+++ b/mRemoteNG/Tools/ExternalToolArgumentParser.cs
@@ -21,35 +21,35 @@ namespace mRemoteNG.Tools
public string ParseArguments(string input)
{
- var replacements = BuildReplacementList(input);
- var result = PerformReplacements(input, replacements);
+ List replacements = BuildReplacementList(input);
+ string result = PerformReplacements(input, replacements);
return result;
}
private List BuildReplacementList(string input)
{
- var index = 0;
- var replacements = new List();
+ int index = 0;
+ List replacements = new();
do
{
- var tokenStart = input.IndexOf("%", index, StringComparison.InvariantCulture);
+ int tokenStart = input.IndexOf("%", index, StringComparison.InvariantCulture);
if (tokenStart == -1)
break;
- var tokenEnd = input.IndexOf("%", tokenStart + 1, StringComparison.InvariantCulture);
+ int tokenEnd = input.IndexOf("%", tokenStart + 1, StringComparison.InvariantCulture);
if (tokenEnd == -1)
break;
- var tokenLength = tokenEnd - tokenStart + 1;
- var variableNameStart = tokenStart + 1;
- var variableNameLength = tokenLength - 2;
- var isEnvironmentVariable = false;
- var variableName = "";
+ int tokenLength = tokenEnd - tokenStart + 1;
+ int variableNameStart = tokenStart + 1;
+ int variableNameLength = tokenLength - 2;
+ bool isEnvironmentVariable = false;
+ string variableName = "";
if (tokenStart > 0)
{
- var tokenStartPrefix = input.Substring(tokenStart - 1, 1).ToCharArray()[0];
- var tokenEndPrefix = input.Substring(tokenEnd - 1, 1).ToCharArray()[0];
+ char tokenStartPrefix = input.Substring(tokenStart - 1, 1).ToCharArray()[0];
+ char tokenEndPrefix = input.Substring(tokenEnd - 1, 1).ToCharArray()[0];
if (tokenStartPrefix == '\\' && tokenEndPrefix == '\\')
{
@@ -79,9 +79,9 @@ namespace mRemoteNG.Tools
}
}
- var token = input.Substring(tokenStart, tokenLength);
+ string token = input.Substring(tokenStart, tokenLength);
- var escape = DetermineEscapeType(token);
+ EscapeType escape = DetermineEscapeType(token);
if (escape != EscapeType.All)
{
@@ -98,13 +98,13 @@ namespace mRemoteNG.Tools
variableName = input.Substring(variableNameStart, variableNameLength);
- var replacementValue = token;
+ string replacementValue = token;
if (!isEnvironmentVariable)
{
replacementValue = GetVariableReplacement(variableName, token);
}
- var haveReplacement = false;
+ bool haveReplacement = false;
if (replacementValue != token)
{
@@ -119,7 +119,7 @@ namespace mRemoteNG.Tools
if (haveReplacement)
{
- var trailing = tokenEnd + 2 <= input.Length
+ char trailing = tokenEnd + 2 <= input.Length
? input.Substring(tokenEnd + 1, 1).ToCharArray()[0]
: '\0';
@@ -147,8 +147,8 @@ namespace mRemoteNG.Tools
private EscapeType DetermineEscapeType(string token)
{
- var escape = EscapeType.All;
- var prefix = token[1];
+ EscapeType escape = EscapeType.All;
+ char prefix = token[1];
switch (prefix)
{
case '-':
@@ -164,7 +164,7 @@ namespace mRemoteNG.Tools
private string GetVariableReplacement(string variable, string original)
{
- var replacement = "";
+ string replacement = "";
if (_connectionInfo == null) return replacement;
switch (variable.ToLowerInvariant())
{
@@ -217,19 +217,19 @@ namespace mRemoteNG.Tools
private string PerformReplacements(string input, List replacements)
{
int index;
- var result = input;
+ string result = input;
for (index = result.Length; index >= 0; index--)
{
- foreach (var replacement in replacements)
+ foreach (Replacement replacement in replacements)
{
if (replacement.Start != index)
{
continue;
}
- var before = result.Substring(0, replacement.Start);
- var after = result.Substring(replacement.Start + replacement.Length);
+ string before = result.Substring(0, replacement.Start);
+ string after = result.Substring(replacement.Start + replacement.Length);
result = before + replacement.Value + after;
}
}
diff --git a/mRemoteNG/Tools/ExternalToolsService.cs b/mRemoteNG/Tools/ExternalToolsService.cs
index f2742d7b2..eeda1cd5b 100644
--- a/mRemoteNG/Tools/ExternalToolsService.cs
+++ b/mRemoteNG/Tools/ExternalToolsService.cs
@@ -7,7 +7,7 @@ namespace mRemoteNG.Tools
[SupportedOSPlatform("windows")]
public class ExternalToolsService
{
- public FullyObservableCollection ExternalTools { get; set; } = new FullyObservableCollection();
+ public FullyObservableCollection ExternalTools { get; set; } = [];
public ExternalTool GetExtAppByName(string name)
{
diff --git a/mRemoteNG/Tools/ExternalToolsTypeConverter.cs b/mRemoteNG/Tools/ExternalToolsTypeConverter.cs
index 658413e2b..3c5d8f5d9 100644
--- a/mRemoteNG/Tools/ExternalToolsTypeConverter.cs
+++ b/mRemoteNG/Tools/ExternalToolsTypeConverter.cs
@@ -11,12 +11,13 @@ namespace mRemoteNG.Tools
{
get
{
- var externalToolList = new List();
+ List externalToolList = new()
+ {
+ // Add a blank entry to signify that no external tool is selected
+ string.Empty
+ };
- // Add a blank entry to signify that no external tool is selected
- externalToolList.Add(string.Empty);
-
- foreach (var externalTool in App.Runtime.ExternalToolsService.ExternalTools)
+ foreach (ExternalTool externalTool in App.Runtime.ExternalToolsService.ExternalTools)
{
externalToolList.Add(externalTool.DisplayName);
}
diff --git a/mRemoteNG/Tools/IeBrowserEmulation.cs b/mRemoteNG/Tools/IeBrowserEmulation.cs
index 37e2c7a23..ee7312370 100644
--- a/mRemoteNG/Tools/IeBrowserEmulation.cs
+++ b/mRemoteNG/Tools/IeBrowserEmulation.cs
@@ -19,7 +19,7 @@ namespace mRemoteNG.Tools
{
if (Environment.Is64BitOperatingSystem)
{
- using (var key = Registry.CurrentUser.CreateSubKey(
+ using (RegistryKey key = Registry.CurrentUser.CreateSubKey(
string
.Concat("Software\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\",
feature),
@@ -30,7 +30,7 @@ namespace mRemoteNG.Tools
}
- using (var key = Registry.CurrentUser.CreateSubKey(
+ using (RegistryKey key = Registry.CurrentUser.CreateSubKey(
string
.Concat("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\",
feature),
@@ -74,7 +74,7 @@ namespace mRemoteNG.Tools
// http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx
// FeatureControl settings are per-process
- var fileName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
+ string fileName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
// make sure the control is not running inside Visual Studio Designer
if (string.Compare(fileName, "devenv.exe", StringComparison.OrdinalIgnoreCase) == 0 ||
@@ -157,16 +157,16 @@ namespace mRemoteNG.Tools
{
// https://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx
- var browserVersion = 9;
+ int browserVersion = 9;
// default to IE9.
- using (var ieKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer",
+ using (RegistryKey ieKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer",
RegistryKeyPermissionCheck.ReadSubTree,
RegistryRights.QueryValues))
{
if (ieKey != null)
{
- var version = ieKey.GetValue("svcVersion");
+ object version = ieKey.GetValue("svcVersion");
if (null == version)
{
version = ieKey.GetValue("Version");
diff --git a/mRemoteNG/Tools/MiscTools.cs b/mRemoteNG/Tools/MiscTools.cs
index 15bd6e213..7eba7e4a0 100644
--- a/mRemoteNG/Tools/MiscTools.cs
+++ b/mRemoteNG/Tools/MiscTools.cs
@@ -48,7 +48,7 @@ namespace mRemoteNG.Tools
//if (PresentationSource.FromVisual(splash))
// splash.Close();
- var passwordForm = new FrmPassword(passwordName, verify);
+ FrmPassword passwordForm = new(passwordName, verify);
return passwordForm.GetKey();
}
@@ -131,9 +131,9 @@ namespace mRemoteNG.Tools
private static string GetExceptionMessageRecursive(Exception ex, string separator)
{
- var message = ex.Message;
+ string message = ex.Message;
if (ex.InnerException == null) return message;
- var innerMessage = GetExceptionMessageRecursive(ex.InnerException, separator);
+ string innerMessage = GetExceptionMessageRecursive(ex.InnerException, separator);
message = String.Join(separator, message, innerMessage);
return message;
}
@@ -145,7 +145,7 @@ namespace mRemoteNG.Tools
{
if (sender != null)
{
- var bmp = new Bitmap(sender.Width, sender.Height, PixelFormat.Format32bppRgb);
+ Bitmap bmp = new(sender.Width, sender.Height, PixelFormat.Format32bppRgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(sender.PointToScreen(System.Drawing.Point.Empty), System.Drawing.Point.Empty, bmp.Size, CopyPixelOperation.SourceCopy);
return bmp;
@@ -179,8 +179,8 @@ namespace mRemoteNG.Tools
Type destType)
{
if (value == null) return null;
- var fi = _enumType.GetField(Enum.GetName(_enumType, value));
- var dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
+ System.Reflection.FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, value));
+ DescriptionAttribute dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
return dna != null ? dna.Description : value.ToString();
}
@@ -192,9 +192,9 @@ namespace mRemoteNG.Tools
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- foreach (var fi in _enumType.GetFields())
+ foreach (System.Reflection.FieldInfo fi in _enumType.GetFields())
{
- var dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
+ DescriptionAttribute dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
if (dna != null && (string)value == dna.Description)
{
@@ -256,7 +256,7 @@ namespace mRemoteNG.Tools
{
bool[] bools = {true, false};
- var svc = new StandardValuesCollection(bools);
+ StandardValuesCollection svc = new(bools);
return svc;
}
diff --git a/mRemoteNG/Tools/MouseClickSimulator.cs b/mRemoteNG/Tools/MouseClickSimulator.cs
index ca65b6b0c..49fbc4d12 100644
--- a/mRemoteNG/Tools/MouseClickSimulator.cs
+++ b/mRemoteNG/Tools/MouseClickSimulator.cs
@@ -12,9 +12,9 @@ namespace mRemoteNG.Tools
public static void Click(Control controlToClick, Point currentMousePosition)
{
// Simulate a mouse event since one wasn't generated by Windows
- var clientMousePosition = controlToClick.PointToClient(currentMousePosition);
- var tempWLow = clientMousePosition.X;
- var tempWHigh = clientMousePosition.Y;
+ Point clientMousePosition = controlToClick.PointToClient(currentMousePosition);
+ int tempWLow = clientMousePosition.X;
+ int tempWHigh = clientMousePosition.Y;
NativeMethods.SendMessage(controlToClick.Handle, NativeMethods.WM_LBUTTONDOWN,
(IntPtr)NativeMethods.MK_LBUTTON,
(IntPtr)NativeMethods.MAKELPARAM(ref tempWLow, ref tempWHigh));
diff --git a/mRemoteNG/Tools/NotificationAreaIcon.cs b/mRemoteNG/Tools/NotificationAreaIcon.cs
index 719ba217b..205207bcf 100644
--- a/mRemoteNG/Tools/NotificationAreaIcon.cs
+++ b/mRemoteNG/Tools/NotificationAreaIcon.cs
@@ -32,9 +32,9 @@ namespace mRemoteNG.Tools
Image = Properties.Resources.ASPWebSite_16x
};
- var cMenSep1 = new ToolStripSeparator();
+ ToolStripSeparator cMenSep1 = new();
- var cMenExit = new ToolStripMenuItem {Text = Language.Exit};
+ ToolStripMenuItem cMenExit = new() { Text = Language.Exit};
cMenExit.Click += cMenExit_Click;
_cMen = new ContextMenuStrip
@@ -82,7 +82,7 @@ namespace mRemoteNG.Tools
{
if (e.Button != MouseButtons.Right) return;
_cMenCons.DropDownItems.Clear();
- var menuItemsConverter = new ConnectionsTreeToMenuItemsConverter
+ ConnectionsTreeToMenuItemsConverter menuItemsConverter = new()
{
MouseUpEventHandler = ConMenItem_MouseUp
};
diff --git a/mRemoteNG/Tools/Optional.cs b/mRemoteNG/Tools/Optional.cs
index 37080bb9f..46e4ebf95 100644
--- a/mRemoteNG/Tools/Optional.cs
+++ b/mRemoteNG/Tools/Optional.cs
@@ -53,7 +53,7 @@ namespace mRemoteNG.Tools
///
/// Returns an empty
///
- public static Optional Empty => new Optional();
+ public static Optional Empty => new();
#region IEnumerable
@@ -81,8 +81,8 @@ namespace mRemoteNG.Tools
///
public int CompareTo(Optional other)
{
- var otherHasAnything = other.Any();
- var thisHasAnything = _optional.Length > 0;
+ bool otherHasAnything = other.Any();
+ bool thisHasAnything = _optional.Length > 0;
// both are empty, equivalent value
if (!thisHasAnything && !otherHasAnything)
@@ -109,7 +109,7 @@ namespace mRemoteNG.Tools
if (ReferenceEquals(this, obj))
return true;
- var objAsOptional = obj as Optional;
+ Optional objAsOptional = obj as Optional;
if (objAsOptional != null)
return Equals(objAsOptional);
@@ -121,8 +121,8 @@ namespace mRemoteNG.Tools
private bool Equals(Optional other)
{
- var otherObj = other.FirstOrDefault();
- var thisObj = _optional.FirstOrDefault();
+ T otherObj = other.FirstOrDefault();
+ T thisObj = _optional.FirstOrDefault();
if (thisObj == null && otherObj == null)
return true;
if (thisObj == null)
diff --git a/mRemoteNG/Tools/PortScanner.cs b/mRemoteNG/Tools/PortScanner.cs
index a3cd6b9c6..4ec5f7eb7 100644
--- a/mRemoteNG/Tools/PortScanner.cs
+++ b/mRemoteNG/Tools/PortScanner.cs
@@ -16,10 +16,10 @@ namespace mRemoteNG.Tools
[SupportedOSPlatform("windows")]
public class PortScanner
{
- private readonly List _ipAddresses = new List();
- private readonly List