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 _ports = new List(); + private readonly List _ipAddresses = []; + private readonly List _ports = []; private Thread _scanThread; - private readonly List _scannedHosts = new List(); + private readonly List _scannedHosts = []; private readonly int _timeoutInMilliseconds; #region Public Methods @@ -31,11 +31,11 @@ namespace mRemoteNG.Tools int timeoutInMilliseconds = 5000, bool checkDefaultPortsOnly = false) { - var ipAddressStart = IpAddressMin(ipAddress1, ipAddress2); - var ipAddressEnd = IpAddressMax(ipAddress1, ipAddress2); + IPAddress ipAddressStart = IpAddressMin(ipAddress1, ipAddress2); + IPAddress ipAddressEnd = IpAddressMax(ipAddress1, ipAddress2); - var portStart = Math.Min(port1, port2); - var portEnd = Math.Max(port1, port2); + int portStart = Math.Min(port1, port2); + int portEnd = Math.Max(port1, port2); // if only one port was specified, just scan the one port... if (portStart == 0) @@ -55,7 +55,7 @@ namespace mRemoteNG.Tools }); else { - for (var port = portStart; port <= portEnd; port++) + for (int port = portStart; port <= portEnd; port++) { _ports.Add(port); } @@ -80,7 +80,7 @@ namespace mRemoteNG.Tools public void StopScan() { - foreach (var p in _pings) + foreach (Ping p in _pings) { p.SendAsyncCancel(); } @@ -93,7 +93,7 @@ namespace mRemoteNG.Tools { try { - var tcpClient = new TcpClient(hostname, Convert.ToInt32(port)); + TcpClient tcpClient = new(hostname, Convert.ToInt32(port)); tcpClient.Close(); return true; } @@ -108,7 +108,7 @@ namespace mRemoteNG.Tools #region Private Methods private int _hostCount; - private readonly List _pings = new List(); + private readonly List _pings = []; private void ScanAsync() { @@ -116,11 +116,11 @@ namespace mRemoteNG.Tools { _hostCount = 0; Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Tools.PortScan: Starting scan of {_ipAddresses.Count} hosts...", true); - foreach (var ipAddress in _ipAddresses) + foreach (IPAddress ipAddress in _ipAddresses) { RaiseBeginHostScanEvent(ipAddress); - var pingSender = new Ping(); + Ping pingSender = new(); _pings.Add(pingSender); try @@ -146,11 +146,11 @@ namespace mRemoteNG.Tools private void PingSender_PingCompleted(object sender, PingCompletedEventArgs e) { // used for clean up later... - var p = (Ping)sender; + Ping p = (Ping)sender; // UserState is the IP Address - var ip = e.UserState.ToString(); - var scanHost = new ScanHost(ip); + string ip = e.UserState.ToString(); + ScanHost scanHost = new(ip); _hostCount++; Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, @@ -195,12 +195,12 @@ namespace mRemoteNG.Tools scanHost.HostName = scanHost.HostIp; } - foreach (var port in _ports) + foreach (int port in _ports) { bool isPortOpen; try { - var tcpClient = new TcpClient(ip, port); + TcpClient tcpClient = new(ip, port); isPortOpen = true; scanHost.OpenPorts.Add(port); tcpClient.Close(); @@ -253,7 +253,7 @@ namespace mRemoteNG.Tools p.PingCompleted -= PingSender_PingCompleted; p.Dispose(); - var h = string.IsNullOrEmpty(scanHost.HostName) ? "HostNameNotFound" : scanHost.HostName; + string h = string.IsNullOrEmpty(scanHost.HostName) ? "HostNameNotFound" : scanHost.HostName; Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Tools.PortScan: Scan of {scanHost.HostIp} ({h}) complete.", true); @@ -266,16 +266,16 @@ namespace mRemoteNG.Tools private static IEnumerable IpAddressArrayFromRange(IPAddress ipAddress1, IPAddress ipAddress2) { - var startIpAddress = IpAddressMin(ipAddress1, ipAddress2); - var endIpAddress = IpAddressMax(ipAddress1, ipAddress2); + IPAddress startIpAddress = IpAddressMin(ipAddress1, ipAddress2); + IPAddress endIpAddress = IpAddressMax(ipAddress1, ipAddress2); - var startAddress = IpAddressToInt32(startIpAddress); - var endAddress = IpAddressToInt32(endIpAddress); - var addressCount = endAddress - startAddress; + int startAddress = IpAddressToInt32(startIpAddress); + int endAddress = IpAddressToInt32(endIpAddress); + int addressCount = endAddress - startAddress; - var addressArray = new IPAddress[addressCount + 1]; - var index = 0; - for (var address = startAddress; address <= endAddress; address++) + IPAddress[] addressArray = new IPAddress[addressCount + 1]; + int index = 0; + for (int address = startAddress; address <= endAddress; address++) { addressArray[index] = IpAddressFromInt32(address); index++; @@ -306,7 +306,7 @@ namespace mRemoteNG.Tools throw (new ArgumentException("ipAddress")); } - var addressBytes = ipAddress.GetAddressBytes(); // in network order (big-endian) + byte[] addressBytes = ipAddress.GetAddressBytes(); // in network order (big-endian) if (BitConverter.IsLittleEndian) { Array.Reverse(addressBytes); // to host order (little-endian) @@ -319,7 +319,7 @@ namespace mRemoteNG.Tools private static IPAddress IpAddressFromInt32(int ipAddress) { - var addressBytes = BitConverter.GetBytes(ipAddress); // in host order + byte[] addressBytes = BitConverter.GetBytes(ipAddress); // in host order if (BitConverter.IsLittleEndian) { Array.Reverse(addressBytes); // to network order (big-endian) diff --git a/mRemoteNG/Tools/ProcessController.cs b/mRemoteNG/Tools/ProcessController.cs index de655f2e7..ecfa6921f 100644 --- a/mRemoteNG/Tools/ProcessController.cs +++ b/mRemoteNG/Tools/ProcessController.cs @@ -35,11 +35,11 @@ namespace mRemoteNG.Tools if (Handle == IntPtr.Zero) return false; - var controlHandle = GetControlHandle(className, text); + IntPtr controlHandle = GetControlHandle(className, text); if (controlHandle == IntPtr.Zero) return false; - var nCmdShow = visible ? NativeMethods.SW_SHOW : NativeMethods.SW_HIDE; + uint nCmdShow = visible ? NativeMethods.SW_SHOW : NativeMethods.SW_HIDE; NativeMethods.ShowWindow(controlHandle, (int)nCmdShow); return true; } @@ -49,11 +49,11 @@ namespace mRemoteNG.Tools if (Process == null || Process.HasExited || Handle == IntPtr.Zero) return false; - var controlHandle = GetControlHandle(className, oldText); + IntPtr controlHandle = GetControlHandle(className, oldText); if (controlHandle == IntPtr.Zero) return false; - var result = NativeMethods.SendMessage(controlHandle, NativeMethods.WM_SETTEXT, (IntPtr)0, + IntPtr result = NativeMethods.SendMessage(controlHandle, NativeMethods.WM_SETTEXT, (IntPtr)0, new StringBuilder(newText)); return result.ToInt32() == NativeMethods.TRUE; } @@ -63,11 +63,11 @@ namespace mRemoteNG.Tools if (Process == null || Process.HasExited || Handle == IntPtr.Zero) return false; - var listBoxHandle = GetControlHandle("ListBox"); + IntPtr listBoxHandle = GetControlHandle("ListBox"); if (listBoxHandle == IntPtr.Zero) return false; - var result = NativeMethods.SendMessage(listBoxHandle, NativeMethods.LB_SELECTSTRING, (IntPtr)(-1), + IntPtr result = NativeMethods.SendMessage(listBoxHandle, NativeMethods.LB_SELECTSTRING, (IntPtr)(-1), new StringBuilder(itemText)); return result.ToInt32() != NativeMethods.LB_ERR; } @@ -77,11 +77,11 @@ namespace mRemoteNG.Tools if (Process == null || Process.HasExited || Handle == IntPtr.Zero) return false; - var buttonHandle = GetControlHandle("Button", text); + IntPtr buttonHandle = GetControlHandle("Button", text); if (buttonHandle == IntPtr.Zero) return false; - var buttonControlId = NativeMethods.GetDlgCtrlID(buttonHandle); + int buttonControlId = NativeMethods.GetDlgCtrlID(buttonHandle); NativeMethods.SendMessage(Handle, NativeMethods.WM_COMMAND, (IntPtr)buttonControlId, buttonHandle); return true; @@ -98,9 +98,9 @@ namespace mRemoteNG.Tools #region Protected Fields - private readonly Process Process = new Process(); + private readonly Process Process = new(); private IntPtr Handle = IntPtr.Zero; - private List Controls = new List(); + private List Controls = []; #endregion @@ -115,7 +115,7 @@ namespace mRemoteNG.Tools Process.WaitForInputIdle(Properties.OptionsAdvancedPage.Default.MaxPuttyWaitTime * 1000); Handle = IntPtr.Zero; - var startTicks = Environment.TickCount; + int startTicks = Environment.TickCount; while (Handle == IntPtr.Zero && Environment.TickCount < startTicks + (Properties.OptionsAdvancedPage.Default.MaxPuttyWaitTime * 1000)) { @@ -137,13 +137,13 @@ namespace mRemoteNG.Tools if (Controls.Count == 0) { - var windowEnumerator = new EnumWindows(); + EnumWindows windowEnumerator = new(); Controls = windowEnumerator.EnumChildWindows(Handle); } - var stringBuilder = new StringBuilder(); - var controlHandle = IntPtr.Zero; - foreach (var control in Controls) + StringBuilder stringBuilder = new(); + IntPtr controlHandle = IntPtr.Zero; + foreach (IntPtr control in Controls) { NativeMethods.GetClassName(control, stringBuilder, stringBuilder.Capacity); if (stringBuilder.ToString() != className) continue; diff --git a/mRemoteNG/Tools/PropertyGridCommandSite.cs b/mRemoteNG/Tools/PropertyGridCommandSite.cs index 8dfb7043c..ad1761332 100644 --- a/mRemoteNG/Tools/PropertyGridCommandSite.cs +++ b/mRemoteNG/Tools/PropertyGridCommandSite.cs @@ -20,29 +20,29 @@ namespace mRemoteNG.Tools { get { - var objectVerbs = new DesignerVerbCollection(); + DesignerVerbCollection objectVerbs = new(); // ReSharper disable VBPossibleMistakenCallToGetType.2 - var methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); + MethodInfo[] methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); // ReSharper restore VBPossibleMistakenCallToGetType.2 - foreach (var method in methods) + foreach (MethodInfo method in methods) { - var commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); + object[] commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); if (commandAttributes.Length == 0) { continue; } - var commandAttribute = (CommandAttribute)commandAttributes[0]; + CommandAttribute commandAttribute = (CommandAttribute)commandAttributes[0]; if (!commandAttribute.Command) { continue; } - var displayName = method.Name; - var displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); + string displayName = method.Name; + object[] displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); if (displayNameAttributes.Length != 0) { - var displayNameAttribute = (DisplayNameAttribute)displayNameAttributes[0]; + DisplayNameAttribute displayNameAttribute = (DisplayNameAttribute)displayNameAttributes[0]; if (!string.IsNullOrEmpty(displayNameAttribute.DisplayName)) { displayName = displayNameAttribute.DisplayName; @@ -58,34 +58,34 @@ namespace mRemoteNG.Tools private void VerbEventHandler(object sender, EventArgs e) { - var verb = sender as DesignerVerb; + DesignerVerb verb = sender as DesignerVerb; if (verb == null) { return; } // ReSharper disable VBPossibleMistakenCallToGetType.2 - var methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); + MethodInfo[] methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); // ReSharper restore VBPossibleMistakenCallToGetType.2 - foreach (var method in methods) + foreach (MethodInfo method in methods) { - var commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); + object[] commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); if (commandAttributes.Length == 0) { continue; } - var commandAttribute = (CommandAttribute)commandAttributes[0]; + CommandAttribute commandAttribute = (CommandAttribute)commandAttributes[0]; if (!commandAttribute.Command) { continue; } - var displayName = method.Name; - var displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); + string displayName = method.Name; + object[] displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); if (displayNameAttributes.Length != 0) { - var displayNameAttribute = (DisplayNameAttribute)displayNameAttributes[0]; + DisplayNameAttribute displayNameAttribute = (DisplayNameAttribute)displayNameAttributes[0]; if (!string.IsNullOrEmpty(displayNameAttribute.DisplayName)) { displayName = displayNameAttribute.DisplayName; diff --git a/mRemoteNG/Tools/PuttyProcessController.cs b/mRemoteNG/Tools/PuttyProcessController.cs index 52b17df1d..911096693 100644 --- a/mRemoteNG/Tools/PuttyProcessController.cs +++ b/mRemoteNG/Tools/PuttyProcessController.cs @@ -9,7 +9,7 @@ namespace mRemoteNG.Tools { public bool Start(CommandLineArguments arguments = null) { - var filename = Properties.OptionsAdvancedPage.Default.UseCustomPuttyPath ? Properties.OptionsAdvancedPage.Default.CustomPuttyPath : App.Info.GeneralAppInfo.PuttyPath; + string filename = Properties.OptionsAdvancedPage.Default.UseCustomPuttyPath ? Properties.OptionsAdvancedPage.Default.CustomPuttyPath : App.Info.GeneralAppInfo.PuttyPath; return Start(filename, arguments); } } diff --git a/mRemoteNG/Tools/ReconnectGroup.cs b/mRemoteNG/Tools/ReconnectGroup.cs index fae084d47..7dbd0fa30 100644 --- a/mRemoteNG/Tools/ReconnectGroup.cs +++ b/mRemoteNG/Tools/ReconnectGroup.cs @@ -32,7 +32,7 @@ namespace mRemoteNG.Tools { if (pbServerStatus.InvokeRequired) { - var d = new SetStatusImageCB(SetStatusImage); + SetStatusImageCB d = new(SetStatusImage); ParentForm?.Invoke(d, new object[] {Img}); } else @@ -64,7 +64,7 @@ namespace mRemoteNG.Tools { if (chkReconnectWhenReady.InvokeRequired) { - var d = new SetCheckboxCB(SetCheckbox); + SetCheckboxCB d = new(SetCheckbox); ParentForm?.Invoke(d, new object[] {Val}); } else @@ -114,7 +114,7 @@ namespace mRemoteNG.Tools { if (InvokeRequired) { - var d = new DisposeReconnectGroupCB(DisposeReconnectGroup); + DisposeReconnectGroupCB d = new(DisposeReconnectGroup); ParentForm?.Invoke(d); } else diff --git a/mRemoteNG/Tools/SSHTunnelTypeConverter.cs b/mRemoteNG/Tools/SSHTunnelTypeConverter.cs index f537cc3e7..e94d93b12 100644 --- a/mRemoteNG/Tools/SSHTunnelTypeConverter.cs +++ b/mRemoteNG/Tools/SSHTunnelTypeConverter.cs @@ -15,7 +15,7 @@ namespace mRemoteNG.Tools { get { - var sshTunnelList = new List {string.Empty}; + List sshTunnelList = new() { string.Empty}; // Add a blank entry to signify that no external tool is selected sshTunnelList.AddRange(GetSshConnectionNames(Runtime.ConnectionsService.ConnectionTreeModel.RootNodes)); @@ -26,8 +26,8 @@ namespace mRemoteNG.Tools // recursively traverse the connection tree to find all ConnectionInfo s of type SSH private static IEnumerable GetSshConnectionNames(IEnumerable rootnodes) { - var result = new List(); - foreach (var node in rootnodes) + List result = new(); + foreach (ConnectionInfo node in rootnodes) if (node is ContainerInfo container) { result.AddRange(GetSshConnectionNames(container.Children)); diff --git a/mRemoteNG/Tools/ScanHost.cs b/mRemoteNG/Tools/ScanHost.cs index 6c77f0271..5fe506ad0 100644 --- a/mRemoteNG/Tools/ScanHost.cs +++ b/mRemoteNG/Tools/ScanHost.cs @@ -58,8 +58,8 @@ namespace mRemoteNG.Tools public ScanHost(string host) { HostIp = host; - OpenPorts = new ArrayList(); - ClosedPorts = new ArrayList(); + OpenPorts = []; + ClosedPorts = []; } public override string ToString() @@ -107,7 +107,7 @@ namespace mRemoteNG.Tools { get { - var strOpen = ""; + string strOpen = ""; foreach (int p in OpenPorts) { strOpen += p + ", "; @@ -121,7 +121,7 @@ namespace mRemoteNG.Tools { get { - var strClosed = ""; + string strClosed = ""; foreach (int p in ClosedPorts) { strClosed += p + ", "; diff --git a/mRemoteNG/Tools/Tools.WindowPlacement.cs b/mRemoteNG/Tools/Tools.WindowPlacement.cs index 3c07d2f8e..1a5721ff1 100644 --- a/mRemoteNG/Tools/Tools.WindowPlacement.cs +++ b/mRemoteNG/Tools/Tools.WindowPlacement.cs @@ -60,7 +60,7 @@ namespace mRemoteNG.Tools throw (new NullReferenceException("WindowPlacement.Form is not set.")); } - NativeMethods.WINDOWPLACEMENT windowPlacement = new NativeMethods.WINDOWPLACEMENT(); + NativeMethods.WINDOWPLACEMENT windowPlacement = new(); windowPlacement.length = (uint)Marshal.SizeOf(windowPlacement); try { diff --git a/mRemoteNG/Tools/WindowsRegistry/WindowsRegistry.cs b/mRemoteNG/Tools/WindowsRegistry/WindowsRegistry.cs index 45c2d95fd..c7c00f8e1 100644 --- a/mRemoteNG/Tools/WindowsRegistry/WindowsRegistry.cs +++ b/mRemoteNG/Tools/WindowsRegistry/WindowsRegistry.cs @@ -27,7 +27,7 @@ namespace mRemoteNG.Tools.WindowsRegistry throw new ArgumentException("Unknown or unsupported RegistryHive value.", nameof(hive)); path.ThrowIfNull(nameof(path)); - using (var key = OpenSubKey(hive, path)) + using (DisposableOptional key = OpenSubKey(hive, path)) { return key.Any() ? key.First().GetSubKeyNames() @@ -62,12 +62,12 @@ namespace mRemoteNG.Tools.WindowsRegistry path.ThrowIfNull(nameof(path)); name.ThrowIfNull(nameof(name)); - using (var key = OpenSubKey(hive, path)) + using (DisposableOptional key = OpenSubKey(hive, path)) { if (!key.Any()) return null; - var keyValue = key.First().GetValue(name); + object keyValue = key.First().GetValue(name); if (keyValue == null) return null; @@ -87,7 +87,7 @@ namespace mRemoteNG.Tools.WindowsRegistry /// The boolean value of the specified property or the default value if not found or cannot be parsed. public bool GetBoolValue(RegistryHive hive, string path, string propertyName, bool defaultValue = false) { - var value = GetPropertyValue(hive, path, propertyName); + string value = GetPropertyValue(hive, path, propertyName); if (!string.IsNullOrEmpty(value)) { @@ -110,7 +110,7 @@ namespace mRemoteNG.Tools.WindowsRegistry /// The DWORD value from the Registry, or the specified default value. public int GetDwordValue(RegistryHive hive, string path, string propertyName, int defaultValue = 0) { - var value = GetPropertyValue(hive, path, propertyName); + string value = GetPropertyValue(hive, path, propertyName); if (int.TryParse(value, out int intValue)) { @@ -153,7 +153,7 @@ namespace mRemoteNG.Tools.WindowsRegistry { if (subKey != null) { - var value = subKey.GetValue(key.Name); + object value = subKey.GetValue(key.Name); if (value != null) key.Value = value.ToString(); @@ -177,7 +177,7 @@ namespace mRemoteNG.Tools.WindowsRegistry throw new ArgumentException("Unknown or unsupported RegistryHive value.", nameof(hive)); path.ThrowIfNull(nameof(path)); - List list = new List(); + List list = []; using (RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default), key = baseKey.OpenSubKey(path)) { if (key != null) diff --git a/mRemoteNG/Tools/WindowsRegistry/WindowsRegistryAdvanced.cs b/mRemoteNG/Tools/WindowsRegistry/WindowsRegistryAdvanced.cs index 928429566..d019d0a30 100644 --- a/mRemoteNG/Tools/WindowsRegistry/WindowsRegistryAdvanced.cs +++ b/mRemoteNG/Tools/WindowsRegistry/WindowsRegistryAdvanced.cs @@ -23,7 +23,7 @@ namespace mRemoteNG.Tools.WindowsRegistry public WindowsRegistryKeyInteger GetInteger(RegistryHive hive, string path, string propertyName, int? defaultValue = null) { // Retrieve the Windows Registry key - var key = GetWindowsRegistryKey(hive, path, propertyName); + WindowsRegistryKey key = GetWindowsRegistryKey(hive, path, propertyName); // Create a WindowsRegistryKeyInteger instance and initialize it from the retrieved key WindowsRegistryKeyInteger IntKey = new(); @@ -45,7 +45,7 @@ namespace mRemoteNG.Tools.WindowsRegistry public WindowsRegistryKeyString GetString(RegistryHive hive, string path, string propertyName, string defaultValue = null) { // Retrieve the Windows Registry key - var key = GetWindowsRegistryKey(hive, path, propertyName); + WindowsRegistryKey key = GetWindowsRegistryKey(hive, path, propertyName); // Create a WindowsRegistryKeyString instance and initialize it from the retrieved key WindowsRegistryKeyString StrKey = new(); @@ -66,12 +66,14 @@ namespace mRemoteNG.Tools.WindowsRegistry public WindowsRegistryKeyString GetStringValidated(RegistryHive hive, string path, string propertyName, string[] allowedValues, bool caseSensitive = false, string defaultValue = null) { // Retrieve the Windows Registry key - var key = GetWindowsRegistryKey(hive, path, propertyName); + WindowsRegistryKey key = GetWindowsRegistryKey(hive, path, propertyName); // Create a WindowsRegistryKeyString instance and initialize it from the retrieved key - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = allowedValues; - StrKey.IsCaseSensitiveValidation = caseSensitive; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = allowedValues, + IsCaseSensitiveValidation = caseSensitive + }; StrKey.ConvertFromWindowsRegistryKey(key, defaultValue); return StrKey; @@ -102,7 +104,7 @@ namespace mRemoteNG.Tools.WindowsRegistry public WindowsRegistryKeyBoolean GetBoolean(RegistryHive hive, string path, string propertyName, bool? defaultValue = null) { // Retrieve the Windows Registry key - var key = GetWindowsRegistryKey(hive, path, propertyName); + WindowsRegistryKey key = GetWindowsRegistryKey(hive, path, propertyName); // Create a WindowsRegistryKeyBoolean instance and initialize it from the retrieved key WindowsRegistryKeyBoolean boolKey = new (); diff --git a/mRemoteNG/Tree/ClickHandlers/ExpandNodeClickHandler.cs b/mRemoteNG/Tree/ClickHandlers/ExpandNodeClickHandler.cs index 41b14f130..7e7977c3f 100644 --- a/mRemoteNG/Tree/ClickHandlers/ExpandNodeClickHandler.cs +++ b/mRemoteNG/Tree/ClickHandlers/ExpandNodeClickHandler.cs @@ -19,7 +19,7 @@ namespace mRemoteNG.Tree.ClickHandlers public void Execute(ConnectionInfo clickedNode) { - var clickedNodeAsContainer = clickedNode as ContainerInfo; + ContainerInfo clickedNodeAsContainer = clickedNode as ContainerInfo; if (clickedNodeAsContainer == null) return; _connectionTree.ToggleExpansion(clickedNodeAsContainer); } diff --git a/mRemoteNG/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs b/mRemoteNG/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs index 327b0bde7..34ee9bc9e 100644 --- a/mRemoteNG/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs +++ b/mRemoteNG/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs @@ -15,7 +15,7 @@ namespace mRemoteNG.Tree.ClickHandlers { if (clickedNode == null) throw new ArgumentNullException(nameof(clickedNode)); - foreach (var handler in ClickHandlers) + foreach (ITreeNodeClickHandler handler in ClickHandlers) { handler.Execute(clickedNode); } diff --git a/mRemoteNG/Tree/ConnectionTreeDragAndDropHandler.cs b/mRemoteNG/Tree/ConnectionTreeDragAndDropHandler.cs index a70d802a8..480aa0106 100644 --- a/mRemoteNG/Tree/ConnectionTreeDragAndDropHandler.cs +++ b/mRemoteNG/Tree/ConnectionTreeDragAndDropHandler.cs @@ -23,7 +23,7 @@ namespace mRemoteNG.Tree public void HandleEvent_ModelDropped(object sender, ModelDropEventArgs e) { if (!(e.TargetModel is ConnectionInfo dropTarget)) return; - foreach(var dropSource in e.SourceModels.Cast()) + foreach(ConnectionInfo dropSource in e.SourceModels.Cast()) { DropModel(dropSource, dropTarget, e.DropTargetLocation); } @@ -76,9 +76,9 @@ namespace mRemoteNG.Tree _enableFeedback = true; _currentFeedbackColor = DropDeniedFeedbackColor; _infoMessage = null; - foreach (var dropSource in e.SourceModels.Cast()) + foreach (ConnectionInfo dropSource in e.SourceModels.Cast()) { - var dropTarget = e.TargetModel as ConnectionInfo; + ConnectionInfo dropTarget = e.TargetModel as ConnectionInfo; e.Effect = CanModelDrop(dropSource, dropTarget, e.DropTargetLocation); e.InfoMessage = _infoMessage; @@ -92,7 +92,7 @@ namespace mRemoteNG.Tree ConnectionInfo dropTarget, DropTargetLocation dropTargetLocation) { - var dragDropEffect = DragDropEffects.None; + DragDropEffects dragDropEffect = DragDropEffects.None; if (!NodeIsDraggable(dropSource)) { _infoMessage = Language.NodeNotDraggable; @@ -115,7 +115,7 @@ namespace mRemoteNG.Tree private DragDropEffects HandleCanDropOnItem(ConnectionInfo dropSource, ConnectionInfo dropTarget) { - var dragDropEffect = DragDropEffects.None; + DragDropEffects dragDropEffect = DragDropEffects.None; if (dropTarget is ContainerInfo && !(dropTarget is RootPuttySessionsNodeInfo)) { if (!IsValidDrag(dropSource, dropTarget)) return dragDropEffect; @@ -132,7 +132,7 @@ namespace mRemoteNG.Tree private DragDropEffects HandleCanDropBetweenItems(ConnectionInfo dropSource, ConnectionInfo dropTarget) { - var dragDropEffect = DragDropEffects.None; + DragDropEffects dragDropEffect = DragDropEffects.None; if (AncestorDraggingOntoChild(dropSource, dropTarget)) _infoMessage = Language.NodeCannotDragParentOnChild; else if (dropTarget is PuttySessionInfo || dropTarget is RootNodeInfo) @@ -148,7 +148,7 @@ namespace mRemoteNG.Tree private bool IsValidDrag(ConnectionInfo dropSource, ConnectionInfo dropTarget) { - var validDrag = false; + bool validDrag = false; if (NodeDraggingOntoSelf(dropSource, dropTarget)) _infoMessage = Language.NodeCannotDragOnSelf; else if (AncestorDraggingOntoChild(dropSource, dropTarget)) diff --git a/mRemoteNG/Tree/ConnectionTreeModel.cs b/mRemoteNG/Tree/ConnectionTreeModel.cs index 676ef130e..95f9a53e3 100644 --- a/mRemoteNG/Tree/ConnectionTreeModel.cs +++ b/mRemoteNG/Tree/ConnectionTreeModel.cs @@ -13,7 +13,7 @@ namespace mRemoteNG.Tree [SupportedOSPlatform("windows")] public sealed class ConnectionTreeModel : INotifyCollectionChanged, INotifyPropertyChanged { - public List RootNodes { get; } = new List(); + public List RootNodes { get; } = []; public void AddRootNode(ContainerInfo rootNode) { @@ -39,8 +39,8 @@ namespace mRemoteNG.Tree public IReadOnlyList GetRecursiveChildList() { - var list = new List(); - foreach (var rootNode in RootNodes) + List list = new(); + foreach (ContainerInfo rootNode in RootNodes) { list.AddRange(GetRecursiveChildList(rootNode)); } diff --git a/mRemoteNG/Tree/NodeSearcher.cs b/mRemoteNG/Tree/NodeSearcher.cs index 655ab8bca..51782f9e1 100644 --- a/mRemoteNG/Tree/NodeSearcher.cs +++ b/mRemoteNG/Tree/NodeSearcher.cs @@ -24,9 +24,9 @@ namespace mRemoteNG.Tree { ResetMatches(); if (searchText == "") return Matches; - var nodes = _connectionTreeModel.GetRecursiveChildList(); - var searchTextLower = searchText.ToLowerInvariant(); - foreach (var node in nodes) + IReadOnlyList nodes = _connectionTreeModel.GetRecursiveChildList(); + string searchTextLower = searchText.ToLowerInvariant(); + foreach (ConnectionInfo node in nodes) { if (node.Name.ToLowerInvariant().Contains(searchTextLower) || node.Description.ToLowerInvariant().Contains(searchTextLower) || @@ -41,7 +41,7 @@ namespace mRemoteNG.Tree public ConnectionInfo NextMatch() { - var currentMatchIndex = Matches.IndexOf(CurrentMatch); + int currentMatchIndex = Matches.IndexOf(CurrentMatch); if (!CurrentMatchIsTheLastMatchInTheList()) CurrentMatch = Matches[currentMatchIndex + 1]; return CurrentMatch; @@ -49,13 +49,13 @@ namespace mRemoteNG.Tree private bool CurrentMatchIsTheLastMatchInTheList() { - var currentMatchIndex = Matches.IndexOf(CurrentMatch); + int currentMatchIndex = Matches.IndexOf(CurrentMatch); return currentMatchIndex >= Matches.Count - 1; } public ConnectionInfo PreviousMatch() { - var currentMatchIndex = Matches.IndexOf(CurrentMatch); + int currentMatchIndex = Matches.IndexOf(CurrentMatch); if (!CurrentMatchIsTheFirstMatchInTheList()) CurrentMatch = Matches[currentMatchIndex - 1]; return CurrentMatch; @@ -63,13 +63,13 @@ namespace mRemoteNG.Tree private bool CurrentMatchIsTheFirstMatchInTheList() { - var currentMatchIndex = Matches.IndexOf(CurrentMatch); + int currentMatchIndex = Matches.IndexOf(CurrentMatch); return currentMatchIndex <= 0; } private void ResetMatches() { - Matches = new List(); + Matches = []; CurrentMatch = null; } } diff --git a/mRemoteNG/Tree/PreviousSessionOpener.cs b/mRemoteNG/Tree/PreviousSessionOpener.cs index 111fe87f6..903c53069 100644 --- a/mRemoteNG/Tree/PreviousSessionOpener.cs +++ b/mRemoteNG/Tree/PreviousSessionOpener.cs @@ -21,15 +21,15 @@ namespace mRemoteNG.Tree public void Execute(IConnectionTree connectionTree) { - var connectionInfoList = connectionTree.GetRootConnectionNode().GetRecursiveChildList() + System.Collections.Generic.IEnumerable connectionInfoList = connectionTree.GetRootConnectionNode().GetRecursiveChildList() .Where(node => !(node is ContainerInfo)); - var previouslyOpenedConnections = connectionInfoList + System.Collections.Generic.IEnumerable previouslyOpenedConnections = connectionInfoList .Where(item => item.PleaseConnect && //ignore items that have already connected !_connectionInitiator.ActiveConnections.Contains(item.ConstantID)); - foreach (var connectionInfo in previouslyOpenedConnections) + foreach (ConnectionInfo connectionInfo in previouslyOpenedConnections) { _connectionInitiator.OpenConnection(connectionInfo); } diff --git a/mRemoteNG/Tree/PreviouslyOpenedFolderExpander.cs b/mRemoteNG/Tree/PreviouslyOpenedFolderExpander.cs index 6ba25e52f..d4099ba26 100644 --- a/mRemoteNG/Tree/PreviouslyOpenedFolderExpander.cs +++ b/mRemoteNG/Tree/PreviouslyOpenedFolderExpander.cs @@ -11,10 +11,10 @@ namespace mRemoteNG.Tree { public void Execute(IConnectionTree connectionTree) { - var rootNode = connectionTree.GetRootConnectionNode(); - var containerList = connectionTree.ConnectionTreeModel.GetRecursiveChildList(rootNode) + Root.RootNodeInfo rootNode = connectionTree.GetRootConnectionNode(); + System.Collections.Generic.IEnumerable containerList = connectionTree.ConnectionTreeModel.GetRecursiveChildList(rootNode) .OfType(); - var previouslyExpandedNodes = containerList.Where(container => container.IsExpanded); + System.Collections.Generic.IEnumerable previouslyExpandedNodes = containerList.Where(container => container.IsExpanded); connectionTree.ExpandedObjects = previouslyExpandedNodes; connectionTree.InvokeRebuildAll(true); } diff --git a/mRemoteNG/Tree/RootNodeExpander.cs b/mRemoteNG/Tree/RootNodeExpander.cs index ec6010af9..66d69d493 100644 --- a/mRemoteNG/Tree/RootNodeExpander.cs +++ b/mRemoteNG/Tree/RootNodeExpander.cs @@ -7,7 +7,7 @@ namespace mRemoteNG.Tree { public void Execute(IConnectionTree connectionTree) { - var rootConnectionNode = connectionTree.GetRootConnectionNode(); + Root.RootNodeInfo rootConnectionNode = connectionTree.GetRootConnectionNode(); connectionTree.InvokeExpand(rootConnectionNode); } } diff --git a/mRemoteNG/Tree/SelectedConnectionDeletionConfirmer.cs b/mRemoteNG/Tree/SelectedConnectionDeletionConfirmer.cs index 04bc87e3d..cbbf23fd7 100644 --- a/mRemoteNG/Tree/SelectedConnectionDeletionConfirmer.cs +++ b/mRemoteNG/Tree/SelectedConnectionDeletionConfirmer.cs @@ -22,7 +22,7 @@ namespace mRemoteNG.Tree if (deletionTarget == null) return false; - var deletionTargetAsContainer = deletionTarget as ContainerInfo; + ContainerInfo deletionTargetAsContainer = deletionTarget as ContainerInfo; if (deletionTargetAsContainer != null) return deletionTargetAsContainer.HasChildren() ? UserConfirmsNonEmptyFolderDeletion(deletionTargetAsContainer) @@ -32,25 +32,25 @@ namespace mRemoteNG.Tree private bool UserConfirmsEmptyFolderDeletion(AbstractConnectionRecord deletionTarget) { - var messagePrompt = string.Format(Language.ConfirmDeleteNodeFolder, deletionTarget.Name); + string messagePrompt = string.Format(Language.ConfirmDeleteNodeFolder, deletionTarget.Name); return PromptUser(messagePrompt); } private bool UserConfirmsNonEmptyFolderDeletion(AbstractConnectionRecord deletionTarget) { - var messagePrompt = string.Format(Language.ConfirmDeleteNodeFolderNotEmpty, deletionTarget.Name); + string messagePrompt = string.Format(Language.ConfirmDeleteNodeFolderNotEmpty, deletionTarget.Name); return PromptUser(messagePrompt); } private bool UserConfirmsConnectionDeletion(AbstractConnectionRecord deletionTarget) { - var messagePrompt = string.Format(Language.ConfirmDeleteNodeConnection, deletionTarget.Name); + string messagePrompt = string.Format(Language.ConfirmDeleteNodeConnection, deletionTarget.Name); return PromptUser(messagePrompt); } private bool PromptUser(string promptMessage) { - var msgBoxResponse = _confirmationFunc(promptMessage); + DialogResult msgBoxResponse = _confirmationFunc(promptMessage); return msgBoxResponse == DialogResult.Yes; } } diff --git a/mRemoteNG/UI/Controls/Adapters/CredentialRecordListAdaptor.cs b/mRemoteNG/UI/Controls/Adapters/CredentialRecordListAdaptor.cs index 38a26569e..472b7b9bf 100644 --- a/mRemoteNG/UI/Controls/Adapters/CredentialRecordListAdaptor.cs +++ b/mRemoteNG/UI/Controls/Adapters/CredentialRecordListAdaptor.cs @@ -23,9 +23,9 @@ namespace mRemoteNG.UI.Controls.Adapters _editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if (_editorService == null) return value; - var credentialManager = Runtime.CredentialProviderCatalog; + Credential.ICredentialRepositoryList credentialManager = Runtime.CredentialProviderCatalog; - var listBox = new CredentialRecordListBox(credentialManager.GetCredentialRecords()); + CredentialRecordListBox listBox = new(credentialManager.GetCredentialRecords()); listBox.SelectedValueChanged += ListBoxOnSelectedValueChanged; _editorService.DropDownControl(listBox); diff --git a/mRemoteNG/UI/Controls/ConnectionContextMenu.cs b/mRemoteNG/UI/Controls/ConnectionContextMenu.cs index dccb95f22..0538e9451 100644 --- a/mRemoteNG/UI/Controls/ConnectionContextMenu.cs +++ b/mRemoteNG/UI/Controls/ConnectionContextMenu.cs @@ -575,7 +575,7 @@ namespace mRemoteNG.UI.Controls _cMenTreeConnectWithOptionsConnectInFullscreen.Enabled = false; _cMenTreeConnectWithOptionsConnectToConsoleSession.Enabled = false; - var hasOpenConnections = containerInfo.Children.Any(child => child.OpenConnections.Count > 0); + bool hasOpenConnections = containerInfo.Children.Any(child => child.OpenConnections.Count > 0); _cMenTreeDisconnect.Enabled = hasOpenConnections; _cMenTreeToolsTransferFile.Enabled = false; @@ -655,7 +655,7 @@ namespace mRemoteNG.UI.Controls { foreach (ToolStripItem item in items) { - var menuItem = item as ToolStripMenuItem; + ToolStripMenuItem menuItem = item as ToolStripMenuItem; if (menuItem == null) { continue; @@ -677,7 +677,7 @@ namespace mRemoteNG.UI.Controls foreach (ExternalTool extA in Runtime.ExternalToolsService.ExternalTools) { - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Text = extA.DisplayName, Tag = extA, @@ -699,7 +699,7 @@ namespace mRemoteNG.UI.Controls private void ResetExternalAppMenu() { if (_cMenTreeToolsExternalApps.DropDownItems.Count <= 0) return; - for (var i = _cMenTreeToolsExternalApps.DropDownItems.Count - 1; i >= 0; i--) + for (int i = _cMenTreeToolsExternalApps.DropDownItems.Count - 1; i >= 0; i--) _cMenTreeToolsExternalApps.DropDownItems[i].Dispose(); _cMenTreeToolsExternalApps.DropDownItems.Clear(); @@ -709,7 +709,7 @@ namespace mRemoteNG.UI.Controls private void OnConnectClicked(object sender, EventArgs e) { - var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; + ContainerInfo selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) Runtime.ConnectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.DoNotJump); else @@ -718,7 +718,7 @@ namespace mRemoteNG.UI.Controls private void OnConnectToConsoleSessionClicked(object sender, EventArgs e) { - var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; + ContainerInfo selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) Runtime.ConnectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.UseConsoleSession | @@ -732,7 +732,7 @@ namespace mRemoteNG.UI.Controls private void OnDontConnectToConsoleSessionClicked(object sender, EventArgs e) { - var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; + ContainerInfo selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) Runtime.ConnectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.DontUseConsoleSession | @@ -745,7 +745,7 @@ namespace mRemoteNG.UI.Controls private void OnConnectInFullscreenClicked(object sender, EventArgs e) { - var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; + ContainerInfo selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) Runtime.ConnectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.Fullscreen | ConnectionInfo.Force.DoNotJump); @@ -756,7 +756,7 @@ namespace mRemoteNG.UI.Controls private void OnConnectWithNoCredentialsClick(object sender, EventArgs e) { - var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; + ContainerInfo selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) Runtime.ConnectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.NoCredentials); else @@ -765,7 +765,7 @@ namespace mRemoteNG.UI.Controls private void OnChoosePanelBeforeConnectingClicked(object sender, EventArgs e) { - var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; + ContainerInfo selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) Runtime.ConnectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.OverridePanel | @@ -778,7 +778,7 @@ namespace mRemoteNG.UI.Controls private void ConnectWithOptionsViewOnlyOnClick(object sender, EventArgs e) { - var connectionTarget = _connectionTree.SelectedNode as ContainerInfo + ConnectionInfo connectionTarget = _connectionTree.SelectedNode as ContainerInfo ?? _connectionTree.SelectedNode; Runtime.ConnectionInitiator.OpenConnection(connectionTarget, ConnectionInfo.Force.ViewOnly); } @@ -793,12 +793,12 @@ namespace mRemoteNG.UI.Controls try { if (connectionInfo == null) return; - var nodeAsContainer = connectionInfo as ContainerInfo; + ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo; if (nodeAsContainer != null) { - foreach (var child in nodeAsContainer.Children) + foreach (ConnectionInfo child in nodeAsContainer.Children) { - for (var i = 0; i <= child.OpenConnections.Count - 1; i++) + for (int i = 0; i <= child.OpenConnections.Count - 1; i++) { child.OpenConnections[i].Disconnect(); } @@ -806,7 +806,7 @@ namespace mRemoteNG.UI.Controls } else { - for (var i = 0; i <= connectionInfo.OpenConnections.Count - 1; i++) + for (int i = 0; i <= connectionInfo.OpenConnections.Count - 1; i++) { connectionInfo.OpenConnections[i].Disconnect(); } diff --git a/mRemoteNG/UI/Controls/ConnectionInfoPropertyGrid/ConnectionInfoPropertyGrid.cs b/mRemoteNG/UI/Controls/ConnectionInfoPropertyGrid/ConnectionInfoPropertyGrid.cs index 2a1d1faf3..7a3545093 100644 --- a/mRemoteNG/UI/Controls/ConnectionInfoPropertyGrid/ConnectionInfoPropertyGrid.cs +++ b/mRemoteNG/UI/Controls/ConnectionInfoPropertyGrid/ConnectionInfoPropertyGrid.cs @@ -24,7 +24,7 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid [SupportedOSPlatform("windows")] public partial class ConnectionInfoPropertyGrid : FilteredPropertyGrid.FilteredPropertyGrid { - private readonly Dictionary> _propertyCache = new Dictionary>(); + private readonly Dictionary> _propertyCache = []; private ConnectionInfo _selectedConnectionInfo; private PropertyMode _propertyMode; @@ -150,7 +150,7 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid .Select(property => property.Name) .ToArray(); - var strHide = new List(); + List strHide = new(); if (PropertyMode == PropertyMode.Connection) { @@ -198,11 +198,11 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid private IEnumerable GetPropertiesForGridObject(object currentGridObject) { - if (_propertyCache.TryGetValue(currentGridObject.GetType(), out var properties)) + if (_propertyCache.TryGetValue(currentGridObject.GetType(), out IEnumerable properties)) return properties; - var type = currentGridObject.GetType(); - var props = type.GetProperties(); + Type type = currentGridObject.GetType(); + PropertyInfo[] props = type.GetProperties(); _propertyCache.Add(type, props); return props; @@ -219,7 +219,7 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid private List SpecialExternalAddressProviderExclusions() { - var strHide = new List(); + List strHide = new(); // aws if (SelectedConnectionInfo.ExternalAddressProvider != ExternalAddressProvider.AmazonWebServices) @@ -232,7 +232,7 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid private List SpecialExternalCredentialProviderExclusions() { - var strHide = new List(); + List strHide = new(); if (SelectedConnectionInfo.ExternalCredentialProvider == ExternalCredentialProvider.None) { @@ -253,7 +253,7 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid /// private List SpecialRdpExclusions() { - var strHide = new List(); + List strHide = new(); if (SelectedConnectionInfo.RDPMinutesToIdleTimeout <= 0) { @@ -322,7 +322,7 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid private List SpecialVncExclusions() { - var strHide = new List(); + List strHide = new(); if (SelectedConnectionInfo.VNCAuthMode == ProtocolVNC.AuthMode.AuthVNC) { strHide.Add(nameof(AbstractConnectionRecord.Username)); @@ -372,8 +372,8 @@ namespace mRemoteNG.UI.Controls.ConnectionInfoPropertyGrid if (rootInfo.Password) { - var passwordName = Properties.OptionsDBsPage.Default.UseSQLServer ? Language.SQLServer.TrimEnd(':') : Path.GetFileName(Runtime.ConnectionsService.GetStartupConnectionFileName()); - var password = MiscTools.PasswordDialog(passwordName); + string passwordName = Properties.OptionsDBsPage.Default.UseSQLServer ? Language.SQLServer.TrimEnd(':') : Path.GetFileName(Runtime.ConnectionsService.GetStartupConnectionFileName()); + Optional password = MiscTools.PasswordDialog(passwordName); // operation cancelled, dont set a password if (!password.Any() || password.First().Length == 0) diff --git a/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTree.cs b/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTree.cs index ee9444385..169d27d17 100644 --- a/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTree.cs +++ b/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTree.cs @@ -25,13 +25,12 @@ namespace mRemoteNG.UI.Controls.ConnectionTree [SupportedOSPlatform("windows")] public partial class ConnectionTree : TreeListView, IConnectionTree { - private readonly ConnectionTreeDragAndDropHandler _dragAndDropHandler = new ConnectionTreeDragAndDropHandler(); + private readonly ConnectionTreeDragAndDropHandler _dragAndDropHandler = new(); private readonly PuttySessionsManager _puttySessionsManager = PuttySessionsManager.Instance; - private readonly StatusImageList _statusImageList = new StatusImageList(); + private readonly StatusImageList _statusImageList = new(); private ThemeManager _themeManager; - private readonly ConnectionTreeSearchTextFilter _connectionTreeSearchTextFilter = - new ConnectionTreeSearchTextFilter(); + private readonly ConnectionTreeSearchTextFilter _connectionTreeSearchTextFilter = new(); private bool _nodeInEditMode; private bool _allowEdit; @@ -44,13 +43,11 @@ namespace mRemoteNG.UI.Controls.ConnectionTree public IConfirm NodeDeletionConfirmer { get; set; } = new AlwaysConfirmYes(); - public IEnumerable PostSetupActions { get; set; } = new IConnectionTreeDelegate[0]; + public IEnumerable PostSetupActions { get; set; } = Array.Empty(); - public ITreeNodeClickHandler DoubleClickHandler { get; set; } = - new TreeNodeCompositeClickHandler(); + public ITreeNodeClickHandler DoubleClickHandler { get; set; } = new TreeNodeCompositeClickHandler(); - public ITreeNodeClickHandler SingleClickHandler { get; set; } = - new TreeNodeCompositeClickHandler(); + public ITreeNodeClickHandler SingleClickHandler { get; set; } = new TreeNodeCompositeClickHandler(); public ConnectionTreeModel ConnectionTreeModel { @@ -58,8 +55,10 @@ namespace mRemoteNG.UI.Controls.ConnectionTree set { if (_connectionTreeModel == value) + { return; - + } + UnregisterModelUpdateHandlers(_connectionTreeModel); _connectionTreeModel = value; PopulateTreeView(value); @@ -86,7 +85,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree if (!_themeManager.ActiveAndExtended) return; - var themePalette = _themeManager.ActiveTheme.ExtendedPalette; + ExtendedColorPalette themePalette = _themeManager.ActiveTheme.ExtendedPalette; BackColor = themePalette.getColor("TreeView_Background"); ForeColor = themePalette.getColor("TreeView_Foreground"); @@ -131,7 +130,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree { CanExpandGetter = item => { - var itemAsContainer = item as ContainerInfo; + ContainerInfo itemAsContainer = item as ContainerInfo; return itemAsContainer?.Children.Count > 0; }; ChildrenGetter = item => ((ContainerInfo)item).Children; @@ -149,20 +148,20 @@ namespace mRemoteNG.UI.Controls.ConnectionTree { Collapsed += (sender, args) => { - if (!(args.Model is ContainerInfo container)) return; + if (args.Model is not ContainerInfo container) return; container.IsExpanded = false; AutoResizeColumn(Columns[0]); }; Expanded += (sender, args) => { - if (!(args.Model is ContainerInfo container)) return; + if (args.Model is not ContainerInfo container) return; container.IsExpanded = true; AutoResizeColumn(Columns[0]); }; - SelectionChanged += tvConnections_AfterSelect; + SelectionChanged += TvConnections_AfterSelect; MouseDoubleClick += OnMouse_DoubleClick; MouseClick += OnMouse_SingleClick; - CellToolTipShowing += tvConnections_CellToolTipShowing; + CellToolTipShowing += TvConnections_CellToolTipShowing; ModelCanDrop += _dragAndDropHandler.HandleEvent_ModelCanDrop; ModelDropped += _dragAndDropHandler.HandleEvent_ModelDropped; BeforeLabelEdit += OnBeforeLabelEdit; @@ -180,23 +179,19 @@ namespace mRemoteNG.UI.Controls.ConnectionTree return; } - var longestIndentationAndTextWidth = int.MinValue; - var horizontalScrollOffset = LowLevelScrollPosition.X; + int longestIndentationAndTextWidth = int.MinValue; + int horizontalScrollOffset = LowLevelScrollPosition.X; const int padding = 10; - for (var i = 0; i < Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { - var rowIndentation = Items[i].Position.X; - var rowTextWidth = TextRenderer.MeasureText(Items[i].Text, Font).Width; + int rowIndentation = Items[i].Position.X; + int rowTextWidth = TextRenderer.MeasureText(Items[i].Text, Font).Width; - longestIndentationAndTextWidth = - Math.Max(rowIndentation + rowTextWidth, longestIndentationAndTextWidth); + longestIndentationAndTextWidth = Math.Max(rowIndentation + rowTextWidth, longestIndentationAndTextWidth); } - column.Width = longestIndentationAndTextWidth + - SmallImageSize.Width + - horizontalScrollOffset + - padding; + column.Width = longestIndentationAndTextWidth + SmallImageSize.Width + horizontalScrollOffset + padding; } private void PopulateTreeView(ConnectionTreeModel newModel) @@ -235,7 +230,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree { // for some reason property changed events are getting triggered twice for each changed property. should be just once. cant find source of duplication // Removed "TO DO" from above comment. Per #142 it apperas that this no longer occurs with ObjectListView 2.9.1 - var property = propertyChangedEventArgs.PropertyName; + string property = propertyChangedEventArgs.PropertyName; if (property != nameof(ConnectionInfo.Name) && property != nameof(ConnectionInfo.OpenConnections) && property != nameof(ConnectionInfo.Icon)) @@ -243,7 +238,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree return; } - if (!(sender is ConnectionInfo senderAsConnectionInfo)) + if (sender is not ConnectionInfo senderAsConnectionInfo) return; RefreshObject(senderAsConnectionInfo); @@ -252,7 +247,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree private void ExecutePostSetupActions() { - foreach (var action in PostSetupActions) + foreach (IConnectionTreeDelegate action in PostSetupActions) { action.Execute(this); } @@ -324,8 +319,8 @@ namespace mRemoteNG.UI.Controls.ConnectionTree ConnectionInfo parentNode = SelectedNode ?? GetRootConnectionNode(); DefaultConnectionInfo.Instance.SaveTo(newNode); DefaultConnectionInheritance.Instance.SaveTo(newNode.Inheritance); - var selectedContainer = parentNode as ContainerInfo; - var parent = selectedContainer ?? parentNode?.Parent; + ContainerInfo selectedContainer = parentNode as ContainerInfo; + ContainerInfo parent = selectedContainer ?? parentNode?.Parent; newNode.SetParent(parent); Expand(parent); SelectObject(newNode, true); @@ -339,11 +334,11 @@ namespace mRemoteNG.UI.Controls.ConnectionTree if (SelectedNode == null) return; - var selectedNodeType = SelectedNode.GetTreeNodeType(); + TreeNodeType selectedNodeType = SelectedNode.GetTreeNodeType(); if (selectedNodeType != TreeNodeType.Connection && selectedNodeType != TreeNodeType.Container) return; - var newNode = SelectedNode.Clone(); + ConnectionInfo newNode = SelectedNode.Clone(); SelectedNode.Parent.AddChildBelow(newNode, SelectedNode); newNode.Parent.SetChildBelow(newNode, SelectedNode); } @@ -372,7 +367,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree if (SelectedNode == null) return; - var textToCopy = SelectedNode.IsContainer ? SelectedNode.Name : SelectedNode.Hostname; + string textToCopy = SelectedNode.IsContainer ? SelectedNode.Name : SelectedNode.Hostname; if (string.IsNullOrEmpty(textToCopy)) return; @@ -382,8 +377,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree public void SortRecursive(ConnectionInfo sortTarget, ListSortDirection sortDirection) { - if (sortTarget == null) - sortTarget = GetRootConnectionNode(); + sortTarget ??= GetRootConnectionNode(); Runtime.ConnectionsService.BeginBatchingSaves(); @@ -429,8 +423,8 @@ namespace mRemoteNG.UI.Controls.ConnectionTree { // disable filtering if necessary. prevents RefreshObjects from // throwing an exception - var filteringEnabled = IsFiltering; - var filter = ModelFilter; + bool filteringEnabled = IsFiltering; + IModelFilter filter = ModelFilter; if (filteringEnabled) { ResetColumnFiltering(); @@ -451,7 +445,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree AutoResizeColumn(Columns[0]); } - private void tvConnections_AfterSelect(object sender, EventArgs e) + private void TvConnections_AfterSelect(object sender, EventArgs e) { try { @@ -459,9 +453,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace( - "tvConnections_AfterSelect (UI.Window.ConnectionTreeWindow) failed", - ex); + Runtime.MessageCollector.AddExceptionStackTrace("tvConnections_AfterSelect (UI.Window.ConnectionTreeWindow) failed", ex); } } @@ -469,9 +461,8 @@ namespace mRemoteNG.UI.Controls.ConnectionTree { if (mouseEventArgs.Clicks < 2) return; // ReSharper disable once NotAccessedVariable - OLVColumn column; - var listItem = GetItemAt(mouseEventArgs.X, mouseEventArgs.Y, out column); - if (!(listItem?.RowObject is ConnectionInfo clickedNode)) return; + OLVListItem listItem = GetItemAt(mouseEventArgs.X, mouseEventArgs.Y, out _); + if (listItem?.RowObject is not ConnectionInfo clickedNode) return; DoubleClickHandler.Execute(clickedNode); } @@ -479,13 +470,12 @@ namespace mRemoteNG.UI.Controls.ConnectionTree { if (mouseEventArgs.Clicks > 1) return; // ReSharper disable once NotAccessedVariable - OLVColumn column; - var listItem = GetItemAt(mouseEventArgs.X, mouseEventArgs.Y, out column); - if (!(listItem?.RowObject is ConnectionInfo clickedNode)) return; + OLVListItem listItem = GetItemAt(mouseEventArgs.X, mouseEventArgs.Y, out _); + if (listItem?.RowObject is not ConnectionInfo clickedNode) return; SingleClickHandler.Execute(clickedNode); } - private void tvConnections_CellToolTipShowing(object sender, ToolTipShowingEventArgs e) + private void TvConnections_CellToolTipShowing(object sender, ToolTipShowingEventArgs e) { try { @@ -496,7 +486,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree return; } - var nodeProducingTooltip = (ConnectionInfo)e.Model; + ConnectionInfo nodeProducingTooltip = (ConnectionInfo)e.Model; e.Text = nodeProducingTooltip.Description; } catch (Exception ex) @@ -509,7 +499,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree private void OnBeforeLabelEdit(object sender, LabelEditEventArgs e) { - if (_nodeInEditMode || !(sender is ConnectionTree)) + if (_nodeInEditMode || sender is not ConnectionTree) return; if (!_allowEdit || SelectedNode is PuttySessionInfo || SelectedNode is RootPuttySessionsNodeInfo) diff --git a/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs b/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs index f137de52b..c0195d7f2 100644 --- a/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs +++ b/mRemoteNG/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs @@ -15,7 +15,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree /// always be included in the output, regardless of matching /// the desired . /// - public List SpecialInclusionList { get; } = new List(); + public List SpecialInclusionList { get; } = []; public bool Filter(object modelObject) { @@ -25,7 +25,7 @@ namespace mRemoteNG.UI.Controls.ConnectionTree if (SpecialInclusionList.Contains(objectAsConnectionInfo)) return true; - var filterTextLower = FilterText.ToLowerInvariant(); + string filterTextLower = FilterText.ToLowerInvariant(); return objectAsConnectionInfo.Name.ToLowerInvariant().Contains(filterTextLower) || objectAsConnectionInfo.Hostname.ToLowerInvariant().Contains(filterTextLower) || diff --git a/mRemoteNG/UI/Controls/CredentialRecordComboBox.cs b/mRemoteNG/UI/Controls/CredentialRecordComboBox.cs index 143ca8504..5eb4a0380 100644 --- a/mRemoteNG/UI/Controls/CredentialRecordComboBox.cs +++ b/mRemoteNG/UI/Controls/CredentialRecordComboBox.cs @@ -18,7 +18,7 @@ namespace mRemoteNG.UI.Controls { if (credentialRecords == null) return; Items.Clear(); - foreach (var credential in credentialRecords) + foreach (ICredentialRecord credential in credentialRecords) Items.Add(credential); } } diff --git a/mRemoteNG/UI/Controls/CredentialRecordListBox.cs b/mRemoteNG/UI/Controls/CredentialRecordListBox.cs index e3c46f7cf..4db8dbb6d 100644 --- a/mRemoteNG/UI/Controls/CredentialRecordListBox.cs +++ b/mRemoteNG/UI/Controls/CredentialRecordListBox.cs @@ -33,7 +33,7 @@ namespace mRemoteNG.UI.Controls Items.Add(NoneSelection); Items.Add(AddNewSelection); - foreach (var credential in listOfCredentialRecords) + foreach (ICredentialRecord credential in listOfCredentialRecords) { Items.Add(credential); } diff --git a/mRemoteNG/UI/Controls/CredentialRecordListView.cs b/mRemoteNG/UI/Controls/CredentialRecordListView.cs index c51cea3a7..5c78f50c7 100644 --- a/mRemoteNG/UI/Controls/CredentialRecordListView.cs +++ b/mRemoteNG/UI/Controls/CredentialRecordListView.cs @@ -62,10 +62,10 @@ namespace mRemoteNG.UI.Controls private void SetObjectList() { - var objects = new Dictionary(); - foreach (var repository in _credentialRepositoryList.CredentialProviders) + Dictionary objects = new(); + foreach (ICredentialRepository repository in _credentialRepositoryList.CredentialProviders) { - foreach (var credential in repository.CredentialRecords) + foreach (ICredentialRecord credential in repository.CredentialRecords) objects.Add(credential, repository); } @@ -81,37 +81,37 @@ namespace mRemoteNG.UI.Controls private object CredentialIdAspectGetter(object rowObject) { - var keyValuePair = CastRowObject(rowObject); + KeyValuePair keyValuePair = CastRowObject(rowObject); return keyValuePair.Key.Id; } private object CredentialTitleAspectGetter(object rowObject) { - var keyValuePair = CastRowObject(rowObject); + KeyValuePair keyValuePair = CastRowObject(rowObject); return keyValuePair.Key.Title; } private object CredentialUsernameAspectGetter(object rowObject) { - var keyValuePair = CastRowObject(rowObject); + KeyValuePair keyValuePair = CastRowObject(rowObject); return keyValuePair.Key.Username; } private object CredentialDomainAspectGetter(object rowObject) { - var keyValuePair = CastRowObject(rowObject); + KeyValuePair keyValuePair = CastRowObject(rowObject); return keyValuePair.Key.Domain; } private object CredentialSourceAspectGetter(object rowObject) { - var keyValuePair = CastRowObject(rowObject); + KeyValuePair keyValuePair = CastRowObject(rowObject); return keyValuePair.Value.Config.Source; } private object RepoTitleAspectGetter(object rowObject) { - var keyValuePair = CastRowObject(rowObject); + KeyValuePair keyValuePair = CastRowObject(rowObject); return keyValuePair.Value.Config.Title; } @@ -119,7 +119,7 @@ namespace mRemoteNG.UI.Controls { if (!(model is KeyValuePair)) return default(KeyValuePair); - var keyValuePair = (KeyValuePair)model; + KeyValuePair keyValuePair = (KeyValuePair)model; return keyValuePair; } diff --git a/mRemoteNG/UI/Controls/CredentialRepositoryListView.cs b/mRemoteNG/UI/Controls/CredentialRepositoryListView.cs index 5225eb8b1..0c8336f70 100644 --- a/mRemoteNG/UI/Controls/CredentialRepositoryListView.cs +++ b/mRemoteNG/UI/Controls/CredentialRepositoryListView.cs @@ -38,7 +38,7 @@ namespace mRemoteNG.UI.Controls public void RefreshObjects() { - var repos = CredentialRepositoryList.CredentialProviders.ToList(); + List repos = CredentialRepositoryList.CredentialProviders.ToList(); objectListView1.RefreshObjects(repos); } @@ -61,7 +61,7 @@ namespace mRemoteNG.UI.Controls private void SetListObjects(IEnumerable repositories) { - var filteredRepositories = RepositoryFilter == null ? repositories : repositories.Where(RepositoryFilter); + IEnumerable filteredRepositories = RepositoryFilter == null ? repositories : repositories.Where(RepositoryFilter); objectListView1.SetObjects(filteredRepositories); } @@ -69,8 +69,8 @@ namespace mRemoteNG.UI.Controls { if (mouseEventArgs.Clicks < 2) return; OLVColumn column; - var listItem = objectListView1.GetItemAt(mouseEventArgs.X, mouseEventArgs.Y, out column); - var clickedNode = listItem.RowObject as ICredentialRepository; + OLVListItem listItem = objectListView1.GetItemAt(mouseEventArgs.X, mouseEventArgs.Y, out column); + ICredentialRepository clickedNode = listItem.RowObject as ICredentialRepository; if (clickedNode == null) return; DoubleClickHandler?.Invoke(clickedNode); } diff --git a/mRemoteNG/UI/Controls/ExternalToolsToolStrip.cs b/mRemoteNG/UI/Controls/ExternalToolsToolStrip.cs index fdb7d1902..26af61e85 100644 --- a/mRemoteNG/UI/Controls/ExternalToolsToolStrip.cs +++ b/mRemoteNG/UI/Controls/ExternalToolsToolStrip.cs @@ -68,14 +68,14 @@ namespace mRemoteNG.UI.Controls { SuspendLayout(); - for (var index = Items.Count - 1; index >= 0; index--) + for (int index = Items.Count - 1; index >= 0; index--) Items[index].Dispose(); Items.Clear(); - foreach (var tool in Runtime.ExternalToolsService.ExternalTools) + foreach (ExternalTool tool in Runtime.ExternalToolsService.ExternalTools) { if (!tool.ShowOnToolbar) continue; - var button = (ToolStripButton)Items.Add(tool.DisplayName, tool.Image, TsExtAppEntry_Click); + ToolStripButton button = (ToolStripButton)Items.Add(tool.DisplayName, tool.Image, TsExtAppEntry_Click); if (CMenToolbarShowText.Checked) button.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; else @@ -98,9 +98,9 @@ namespace mRemoteNG.UI.Controls private static void TsExtAppEntry_Click(object sender, EventArgs e) { - var extA = (ExternalTool)((ToolStripButton)sender).Tag; + ExternalTool extA = (ExternalTool)((ToolStripButton)sender).Tag; - var selectedTreeNode = Windows.TreeForm.SelectedNode; + Connection.ConnectionInfo selectedTreeNode = Windows.TreeForm.SelectedNode; if (selectedTreeNode != null && selectedTreeNode.GetTreeNodeType() == TreeNodeType.Connection || selectedTreeNode.GetTreeNodeType() == TreeNodeType.PuttySession) extA.Start(selectedTreeNode); diff --git a/mRemoteNG/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs b/mRemoteNG/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs index 80e3ae41f..fc8bcc97f 100644 --- a/mRemoteNG/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs +++ b/mRemoteNG/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs @@ -16,7 +16,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// Contain a reference to the collection of properties to show in the parent PropertyGrid. /// /// By default, m_PropertyDescriptors contain all the properties of the object. - readonly List _propertyDescriptors = new List(); + readonly List _propertyDescriptors = []; /// /// Contain a reference to the array of properties to display in the PropertyGrid. @@ -125,7 +125,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid } else if (_mWrapper.SelectedObject != value) { - var needrefresh = value?.GetType() != _mWrapper.SelectedObject?.GetType(); + bool needrefresh = value?.GetType() != _mWrapper.SelectedObject?.GetType(); _mWrapper.SelectedObject = value ?? new object(); if (needrefresh) RefreshProperties(); @@ -140,12 +140,12 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid public List GetVisibleGridItems() { - var gridRoot = SelectedGridItem; + GridItem gridRoot = SelectedGridItem; while (gridRoot.GridItemType != GridItemType.Root) { gridRoot = gridRoot.Parent; } - return GetVisibleGridItemsRecursive(gridRoot, new List()); + return GetVisibleGridItemsRecursive(gridRoot, []); } private List GetVisibleGridItemsRecursive(GridItem item, List gridItems) @@ -166,12 +166,12 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid public GridItem FindPreviousGridItemProperty(GridItem startItem) { - var gridItems = GetVisibleGridItems(); + List gridItems = GetVisibleGridItems(); if (gridItems.Count == 0 || startItem == null) return null; - var startIndex = gridItems.IndexOf(startItem); + int startIndex = gridItems.IndexOf(startItem); if (startItem.GridItemType == GridItemType.Property) { startIndex--; @@ -181,9 +181,9 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid } } - var previousIndex = 0; - var previousIndexValid = false; - for (var index = startIndex; index >= 0; index--) + int previousIndex = 0; + bool previousIndexValid = false; + for (int index = startIndex; index >= 0; index--) { if (gridItems[index].GridItemType != GridItemType.Property) continue; previousIndex = index; @@ -194,7 +194,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid if (previousIndexValid) return gridItems[previousIndex]; - for (var index = gridItems.Count - 1; index >= startIndex + 1; index--) + for (int index = gridItems.Count - 1; index >= startIndex + 1; index--) { if (gridItems[index].GridItemType != GridItemType.Property) continue; previousIndex = index; @@ -207,12 +207,12 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid public GridItem FindNextGridItemProperty(GridItem startItem) { - var gridItems = GetVisibleGridItems(); + List gridItems = GetVisibleGridItems(); if (gridItems.Count == 0 || startItem == null) return null; - var startIndex = gridItems.IndexOf(startItem); + int startIndex = gridItems.IndexOf(startItem); if (startItem.GridItemType == GridItemType.Property) { startIndex++; @@ -222,9 +222,9 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid } } - var nextIndex = 0; - var nextIndexValid = false; - for (var index = startIndex; index <= gridItems.Count - 1; index++) + int nextIndex = 0; + bool nextIndexValid = false; + for (int index = startIndex; index <= gridItems.Count - 1; index++) { if (gridItems[index].GridItemType != GridItemType.Property) continue; nextIndex = index; @@ -235,7 +235,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid if (nextIndexValid) return gridItems[nextIndex]; - for (var index = 0; index <= startIndex - 1; index++) + for (int index = 0; index <= startIndex - 1; index++) { if (gridItems[index].GridItemType != GridItemType.Property) continue; nextIndex = index; @@ -253,7 +253,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// public void SelectNextGridItem() { - var nextGridItem = FindNextGridItemProperty(SelectedGridItem); + GridItem nextGridItem = FindNextGridItemProperty(SelectedGridItem); if (nextGridItem != null) SelectedGridItem = nextGridItem; } @@ -265,7 +265,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// public void SelectPreviousGridItem() { - var previousGridItem = FindPreviousGridItemProperty(SelectedGridItem); + GridItem previousGridItem = FindPreviousGridItemProperty(SelectedGridItem); if (previousGridItem != null) SelectedGridItem = previousGridItem; } @@ -277,7 +277,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// public void SelectGridItem(string propertyName) { - var item = GetVisibleGridItems() + GridItem item = GetVisibleGridItems() .FirstOrDefault(gridItem => gridItem.PropertyDescriptor?.Name == propertyName); if (item != null) @@ -312,10 +312,10 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid // Display if necessary, some properties if (_mBrowsableProperties != null && _mBrowsableProperties.Length > 0) { - var allproperties = TypeDescriptor.GetProperties(_mWrapper.SelectedObject); - foreach (var propertyname in _mBrowsableProperties) + PropertyDescriptorCollection allproperties = TypeDescriptor.GetProperties(_mWrapper.SelectedObject); + foreach (string propertyname in _mBrowsableProperties) { - var property = allproperties[propertyname]; + PropertyDescriptor property = allproperties[propertyname]; if (property == null) throw new InvalidOperationException($"Property '{propertyname}' not found on object '{_mWrapper.GetClassName()}'"); @@ -328,7 +328,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid (_mBrowsableProperties == null || _mBrowsableProperties.Length == 0)) { // Fill the collection with all the properties. - var originalPropertyDescriptors = TypeDescriptor + IEnumerable originalPropertyDescriptors = TypeDescriptor .GetProperties(_mWrapper.SelectedObject) .OfType() .Where(PropertyDoesntHaveBrowsableFalseAttribute); @@ -346,9 +346,9 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid if (_mHiddenProperties != null && _mHiddenProperties.Length > 0) { // Remove from the list the properties that mustn't be displayed. - foreach (var propertyname in _mHiddenProperties) + foreach (string propertyname in _mHiddenProperties) { - var property = _propertyDescriptors.FirstOrDefault(p => p.Name == propertyname); + PropertyDescriptor property = _propertyDescriptors.FirstOrDefault(p => p.Name == propertyname); // Remove from the list the property HideProperty(property); @@ -374,7 +374,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// For better performance, include the BrowsableAttribute with true value. private void HideAttribute(Attribute attribute) { - var filteredoriginalpropertydescriptors = + PropertyDescriptorCollection filteredoriginalpropertydescriptors = TypeDescriptor.GetProperties(_mWrapper.SelectedObject, new[] {attribute}); if (filteredoriginalpropertydescriptors == null || filteredoriginalpropertydescriptors.Count == 0) throw new ArgumentException("Attribute not found", attribute.ToString()); @@ -389,7 +389,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// The attribute to be added. private void ShowAttribute(Attribute attribute) { - var filteredoriginalpropertydescriptors = + PropertyDescriptorCollection filteredoriginalpropertydescriptors = TypeDescriptor.GetProperties(_mWrapper.SelectedObject, new[] {attribute}); if (filteredoriginalpropertydescriptors == null || filteredoriginalpropertydescriptors.Count == 0) throw new ArgumentException("Attribute not found", attribute.ToString()); diff --git a/mRemoteNG/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs b/mRemoteNG/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs index 221edec33..4f4f81c0b 100644 --- a/mRemoteNG/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs +++ b/mRemoteNG/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs @@ -26,7 +26,7 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// /// Get or set a reference to the collection of properties to show in the parent PropertyGrid /// - public List PropertyDescriptors { get; set; } = new List(); + public List PropertyDescriptors { get; set; } = []; #region ICustomTypeDescriptor Members diff --git a/mRemoteNG/UI/Controls/MultiSshToolStrip.cs b/mRemoteNG/UI/Controls/MultiSshToolStrip.cs index 498c8ff9f..1e029e216 100644 --- a/mRemoteNG/UI/Controls/MultiSshToolStrip.cs +++ b/mRemoteNG/UI/Controls/MultiSshToolStrip.cs @@ -19,9 +19,9 @@ namespace mRemoteNG.UI.Controls private ToolStripLabel lblMultiSsh; private ToolStripTextBox txtMultiSsh; private int previousCommandIndex = 0; - private readonly ArrayList processHandlers = new ArrayList(); - private readonly ArrayList quickConnectConnections = new ArrayList(); - private readonly ArrayList previousCommands = new ArrayList(); + private readonly ArrayList processHandlers = []; + private readonly ArrayList quickConnectConnections = []; + private readonly ArrayList previousCommands = []; private readonly ThemeManager _themeManager; private int CommandHistoryLength { get; set; } = 100; @@ -43,7 +43,7 @@ namespace mRemoteNG.UI.Controls private ArrayList ProcessOpenConnections(ConnectionInfo connection) { - var handlers = new ArrayList(); + ArrayList handlers = new(); foreach (ProtocolBase _base in connection.OpenConnections) { @@ -76,9 +76,9 @@ namespace mRemoteNG.UI.Controls processHandlers.AddRange(ProcessOpenConnections(connection)); } - var connectionTreeConnections = Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveChildList().Where(item => item.OpenConnections.Count > 0); + System.Collections.Generic.IEnumerable connectionTreeConnections = Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveChildList().Where(item => item.OpenConnections.Count > 0); - foreach (var connection in connectionTreeConnections) + foreach (ConnectionInfo connection in connectionTreeConnections) { processHandlers.AddRange(ProcessOpenConnections(connection)); } @@ -116,7 +116,7 @@ namespace mRemoteNG.UI.Controls if (e.KeyCode == Keys.Enter) { - foreach (var chr1 in txtMultiSsh.Text) + foreach (char chr1 in txtMultiSsh.Text) { SendAllKeystrokes(NativeMethods.WM_CHAR, Convert.ToByte(chr1)); } diff --git a/mRemoteNG/UI/Controls/NewPasswordWithVerification.cs b/mRemoteNG/UI/Controls/NewPasswordWithVerification.cs index 2a4ae999b..c58ef7210 100644 --- a/mRemoteNG/UI/Controls/NewPasswordWithVerification.cs +++ b/mRemoteNG/UI/Controls/NewPasswordWithVerification.cs @@ -50,7 +50,7 @@ namespace mRemoteNG.UI.Controls public void SetPassword(SecureString password) { - var text = password.ConvertToUnsecureString(); + string text = password.ConvertToUnsecureString(); secureTextBox1.Text = text; secureTextBox2.Text = text; } diff --git a/mRemoteNG/UI/Controls/PageSequence/PageSequence.cs b/mRemoteNG/UI/Controls/PageSequence/PageSequence.cs index ebf4874a1..cfb6a739b 100644 --- a/mRemoteNG/UI/Controls/PageSequence/PageSequence.cs +++ b/mRemoteNG/UI/Controls/PageSequence/PageSequence.cs @@ -25,7 +25,7 @@ namespace mRemoteNG.UI.Controls.PageSequence throw new ArgumentNullException(nameof(pages)); _pageContainer = pageContainer ?? throw new ArgumentNullException(nameof(pageContainer)); - foreach (var page in pages) + foreach (SequencedControl page in pages) { SubscribeToPageEvents(page); _pages.Add(page); @@ -50,7 +50,7 @@ namespace mRemoteNG.UI.Controls.PageSequence public virtual void ReplacePage(SequencedControl newPage, RelativePagePosition pageToReplace) { - var indexModifier = 0; + int indexModifier = 0; // ReSharper disable once SwitchStatementMissingSomeCases switch (pageToReplace) { @@ -62,7 +62,7 @@ namespace mRemoteNG.UI.Controls.PageSequence break; } - var pageIndexToReplace = CurrentPageIndex + indexModifier; + int pageIndexToReplace = CurrentPageIndex + indexModifier; UnsubscribeFromPageEvents(_pages[pageIndexToReplace]); SubscribeToPageEvents(newPage); _pages[pageIndexToReplace] = newPage; @@ -113,7 +113,7 @@ namespace mRemoteNG.UI.Controls.PageSequence protected virtual void Dispose(bool disposing) { if (!disposing) return; - foreach (var page in _pages) + foreach (SequencedControl page in _pages) { UnsubscribeFromPageEvents(page); } diff --git a/mRemoteNG/UI/Controls/QuickConnectComboBox.cs b/mRemoteNG/UI/Controls/QuickConnectComboBox.cs index e3272296b..d00de8fb6 100644 --- a/mRemoteNG/UI/Controls/QuickConnectComboBox.cs +++ b/mRemoteNG/UI/Controls/QuickConnectComboBox.cs @@ -58,7 +58,7 @@ namespace mRemoteNG.UI.Controls // Items can't be removed from the ComboBox while it is dropped down without possibly causing // an exception so we must close it, delete the item, and then drop it down again. When we // close it programmatically, the SelectedItem may revert to Nothing, so we must save it first. - var item = _comboBox.SelectedItem; + object item = _comboBox.SelectedItem; _comboBox.DroppedDown = false; _comboBox.Items.Remove(item); _comboBox.SelectedIndex = -1; @@ -79,24 +79,24 @@ namespace mRemoteNG.UI.Controls return; } - var historyItem = (HistoryItem)_comboBox.SelectedItem; + HistoryItem historyItem = (HistoryItem)_comboBox.SelectedItem; OnProtocolChanged(new ProtocolChangedEventArgs(historyItem.ConnectionInfo.Protocol)); } private static void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { - var comboBox = sender as ComboBox; + ComboBox comboBox = sender as ComboBox; if (comboBox == null) { return; } - var drawItem = comboBox.Items[e.Index]; + object drawItem = comboBox.Items[e.Index]; string drawString; if (drawItem is HistoryItem) { - var historyItem = (HistoryItem)drawItem; + HistoryItem historyItem = (HistoryItem)drawItem; drawString = historyItem.ToString(true); } else @@ -136,7 +136,7 @@ namespace mRemoteNG.UI.Controls public string ToString(bool includeProtocol) { - var port = string.Empty; + string port = string.Empty; if (ConnectionInfo.Port != ConnectionInfo.GetDefaultPort()) { port = $":{ConnectionInfo.Port}"; @@ -150,14 +150,14 @@ namespace mRemoteNG.UI.Controls private bool Exists(HistoryItem searchItem) { - foreach (var item in _comboBox.Items) + foreach (object item in _comboBox.Items) { if (!(item is HistoryItem)) { continue; } - var historyItem = (HistoryItem)item; + HistoryItem historyItem = (HistoryItem)item; if (historyItem.Equals(searchItem)) { return true; @@ -171,7 +171,7 @@ namespace mRemoteNG.UI.Controls { try { - var historyItem = new HistoryItem {ConnectionInfo = connectionInfo}; + HistoryItem historyItem = new() { ConnectionInfo = connectionInfo}; if (!Exists(historyItem)) { _comboBox.Items.Insert(0, historyItem); diff --git a/mRemoteNG/UI/Controls/QuickConnectToolStrip.cs b/mRemoteNG/UI/Controls/QuickConnectToolStrip.cs index ded6f5d98..290f65a79 100644 --- a/mRemoteNG/UI/Controls/QuickConnectToolStrip.cs +++ b/mRemoteNG/UI/Controls/QuickConnectToolStrip.cs @@ -155,10 +155,10 @@ namespace mRemoteNG.UI.Controls try { _mnuQuickConnectProtocol.Items.Clear(); - foreach (var fieldInfo in typeof(ProtocolType).GetFields()) + foreach (System.Reflection.FieldInfo fieldInfo in typeof(ProtocolType).GetFields()) { if (fieldInfo.Name == "value__" || fieldInfo.Name == "IntApp") continue; - var menuItem = new ToolStripMenuItem(fieldInfo.Name); + ToolStripMenuItem menuItem = new(fieldInfo.Name); if (fieldInfo.Name == Settings.Default.QuickConnectProtocol) { menuItem.Checked = true; @@ -188,7 +188,7 @@ namespace mRemoteNG.UI.Controls { try { - var connectionInfo = Runtime.ConnectionsService.CreateQuickConnect(_cmbQuickConnect.Text.Trim(), + ConnectionInfo connectionInfo = Runtime.ConnectionsService.CreateQuickConnect(_cmbQuickConnect.Text.Trim(), Converter.StringToProtocol(Settings .Default .QuickConnectProtocol)); @@ -238,7 +238,7 @@ namespace mRemoteNG.UI.Controls private void btnConnections_DropDownOpening(object sender, EventArgs e) { _btnConnections.DropDownItems.Clear(); - var menuItemsConverter = new ConnectionsTreeToMenuItemsConverter + ConnectionsTreeToMenuItemsConverter menuItemsConverter = new() { MouseUpEventHandler = ConnectionsMenuItem_MouseUp }; @@ -249,15 +249,15 @@ namespace mRemoteNG.UI.Controls .ConnectionTreeModel).ToArray(); _btnConnections.DropDownItems.AddRange(rootMenuItems); - ToolStripMenuItem favorites = new ToolStripMenuItem(Language.Favorites, Properties.Resources.Favorite_16x); - var rootNodes = Runtime.ConnectionsService.ConnectionTreeModel.RootNodes; - List favoritesList = new List(); + ToolStripMenuItem favorites = new(Language.Favorites, Properties.Resources.Favorite_16x); + List rootNodes = Runtime.ConnectionsService.ConnectionTreeModel.RootNodes; + List favoritesList = []; - foreach (var node in rootNodes) + foreach (ContainerInfo node in rootNodes) { - foreach (var containerInfo in Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveFavoriteChildList(node)) + foreach (ConnectionInfo containerInfo in Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveFavoriteChildList(node)) { - var favoriteMenuItem = new ToolStripMenuItem + ToolStripMenuItem favoriteMenuItem = new() { Text = containerInfo.Name, Tag = containerInfo, @@ -274,7 +274,7 @@ namespace mRemoteNG.UI.Controls private void ConnectionsMenuItem_MouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; - var menuItem = (ToolStripMenuItem)sender; + ToolStripMenuItem menuItem = (ToolStripMenuItem)sender; switch (menuItem.Tag) { diff --git a/mRemoteNG/UI/Controls/mrngAdTree.cs b/mRemoteNG/UI/Controls/mrngAdTree.cs index 54f93f3c2..0211a8ec6 100644 --- a/mRemoteNG/UI/Controls/mrngAdTree.cs +++ b/mRemoteNG/UI/Controls/mrngAdTree.cs @@ -52,14 +52,14 @@ namespace mRemoteNG.UI.Controls private void TvActiveDirectory_AfterSelect(object sender, TreeViewEventArgs e) { AdPath = e.Node.Tag.ToString(); - var pathChangedEvent = AdPathChanged; + AdPathChangedEventHandler pathChangedEvent = AdPathChanged; pathChangedEvent?.Invoke(this); } private void AdTree_Load(object sender, EventArgs e) { tvActiveDirectory.Nodes.Clear(); - var treeNode = new TreeNode(Domain) { Tag = "" }; + TreeNode treeNode = new(Domain) { Tag = "" }; tvActiveDirectory.Nodes.Add(treeNode); AddTreeNodes(treeNode); tvActiveDirectory.Nodes[0].Expand(); @@ -67,15 +67,15 @@ namespace mRemoteNG.UI.Controls private void AddTreeNodes(TreeNode tNode) { - var adhelper = new AdHelper(Domain); + AdHelper adhelper = new(Domain); adhelper.GetChildEntries(tNode.Tag.ToString()); - var enumerator = adhelper.Children.GetEnumerator(); + System.Collections.IDictionaryEnumerator enumerator = adhelper.Children.GetEnumerator(); tvActiveDirectory.BeginUpdate(); while (enumerator.MoveNext()) { - var flag1 = false; + bool flag1 = false; if (enumerator.Key == null) continue; - var node1 = new TreeNode(enumerator.Key.ToString().Substring(3)) + TreeNode node1 = new(enumerator.Key.ToString().Substring(3)) { Tag = RuntimeHelpers.GetObjectValue(enumerator.Value) }; @@ -86,7 +86,7 @@ namespace mRemoteNG.UI.Controls if (flag1) { - var flag2 = false; + bool flag2 = false; try { foreach (TreeNode node2 in tNode.Nodes) @@ -105,7 +105,7 @@ namespace mRemoteNG.UI.Controls tNode.Nodes.Add(node1); } - var imageIndex = GetImageIndex(enumerator.Key.ToString().Substring(0, 2)); + int imageIndex = GetImageIndex(enumerator.Key.ToString().Substring(0, 2)); node1.ImageIndex = imageIndex; node1.SelectedImageIndex = imageIndex; } diff --git a/mRemoteNG/UI/Controls/mrngCheckBox.cs b/mRemoteNG/UI/Controls/mrngCheckBox.cs index 35447ad43..b2cfe4ff4 100644 --- a/mRemoteNG/UI/Controls/mrngCheckBox.cs +++ b/mRemoteNG/UI/Controls/mrngCheckBox.cs @@ -24,7 +24,7 @@ namespace mRemoteNG.UI.Controls { InitializeComponent(); ThemeManager.getInstance().ThemeChanged += OnCreateControl; - var display = new DisplayProperties(); + DisplayProperties display = new(); _checkboxSize = new Size(display.ScaleWidth(11), display.ScaleHeight(11)); _checkboxYCoord = (display.ScaleHeight(Height) - _checkboxSize.Height) / 2 - display.ScaleHeight(5); _textXCoord = _checkboxSize.Width + display.ScaleWidth(2); @@ -86,7 +86,7 @@ namespace mRemoteNG.UI.Controls Color glyph; Color checkBorder; - var back = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Background"); + Color back = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Background"); if (Enabled) { glyph = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Glyph"); @@ -114,9 +114,9 @@ namespace mRemoteNG.UI.Controls e.Graphics.Clear(Parent.BackColor); - using (var p = new Pen(checkBorder)) + using (Pen p = new(checkBorder)) { - var boxRect = new Rectangle(0, _checkboxYCoord, _checkboxSize.Width, _checkboxSize.Height); + Rectangle boxRect = new(0, _checkboxYCoord, _checkboxSize.Width, _checkboxSize.Height); e.Graphics.FillRectangle(new SolidBrush(back), boxRect); e.Graphics.DrawRectangle(p, boxRect); } @@ -127,7 +127,7 @@ namespace mRemoteNG.UI.Controls e.Graphics.DrawString("\uE001", new Font("Segoe UI Symbol", 7.75f), new SolidBrush(glyph), -4, 0); } - var textRect = new Rectangle(_textXCoord, 0, Width - 16, Height); + Rectangle textRect = new(_textXCoord, 0, Width - 16, Height); TextRenderer.DrawText(e.Graphics, Text, Font, textRect, fore, Parent.BackColor, TextFormatFlags.PathEllipsis); } diff --git a/mRemoteNG/UI/Controls/mrngComboBox.cs b/mRemoteNG/UI/Controls/mrngComboBox.cs index f90b523fa..01f4f5b05 100644 --- a/mRemoteNG/UI/Controls/mrngComboBox.cs +++ b/mRemoteNG/UI/Controls/mrngComboBox.cs @@ -65,7 +65,7 @@ namespace mRemoteNG.UI.Controls private void NG_DrawItem(object sender, DrawItemEventArgs e) { - var index = e.Index >= 0 ? e.Index : 0; + int index = e.Index >= 0 ? e.Index : 0; Brush itemBrush = new SolidBrush(_themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Foreground")); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) @@ -115,11 +115,11 @@ namespace mRemoteNG.UI.Controls } //Colors - var Border = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Border"); - var Back = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Background"); - var Fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Foreground"); - var ButtBack = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_Background"); - var ButtFore = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_Foreground"); + Color Border = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Border"); + Color Back = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Background"); + Color Fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Foreground"); + Color ButtBack = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_Background"); + Color ButtFore = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_Foreground"); if (_mice == MouseState.HOVER) { @@ -139,14 +139,14 @@ namespace mRemoteNG.UI.Controls e.Graphics.Clear(Back); //Border - using (var p = new Pen(Border)) + using (Pen p = new(Border)) { - var boxRect = new Rectangle(0, 0, Width - 1, Height - 1); + Rectangle boxRect = new(0, 0, Width - 1, Height - 1); e.Graphics.DrawRectangle(p, boxRect); } //Button - using (var b = new SolidBrush(ButtBack)) + using (SolidBrush b = new(ButtBack)) { e.Graphics.FillRectangle(b, Width - 18, 2, 16, Height - 4); } @@ -155,7 +155,7 @@ namespace mRemoteNG.UI.Controls e.Graphics.DrawString("\u25BC", Font, new SolidBrush(ButtFore), Width - 17, Height / 2 - 5); //Text - var textRect = new Rectangle(2, 2, Width - 20, Height - 4); + Rectangle textRect = new(2, 2, Width - 20, Height - 4); TextRenderer.DrawText(e.Graphics, Text, Font, textRect, Fore, Back, TextFormatFlags.Left | TextFormatFlags.VerticalCenter); } diff --git a/mRemoteNG/UI/Controls/mrngGroupBox.cs b/mRemoteNG/UI/Controls/mrngGroupBox.cs index 5f3c53709..22a9197bf 100644 --- a/mRemoteNG/UI/Controls/mrngGroupBox.cs +++ b/mRemoteNG/UI/Controls/mrngGroupBox.cs @@ -37,9 +37,9 @@ namespace mRemoteNG.UI.Controls } //Reusing the textbox colors - var titleColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Foreground"); + Color titleColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Foreground"); //var backColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Backgorund"); - var lineColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Line"); + Color lineColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Line"); if (!Enabled) { @@ -50,7 +50,7 @@ namespace mRemoteNG.UI.Controls //var state = Enabled ? GroupBoxState.Normal : GroupBoxState.Disabled; - var flags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping | + TextFormatFlags flags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak; if (!ShowKeyboardCues) @@ -61,10 +61,10 @@ namespace mRemoteNG.UI.Controls //No clear backgorund, this control is transparently //e.Graphics.FillRectangle(new SolidBrush(backColor), 0, 0, Width, Height); - var bounds = new Rectangle(0, 0, Width, Height); - var rectangle = bounds; + Rectangle bounds = new(0, 0, Width, Height); + Rectangle rectangle = bounds; rectangle.Width -= 8; - var size = TextRenderer.MeasureText(e.Graphics, Text, Font, new Size(rectangle.Width, rectangle.Height), + Size size = TextRenderer.MeasureText(e.Graphics, Text, Font, new Size(rectangle.Width, rectangle.Height), flags); rectangle.Width = size.Width; rectangle.Height = size.Height; @@ -76,9 +76,9 @@ namespace mRemoteNG.UI.Controls if (rectangle.Width > 0) rectangle.Inflate(2, 0); - using (var pen = new Pen(lineColor)) + using (Pen pen = new(lineColor)) { - var num = bounds.Top + (Font.Height / 2); + int num = bounds.Top + (Font.Height / 2); //Left line e.Graphics.DrawLine(pen, bounds.Left + Padding.Left, num - Padding.Top, bounds.Left + Padding.Left, bounds.Height - Padding.Bottom); diff --git a/mRemoteNG/UI/Controls/mrngIpTextBox.cs b/mRemoteNG/UI/Controls/mrngIpTextBox.cs index 134314a1c..445dd7e7a 100644 --- a/mRemoteNG/UI/Controls/mrngIpTextBox.cs +++ b/mRemoteNG/UI/Controls/mrngIpTextBox.cs @@ -53,7 +53,7 @@ namespace mRemoteNG.UI.Controls { if (!string.IsNullOrEmpty(value)) { - var pieces = value.Split(@".".ToCharArray(), 4); + string[] pieces = value.Split(@".".ToCharArray(), 4); Octet1.Text = pieces[0]; Octet2.Text = pieces[1]; Octet3.Text = pieces[2]; @@ -256,7 +256,7 @@ namespace mRemoteNG.UI.Controls { try { - var theValue = int.Parse(inString); + int theValue = int.Parse(inString); if (theValue >= 0 && theValue <= 255) return true; @@ -431,7 +431,7 @@ namespace mRemoteNG.UI.Controls // Selects All text in a box for overwriting upon entering the box private void Box_Enter(object sender, EventArgs e) { - var tb = (TextBox)sender; + TextBox tb = (TextBox)sender; tb.SelectAll(); } } diff --git a/mRemoteNG/UI/Controls/mrngLabel.cs b/mRemoteNG/UI/Controls/mrngLabel.cs index 96b92e023..0dab13999 100644 --- a/mRemoteNG/UI/Controls/mrngLabel.cs +++ b/mRemoteNG/UI/Controls/mrngLabel.cs @@ -92,7 +92,7 @@ namespace mRemoteNG.UI.Controls } else { - var disabledtextLabel = + Color disabledtextLabel = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Disabled_Foreground"); TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, disabledtextLabel, _textFormatFlags); } diff --git a/mRemoteNG/UI/Controls/mrngListView.cs b/mRemoteNG/UI/Controls/mrngListView.cs index 13a8580eb..12ae31a81 100644 --- a/mRemoteNG/UI/Controls/mrngListView.cs +++ b/mRemoteNG/UI/Controls/mrngListView.cs @@ -25,7 +25,7 @@ namespace mRemoteNG.UI.Controls protected override void OnCreateControl() { base.OnCreateControl(); - var _themeManager = ThemeManager.getInstance(); + ThemeManager _themeManager = ThemeManager.getInstance(); if (!_themeManager.ActiveAndExtended) return; //List back color BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Background"); @@ -36,7 +36,7 @@ namespace mRemoteNG.UI.Controls //Header style HeaderUsesThemes = false; - var headerStylo = new HeaderFormatStyle + HeaderFormatStyle headerStylo = new() { Normal = { diff --git a/mRemoteNG/UI/Controls/mrngNumericUpDown.cs b/mRemoteNG/UI/Controls/mrngNumericUpDown.cs index 9d6c0861d..87b8f77aa 100644 --- a/mRemoteNG/UI/Controls/mrngNumericUpDown.cs +++ b/mRemoteNG/UI/Controls/mrngNumericUpDown.cs @@ -33,7 +33,7 @@ namespace mRemoteNG.UI.Controls if (Controls.Count > 0) { - for (var i = 0; i < Controls.Count; i++) + for (int i = 0; i < Controls.Count; i++) { //Remove those non-themable buttons if (Controls[i].GetType().ToString().Equals("System.Windows.Forms.UpDownBase+UpDownButtons")) diff --git a/mRemoteNG/UI/Controls/mrngProgressBar.cs b/mRemoteNG/UI/Controls/mrngProgressBar.cs index aaff26a41..38fa1ca54 100644 --- a/mRemoteNG/UI/Controls/mrngProgressBar.cs +++ b/mRemoteNG/UI/Controls/mrngProgressBar.cs @@ -35,9 +35,9 @@ namespace mRemoteNG.UI.Controls return; } - var progressFill = _themeManager.ActiveTheme.ExtendedPalette.getColor("ProgressBar_Fill"); - var back = _themeManager.ActiveTheme.ExtendedPalette.getColor("ProgressBar_Background"); - var doneProgress = (int)(e.ClipRectangle.Width * ((double)Value / Maximum)); + Color progressFill = _themeManager.ActiveTheme.ExtendedPalette.getColor("ProgressBar_Fill"); + Color back = _themeManager.ActiveTheme.ExtendedPalette.getColor("ProgressBar_Background"); + int doneProgress = (int)(e.ClipRectangle.Width * ((double)Value / Maximum)); e.Graphics.FillRectangle(new SolidBrush(progressFill), 0, 0, doneProgress, e.ClipRectangle.Height); e.Graphics.FillRectangle(new SolidBrush(back), doneProgress, 0, e.ClipRectangle.Width, e.ClipRectangle.Height); diff --git a/mRemoteNG/UI/Controls/mrngRadioButton.cs b/mRemoteNG/UI/Controls/mrngRadioButton.cs index 988f1fb54..5325251e2 100644 --- a/mRemoteNG/UI/Controls/mrngRadioButton.cs +++ b/mRemoteNG/UI/Controls/mrngRadioButton.cs @@ -19,7 +19,7 @@ namespace mRemoteNG.UI.Controls // Constructor public MrngRadioButton() { - var display = new DisplayProperties(); + DisplayProperties display = new(); _circleSmall = new Rectangle(display.ScaleWidth(4), display.ScaleHeight(4), display.ScaleWidth(6), display.ScaleHeight(6)); @@ -85,12 +85,12 @@ namespace mRemoteNG.UI.Controls } // Init - var g = e.Graphics; + Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; - var fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Text"); - var outline = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Border"); - var centerBack = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Background"); + Color fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Text"); + Color outline = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Border"); + Color centerBack = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Background"); Color center; // Overlay Graphic @@ -116,7 +116,7 @@ namespace mRemoteNG.UI.Controls fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Text_Disabled"); } - var textRect = new Rectangle(_textXCoord, Padding.Top, Width - 16, Height); + Rectangle textRect = new(_textXCoord, Padding.Top, Width - 16, Height); TextRenderer.DrawText(e.Graphics, Text, Font, textRect, fore, Parent.BackColor, TextFormatFlags.PathEllipsis); diff --git a/mRemoteNG/UI/Controls/mrngSearchBox.cs b/mRemoteNG/UI/Controls/mrngSearchBox.cs index eab3887d6..8130d733f 100644 --- a/mRemoteNG/UI/Controls/mrngSearchBox.cs +++ b/mRemoteNG/UI/Controls/mrngSearchBox.cs @@ -8,8 +8,8 @@ namespace mRemoteNG.UI.Controls { private bool _showDefaultText = true; private bool _settingDefaultText = true; - private readonly PictureBox _pbClear = new PictureBox(); - private readonly ToolTip _btClearToolTip = new ToolTip(); + private readonly PictureBox _pbClear = new(); + private readonly ToolTip _btClearToolTip = new(); public MrngSearchBox() { diff --git a/mRemoteNG/UI/DPI_Per_Monitor.cs b/mRemoteNG/UI/DPI_Per_Monitor.cs index e9a9c6b89..e438d9e95 100644 --- a/mRemoteNG/UI/DPI_Per_Monitor.cs +++ b/mRemoteNG/UI/DPI_Per_Monitor.cs @@ -91,7 +91,7 @@ static class DPI_Per_Monitor [DllImport("User32.dll")] private static extern IntPtr MonitorFromPoint([In]System.Drawing.Point pt, [In]uint dwFlags); - static List> ManResCtrl = new List>(); + static List> ManResCtrl = []; internal static void TryEnableDPIAware(Form form, VoidOfFloatFloatDelegate CallBackWithScale) { int handledLev = 0; @@ -110,7 +110,7 @@ static class DPI_Per_Monitor handledLev = 1; } catch { } try { - var mon = MonitorFromPoint(new System.Drawing.Point(1, 1), 2/*MONITOR_DEFAULTTONEAREST*/); //(0,0) always top left of primary + IntPtr mon = MonitorFromPoint(new System.Drawing.Point(1, 1), 2/*MONITOR_DEFAULTTONEAREST*/); //(0,0) always top left of primary uint dpiX; uint dpiY; GetDpiForMonitor(mon, DpiType.Effective, out dpiX, out dpiY); @@ -123,7 +123,7 @@ static class DPI_Per_Monitor [DllImport("user32.dll", SetLastError = true)] public static extern bool EnableNonClientDpiScaling(IntPtr hWnd); - private static SemaphoreSlim semaphoreScale = new SemaphoreSlim(1, 1); + private static SemaphoreSlim semaphoreScale = new(1, 1); internal delegate void VoidOfFloatFloatDelegate(float x, float y); static Int32 Oldscales = -1; static bool isCurrentlyScaling=false; diff --git a/mRemoteNG/UI/DialogFactory.cs b/mRemoteNG/UI/DialogFactory.cs index fe4864ed2..50bd18e67 100644 --- a/mRemoteNG/UI/DialogFactory.cs +++ b/mRemoteNG/UI/DialogFactory.cs @@ -35,7 +35,7 @@ namespace mRemoteNG.UI /// public static void ShowLoadConnectionsFailedDialog(string connectionFileName, string messageText, bool showCancelButton) { - var commandButtons = new List + List commandButtons = new() { Language.ConfigurationCreateNew, Language.OpenADifferentFile, @@ -45,7 +45,7 @@ namespace mRemoteNG.UI if (showCancelButton) commandButtons.Add(Language._Cancel); - var answered = false; + bool answered = false; while (!answered) { try @@ -55,7 +55,7 @@ namespace mRemoteNG.UI switch (CTaskDialog.CommandButtonResult) { case 0: // New - var saveAsDialog = ConnectionsSaveAsDialog(); + SaveFileDialog saveAsDialog = ConnectionsSaveAsDialog(); saveAsDialog.ShowDialog(); Runtime.ConnectionsService.NewConnectionsFile(saveAsDialog.FileName); answered = true; diff --git a/mRemoteNG/UI/DisplayProperties.cs b/mRemoteNG/UI/DisplayProperties.cs index 9098c3471..2487d1ef0 100644 --- a/mRemoteNG/UI/DisplayProperties.cs +++ b/mRemoteNG/UI/DisplayProperties.cs @@ -76,14 +76,14 @@ namespace mRemoteNG.UI if (image == null) throw new ArgumentNullException(nameof(image)); - var width = ScaleWidth(image.Width); - var height = ScaleHeight(image.Height); - var destRect = new Rectangle(0, 0, width, height); - var destImage = new Bitmap(width, height); + int width = ScaleWidth(image.Width); + int height = ScaleHeight(image.Height); + Rectangle destRect = new(0, 0, width, height); + Bitmap destImage = new(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - using (var graphics = Graphics.FromImage(destImage)) + using (Graphics graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; @@ -91,7 +91,7 @@ namespace mRemoteNG.UI graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - using (var wrapMode = new ImageAttributes()) + using (ImageAttributes wrapMode = new()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); diff --git a/mRemoteNG/UI/FontOverrider.cs b/mRemoteNG/UI/FontOverrider.cs index 08d7092e3..610cb62b4 100644 --- a/mRemoteNG/UI/FontOverrider.cs +++ b/mRemoteNG/UI/FontOverrider.cs @@ -12,7 +12,7 @@ namespace mRemoteNG.UI // Override the font of all controls in a container with the default font based on the OS version foreach (Control tempLoopVarCtlChild in ctlParent.Controls) { - var ctlChild = tempLoopVarCtlChild; + Control ctlChild = tempLoopVarCtlChild; ctlChild.Font = new Font(SystemFonts.MessageBoxFont.Name, ctlChild.Font.Size, ctlChild.Font.Style, ctlChild.Font.Unit, ctlChild.Font.GdiCharSet); if (ctlChild.Controls.Count > 0) diff --git a/mRemoteNG/UI/FormExtensions.cs b/mRemoteNG/UI/FormExtensions.cs index a3fcb6c56..92334a067 100644 --- a/mRemoteNG/UI/FormExtensions.cs +++ b/mRemoteNG/UI/FormExtensions.cs @@ -8,11 +8,11 @@ namespace mRemoteNG.UI { public static void CenterOnTarget(this Form formToMove, Form formToCenterOn) { - var targetFormCenterX = formToCenterOn.Location.X + formToCenterOn.Width / 2; - var targetFormCenterY = formToCenterOn.Location.Y + formToCenterOn.Height / 2; + int targetFormCenterX = formToCenterOn.Location.X + formToCenterOn.Width / 2; + int targetFormCenterY = formToCenterOn.Location.Y + formToCenterOn.Height / 2; - var thisFormCenterX = formToMove.Location.X + formToMove.Width / 2; - var thisFormCenterY = formToMove.Location.Y + formToMove.Height / 2; + int thisFormCenterX = formToMove.Location.X + formToMove.Width / 2; + int thisFormCenterY = formToMove.Location.Y + formToMove.Height / 2; formToMove.Location = new Point(targetFormCenterX - thisFormCenterX, targetFormCenterY - thisFormCenterY); } diff --git a/mRemoteNG/UI/Forms/FrmExport.cs b/mRemoteNG/UI/Forms/FrmExport.cs index 1376805df..fc5d284cd 100644 --- a/mRemoteNG/UI/Forms/FrmExport.cs +++ b/mRemoteNG/UI/Forms/FrmExport.cs @@ -28,14 +28,14 @@ namespace mRemoteNG.UI.Forms { get { - var exportFormat = cboFileFormat.SelectedItem as ExportFormat; + ExportFormat exportFormat = cboFileFormat.SelectedItem as ExportFormat; return exportFormat?.Format ?? SaveFormat.mRXML; } set { - foreach (var item in cboFileFormat.Items) + foreach (object item in cboFileFormat.Items) { - var exportFormat = item as ExportFormat; + ExportFormat exportFormat = item as ExportFormat; if (exportFormat?.Format != value) continue; cboFileFormat.SelectedItem = item; break; @@ -164,13 +164,13 @@ namespace mRemoteNG.UI.Forms private void btnBrowse_Click(object sender, EventArgs e) { - using (var saveFileDialog = new SaveFileDialog()) + using (SaveFileDialog saveFileDialog = new()) { saveFileDialog.CheckPathExists = true; saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); saveFileDialog.OverwritePrompt = true; - var fileTypes = new List(); + List fileTypes = new(); fileTypes.AddRange(new[] {Language.FiltermRemoteXML, "*.xml"}); fileTypes.AddRange(new[] {Language.FiltermRemoteCSV, "*.csv"}); fileTypes.AddRange(new[] {Language.FilterAll, "*.*"}); diff --git a/mRemoteNG/UI/Forms/FrmInputBox.cs b/mRemoteNG/UI/Forms/FrmInputBox.cs index 59bb8fe28..73f4bc223 100644 --- a/mRemoteNG/UI/Forms/FrmInputBox.cs +++ b/mRemoteNG/UI/Forms/FrmInputBox.cs @@ -29,7 +29,7 @@ namespace mRemoteNG.UI.Forms private void ApplyTheme() { - var _themeManager = ThemeManager.getInstance(); + ThemeManager _themeManager = ThemeManager.getInstance(); if (!_themeManager.ActiveAndExtended) return; BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); diff --git a/mRemoteNG/UI/Forms/FrmPassword.cs b/mRemoteNG/UI/Forms/FrmPassword.cs index b07de48df..329df7d2c 100644 --- a/mRemoteNG/UI/Forms/FrmPassword.cs +++ b/mRemoteNG/UI/Forms/FrmPassword.cs @@ -13,7 +13,7 @@ namespace mRemoteNG.UI.Forms public partial class FrmPassword : IKeyProvider { private readonly string _passwordName; - private SecureString _password = new SecureString(); + private SecureString _password = new(); /// /// Puts the dialog into the New Password mode. An extra @@ -45,7 +45,7 @@ namespace mRemoteNG.UI.Forms /// public Optional GetKey() { - var dialog = ShowDialog(); + DialogResult dialog = ShowDialog(); return dialog == DialogResult.OK ? _password : Optional.Empty; @@ -57,7 +57,7 @@ namespace mRemoteNG.UI.Forms { ApplyLanguage(); ApplyTheme(); - var display = new DisplayProperties(); + DisplayProperties display = new(); pbLock.Image = display.ScaleImage(pbLock.Image); Height = tableLayoutPanel1.Height; @@ -113,7 +113,7 @@ namespace mRemoteNG.UI.Forms if (!ThemeManager.getInstance().ActiveAndExtended) return; - var activeTheme = ThemeManager.getInstance().ActiveTheme; + ThemeInfo activeTheme = ThemeManager.getInstance().ActiveTheme; BackColor = activeTheme.ExtendedPalette.getColor("Dialog_Background"); ForeColor = activeTheme.ExtendedPalette.getColor("Dialog_Foreground"); diff --git a/mRemoteNG/UI/Forms/FrmSplashScreenNew.xaml.cs b/mRemoteNG/UI/Forms/FrmSplashScreenNew.xaml.cs index 35bb1037a..6da31e90f 100644 --- a/mRemoteNG/UI/Forms/FrmSplashScreenNew.xaml.cs +++ b/mRemoteNG/UI/Forms/FrmSplashScreenNew.xaml.cs @@ -19,10 +19,11 @@ namespace mRemoteNG.UI.Forms } public static FrmSplashScreenNew GetInstance() { - if (instance == null) - instance = new FrmSplashScreenNew(); + //instance == null + instance ??= new FrmSplashScreenNew(); return instance; } + void LoadFont() { lblLogoPartA.FontFamily = new System.Windows.Media.FontFamily(new Uri("pack://application:,,,/"), "./UI/Font/#HandelGotDBol"); diff --git a/mRemoteNG/UI/Forms/FrmUnhandledException.cs b/mRemoteNG/UI/Forms/FrmUnhandledException.cs index e45cb9e1d..86865b115 100644 --- a/mRemoteNG/UI/Forms/FrmUnhandledException.cs +++ b/mRemoteNG/UI/Forms/FrmUnhandledException.cs @@ -65,7 +65,7 @@ namespace mRemoteNG.UI.Forms private void buttonCopyAll_Click(object sender, EventArgs e) { - var text = new StringBuilder() + string text = new StringBuilder() .AppendLine("```") .AppendLine(labelExceptionMessageHeader.Text) .AppendLine("\"" + textBoxExceptionMessage.Text + "\"") diff --git a/mRemoteNG/UI/Forms/OptionsPages/AdvancedPage.cs b/mRemoteNG/UI/Forms/OptionsPages/AdvancedPage.cs index cac5b4783..1e27d4512 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/AdvancedPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/AdvancedPage.cs @@ -20,8 +20,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages InitializeComponent(); ApplyTheme(); PageIcon = Resources.ImageConverter.GetImageAsIcon(Properties.Resources.Settings_16x); - var display = new DisplayProperties(); - var img = display.ScaleImage(Properties.Resources.PuttyConfig); + DisplayProperties display = new(); + System.Drawing.Bitmap img = display.ScaleImage(Properties.Resources.PuttyConfig); btnLaunchPutty.Image = img; } @@ -71,7 +71,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages Properties.OptionsAdvancedPage.Default.NoReconnect = chkNoReconnect.Checked; Properties.OptionsAdvancedPage.Default.RdpLoadBalanceInfoUseUtf8 = chkLoadBalanceInfoUseUtf8.Checked; - var puttyPathChanged = false; + bool puttyPathChanged = false; if (Properties.OptionsAdvancedPage.Default.CustomPuttyPath != txtCustomPuttyPath.Text) { puttyPathChanged = true; @@ -114,7 +114,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void btnBrowseCustomPuttyPath_Click(object sender, EventArgs e) { - using (var openFileDialog = new OpenFileDialog()) + using (OpenFileDialog openFileDialog = new()) { openFileDialog.Filter = $@"{Language.FilterApplication}|*.exe|{Language.FilterAll}|*.*"; openFileDialog.FileName = Path.GetFileName(GeneralAppInfo.PuttyPath); @@ -131,8 +131,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages { try { - var puttyProcess = new PuttyProcessController(); - var fileName = chkUseCustomPuttyPath.Checked ? txtCustomPuttyPath.Text : GeneralAppInfo.PuttyPath; + PuttyProcessController puttyProcess = new(); + string fileName = chkUseCustomPuttyPath.Checked ? txtCustomPuttyPath.Text : GeneralAppInfo.PuttyPath; puttyProcess.Start(fileName); puttyProcess.SetControlText("Button", "&Cancel", "&Close"); puttyProcess.SetControlVisible("Button", "&Open", false); @@ -150,9 +150,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void SetPuttyLaunchButtonEnabled() { - var puttyPath = chkUseCustomPuttyPath.Checked ? txtCustomPuttyPath.Text : GeneralAppInfo.PuttyPath; + string puttyPath = chkUseCustomPuttyPath.Checked ? txtCustomPuttyPath.Text : GeneralAppInfo.PuttyPath; - var exists = false; + bool exists = false; try { exists = File.Exists(puttyPath); diff --git a/mRemoteNG/UI/Forms/OptionsPages/AppearancePage.cs b/mRemoteNG/UI/Forms/OptionsPages/AppearancePage.cs index 98dba43d5..81c8d2fbb 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/AppearancePage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/AppearancePage.cs @@ -43,7 +43,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages cboLanguage.Items.Clear(); cboLanguage.Items.Add(Language.LanguageDefault); - foreach (var nativeName in SupportedCultures.CultureNativeNames) + foreach (string nativeName in SupportedCultures.CultureNativeNames) { cboLanguage.Items.Add(nativeName); } diff --git a/mRemoteNG/UI/Forms/OptionsPages/BackupPage.cs b/mRemoteNG/UI/Forms/OptionsPages/BackupPage.cs index b60b3f7cb..44b5d21d7 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/BackupPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/BackupPage.cs @@ -241,7 +241,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void ButtonBrowsePath_Click(object sender, EventArgs e) { - var selectFolderDialog = DialogFactory.SelectFolder(Language.lblConnectionsBackupPath); + CommonOpenFileDialog selectFolderDialog = DialogFactory.SelectFolder(Language.lblConnectionsBackupPath); txtConnectionsBackupPath.Text = selectFolderDialog.ShowDialog() == CommonFileDialogResult.Ok ? selectFolderDialog.FileName : txtConnectionsBackupPath.Text; } diff --git a/mRemoteNG/UI/Forms/OptionsPages/CredentialsPage.cs b/mRemoteNG/UI/Forms/OptionsPages/CredentialsPage.cs index 465a3ad1e..4f8485214 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/CredentialsPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/CredentialsPage.cs @@ -62,7 +62,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages } txtCredentialsUsername.Text = Properties.OptionsCredentialsPage.Default.DefaultUsername; - var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); + LegacyRijndaelCryptographyProvider cryptographyProvider = new(); txtCredentialsPassword.Text = cryptographyProvider.Decrypt(Properties.OptionsCredentialsPage.Default.DefaultPassword, Runtime.EncryptionKey); txtCredentialsDomain.Text = Properties.OptionsCredentialsPage.Default.DefaultDomain; txtCredentialsUserViaAPI.Text = Properties.OptionsCredentialsPage.Default.UserViaAPIDefault; @@ -84,7 +84,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages } Properties.OptionsCredentialsPage.Default.DefaultUsername = txtCredentialsUsername.Text; - var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); + LegacyRijndaelCryptographyProvider cryptographyProvider = new(); Properties.OptionsCredentialsPage.Default.DefaultPassword = cryptographyProvider.Encrypt(txtCredentialsPassword.Text, Runtime.EncryptionKey); Properties.OptionsCredentialsPage.Default.DefaultDomain = txtCredentialsDomain.Text; Properties.OptionsCredentialsPage.Default.UserViaAPIDefault = txtCredentialsUserViaAPI.Text; diff --git a/mRemoteNG/UI/Forms/OptionsPages/NotificationsPage.cs b/mRemoteNG/UI/Forms/OptionsPages/NotificationsPage.cs index 9ac19ae70..159dee05e 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/NotificationsPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/NotificationsPage.cs @@ -137,13 +137,13 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void buttonSelectLogPath_Click(object sender, System.EventArgs e) { - var currentFile = textBoxLogPath.Text; - var currentDirectory = Path.GetDirectoryName(currentFile); + string currentFile = textBoxLogPath.Text; + string currentDirectory = Path.GetDirectoryName(currentFile); saveFileDialogLogging.Title = Language.ChooseLogPath; saveFileDialogLogging.Filter = @"Log file|*.log"; saveFileDialogLogging.InitialDirectory = currentDirectory; saveFileDialogLogging.FileName = currentFile; - var dialogResult = saveFileDialogLogging.ShowDialog(); + DialogResult dialogResult = saveFileDialogLogging.ShowDialog(); if (dialogResult != DialogResult.OK) return; textBoxLogPath.Text = saveFileDialogLogging.FileName; } diff --git a/mRemoteNG/UI/Forms/OptionsPages/SecurityPage.cs b/mRemoteNG/UI/Forms/OptionsPages/SecurityPage.cs index 591f5f8cf..502c68162 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/SecurityPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/SecurityPage.cs @@ -76,21 +76,21 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void BtnTestSettings_Click(object sender, EventArgs e) { - var connectionTree = Runtime.ConnectionsService.ConnectionTreeModel; + Tree.ConnectionTreeModel connectionTree = Runtime.ConnectionsService.ConnectionTreeModel; if (!connectionTree.RootNodes.Any()) return; - var engine = (BlockCipherEngines)comboBoxEncryptionEngine.SelectedItem; - var mode = (BlockCipherModes)comboBoxBlockCipher.SelectedItem; - var cryptographyProvider = new CryptoProviderFactory(engine, mode).Build(); + BlockCipherEngines engine = (BlockCipherEngines)comboBoxEncryptionEngine.SelectedItem; + BlockCipherModes mode = (BlockCipherModes)comboBoxBlockCipher.SelectedItem; + ICryptographyProvider cryptographyProvider = new CryptoProviderFactory(engine, mode).Build(); cryptographyProvider.KeyDerivationIterations = (int)numberBoxKdfIterations.Value; - var serializerFactory = new XmlConnectionSerializerFactory(); - var serializer = serializerFactory.Build(cryptographyProvider, connectionTree, useFullEncryption: chkEncryptCompleteFile.Checked); - var nodeCount = connectionTree.GetRecursiveChildList().Count; + XmlConnectionSerializerFactory serializerFactory = new(); + Config.Serializers.ISerializer serializer = serializerFactory.Build(cryptographyProvider, connectionTree, useFullEncryption: chkEncryptCompleteFile.Checked); + int nodeCount = connectionTree.GetRecursiveChildList().Count; - var timer = Stopwatch.StartNew(); - var rootNode = connectionTree.RootNodes.First(); + Stopwatch timer = Stopwatch.StartNew(); + Container.ContainerInfo rootNode = connectionTree.RootNodes.First(); serializer.Serialize(rootNode); timer.Stop(); diff --git a/mRemoteNG/UI/Forms/OptionsPages/SqlServerPage.cs b/mRemoteNG/UI/Forms/OptionsPages/SqlServerPage.cs index d283188f1..fa04075a7 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/SqlServerPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/SqlServerPage.cs @@ -51,7 +51,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages txtSQLServer.Text = Properties.OptionsDBsPage.Default.SQLHost; txtSQLDatabaseName.Text = Properties.OptionsDBsPage.Default.SQLDatabaseName; txtSQLUsername.Text = Properties.OptionsDBsPage.Default.SQLUser; - var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); + LegacyRijndaelCryptographyProvider cryptographyProvider = new(); txtSQLPassword.Text = cryptographyProvider.Decrypt(Properties.OptionsDBsPage.Default.SQLPass, Runtime.EncryptionKey); chkSQLReadOnly.Checked = Properties.OptionsDBsPage.Default.SQLReadOnly; lblTestConnectionResults.Text = ""; @@ -60,14 +60,14 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void SaveSettings() { base.SaveSettings(); - var sqlServerWasPreviouslyEnabled = Properties.OptionsDBsPage.Default.UseSQLServer; + bool sqlServerWasPreviouslyEnabled = Properties.OptionsDBsPage.Default.UseSQLServer; Properties.OptionsDBsPage.Default.UseSQLServer = chkUseSQLServer.Checked; Properties.OptionsDBsPage.Default.SQLServerType = txtSQLType.Text; Properties.OptionsDBsPage.Default.SQLHost = txtSQLServer.Text; Properties.OptionsDBsPage.Default.SQLDatabaseName = txtSQLDatabaseName.Text; Properties.OptionsDBsPage.Default.SQLUser = txtSQLUsername.Text; - var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); + LegacyRijndaelCryptographyProvider cryptographyProvider = new(); Properties.OptionsDBsPage.Default.SQLPass = cryptographyProvider.Encrypt(txtSQLPassword.Text, Runtime.EncryptionKey); Properties.OptionsDBsPage.Default.SQLReadOnly = chkSQLReadOnly.Checked; @@ -115,17 +115,17 @@ namespace mRemoteNG.UI.Forms.OptionsPages private async void btnTestConnection_Click(object sender, EventArgs e) { - var type = txtSQLType.Text; - var server = txtSQLServer.Text; - var database = txtSQLDatabaseName.Text; - var username = txtSQLUsername.Text; - var password = txtSQLPassword.Text; + string type = txtSQLType.Text; + string server = txtSQLServer.Text; + string database = txtSQLDatabaseName.Text; + string username = txtSQLUsername.Text; + string password = txtSQLPassword.Text; lblTestConnectionResults.Text = Language.TestingConnection; imgConnectionStatus.Image = Properties.Resources.Loading_Spinner; btnTestConnection.Enabled = false; - var connectionTestResult = + ConnectionTestResult connectionTestResult = await _databaseConnectionTester.TestConnectivity(type, server, database, username, password); btnTestConnection.Enabled = true; diff --git a/mRemoteNG/UI/Forms/OptionsPages/ThemePage.cs b/mRemoteNG/UI/Forms/OptionsPages/ThemePage.cs index 2d534f1f3..cadd833de 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/ThemePage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/ThemePage.cs @@ -18,7 +18,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages private readonly ThemeManager _themeManager; private readonly bool _oriActiveTheming; - private readonly List modifiedThemes = new List(); + private readonly List modifiedThemes = []; #endregion @@ -74,7 +74,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void ListPalette_FormatCell(object sender, FormatCellEventArgs e) { if (e.ColumnIndex != ColorCol.Index) return; - var colorElem = (PseudoKeyColor)e.Model; + PseudoKeyColor colorElem = (PseudoKeyColor)e.Model; e.SubItem.BackColor = colorElem.Value; } @@ -97,7 +97,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages } } - foreach (var updatedTheme in modifiedThemes) + foreach (ThemeInfo updatedTheme in modifiedThemes) { _themeManager.updateTheme(updatedTheme); } @@ -127,7 +127,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages btnThemeNew.Enabled = true; - var selectedTheme = (ThemeInfo)cboTheme.SelectedItem; + ThemeInfo selectedTheme = (ThemeInfo)cboTheme.SelectedItem; if (selectedTheme != null && selectedTheme.IsExtendable) { @@ -152,9 +152,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages /// private void ListPalette_CellClick(object sender, CellClickEventArgs e) { - var colorElem = (PseudoKeyColor)e.Model; + PseudoKeyColor colorElem = (PseudoKeyColor)e.Model; - var colorDlg = new ColorDialog + ColorDialog colorDlg = new() { AllowFullOpen = true, FullOpen = true, @@ -173,19 +173,19 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void ColorMeList(ThemeInfo ti) { - foreach (var colorElem in ti.ExtendedPalette.ExtColorPalette) + foreach (KeyValuePair colorElem in ti.ExtendedPalette.ExtColorPalette) listPalette.AddObject(new PseudoKeyColor(colorElem.Key, colorElem.Value)); } private void btnThemeNew_Click(object sender, EventArgs e) { - using (var frmInputBox = new FrmInputBox(Language.OptionsThemeNewThemeCaption, Language.OptionsThemeNewThemeText, _themeManager.ActiveTheme.Name)) + using (FrmInputBox frmInputBox = new(Language.OptionsThemeNewThemeCaption, Language.OptionsThemeNewThemeText, _themeManager.ActiveTheme.Name)) { - var dr = frmInputBox.ShowDialog(); + DialogResult dr = frmInputBox.ShowDialog(); if (dr != DialogResult.OK) return; if (_themeManager.isThemeNameOk(frmInputBox.returnValue)) { - var addedTheme = _themeManager.addTheme(_themeManager.ActiveTheme, frmInputBox.returnValue); + ThemeInfo addedTheme = _themeManager.addTheme(_themeManager.ActiveTheme, frmInputBox.returnValue); _themeManager.ActiveTheme = addedTheme; LoadSettings(); } @@ -198,7 +198,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void btnThemeDelete_Click(object sender, EventArgs e) { - var res = CTaskDialog.ShowTaskDialogBox(this, Language.Warnings, + DialogResult res = CTaskDialog.ShowTaskDialogBox(this, Language.Warnings, Language.OptionsThemeDeleteConfirmation, "", "", "", "", "", "", ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Information, 0); diff --git a/mRemoteNG/UI/Forms/OptionsPages/UpdatesPage.cs b/mRemoteNG/UI/Forms/OptionsPages/UpdatesPage.cs index 5cd9a0d43..9f1951c8d 100644 --- a/mRemoteNG/UI/Forms/OptionsPages/UpdatesPage.cs +++ b/mRemoteNG/UI/Forms/OptionsPages/UpdatesPage.cs @@ -77,9 +77,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages if (CommonRegistrySettings.AllowCheckForUpdatesAutomatical) { cboUpdateCheckFrequency.Items.Clear(); - var nDaily = cboUpdateCheckFrequency.Items.Add(Language.Daily); - var nWeekly = cboUpdateCheckFrequency.Items.Add(Language.Weekly); - var nMonthly = cboUpdateCheckFrequency.Items.Add(Language.Monthly); + int nDaily = cboUpdateCheckFrequency.Items.Add(Language.Daily); + int nWeekly = cboUpdateCheckFrequency.Items.Add(Language.Weekly); + int nMonthly = cboUpdateCheckFrequency.Items.Add(Language.Monthly); if (Properties.OptionsUpdatesPage.Default.CheckForUpdatesFrequencyDays < 1) { chkCheckForUpdatesOnStartup.Checked = false; @@ -99,7 +99,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages cboUpdateCheckFrequency.SelectedIndex = nMonthly; break; default: - var nCustom = + int nCustom = cboUpdateCheckFrequency.Items.Add(string.Format(Language.UpdateFrequencyCustom, Properties.OptionsUpdatesPage.Default.CheckForUpdatesFrequencyDays)); cboUpdateCheckFrequency.SelectedIndex = nCustom; break; @@ -107,9 +107,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages } } - var stable = cboReleaseChannel.Items.Add(UpdateChannelInfo.STABLE); - var beta = cboReleaseChannel.Items.Add(UpdateChannelInfo.PREVIEW); - var dev = cboReleaseChannel.Items.Add(UpdateChannelInfo.NIGHTLY); + int stable = cboReleaseChannel.Items.Add(UpdateChannelInfo.STABLE); + int beta = cboReleaseChannel.Items.Add(UpdateChannelInfo.PREVIEW); + int dev = cboReleaseChannel.Items.Add(UpdateChannelInfo.NIGHTLY); switch (Properties.OptionsUpdatesPage.Default.UpdateChannel) { case UpdateChannelInfo.STABLE: @@ -134,7 +134,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages chkUseProxyAuthentication.Checked = Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication; tblProxyAuthentication.Enabled = Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication; txtProxyUsername.Text = Properties.OptionsUpdatesPage.Default.UpdateProxyAuthUser; - var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); + LegacyRijndaelCryptographyProvider cryptographyProvider = new(); txtProxyPassword.Text = cryptographyProvider.Decrypt(Properties.OptionsUpdatesPage.Default.UpdateProxyAuthPass, Runtime.EncryptionKey); @@ -170,7 +170,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication = chkUseProxyAuthentication.Checked; Properties.OptionsUpdatesPage.Default.UpdateProxyAuthUser = txtProxyUsername.Text; - var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); + LegacyRijndaelCryptographyProvider cryptographyProvider = new(); Properties.OptionsUpdatesPage.Default.UpdateProxyAuthPass = cryptographyProvider.Encrypt(txtProxyPassword.Text, Runtime.EncryptionKey); } diff --git a/mRemoteNG/UI/Forms/frmChoosePanel.cs b/mRemoteNG/UI/Forms/frmChoosePanel.cs index 05269d30e..414b63681 100644 --- a/mRemoteNG/UI/Forms/frmChoosePanel.cs +++ b/mRemoteNG/UI/Forms/frmChoosePanel.cs @@ -55,7 +55,7 @@ namespace mRemoteNG.UI.Forms { cbPanels.Items.Clear(); - for (var i = 0; i <= Runtime.WindowList.Count - 1; i++) + for (int i = 0; i <= Runtime.WindowList.Count - 1; i++) { cbPanels.Items.Add(Runtime.WindowList[i].Text.Replace("&&", "&")); } @@ -75,10 +75,10 @@ namespace mRemoteNG.UI.Forms private void btnNew_Click(object sender, System.EventArgs e) { - using (var frmInputBox = - new FrmInputBox(Language.NewPanel, Language.PanelName + ":", Language.NewPanel)) + using (FrmInputBox frmInputBox = + new(Language.NewPanel, Language.PanelName + ":", Language.NewPanel)) { - var dr = frmInputBox.ShowDialog(); + DialogResult dr = frmInputBox.ShowDialog(); if (dr != DialogResult.OK || string.IsNullOrEmpty(frmInputBox.returnValue)) return; _panelAdder.AddPanel(frmInputBox.returnValue); AddAvailablePanels(); diff --git a/mRemoteNG/UI/Forms/frmMain.cs b/mRemoteNG/UI/Forms/frmMain.cs index 4ad65af51..9a58d803c 100644 --- a/mRemoteNG/UI/Forms/frmMain.cs +++ b/mRemoteNG/UI/Forms/frmMain.cs @@ -54,7 +54,7 @@ namespace mRemoteNG.UI.Forms private bool _showFullPathInTitle; private readonly AdvancedWindowMenu _advancedWindowMenu; private ConnectionInfo _selectedConnection; - private readonly IList _messageWriters = new List(); + private readonly IList _messageWriters = []; private readonly ThemeManager _themeManager; private readonly FileBackupPruner _backupPruner = new(); public static FrmOptions OptionsForm; @@ -159,9 +159,9 @@ namespace mRemoteNG.UI.Forms private void FrmMain_Load(object sender, EventArgs e) { - var messageCollector = Runtime.MessageCollector; + MessageCollector messageCollector = Runtime.MessageCollector; - var settingsLoader = new SettingsLoader(this, messageCollector, _quickConnectToolStrip, _externalToolsToolStrip, _multiSshToolStrip, msMain); + SettingsLoader settingsLoader = new(this, messageCollector, _quickConnectToolStrip, _externalToolsToolStrip, _multiSshToolStrip, msMain); settingsLoader.LoadSettings(); MessageCollectorSetup.SetupMessageCollector(messageCollector, _messageWriters); @@ -171,7 +171,7 @@ namespace mRemoteNG.UI.Forms SetMenuDependencies(); - var uiLoader = new DockPanelLayoutLoader(this, messageCollector); + DockPanelLayoutLoader uiLoader = new(this, messageCollector); uiLoader.LoadPanelsFromXml(); LockToolbarPositions(Properties.Settings.Default.LockToolbars); @@ -181,7 +181,7 @@ namespace mRemoteNG.UI.Forms _fpChainedWindowHandle = NativeMethods.SetClipboardViewer(Handle); - Runtime.WindowList = new WindowList(); + Runtime.WindowList = []; if (Properties.App.Default.ResetPanels) SetDefaultLayout(); @@ -190,7 +190,7 @@ namespace mRemoteNG.UI.Forms Runtime.ConnectionsService.ConnectionsLoaded += ConnectionsServiceOnConnectionsLoaded; Runtime.ConnectionsService.ConnectionsSaved += ConnectionsServiceOnConnectionsSaved; - var credsAndConsSetup = new CredsAndConsSetup(); + CredsAndConsSetup credsAndConsSetup = new(); credsAndConsSetup.LoadCredsAndCons(); Windows.TreeForm.Focus(); @@ -224,9 +224,9 @@ namespace mRemoteNG.UI.Forms OptionsForm = new FrmOptions(); if (!Properties.OptionsTabsPanelsPage.Default.CreateEmptyPanelOnStartUp) return; - var panelName = !string.IsNullOrEmpty(Properties.OptionsTabsPanelsPage.Default.StartUpPanelName) ? Properties.OptionsTabsPanelsPage.Default.StartUpPanelName : Language.NewPanel; + string panelName = !string.IsNullOrEmpty(Properties.OptionsTabsPanelsPage.Default.StartUpPanelName) ? Properties.OptionsTabsPanelsPage.Default.StartUpPanelName : Language.NewPanel; - var panelAdder = new PanelAdder(); + PanelAdder panelAdder = new(); if (!panelAdder.DoesPanelExist(panelName)) panelAdder.AddPanel(panelName); } @@ -265,8 +265,8 @@ namespace mRemoteNG.UI.Forms private void LockToolbarPositions(bool shouldBeLocked) { - var toolbars = new ToolStrip[] {_quickConnectToolStrip, _multiSshToolStrip, _externalToolsToolStrip, msMain}; - foreach (var toolbar in toolbars) + ToolStrip[] toolbars = [_quickConnectToolStrip, _multiSshToolStrip, _externalToolsToolStrip, msMain]; + foreach (ToolStrip toolbar in toolbars) { toolbar.GripStyle = shouldBeLocked ? ToolStripGripStyle.Hidden : ToolStripGripStyle.Visible; } @@ -352,11 +352,11 @@ namespace mRemoteNG.UI.Forms if (Properties.OptionsUpdatesPage.Default.CheckForUpdatesAsked) return; string[] commandButtons = - { + [ Language.AskUpdatesCommandRecommended, Language.AskUpdatesCommandCustom, Language.AskUpdatesCommandAskLater - }; + ]; CTaskDialog.ShowTaskDialogBox(this, GeneralAppInfo.ProductName, Language.AskUpdatesMainInstruction, string.Format(Language.AskUpdatesContent, GeneralAppInfo.ProductName), "", "", "", "", string.Join(" | ", commandButtons), ETaskDialogButtons.None, ESysIcons.Question, ESysIcons.Question); @@ -378,7 +378,7 @@ namespace mRemoteNG.UI.Forms if (!Properties.OptionsUpdatesPage.Default.CheckForUpdatesOnStartup) return; - var nextUpdateCheck = + 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; @@ -417,10 +417,10 @@ namespace mRemoteNG.UI.Forms if (!(Runtime.WindowList == null || Runtime.WindowList.Count == 0)) { - var openConnections = 0; + int openConnections = 0; if (pnlDock.Contents.Count > 0) { - foreach (var dc in pnlDock.Contents) + foreach (IDockContent dc in pnlDock.Contents) { if (dc is not ConnectionWindow cw) continue; if (cw.Controls.Count < 1) continue; @@ -435,7 +435,7 @@ namespace mRemoteNG.UI.Forms (Properties.Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple & openConnections > 1) || Properties.Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Exit)) { - var result = CTaskDialog.MessageBox(this, Application.ProductName, Language.ConfirmExitMainInstruction, "", "", "", Language.CheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); + DialogResult result = CTaskDialog.MessageBox(this, Application.ProductName, Language.ConfirmExitMainInstruction, "", "", "", Language.CheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); if (CTaskDialog.VerificationChecked) { Properties.Settings.Default.ConfirmCloseConnection--; //--? @@ -510,7 +510,7 @@ namespace mRemoteNG.UI.Forms _inMouseActivate = true; break; case NativeMethods.WM_ACTIVATEAPP: - var candidateTabToFocus = FromChildHandle(NativeMethods.WindowFromPoint(MousePosition)) + Control candidateTabToFocus = FromChildHandle(NativeMethods.WindowFromPoint(MousePosition)) ?? GetChildAtPoint(MousePosition); if (candidateTabToFocus is InterfaceControl) candidateTabToFocus.Parent.Focus(); _inMouseActivate = false; @@ -519,7 +519,7 @@ namespace mRemoteNG.UI.Forms // Only handle this msg if it was triggered by a click if (NativeMethods.LOWORD(m.WParam) == NativeMethods.WA_CLICKACTIVE) { - var controlThatWasClicked = FromChildHandle(NativeMethods.WindowFromPoint(MousePosition)) + Control controlThatWasClicked = FromChildHandle(NativeMethods.WindowFromPoint(MousePosition)) ?? GetChildAtPoint(MousePosition); if (controlThatWasClicked != null) { @@ -553,7 +553,7 @@ namespace mRemoteNG.UI.Forms break; case NativeMethods.WM_WINDOWPOSCHANGED: // Ignore this message if the window wasn't activated - var windowPos = + NativeMethods.WINDOWPOS windowPos = (NativeMethods.WINDOWPOS)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.WINDOWPOS)); if ((windowPos.flags & NativeMethods.SWP_NOACTIVATE) == 0) { @@ -564,7 +564,7 @@ namespace mRemoteNG.UI.Forms case NativeMethods.WM_SYSCOMMAND: if (m.WParam == new IntPtr(0)) ShowHideMenu(); - var screen = _advancedWindowMenu.GetScreenById(m.WParam.ToInt32()); + Screen screen = _advancedWindowMenu.GetScreenById(m.WParam.ToInt32()); if (screen != null) { Screens.SendFormToScreen(screen); @@ -608,9 +608,9 @@ namespace mRemoteNG.UI.Forms private static void SimulateClick(Control control) { - var clientMousePosition = control.PointToClient(MousePosition); - var temp_wLow = clientMousePosition.X; - var temp_wHigh = clientMousePosition.Y; + Point clientMousePosition = control.PointToClient(MousePosition); + int temp_wLow = clientMousePosition.X; + int temp_wHigh = clientMousePosition.Y; NativeMethods.SendMessage(control.Handle, NativeMethods.WM_LBUTTONDOWN, (IntPtr)NativeMethods.MK_LBUTTON, (IntPtr)NativeMethods.MAKELPARAM(ref temp_wLow, ref temp_wHigh)); clientMousePosition.X = temp_wLow; @@ -619,15 +619,15 @@ namespace mRemoteNG.UI.Forms private void ActivateConnection() { - var cw = pnlDock.ActiveDocument as ConnectionWindow; - var dp = cw?.ActiveControl as DockPane; + ConnectionWindow cw = pnlDock.ActiveDocument as ConnectionWindow; + DockPane dp = cw?.ActiveControl as DockPane; if (dp?.ActiveContent is not ConnectionTab tab) return; - var ifc = InterfaceControl.FindInterfaceControl(tab); + InterfaceControl ifc = InterfaceControl.FindInterfaceControl(tab); if (ifc == null) return; ifc.Protocol.Focus(); - var conFormWindow = ifc.FindForm(); + Form conFormWindow = ifc.FindForm(); ((ConnectionTab)conFormWindow)?.RefreshInterfaceController(); } @@ -644,7 +644,7 @@ namespace mRemoteNG.UI.Forms return; } - var titleBuilder = new StringBuilder(Application.ProductName); + StringBuilder titleBuilder = new(Application.ProductName); const string separator = " - "; if (Runtime.ConnectionsService.IsConnectionsFileLoaded) @@ -686,10 +686,10 @@ namespace mRemoteNG.UI.Forms } else { - var nonConnectionPanelCount = 0; - foreach (var dockContent in pnlDock.Documents) + int nonConnectionPanelCount = 0; + foreach (IDockContent dockContent in pnlDock.Documents) { - var document = (DockContent)dockContent; + DockContent document = (DockContent)dockContent; if ((closingDocument == null || document != closingDocument) && document is not ConnectionWindow) { nonConnectionPanelCount++; diff --git a/mRemoteNG/UI/Forms/frmOptions.cs b/mRemoteNG/UI/Forms/frmOptions.cs index fc4e97897..267d3b7a2 100644 --- a/mRemoteNG/UI/Forms/frmOptions.cs +++ b/mRemoteNG/UI/Forms/frmOptions.cs @@ -18,7 +18,7 @@ namespace mRemoteNG.UI.Forms public partial class FrmOptions : Form { private int _currentIndex = 0; - private readonly List _optionPages = new(); + private readonly List _optionPages = []; private string _pageName; private readonly DisplayProperties _display = new(); private readonly List _optionPageObjectNames; @@ -36,8 +36,8 @@ namespace mRemoteNG.UI.Forms _pageName = pageName; Cursor.Current = Cursors.Default; - _optionPageObjectNames = new List - { + _optionPageObjectNames = + [ nameof(StartupExitPage), nameof(AppearancePage), nameof(ConnectionsPage), @@ -50,7 +50,7 @@ namespace mRemoteNG.UI.Forms nameof(SecurityPage), nameof(AdvancedPage), nameof(BackupPage) - }; + ]; InitOptionsPagesToListView(); } @@ -222,8 +222,8 @@ namespace mRemoteNG.UI.Forms { _pageName = pageName ?? Language.StartupExit; - var isSet = false; - for (var i = 0; i < lstOptionPages.Items.Count; i++) + bool isSet = false; + for (int i = 0; i < lstOptionPages.Items.Count; i++) { if (!lstOptionPages.Items[i].Text.Equals(_pageName)) continue; lstOptionPages.Items[i].Selected = true; @@ -248,7 +248,7 @@ namespace mRemoteNG.UI.Forms private void SaveOptions() { - foreach (var page in _optionPages) + foreach (OptionsPage page in _optionPages) { Debug.WriteLine(page.PageName); page.SaveSettings(); @@ -262,7 +262,7 @@ namespace mRemoteNG.UI.Forms { pnlMain.Controls.Clear(); - var page = (OptionsPage)lstOptionPages.SelectedObject; + OptionsPage page = (OptionsPage)lstOptionPages.SelectedObject; if (page != null) pnlMain.Controls.Add(page); } diff --git a/mRemoteNG/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs b/mRemoteNG/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs index f3a39a165..27c115a1b 100644 --- a/mRemoteNG/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs +++ b/mRemoteNG/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs @@ -18,9 +18,9 @@ namespace mRemoteNG.UI.GraphicsUtilities { //This method could be optimized, as it is called for every control / subcontrol //and causes overhead for 100s in the options page - using (var f = new Form()) + using (Form f = new()) { - var g = f.CreateGraphics(); + Graphics g = f.CreateGraphics(); return new SizeF(g.DpiX / BaselineDpi, g.DpiY / BaselineDpi); } } diff --git a/mRemoteNG/UI/Menu/AdvancedWindowMenu.cs b/mRemoteNG/UI/Menu/AdvancedWindowMenu.cs index 67fa2502c..4c179d6cb 100644 --- a/mRemoteNG/UI/Menu/AdvancedWindowMenu.cs +++ b/mRemoteNG/UI/Menu/AdvancedWindowMenu.cs @@ -20,7 +20,7 @@ namespace mRemoteNG.UI.Menu public Screen GetScreenById(int id) { - for (var i = 0; i <= _sysMenSubItems.Length - 1; i++) + for (int i = 0; i <= _sysMenSubItems.Length - 1; i++) { if (_sysMenSubItems[i] != id) continue; return Screen.AllScreens[i]; @@ -43,8 +43,8 @@ namespace mRemoteNG.UI.Menu public void BuildAdditionalMenuItems() { // option to send main form to another screen - var popMen = _windowMenu.CreatePopupMenuItem(); - for (var i = 0; i <= Screen.AllScreens.Length - 1; i++) + IntPtr popMen = _windowMenu.CreatePopupMenuItem(); + for (int i = 0; i <= Screen.AllScreens.Length - 1; i++) { _sysMenSubItems[i] = 200 + i; _windowMenu.AppendMenuItem(popMen, WindowMenu.Flags.MF_STRING, new IntPtr(_sysMenSubItems[i]), diff --git a/mRemoteNG/UI/Menu/msMain/FileMenu.cs b/mRemoteNG/UI/Menu/msMain/FileMenu.cs index 248924117..d98608ffa 100644 --- a/mRemoteNG/UI/Menu/msMain/FileMenu.cs +++ b/mRemoteNG/UI/Menu/msMain/FileMenu.cs @@ -137,7 +137,7 @@ namespace mRemoteNG.UI.Menu private void mMenFileNew_Click(object sender, EventArgs e) { - using (var saveFileDialog = DialogFactory.ConnectionsSaveAsDialog()) + using (SaveFileDialog saveFileDialog = DialogFactory.ConnectionsSaveAsDialog()) { if (saveFileDialog.ShowDialog() != DialogResult.OK) { @@ -152,7 +152,7 @@ namespace mRemoteNG.UI.Menu { if (Runtime.ConnectionsService.IsConnectionsFileLoaded) { - var msgBoxResult = MessageBox.Show(Language.SaveConnectionsFileBeforeOpeningAnother, + DialogResult msgBoxResult = MessageBox.Show(Language.SaveConnectionsFileBeforeOpeningAnother, Language.Save, MessageBoxButtons.YesNoCancel); // ReSharper disable once SwitchStatementMissingSomeCases switch (msgBoxResult) @@ -175,12 +175,12 @@ namespace mRemoteNG.UI.Menu private void mMenFileSaveAs_Click(object sender, EventArgs e) { - using (var saveFileDialog = DialogFactory.ConnectionsSaveAsDialog()) + using (SaveFileDialog saveFileDialog = DialogFactory.ConnectionsSaveAsDialog()) { if (saveFileDialog.ShowDialog(FrmMain.Default) != DialogResult.OK) return; - var newFileName = saveFileDialog.FileName; + string newFileName = saveFileDialog.FileName; Runtime.ConnectionsService.SaveConnections(Runtime.ConnectionsService.ConnectionTreeModel, false, new SaveFilter(), newFileName); diff --git a/mRemoteNG/UI/Menu/msMain/ViewMenu.cs b/mRemoteNG/UI/Menu/msMain/ViewMenu.cs index 6f1cd3ac0..e2b63147b 100644 --- a/mRemoteNG/UI/Menu/msMain/ViewMenu.cs +++ b/mRemoteNG/UI/Menu/msMain/ViewMenu.cs @@ -207,9 +207,9 @@ namespace mRemoteNG.UI.Menu _mMenViewConnectionPanels.DropDownItems.Clear(); - for (var i = 0; i <= Runtime.WindowList.Count - 1; i++) + for (int i = 0; i <= Runtime.WindowList.Count - 1; i++) { - var tItem = new ToolStripMenuItem(Runtime.WindowList[i].Text, Runtime.WindowList[i].Icon.ToBitmap(), ConnectionPanelMenuItem_Click) + ToolStripMenuItem tItem = new(Runtime.WindowList[i].Text, Runtime.WindowList[i].Icon.ToBitmap(), ConnectionPanelMenuItem_Click) { Tag = Runtime.WindowList[i] }; _mMenViewConnectionPanels.DropDownItems.Add(tItem); } @@ -251,7 +251,7 @@ namespace mRemoteNG.UI.Menu private void mMenViewResetLayout_Click(object sender, EventArgs e) { - var msgBoxResult = MessageBox.Show(Language.ConfirmResetLayout, string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult msgBoxResult = MessageBox.Show(Language.ConfirmResetLayout, string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (msgBoxResult == DialogResult.Yes) { MainForm.SetDefaultLayout(); diff --git a/mRemoteNG/UI/Panels/PanelAdder.cs b/mRemoteNG/UI/Panels/PanelAdder.cs index e33ddbe67..75d9afde7 100644 --- a/mRemoteNG/UI/Panels/PanelAdder.cs +++ b/mRemoteNG/UI/Panels/PanelAdder.cs @@ -19,7 +19,7 @@ namespace mRemoteNG.UI.Panels { try { - var connectionForm = new ConnectionWindow(new DockContent()); + ConnectionWindow connectionForm = new(new DockContent()); BuildConnectionWindowContextMenu(connectionForm); SetConnectionWindowTitle(title, connectionForm); ShowConnectionWindow(connectionForm); @@ -58,17 +58,17 @@ namespace mRemoteNG.UI.Panels private static void BuildConnectionWindowContextMenu(DockContent pnlcForm) { - var cMen = new ContextMenuStrip(); - var cMenRen = CreateRenameMenuItem(pnlcForm); - var cMenScreens = CreateScreensMenuItem(pnlcForm); - var cMenClose = CreateCloseMenuItem(pnlcForm); + ContextMenuStrip cMen = new(); + ToolStripMenuItem cMenRen = CreateRenameMenuItem(pnlcForm); + ToolStripMenuItem cMenScreens = CreateScreensMenuItem(pnlcForm); + ToolStripMenuItem cMenClose = CreateCloseMenuItem(pnlcForm); cMen.Items.AddRange(new ToolStripItem[] {cMenRen, cMenScreens, cMenClose}); pnlcForm.TabPageContextMenuStrip = cMen; } private static ToolStripMenuItem CreateScreensMenuItem(DockContent pnlcForm) { - var cMenScreens = new ToolStripMenuItem + ToolStripMenuItem cMenScreens = new() { Text = Language.SendTo, Image = Properties.Resources.Monitor_16x, @@ -81,7 +81,7 @@ namespace mRemoteNG.UI.Panels private static ToolStripMenuItem CreateRenameMenuItem(DockContent pnlcForm) { - var cMenRen = new ToolStripMenuItem + ToolStripMenuItem cMenRen = new() { Text = Language.Rename, Image = Properties.Resources.Rename_16x, @@ -93,7 +93,7 @@ namespace mRemoteNG.UI.Panels private static ToolStripMenuItem CreateCloseMenuItem(DockContent pnlcForm) { - var cMenClose = new ToolStripMenuItem + ToolStripMenuItem cMenClose = new() { Text = Language._Close, Image = Properties.Resources.Close_16x, @@ -107,9 +107,9 @@ namespace mRemoteNG.UI.Panels { try { - var conW = (ConnectionWindow)((ToolStripMenuItem)sender).Tag; + ConnectionWindow conW = (ConnectionWindow)((ToolStripMenuItem)sender).Tag; - using (var newTitle = new FrmInputBox(Language.NewTitle, Language.NewTitle + ":", "")) + using (FrmInputBox newTitle = new(Language.NewTitle, Language.NewTitle + ":", "")) if (newTitle.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(newTitle.returnValue)) conW.SetFormText(newTitle.returnValue.Replace("&", "&&")); } @@ -123,7 +123,7 @@ namespace mRemoteNG.UI.Panels { try { - var conW = (ConnectionWindow)((ToolStripMenuItem)sender).Tag; + ConnectionWindow conW = (ConnectionWindow)((ToolStripMenuItem)sender).Tag; conW.Close(); } catch (Exception ex) @@ -136,12 +136,12 @@ namespace mRemoteNG.UI.Panels { try { - var cMenScreens = (ToolStripMenuItem)sender; + ToolStripMenuItem cMenScreens = (ToolStripMenuItem)sender; cMenScreens.DropDownItems.Clear(); - for (var i = 0; i <= Screen.AllScreens.Length - 1; i++) + for (int i = 0; i <= Screen.AllScreens.Length - 1; i++) { - var cMenScreen = new ToolStripMenuItem(Language.Screen + " " + Convert.ToString(i + 1)) + ToolStripMenuItem cMenScreen = new(Language.Screen + " " + Convert.ToString(i + 1)) { Tag = new ArrayList(), Image = Properties.Resources.Monitor_16x @@ -164,9 +164,9 @@ namespace mRemoteNG.UI.Panels DockContent panel = null; try { - var tagEnumeration = (IEnumerable)((ToolStripMenuItem)sender).Tag; + IEnumerable tagEnumeration = (IEnumerable)((ToolStripMenuItem)sender).Tag; if (tagEnumeration == null) return; - foreach (var obj in tagEnumeration) + foreach (object obj in tagEnumeration) { if (obj is Screen screen1) { diff --git a/mRemoteNG/UI/StatusImageList.cs b/mRemoteNG/UI/StatusImageList.cs index ca6b6b2fb..92257ae2e 100644 --- a/mRemoteNG/UI/StatusImageList.cs +++ b/mRemoteNG/UI/StatusImageList.cs @@ -16,14 +16,12 @@ namespace mRemoteNG.UI public StatusImageList() { - var display = new DisplayProperties(); + DisplayProperties display = new(); ImageList = new ImageList { ColorDepth = ColorDepth.Depth32Bit, - ImageSize = new Size( - (int)Math.Round(16 * display.ResolutionScalingFactor.Width), - (int)Math.Round(16 * display.ResolutionScalingFactor.Height)), + ImageSize = new Size((int)Math.Round(16 * display.ResolutionScalingFactor.Width), (int)Math.Round(16 * display.ResolutionScalingFactor.Height)), TransparentColor = Color.Transparent }; @@ -37,7 +35,7 @@ namespace mRemoteNG.UI public Image GetImage(ConnectionInfo connectionInfo) { - var key = GetKey(connectionInfo); + string key = GetKey(connectionInfo); return ImageList.Images.ContainsKey(key) ? ImageList.Images[key] : null; @@ -55,7 +53,7 @@ namespace mRemoteNG.UI private static string BuildConnectionIconName(string icon, bool connected) { - var status = connected ? "Play" : "Default"; + string status = connected ? "Play" : "Default"; return $"Connection_{icon}_{status}"; } @@ -68,25 +66,24 @@ namespace mRemoteNG.UI return DefaultConnectionIcon; } - var connected = connection.OpenConnections.Count > 0; - var name = BuildConnectionIconName(connection.Icon, connected); + bool connected = connection.OpenConnections.Count > 0; + string name = BuildConnectionIconName(connection.Icon, connected); if (ImageList.Images.ContainsKey(name)) return name; - var image = ConnectionIcon.FromString(connection.Icon); + Icon image = ConnectionIcon.FromString(connection.Icon); if (image == null) { return DefaultConnectionIcon; } ImageList.Images.Add(BuildConnectionIconName(connection.Icon, false), image); - ImageList.Images.Add(BuildConnectionIconName(connection.Icon, true), - Overlay(image, Properties.Resources.ConnectedOverlay)); + ImageList.Images.Add(BuildConnectionIconName(connection.Icon, true), Overlay(image, Properties.Resources.ConnectedOverlay)); return name; } private static Bitmap Overlay(Icon background, Image foreground) { - var result = new Bitmap(background.ToBitmap(), new Size(16, 16)); - using (var gr = Graphics.FromImage(result)) + Bitmap result = new(background.ToBitmap(), new Size(16, 16)); + using (Graphics gr = Graphics.FromImage(result)) { gr.DrawImage(foreground, new Rectangle(0, 0, foreground.Width, foreground.Height)); } @@ -104,9 +101,7 @@ namespace mRemoteNG.UI } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace( - $"Unable to fill the image list of type {nameof(StatusImageList)}", - ex); + Runtime.MessageCollector.AddExceptionStackTrace($"Unable to fill the image list of type {nameof(StatusImageList)}", ex); } } diff --git a/mRemoteNG/UI/Tabs/ConnectionTab.cs b/mRemoteNG/UI/Tabs/ConnectionTab.cs index 894f7cccf..82d2926f1 100644 --- a/mRemoteNG/UI/Tabs/ConnectionTab.cs +++ b/mRemoteNG/UI/Tabs/ConnectionTab.cs @@ -46,7 +46,7 @@ namespace mRemoteNG.UI.Tabs { if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All) { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, + DialogResult result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string .Format(Language.ConfirmCloseConnectionPanelMainInstruction, TabText), "", "", "", @@ -89,7 +89,7 @@ namespace mRemoteNG.UI.Tabs { try { - var interfaceControl = Tag as InterfaceControl; + InterfaceControl interfaceControl = Tag as InterfaceControl; if (interfaceControl?.Info.Protocol == ProtocolType.VNC) ((ProtocolVNC)interfaceControl.Protocol).RefreshScreen(); } diff --git a/mRemoteNG/UI/Tabs/DockPaneStripNG.cs b/mRemoteNG/UI/Tabs/DockPaneStripNG.cs index c798621db..485c651f7 100644 --- a/mRemoteNG/UI/Tabs/DockPaneStripNG.cs +++ b/mRemoteNG/UI/Tabs/DockPaneStripNG.cs @@ -117,7 +117,7 @@ namespace mRemoteNG.UI.Tabs { get { - var rect = ClientRectangle; + Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } @@ -127,7 +127,7 @@ namespace mRemoteNG.UI.Tabs { get { - var rect = ClientRectangle; + Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - DocumentStripGapBottom); } @@ -140,11 +140,11 @@ namespace mRemoteNG.UI.Tabs if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; - var rectWindow = TabStripRectangle; - var x = rectWindow.X; - var y = rectWindow.Y; - var width = rectWindow.Width; - var height = rectWindow.Height; + Rectangle rectWindow = TabStripRectangle; + int x = rectWindow.X; + int y = rectWindow.Y; + int width = rectWindow.Width; + int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + @@ -393,7 +393,7 @@ namespace mRemoteNG.UI.Tabs if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; - var height = Math.Max(TextFont.Height + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), + int height = Math.Max(TextFont.Height + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; @@ -402,7 +402,7 @@ namespace mRemoteNG.UI.Tabs private int MeasureHeight_Document() { - var height = + int height = Math.Max( TextFont.Height + DocumentTabGapTop + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), @@ -440,16 +440,16 @@ namespace mRemoteNG.UI.Tabs private GraphicsPath GetOutline_Document(int index) { - var rectangle = Tabs[index].Rectangle; + Rectangle? rectangle = Tabs[index].Rectangle; if (rectangle == null) return null; - var rectTab = rectangle.Value; + Rectangle rectTab = rectangle.Value; rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); - var rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); + Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); - var path = new GraphicsPath(); - var pathTab = GetTabOutline_Document(Tabs[index], true, true, true); + GraphicsPath path = new(); + GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) @@ -474,15 +474,15 @@ namespace mRemoteNG.UI.Tabs private GraphicsPath GetOutline_ToolWindow(int index) { - var rectangle = Tabs[index].Rectangle; + Rectangle? rectangle = Tabs[index].Rectangle; if (rectangle == null) return null; - var rectTab = rectangle.Value; + Rectangle rectTab = rectangle.Value; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); - var rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); + Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); - var path = new GraphicsPath(); - var pathTab = GetTabOutline(Tabs[index], true, true); + GraphicsPath path = new(); + GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); @@ -505,29 +505,29 @@ namespace mRemoteNG.UI.Tabs if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; - var rectTabStrip = TabStripRectangle; + Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths - var countTabs = Tabs.Count; - foreach (var tab1 in Tabs) + int countTabs = Tabs.Count; + foreach (Tab tab1 in Tabs) { - var tab = (MremoteNGTab)tab1; + MremoteNGTab tab = (MremoteNGTab)tab1; tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage; - var totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; - var totalAllocatedWidth = 0; - var averageWidth = totalWidth / countTabs; - var remainedTabs = countTabs; + int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; + int totalAllocatedWidth = 0; + int averageWidth = totalWidth / countTabs; + int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0;) { anyWidthWithinAverage = false; - foreach (var tab1 in Tabs) + foreach (Tab tab1 in Tabs) { - var tab = (MremoteNGTab)tab1; + MremoteNGTab tab = (MremoteNGTab)tab1; if (tab.Flag) continue; @@ -546,10 +546,10 @@ namespace mRemoteNG.UI.Tabs // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { - var roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); - foreach (var tab1 in Tabs) + int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); + foreach (Tab tab1 in Tabs) { - var tab = (MremoteNGTab)tab1; + MremoteNGTab tab = (MremoteNGTab)tab1; if (tab.Flag) continue; @@ -565,10 +565,10 @@ namespace mRemoteNG.UI.Tabs } // Set the X position of the tabs - var x = rectTabStrip.X + ToolWindowStripGapLeft; - foreach (var tab1 in Tabs) + int x = rectTabStrip.X + ToolWindowStripGapLeft; + foreach (Tab tab1 in Tabs) { - var tab = (MremoteNGTab)tab1; + MremoteNGTab tab = (MremoteNGTab)tab1; tab.TabX = x; x += tab.TabWidth; } @@ -576,11 +576,11 @@ namespace mRemoteNG.UI.Tabs private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { - var overflow = false; + bool overflow = false; if (!(Tabs[index] is MremoteNGTab tab)) return false; tab.MaxWidth = GetMaxTabWidth(index); - var width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); + int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; @@ -607,10 +607,10 @@ namespace mRemoteNG.UI.Tabs if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; - var rectTabStrip = TabsRectangle; + Rectangle rectTabStrip = TabsRectangle; - var x = rectTabStrip.X; //+ rectTabStrip.Height / 2; - var overflow = false; + int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; + bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to @@ -619,12 +619,12 @@ namespace mRemoteNG.UI.Tabs // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { - var tempX = x; + int tempX = x; if (Tabs[m_startDisplayingTab] is MremoteNGTab tab) tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left - for (var i = StartDisplayingTab; i >= 0; i--) + for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it @@ -636,7 +636,7 @@ namespace mRemoteNG.UI.Tabs // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. - for (var i = EndDisplayingTab; i < Tabs.Count; i++) + for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. @@ -645,9 +645,9 @@ namespace mRemoteNG.UI.Tabs } else { - for (var i = StartDisplayingTab; i < Tabs.Count; i++) + for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); - for (var i = 0; i < StartDisplayingTab; i++) + for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; @@ -658,9 +658,9 @@ namespace mRemoteNG.UI.Tabs m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X; - foreach (var tab1 in Tabs) + foreach (Tab tab1 in Tabs) { - var tab = (MremoteNGTab)tab1; + MremoteNGTab tab = (MremoteNGTab)tab1; tab.TabX = x; x += tab.TabWidth; } @@ -680,7 +680,7 @@ namespace mRemoteNG.UI.Tabs private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { - var index = Tabs.IndexOf(content); + int index = Tabs.IndexOf(content); if (index == -1) // TODO: should prevent it from being -1; return false; @@ -703,8 +703,8 @@ namespace mRemoteNG.UI.Tabs private int GetMaxTabWidth_ToolWindow(int index) { - var content = Tabs[index].Content; - var sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); + IDockContent content = Tabs[index].Content; + Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } @@ -713,9 +713,9 @@ namespace mRemoteNG.UI.Tabs private int GetMaxTabWidth_Document(int index) { - var content = Tabs[index].Content; - var height = GetTabRectangle_Document(index).Height; - var sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, + IDockContent content = Tabs[index].Content; + int height = GetTabRectangle_Document(index).Height; + Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; @@ -732,7 +732,7 @@ namespace mRemoteNG.UI.Tabs private void DrawTabStrip(Graphics g) { // IMPORTANT: fill background. - var rectTabStrip = TabStripRectangle; + Rectangle rectTabStrip = TabStripRectangle; g.FillRectangle( DockPane.DockPanel.Theme.PaintingService.GetBrush(DockPane.DockPanel.Theme.ColorPalette .MainWindowActive @@ -746,19 +746,19 @@ namespace mRemoteNG.UI.Tabs private void DrawTabStrip_Document(Graphics g) { - var count = Tabs.Count; + int count = Tabs.Count; if (count == 0) return; - var rectTabStrip = new Rectangle(TabStripRectangle.Location, TabStripRectangle.Size); + Rectangle rectTabStrip = new(TabStripRectangle.Location, TabStripRectangle.Size); rectTabStrip.Height += 1; // Draw the tabs - var rectTabOnly = TabsRectangle; + Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab; MremoteNGTab tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) @@ -799,13 +799,13 @@ namespace mRemoteNG.UI.Tabs private void DrawTabStrip_ToolWindow(Graphics g) { - var rect = TabStripRectangle_ToolWindow; - var borderColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowBorder; + Rectangle rect = TabStripRectangle_ToolWindow; + Color borderColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowBorder; g.DrawLine(DockPane.DockPanel.Theme.PaintingService.GetPen(borderColor), rect.Left, rect.Top, rect.Right, rect.Top); - for (var i = 0; i < Tabs.Count; i++) + for (int i = 0; i < Tabs.Count; i++) { if (!(Tabs[i] is MremoteNGTab tab)) continue; tab.Rectangle = GetTabRectangle(i); @@ -822,18 +822,18 @@ namespace mRemoteNG.UI.Tabs private Rectangle GetTabRectangle_ToolWindow(int index) { - var rectTabStrip = TabStripRectangle; + Rectangle rectTabStrip = TabStripRectangle; - var tab = (MremoteNGTab)Tabs[index]; + MremoteNGTab tab = (MremoteNGTab)Tabs[index]; return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { - var rectTabStrip = TabStripRectangle; - var tab = (MremoteNGTab)Tabs[index]; + Rectangle rectTabStrip = TabStripRectangle; + MremoteNGTab tab = (MremoteNGTab)Tabs[index]; - var rect = new Rectangle + Rectangle rect = new() { X = tab.TabX, Width = tab.TabWidth, Height = rectTabStrip.Height - DocumentTabGapTop }; @@ -863,7 +863,7 @@ namespace mRemoteNG.UI.Tabs private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { - var rect = GetTabRectangle(Tabs.IndexOf(tab)); + Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) @@ -876,7 +876,7 @@ namespace mRemoteNG.UI.Tabs private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); - var rect = GetTabRectangle(Tabs.IndexOf(tab)); + Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); @@ -894,12 +894,12 @@ namespace mRemoteNG.UI.Tabs private void DrawTab_ToolWindow(Graphics g, MremoteNGTab tab) { if (tab.Rectangle == null) return; - var rect = tab.Rectangle.Value; - var rectIcon = new Rectangle( + Rectangle rect = tab.Rectangle.Value; + Rectangle rectIcon = new( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); - var rectText = PatchController.EnableHighDpi == true + Rectangle rectText = PatchController.EnableHighDpi == true ? new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - ToolWindowImageGapBottom - TextFont.Height, @@ -909,12 +909,12 @@ namespace mRemoteNG.UI.Tabs rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; - var rectTab = DrawHelper.RtlTransform(this, rect); + Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); - var borderColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowBorder; + Color borderColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowBorder; - var separatorColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowSeparator; + Color separatorColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowSeparator; if (DockPane.ActiveContent == tab.Content) { Color textColor; @@ -969,16 +969,16 @@ namespace mRemoteNG.UI.Tabs private void DrawTab_Document(Graphics g, MremoteNGTab tab) { if (tab.Rectangle == null) return; - var rect = tab.Rectangle.Value; + Rectangle rect = tab.Rectangle.Value; if (tab.TabWidth == 0) return; - var rectCloseButton = GetCloseButtonRect(rect); - var rectIcon = new Rectangle( + Rectangle rectCloseButton = GetCloseButtonRect(rect); + Rectangle rectIcon = new( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); - var rectText = PatchController.EnableHighDpi == true + Rectangle rectText = PatchController.EnableHighDpi == true ? new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - TextFont.Height, @@ -995,28 +995,28 @@ namespace mRemoteNG.UI.Tabs else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; - var rectTab = DrawHelper.RtlTransform(this, rect); - var rectBack = DrawHelper.RtlTransform(this, rect); + Rectangle rectTab = DrawHelper.RtlTransform(this, rect); + Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += DocumentIconGapLeft; rectBack.X -= DocumentIconGapLeft; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); - var activeColor = DockPane.DockPanel.Theme.ColorPalette.TabSelectedActive.Background; - var lostFocusColor = DockPane.DockPanel.Theme.ColorPalette.TabSelectedInactive.Background; - var inactiveColor = DockPane.DockPanel.Theme.ColorPalette.MainWindowActive.Background; - var mouseHoverColor = DockPane.DockPanel.Theme.ColorPalette.TabUnselectedHovered.Background; + Color activeColor = DockPane.DockPanel.Theme.ColorPalette.TabSelectedActive.Background; + Color lostFocusColor = DockPane.DockPanel.Theme.ColorPalette.TabSelectedInactive.Background; + Color inactiveColor = DockPane.DockPanel.Theme.ColorPalette.MainWindowActive.Background; + Color mouseHoverColor = DockPane.DockPanel.Theme.ColorPalette.TabUnselectedHovered.Background; - var activeText = DockPane.DockPanel.Theme.ColorPalette.TabSelectedActive.Text; - var lostFocusText = DockPane.DockPanel.Theme.ColorPalette.TabSelectedInactive.Text; - var inactiveText = DockPane.DockPanel.Theme.ColorPalette.TabUnselected.Text; - var mouseHoverText = DockPane.DockPanel.Theme.ColorPalette.TabUnselectedHovered.Text; + Color activeText = DockPane.DockPanel.Theme.ColorPalette.TabSelectedActive.Text; + Color lostFocusText = DockPane.DockPanel.Theme.ColorPalette.TabSelectedInactive.Text; + Color inactiveText = DockPane.DockPanel.Theme.ColorPalette.TabUnselected.Text; + Color mouseHoverText = DockPane.DockPanel.Theme.ColorPalette.TabUnselectedHovered.Text; Color text; Image image = null; Color paint; - var imageService = DockPane.DockPanel.Theme.ImageService; + IImageService imageService = DockPane.DockPanel.Theme.ImageService; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) @@ -1104,11 +1104,11 @@ namespace mRemoteNG.UI.Tabs if (!m_suspendDrag) base.OnMouseMove(e); - var index = HitTest(PointToClient(MousePosition)); - var toolTip = string.Empty; + int index = HitTest(PointToClient(MousePosition)); + string toolTip = string.Empty; - var tabUpdate = false; - var buttonUpdate = false; + bool tabUpdate = false; + bool buttonUpdate = false; if (index != -1) { if (Tabs[index] is MremoteNGTab tab) @@ -1124,12 +1124,12 @@ namespace mRemoteNG.UI.Tabs else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; - var mousePos = PointToClient(MousePosition); + Point mousePos = PointToClient(MousePosition); if (tab.Rectangle != null) { - var tabRect = tab.Rectangle.Value; - var closeButtonRect = GetCloseButtonRect(tabRect); - var mouseRect = new Rectangle(mousePos, new Size(1, 1)); + Rectangle tabRect = tab.Rectangle.Value; + Rectangle closeButtonRect = GetCloseButtonRect(tabRect); + Rectangle mouseRect = new(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); @@ -1157,15 +1157,15 @@ namespace mRemoteNG.UI.Tabs if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; - var indexHit = HitTest(); + int indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { - var mousePos = PointToClient(MousePosition); - var tabRect = GetTabBounds(Tabs[index]); + Point mousePos = PointToClient(MousePosition); + Rectangle tabRect = GetTabBounds(Tabs[index]); if (tabRect.Contains(ActiveClose) && ActiveCloseHitTest(mousePos)) TryCloseTab(index); } @@ -1178,7 +1178,7 @@ namespace mRemoteNG.UI.Tabs } const int gap = 3; - var imageSize = PatchController.EnableHighDpi == true ? rectTab.Height - gap * 2 : 15; + int imageSize = PatchController.EnableHighDpi == true ? rectTab.Height - gap * 2 : 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize); } @@ -1186,24 +1186,24 @@ namespace mRemoteNG.UI.Tabs private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); - foreach (var tab1 in Tabs) + foreach (Tab tab1 in Tabs) { - var tab = (MremoteNGTab)tab1; - var content = tab.Content; - var item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); + MremoteNGTab tab = (MremoteNGTab)tab1; + IDockContent content = tab.Content; + ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += ContextMenuItem_Click; } - var workingArea = + Rectangle workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); - var menu = new Rectangle( + Rectangle menu = new( ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); - var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, + Rectangle menuMargined = new(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { @@ -1211,12 +1211,12 @@ namespace mRemoteNG.UI.Tabs } else { - var newPoint = menu.Location; + Point newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); - var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); + Point button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. @@ -1233,7 +1233,7 @@ namespace mRemoteNG.UI.Tabs private void ContextMenuItem_Click(object sender, EventArgs e) { if (!(sender is ToolStripMenuItem item)) return; - var content = (IDockContent)item.Tag; + IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } @@ -1270,24 +1270,24 @@ namespace mRemoteNG.UI.Tabs private void LayoutButtons() { - var rectTabStrip = TabStripRectangle; + Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons - var buttonWidth = ButtonOverflow.Image.Width; - var buttonHeight = ButtonOverflow.Image.Height; - var height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; + int buttonWidth = ButtonOverflow.Image.Width; + int buttonHeight = ButtonOverflow.Image.Height; + int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * height / buttonHeight; buttonHeight = height; } - var buttonSize = new Size(buttonWidth, buttonHeight); + Size buttonSize = new(buttonWidth, buttonHeight); - var x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft + int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; - var y = rectTabStrip.Y + DocumentButtonGapTop; - var point = new Point(x, y); + int y = rectTabStrip.Y + DocumentButtonGapTop; + Point point = new(x, y); ButtonOverflow.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. @@ -1310,9 +1310,9 @@ namespace mRemoteNG.UI.Tabs if (!TabsRectangle.Contains(point)) return -1; - foreach (var tab in Tabs) + foreach (Tab tab in Tabs) { - var path = GetTabOutline(tab, true, false); + GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(point)) return Tabs.IndexOf(tab); } @@ -1322,7 +1322,7 @@ namespace mRemoteNG.UI.Tabs protected override bool MouseDownActivateTest(MouseEventArgs e) { - var result = base.MouseDownActivateTest(e); + bool result = base.MouseDownActivateTest(e); if (result && (e.Button == MouseButtons.Left) && (Appearance == DockPane.AppearanceStyle.Document)) { // don't activate if mouse is down on active close button @@ -1335,14 +1335,14 @@ namespace mRemoteNG.UI.Tabs private bool ActiveCloseHitTest(Point ptMouse) { if (ActiveClose.IsEmpty) return false; - var mouseRect = new Rectangle(ptMouse, new Size(1, 1)); + Rectangle mouseRect = new(ptMouse, new Size(1, 1)); return ActiveClose.IntersectsWith(mouseRect); } protected override Rectangle GetTabBounds(Tab tab) { - var path = GetTabOutline(tab, true, false); - var rectangle = path.GetBounds(); + GraphicsPath path = GetTabOutline(tab, true, false); + RectangleF rectangle = path.GetBounds(); return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height); } @@ -1368,8 +1368,8 @@ namespace mRemoteNG.UI.Tabs protected override void OnMouseLeave(EventArgs e) { - var tabUpdate = SetMouseOverTab(null); - var buttonUpdate = SetActiveClose(Rectangle.Empty); + bool tabUpdate = SetMouseOverTab(null); + bool buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); @@ -1384,7 +1384,7 @@ namespace mRemoteNG.UI.Tabs private void CloseProtocol() { - var ic = InterfaceControl.FindInterfaceControl(DockPane.DockPanel); + InterfaceControl ic = InterfaceControl.FindInterfaceControl(DockPane.DockPanel); ic?.Protocol.Close(); } diff --git a/mRemoteNG/UI/Tabs/MremoteNGAutoHideStrip.cs b/mRemoteNG/UI/Tabs/MremoteNGAutoHideStrip.cs index 86602854d..41dc95c8e 100644 --- a/mRemoteNG/UI/Tabs/MremoteNGAutoHideStrip.cs +++ b/mRemoteNG/UI/Tabs/MremoteNGAutoHideStrip.cs @@ -72,12 +72,14 @@ namespace mRemoteNG.UI.Tabs { if (_stringFormatTabVertical == null) { - _stringFormatTabVertical = new StringFormat(); - _stringFormatTabVertical.Alignment = StringAlignment.Near; - _stringFormatTabVertical.LineAlignment = StringAlignment.Center; - _stringFormatTabVertical.FormatFlags = - StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; - _stringFormatTabVertical.Trimming = StringTrimming.None; + _stringFormatTabVertical = new StringFormat + { + Alignment = StringAlignment.Near, + LineAlignment = StringAlignment.Center, + FormatFlags = + StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical, + Trimming = StringTrimming.None + }; } if (RightToLeft == RightToLeft.Yes) @@ -162,12 +164,12 @@ namespace mRemoteNG.UI.Tabs protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); - var g = e.Graphics; + Graphics g = e.Graphics; - var startColor = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.StartColor; - var endColor = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.EndColor; - var gradientMode = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode; - using (var brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) + Color startColor = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.StartColor; + Color endColor = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.EndColor; + LinearGradientMode gradientMode = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode; + using (LinearGradientBrush brush = new(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } @@ -191,21 +193,21 @@ namespace mRemoteNG.UI.Tabs private void DrawTabStrip(Graphics g, DockState dockState) { - var rectTabStrip = GetLogicalTabStripRectangle(dockState); + Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; - var matrixIdentity = g.Transform; + Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { - var matrixRotated = new Matrix(); + Matrix matrixRotated = new(); matrixRotated.RotateAt(90, new PointF(rectTabStrip.X + (float)rectTabStrip.Height / 2, rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } - foreach (var pane in GetPanes(dockState)) + foreach (Pane pane in GetPanes(dockState)) { foreach (TabNG tab in pane.AutoHideTabs) DrawTab(g, tab); @@ -224,19 +226,19 @@ namespace mRemoteNG.UI.Tabs private void CalculateTabs(DockState dockState) { - var rectTabStrip = GetLogicalTabStripRectangle(dockState); + Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); - var imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; - var imageWidth = ImageWidth; + int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; + int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); - var x = TabGapLeft + rectTabStrip.X; - foreach (var pane in GetPanes(dockState)) + int x = TabGapLeft + rectTabStrip.X; + foreach (Pane pane in GetPanes(dockState)) { foreach (TabNG tab in pane.AutoHideTabs) { - var width = imageWidth + ImageGapLeft + ImageGapRight + + int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; @@ -261,11 +263,11 @@ namespace mRemoteNG.UI.Tabs private GraphicsPath GetTabOutline(TabNG tab, bool transformed, bool rtlTransform) { - var dockState = tab.Content.DockHandler.DockState; - var rectTab = GetTabRectangle(tab, transformed); + DockState dockState = tab.Content.DockHandler.DockState; + Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); - var upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); + bool upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); return GraphicsPath; @@ -273,31 +275,31 @@ namespace mRemoteNG.UI.Tabs private void DrawTab(Graphics g, TabNG tab) { - var rectTabOrigin = GetTabRectangle(tab); + Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; - var dockState = tab.Content.DockHandler.DockState; - var content = tab.Content; + DockState dockState = tab.Content.DockHandler.DockState; + IDockContent content = tab.Content; - var path = GetTabOutline(tab, false, true); - var startColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.StartColor; - var endColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.EndColor; - var gradientMode = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode; + GraphicsPath path = GetTabOutline(tab, false, true); + Color startColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.StartColor; + Color endColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.EndColor; + LinearGradientMode gradientMode = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTabOrigin, startColor, endColor, gradientMode), path); g.DrawPath(PenTabBorder, path); // Set no rotate for drawing icon and text - using (var matrixRotate = g.Transform) + using (Matrix matrixRotate = g.Transform) { g.Transform = MatrixIdentity; // Draw the icon - var rectImage = rectTabOrigin; + Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; - var imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; - var imageWidth = ImageWidth; + int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; + int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); rectImage.Height = imageHeight; @@ -307,15 +309,15 @@ namespace mRemoteNG.UI.Tabs if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. - var rectTransform = RtlTransform(rectImage, dockState); + Rectangle rectTransform = RtlTransform(rectImage, dockState); Point[] rotationPoints = { - new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), - new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), - new Point(rectTransform.X, rectTransform.Y) + new(rectTransform.X + rectTransform.Width, rectTransform.Y), + new(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), + new(rectTransform.X, rectTransform.Y) }; - using (var rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) + using (Icon rotatedIcon = new(((Form)content).Icon, 16, 16)) { g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); } @@ -327,12 +329,12 @@ namespace mRemoteNG.UI.Tabs } // Draw the text - var rectText = rectTabOrigin; + Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); - var textColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.TextColor; + Color textColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.TextColor; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, @@ -356,10 +358,10 @@ namespace mRemoteNG.UI.Tabs if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; - var leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; - var rightPanes = GetPanes(DockState.DockRightAutoHide).Count; - var topPanes = GetPanes(DockState.DockTopAutoHide).Count; - var bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; + int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; + int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; + int topPanes = GetPanes(DockState.DockTopAutoHide).Count; + int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; @@ -400,7 +402,7 @@ namespace mRemoteNG.UI.Tabs return Rectangle.Empty; } - var rect = new Rectangle(x, y, width, height); + Rectangle rect = new(x, y, width, height); return transformed ? GetTransformedRectangle(dockState, rect) : rect; } @@ -411,19 +413,19 @@ namespace mRemoteNG.UI.Tabs private Rectangle GetTabRectangle(TabNG tab, bool transformed) { - var dockState = tab.Content.DockHandler.DockState; - var rectTabStrip = GetLogicalTabStripRectangle(dockState); + DockState dockState = tab.Content.DockHandler.DockState; + Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; - var x = tab.TabX; - var y = rectTabStrip.Y + + int x = tab.TabX; + int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); - var width = tab.TabWidth; - var height = rectTabStrip.Height - TabGapTop; + int width = tab.TabWidth; + int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); @@ -436,12 +438,12 @@ namespace mRemoteNG.UI.Tabs if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; - var pts = new PointF[1]; + PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = rect.X + (float)rect.Width / 2; pts[0].Y = rect.Y + (float)rect.Height / 2; - var rectTabStrip = GetLogicalTabStripRectangle(dockState); - using (var matrix = new Matrix()) + Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); + using (Matrix matrix = new()) { matrix.RotateAt(90, new PointF(rectTabStrip.X + (float)rectTabStrip.Height / 2, rectTabStrip.Y + (float)rectTabStrip.Height / 2)); @@ -455,17 +457,17 @@ namespace mRemoteNG.UI.Tabs protected override IDockContent HitTest(Point point) { - foreach (var state in DockStates) + foreach (DockState state in DockStates) { - var rectTabStrip = GetLogicalTabStripRectangle(state, true); + Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(point)) continue; - foreach (var pane in GetPanes(state)) + foreach (Pane pane in GetPanes(state)) { foreach (TabNG tab in pane.AutoHideTabs) { - var path = GetTabOutline(tab, true, true); + GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(point)) return tab.Content; } @@ -477,8 +479,8 @@ namespace mRemoteNG.UI.Tabs protected override Rectangle GetTabBounds(Tab tab) { - var path = GetTabOutline((TabNG)tab, true, true); - var bounds = path.GetBounds(); + GraphicsPath path = GetTabOutline((TabNG)tab, true, true); + RectangleF bounds = path.GetBounds(); return new Rectangle((int)bounds.Left, (int)bounds.Top, (int)bounds.Width, (int)bounds.Height); } diff --git a/mRemoteNG/UI/Tabs/TabHelper.cs b/mRemoteNG/UI/Tabs/TabHelper.cs index 32abad7f4..956556af7 100644 --- a/mRemoteNG/UI/Tabs/TabHelper.cs +++ b/mRemoteNG/UI/Tabs/TabHelper.cs @@ -8,7 +8,7 @@ namespace mRemoteNG.UI.Tabs [SupportedOSPlatform("windows")] class TabHelper { - private static readonly Lazy lazyHelper = new Lazy(() => new TabHelper()); + private static readonly Lazy lazyHelper = new(() => new TabHelper()); public static TabHelper Instance => lazyHelper.Value; @@ -31,7 +31,7 @@ namespace mRemoteNG.UI.Tabs private void findCurrentPanel() { - var currentForm = currentTab.Parent; + System.Windows.Forms.Control currentForm = currentTab.Parent; while (currentForm != null && !(currentForm is ConnectionWindow)) { currentForm = currentForm.Parent; diff --git a/mRemoteNG/UI/TaskDialog/CommandButton.cs b/mRemoteNG/UI/TaskDialog/CommandButton.cs index 4123d37ec..5ea7e9d4c 100644 --- a/mRemoteNG/UI/TaskDialog/CommandButton.cs +++ b/mRemoteNG/UI/TaskDialog/CommandButton.cs @@ -107,7 +107,7 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- string GetLargeText() { - var lines = Text.Split('\n'); + string[] lines = Text.Split('\n'); return lines[0]; } @@ -116,31 +116,31 @@ namespace mRemoteNG.UI.TaskDialog if (Text.IndexOf('\n') < 0) return ""; - var s = Text; - var lines = s.Split('\n'); + string s = Text; + string[] lines = s.Split('\n'); s = ""; - for (var i = 1; i < lines.Length; i++) + for (int i = 1; i < lines.Length; i++) s += lines[i] + "\n"; return s.Trim('\n'); } SizeF GetLargeTextSizeF() { - var x = LEFT_MARGIN + ARROW_WIDTH + 5; - var mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN - var g = Graphics.FromHwnd(Handle); - var textSize = g.MeasureString(GetLargeText(), Font, mzSize); + int x = LEFT_MARGIN + ARROW_WIDTH + 5; + SizeF mzSize = new(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN + Graphics g = Graphics.FromHwnd(Handle); + SizeF textSize = g.MeasureString(GetLargeText(), Font, mzSize); return textSize; } SizeF GetSmallTextSizeF() { - var s = GetSmallText(); + string s = GetSmallText(); if (s == "") return new SizeF(0, 0); - var x = LEFT_MARGIN + ARROW_WIDTH + 8; // <- indent small text slightly more - var mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN - var g = Graphics.FromHwnd(Handle); - var textSize = g.MeasureString(s, SmallFont, mzSize); + int x = LEFT_MARGIN + ARROW_WIDTH + 8; // <- indent small text slightly more + SizeF mzSize = new(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN + Graphics g = Graphics.FromHwnd(Handle); + SizeF textSize = g.MeasureString(s, SmallFont, mzSize); return textSize; } @@ -172,10 +172,10 @@ namespace mRemoteNG.UI.TaskDialog const LinearGradientMode mode = LinearGradientMode.Vertical; - var newRect = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, + Rectangle newRect = new(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1); - var img = imgArrow1; + Image img = imgArrow1; Color back; @@ -216,15 +216,15 @@ namespace mRemoteNG.UI.TaskDialog } else { - var brush = new LinearGradientBrush(newRect, back, back, mode); + LinearGradientBrush brush = new(newRect, back, back, mode); e.Graphics.FillRectangle(brush, newRect); e.Graphics.DrawRectangle(new Pen(border, 1), newRect); } - var largetext = GetLargeText(); - var smalltext = GetSmallText(); + string largetext = GetLargeText(); + string smalltext = GetSmallText(); - var szL = GetLargeTextSizeF(); + SizeF szL = GetLargeTextSizeF(); //e.Graphics.DrawString(largetext, base.Font, new SolidBrush(text_color), new RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN), szL)); TextRenderer.DrawText(e.Graphics, largetext, Font, new Rectangle(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN, (int)szL.Width, @@ -233,7 +233,7 @@ namespace mRemoteNG.UI.TaskDialog if (smalltext != "") { - var szS = GetSmallTextSizeF(); + SizeF szS = GetSmallTextSizeF(); e.Graphics.DrawString(smalltext, SmallFont, new SolidBrush(fore), new RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 8, TOP_MARGIN + (int)szL.Height), @@ -280,7 +280,7 @@ namespace mRemoteNG.UI.TaskDialog { if (m_autoHeight) { - var h = GetBestHeight(); + int h = GetBestHeight(); if (Height != h) { Height = h; diff --git a/mRemoteNG/UI/TaskDialog/cTaskDialog.cs b/mRemoteNG/UI/TaskDialog/cTaskDialog.cs index f356f31e7..18dd7e605 100644 --- a/mRemoteNG/UI/TaskDialog/cTaskDialog.cs +++ b/mRemoteNG/UI/TaskDialog/cTaskDialog.cs @@ -47,9 +47,9 @@ namespace mRemoteNG.UI.TaskDialog DialogResult result; OnTaskDialogShown?.Invoke(null, EventArgs.Empty); - using (var td = new frmTaskDialog()) + using (frmTaskDialog td = new()) { - var display = new DisplayProperties(); + DisplayProperties display = new(); td.Title = title; td.MainInstruction = mainInstruction; td.Content = content; @@ -154,7 +154,7 @@ namespace mRemoteNG.UI.TaskDialog [SupportedOSPlatform("windows")] public static int ShowRadioBox(IWin32Window owner, string title, string mainInstruction, string content, string expandedInfo, string footer, string verificationText, string radioButtons, ESysIcons mainIcon, ESysIcons footerIcon, int defaultIndex) { - var res = ShowTaskDialogBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, radioButtons, "", ETaskDialogButtons.OkCancel, mainIcon, footerIcon, defaultIndex); + DialogResult res = ShowTaskDialogBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, radioButtons, "", ETaskDialogButtons.OkCancel, mainIcon, footerIcon, defaultIndex); if (res == DialogResult.OK) return RadioButtonResult; return -1; @@ -166,7 +166,7 @@ namespace mRemoteNG.UI.TaskDialog [SupportedOSPlatform("windows")] public static int ShowRadioBox(string title, string mainInstruction, string content, string expandedInfo, string footer, string verificationText, string radioButtons, ESysIcons mainIcon, ESysIcons footerIcon, int defaultIndex) { - var res = ShowTaskDialogBox(null, title, mainInstruction, content, expandedInfo, footer, verificationText, radioButtons, "", ETaskDialogButtons.OkCancel, mainIcon, footerIcon, defaultIndex); + DialogResult res = ShowTaskDialogBox(null, title, mainInstruction, content, expandedInfo, footer, verificationText, radioButtons, "", ETaskDialogButtons.OkCancel, mainIcon, footerIcon, defaultIndex); if (res == DialogResult.OK) return RadioButtonResult; return -1; @@ -206,7 +206,7 @@ namespace mRemoteNG.UI.TaskDialog [SupportedOSPlatform("windows")] public static int ShowCommandBox(IWin32Window owner, string title, string mainInstruction, string content, string expandedInfo, string footer, string verificationText,string commandButtons, bool showCancelButton, ESysIcons mainIcon, ESysIcons footerIcon) { - var res = ShowTaskDialogBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, "", commandButtons, showCancelButton ? ETaskDialogButtons.Cancel : ETaskDialogButtons.None, mainIcon, footerIcon); + DialogResult res = ShowTaskDialogBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, "", commandButtons, showCancelButton ? ETaskDialogButtons.Cancel : ETaskDialogButtons.None, mainIcon, footerIcon); if (res == DialogResult.OK) return CommandButtonResult; return -1; @@ -218,7 +218,7 @@ namespace mRemoteNG.UI.TaskDialog [SupportedOSPlatform("windows")] public static int ShowCommandBox(string title, string mainInstruction, string content, string expandedInfo, string footer, string verificationText, string commandButtons, bool showCancelButton, ESysIcons mainIcon, ESysIcons footerIcon) { - var res = ShowTaskDialogBox(null, title, mainInstruction, content, expandedInfo, footer, verificationText,"", commandButtons, showCancelButton ? ETaskDialogButtons.Cancel : ETaskDialogButtons.None, mainIcon, footerIcon); + DialogResult res = ShowTaskDialogBox(null, title, mainInstruction, content, expandedInfo, footer, verificationText,"", commandButtons, showCancelButton ? ETaskDialogButtons.Cancel : ETaskDialogButtons.None, mainIcon, footerIcon); if (res == DialogResult.OK) return CommandButtonResult; return -1; diff --git a/mRemoteNG/UI/TaskDialog/frmTaskDialog.cs b/mRemoteNG/UI/TaskDialog/frmTaskDialog.cs index 0a30e6cff..87f3891de 100644 --- a/mRemoteNG/UI/TaskDialog/frmTaskDialog.cs +++ b/mRemoteNG/UI/TaskDialog/frmTaskDialog.cs @@ -21,10 +21,10 @@ namespace mRemoteNG.UI.TaskDialog private string _mainInstruction = "Main Instruction Text"; private readonly Font _mainInstructionFont = - new Font("Segoe UI", 11.75F, FontStyle.Regular, GraphicsUnit.Point, 0); + new("Segoe UI", 11.75F, FontStyle.Regular, GraphicsUnit.Point, 0); - private readonly List _radioButtonCtrls = new List(); - private readonly DisplayProperties _display = new DisplayProperties(); + private readonly List _radioButtonCtrls = []; + private readonly DisplayProperties _display = new(); private Control _focusControl; private bool _isVista = false; @@ -84,7 +84,7 @@ namespace mRemoteNG.UI.TaskDialog { get { - foreach (var rb in _radioButtonCtrls) + foreach (MrngRadioButton rb in _radioButtonCtrls) if (rb.Checked) return (int)rb.Tag; return -1; @@ -144,7 +144,7 @@ namespace mRemoteNG.UI.TaskDialog public void BuildForm() { - var formHeight = 0; + int formHeight = 0; imgMain.Width = _display.ScaleWidth(imgMain.Width); imgMain.Height = _display.ScaleHeight(imgMain.Height); @@ -185,7 +185,7 @@ namespace mRemoteNG.UI.TaskDialog formHeight += pnlContent.Height; } - var showVerifyCheckbox = cbVerify.Text != ""; + bool showVerifyCheckbox = cbVerify.Text != ""; cbVerify.Visible = showVerifyCheckbox; // Setup Expanded Info and Buttons panels @@ -213,11 +213,11 @@ namespace mRemoteNG.UI.TaskDialog pnlRadioButtons.Visible = RadioButtons != ""; if (RadioButtons != "") { - var arr = RadioButtons.Split('|'); - var pnlHeight = _display.ScaleHeight(12); - for (var i = 0; i < arr.Length; i++) + string[] arr = RadioButtons.Split('|'); + int pnlHeight = _display.ScaleHeight(12); + for (int i = 0; i < arr.Length; i++) { - var rb = new MrngRadioButton {Parent = pnlRadioButtons}; + MrngRadioButton rb = new() { Parent = pnlRadioButtons}; rb.Location = new Point(_display.ScaleWidth(60), _display.ScaleHeight(4) + i * rb.Height); rb.Text = arr[i]; rb.Tag = i; @@ -235,12 +235,12 @@ namespace mRemoteNG.UI.TaskDialog pnlCommandButtons.Visible = CommandButtons != ""; if (CommandButtons != "") { - var arr = CommandButtons.Split('|'); - var t = _display.ScaleHeight(8); - var pnlHeight = _display.ScaleHeight(16); - for (var i = 0; i < arr.Length; i++) + string[] arr = CommandButtons.Split('|'); + int t = _display.ScaleHeight(8); + int pnlHeight = _display.ScaleHeight(16); + for (int i = 0; i < arr.Length; i++) { - var btn = new CommandButton + CommandButton btn = new() { Parent = pnlCommandButtons, Location = new Point(_display.ScaleWidth(50), t) }; @@ -402,16 +402,16 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- private Image ResizeBitmap(Image srcImg, int newWidth, int newHeight) { - var percentWidth = _display.ScaleWidth(newWidth) / (float)srcImg.Width; - var percentHeight = _display.ScaleHeight(newHeight) / (float)srcImg.Height; + float percentWidth = _display.ScaleWidth(newWidth) / (float)srcImg.Width; + float percentHeight = _display.ScaleHeight(newHeight) / (float)srcImg.Height; - var resizePercent = percentHeight < percentWidth ? percentHeight : percentWidth; + float resizePercent = percentHeight < percentWidth ? percentHeight : percentWidth; - var w = (int)(srcImg.Width * resizePercent); - var h = (int)(srcImg.Height * resizePercent); - var b = new Bitmap(w, h); + int w = (int)(srcImg.Width * resizePercent); + int h = (int)(srcImg.Height * resizePercent); + Bitmap b = new(w, h); - using (var g = Graphics.FromImage(b)) + using (Graphics g = Graphics.FromImage(b)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(srcImg, 0, 0, w, h); @@ -424,13 +424,13 @@ namespace mRemoteNG.UI.TaskDialog // utility function for setting a Label's height private static void AdjustLabelHeight(Control lb) { - var text = lb.Text; - var textFont = lb.Font; - var layoutSize = new SizeF(lb.ClientSize.Width, 5000.0F); + string text = lb.Text; + Font textFont = lb.Font; + SizeF layoutSize = new(lb.ClientSize.Width, 5000.0F); - using (var g = Graphics.FromHwnd(lb.Handle)) + using (Graphics g = Graphics.FromHwnd(lb.Handle)) { - var stringSize = g.MeasureString(text, textFont, layoutSize); + SizeF stringSize = g.MeasureString(text, textFont, layoutSize); lb.Height = (int)stringSize.Height + 4; } } diff --git a/mRemoteNG/UI/TextBoxExtensions.cs b/mRemoteNG/UI/TextBoxExtensions.cs index 2cca4acf6..eca24f8cb 100644 --- a/mRemoteNG/UI/TextBoxExtensions.cs +++ b/mRemoteNG/UI/TextBoxExtensions.cs @@ -12,15 +12,15 @@ namespace mRemoteNG.UI public static bool SetCueBannerText(this TextBox textBox, string cueText, bool showCueWhenFocused = false) { if (!textBox.IsHandleCreated || cueText == null) return false; - var result = NativeMethods.SendMessage(textBox.Handle, NativeMethods.EM_SETCUEBANNER, + IntPtr result = NativeMethods.SendMessage(textBox.Handle, NativeMethods.EM_SETCUEBANNER, (IntPtr)Convert.ToInt32(showCueWhenFocused), cueText); return result.ToInt64() == NativeMethods.TRUE; } public static string GetCueBannerText(this TextBox textBox) { - var cueBannerText = new StringBuilder(256); - var result = NativeMethods.SendMessage(textBox.Handle, NativeMethods.EM_GETCUEBANNER, cueBannerText, + StringBuilder cueBannerText = new(256); + IntPtr result = NativeMethods.SendMessage(textBox.Handle, NativeMethods.EM_GETCUEBANNER, cueBannerText, new IntPtr(cueBannerText.Capacity)); return result.ToInt64() != 0 ? cueBannerText.ToString() : null; } diff --git a/mRemoteNG/UI/Window/ActiveDirectoryImportWindow.cs b/mRemoteNG/UI/Window/ActiveDirectoryImportWindow.cs index bb459d732..890bb7dae 100644 --- a/mRemoteNG/UI/Window/ActiveDirectoryImportWindow.cs +++ b/mRemoteNG/UI/Window/ActiveDirectoryImportWindow.cs @@ -44,7 +44,7 @@ namespace mRemoteNG.UI.Window private void BtnImport_Click(object sender, EventArgs e) { - var selectedNode = Windows.TreeForm.SelectedNode; + Connection.ConnectionInfo selectedNode = Windows.TreeForm.SelectedNode; ContainerInfo importDestination; if (selectedNode != null) importDestination = selectedNode as ContainerInfo ?? selectedNode.Parent; diff --git a/mRemoteNG/UI/Window/ConfigWindow.cs b/mRemoteNG/UI/Window/ConfigWindow.cs index 2f06a7fbd..e406a39a8 100644 --- a/mRemoteNG/UI/Window/ConfigWindow.cs +++ b/mRemoteNG/UI/Window/ConfigWindow.cs @@ -59,28 +59,28 @@ namespace mRemoteNG.UI.Window Load += Config_Load; SystemColorsChanged += Config_SystemColorsChanged; _pGrid = new ConnectionInfoPropertyGrid(); - _pGrid.PropertyValueChanged += pGrid_PropertyValueChanged; - _pGrid.PropertySortChanged += pGrid_PropertySortChanged; + _pGrid.PropertyValueChanged += PGrid_PropertyValueChanged; + _pGrid.PropertySortChanged += PGrid_PropertySortChanged; PropertyGridContextMenu = new ContextMenuStrip(_components); - PropertyGridContextMenu.Opening += propertyGridContextMenu_Opening; + PropertyGridContextMenu.Opening += PropertyGridContextMenu_Opening; _propertyGridContextMenuReset = new ToolStripMenuItem(); - _propertyGridContextMenuReset.Click += propertyGridContextMenuReset_Click; + _propertyGridContextMenuReset.Click += PropertyGridContextMenuReset_Click; _toolStripSeparator1 = new ToolStripSeparator(); _propertyGridContextMenuShowHelpText = new ToolStripMenuItem(); - _propertyGridContextMenuShowHelpText.Click += propertyGridContextMenuShowHelpText_Click; - _propertyGridContextMenuShowHelpText.CheckedChanged += propertyGridContextMenuShowHelpText_CheckedChanged; + _propertyGridContextMenuShowHelpText.Click += PropertyGridContextMenuShowHelpText_Click; + _propertyGridContextMenuShowHelpText.CheckedChanged += PropertyGridContextMenuShowHelpText_CheckedChanged; _btnShowInheritance = new ToolStripButton(); - _btnShowInheritance.Click += btnShowInheritance_Click; + _btnShowInheritance.Click += BtnShowInheritance_Click; _btnShowDefaultInheritance = new ToolStripButton(); - _btnShowDefaultInheritance.Click += btnShowDefaultInheritance_Click; + _btnShowDefaultInheritance.Click += BtnShowDefaultInheritance_Click; _btnShowProperties = new ToolStripButton(); - _btnShowProperties.Click += btnShowProperties_Click; + _btnShowProperties.Click += BtnShowProperties_Click; _btnShowDefaultProperties = new ToolStripButton(); - _btnShowDefaultProperties.Click += btnShowDefaultProperties_Click; + _btnShowDefaultProperties.Click += BtnShowDefaultProperties_Click; _btnIcon = new ToolStripButton(); - _btnIcon.MouseUp += btnIcon_Click; + _btnIcon.MouseUp += BtnIcon_Click; _btnHostStatus = new ToolStripButton(); - _btnHostStatus.Click += btnHostStatus_Click; + _btnHostStatus.Click += BtnHostStatus_Click; CMenIcons = new ContextMenuStrip(_components); PropertyGridContextMenu.SuspendLayout(); SuspendLayout(); @@ -385,7 +385,7 @@ namespace mRemoteNG.UI.Window _btnHostStatus.Enabled = !_pGrid.RootNodeSelected && !_pGrid.IsShowingDefaultProperties && - !(_pGrid.SelectedConnectionInfo is ContainerInfo); + _pGrid.SelectedConnectionInfo is not ContainerInfo; SetHostStatus(_pGrid.SelectedObject); } @@ -408,7 +408,7 @@ namespace mRemoteNG.UI.Window { try { - var customToolStrip = new ToolStrip(); + ToolStrip customToolStrip = new(); customToolStrip.Items.Add(_btnShowProperties); customToolStrip.Items.Add(_btnShowInheritance); customToolStrip.Items.Add(_btnShowDefaultProperties); @@ -417,7 +417,7 @@ namespace mRemoteNG.UI.Window customToolStrip.Items.Add(_btnIcon); customToolStrip.Show(); - var propertyGridToolStrip = new ToolStrip(); + ToolStrip propertyGridToolStrip = new(); ToolStrip toolStrip = null; foreach (Control control in _pGrid.Controls) @@ -446,7 +446,7 @@ namespace mRemoteNG.UI.Window // Hide the "Property Pages" button propertyGridToolStrip.Items[_originalPropertyGridToolStripItemCount - 1].Visible = false; - var expectedToolStripItemCount = _originalPropertyGridToolStripItemCount + customToolStrip.Items.Count; + int expectedToolStripItemCount = _originalPropertyGridToolStripItemCount + customToolStrip.Items.Count; if (propertyGridToolStrip.Items.Count == expectedToolStripItemCount) return; propertyGridToolStrip.AllowMerge = true; ToolStripManager.Merge(customToolStrip, propertyGridToolStrip); @@ -473,13 +473,13 @@ namespace mRemoteNG.UI.Window AddToolStripItems(); } - private void pGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) + private void PGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { try { if (e.ChangedItem.Label == Language.Icon) { - var conIcon = ConnectionIcon.FromString(_pGrid.SelectedConnectionInfo.Icon); + Icon conIcon = ConnectionIcon.FromString(_pGrid.SelectedConnectionInfo.Icon); if (conIcon != null) _btnIcon.Image = conIcon.ToBitmap(); } @@ -496,47 +496,47 @@ namespace mRemoteNG.UI.Window } } - private void pGrid_PropertySortChanged(object sender, EventArgs e) + private void PGrid_PropertySortChanged(object sender, EventArgs e) { if (_pGrid.PropertySort == PropertySort.CategorizedAlphabetical) _pGrid.PropertySort = PropertySort.Categorized; } - private void btnShowProperties_Click(object sender, EventArgs e) + private void BtnShowProperties_Click(object sender, EventArgs e) { ShowConnectionProperties(); } - private void btnShowInheritance_Click(object sender, EventArgs e) + private void BtnShowInheritance_Click(object sender, EventArgs e) { ShowInheritanceProperties(); } - private void btnShowDefaultProperties_Click(object sender, EventArgs e) + private void BtnShowDefaultProperties_Click(object sender, EventArgs e) { ShowDefaultConnectionProperties(); } - private void btnShowDefaultInheritance_Click(object sender, EventArgs e) + private void BtnShowDefaultInheritance_Click(object sender, EventArgs e) { ShowDefaultInheritanceProperties(); } - private void btnHostStatus_Click(object sender, EventArgs e) + private void BtnHostStatus_Click(object sender, EventArgs e) { SetHostStatus(_pGrid.SelectedObject); } - private void btnIcon_Click(object sender, MouseEventArgs e) + private void BtnIcon_Click(object sender, MouseEventArgs e) { try { - if (!(_pGrid.SelectedObject is ConnectionInfo) || _pGrid.SelectedObject is PuttySessionInfo) return; + if (_pGrid.SelectedObject is not ConnectionInfo || _pGrid.SelectedObject is PuttySessionInfo) return; CMenIcons.Items.Clear(); - foreach (var iStr in ConnectionIcon.Icons) + foreach (string iStr in ConnectionIcon.Icons) { - var tI = new ToolStripMenuItem + ToolStripMenuItem tI = new() { Text = iStr, Image = ConnectionIcon.FromString(iStr).ToBitmap() @@ -546,16 +546,12 @@ namespace mRemoteNG.UI.Window CMenIcons.Items.Add(tI); } - var mPos = new Point( - new Size(PointToScreen(new Point(e.Location.X + _pGrid.Width - 100, - e.Location.Y)))); + Point mPos = new(new Size(PointToScreen(new Point(e.Location.X + _pGrid.Width - 100, e.Location.Y)))); CMenIcons.Show(mPos); } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, - Language.ConfigPropertyGridButtonIconClickFailed + - Environment.NewLine + ex.Message, true); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.ConfigPropertyGridButtonIconClickFailed + Environment.NewLine + ex.Message, true); } } @@ -563,15 +559,15 @@ namespace mRemoteNG.UI.Window { try { - var connectionInfo = (ConnectionInfo)_pGrid.SelectedObject; + ConnectionInfo connectionInfo = (ConnectionInfo)_pGrid.SelectedObject; if (connectionInfo == null) return; - var selectedMenuItem = (ToolStripMenuItem)sender; + ToolStripMenuItem selectedMenuItem = (ToolStripMenuItem)sender; - var iconName = selectedMenuItem?.Text; + string iconName = selectedMenuItem?.Text; if (string.IsNullOrEmpty(iconName)) return; - var connectionIcon = ConnectionIcon.FromString(iconName); + Icon connectionIcon = ConnectionIcon.FromString(iconName); if (connectionIcon == null) return; _btnIcon.Image = connectionIcon.ToBitmap(); @@ -583,9 +579,7 @@ namespace mRemoteNG.UI.Window } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, - Language.ConfigPropertyGridMenuClickFailed + - Environment.NewLine + ex.Message, true); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.ConfigPropertyGridMenuClickFailed + Environment.NewLine + ex.Message, true); } } @@ -603,26 +597,35 @@ namespace mRemoteNG.UI.Window return; } - var pingSender = new Ping(); + Ping pingSender = new(); try { - var pReply = pingSender.Send((string)hostName); + PingReply pReply = pingSender.Send((string)hostName); if (pReply?.Status == IPStatus.Success) { if ((string)_btnHostStatus.Tag == "checking") + { ShowStatusImage(Properties.Resources.HostStatus_On); + } + } else { if ((string)_btnHostStatus.Tag == "checking") + { ShowStatusImage(Properties.Resources.HostStatus_Off); + } + } } catch (Exception) { if ((string)_btnHostStatus.Tag == "checking") + { ShowStatusImage(Properties.Resources.HostStatus_Off); + } + } } @@ -648,7 +651,7 @@ namespace mRemoteNG.UI.Window { _btnHostStatus.Image = Properties.Resources.HostStatus_Check; // To check status, ConnectionInfo must be an mRemoteNG.Connection.Info that is not a container - if (!(connectionInfo is ConnectionInfo info)) return; + if (connectionInfo is not ConnectionInfo info) return; if (info.IsContainer) return; _btnHostStatus.Tag = "checking"; @@ -669,12 +672,12 @@ namespace mRemoteNG.UI.Window #region Event Handlers - private void propertyGridContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) + private void PropertyGridContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) { try { _propertyGridContextMenuShowHelpText.Checked = Settings.Default.ShowConfigHelpText; - var gridItem = _pGrid.SelectedGridItem; + GridItem gridItem = _pGrid.SelectedGridItem; _propertyGridContextMenuReset.Enabled = Convert.ToBoolean(_pGrid.SelectedObject != null && gridItem?.PropertyDescriptor != null && gridItem.PropertyDescriptor.CanResetValue(_pGrid.SelectedObject)); @@ -685,11 +688,11 @@ namespace mRemoteNG.UI.Window } } - private void propertyGridContextMenuReset_Click(object sender, EventArgs e) + private void PropertyGridContextMenuReset_Click(object sender, EventArgs e) { try { - var gridItem = _pGrid.SelectedGridItem; + GridItem gridItem = _pGrid.SelectedGridItem; if (_pGrid.SelectedObject != null && gridItem?.PropertyDescriptor != null && gridItem.PropertyDescriptor.CanResetValue(_pGrid.SelectedObject)) { @@ -702,12 +705,12 @@ namespace mRemoteNG.UI.Window } } - private void propertyGridContextMenuShowHelpText_Click(object sender, EventArgs e) + private void PropertyGridContextMenuShowHelpText_Click(object sender, EventArgs e) { _propertyGridContextMenuShowHelpText.Checked = !_propertyGridContextMenuShowHelpText.Checked; } - private void propertyGridContextMenuShowHelpText_CheckedChanged(object sender, EventArgs e) + private void PropertyGridContextMenuShowHelpText_CheckedChanged(object sender, EventArgs e) { Settings.Default.ShowConfigHelpText = _propertyGridContextMenuShowHelpText.Checked; _pGrid.HelpVisible = _propertyGridContextMenuShowHelpText.Checked; diff --git a/mRemoteNG/UI/Window/ConnectionTreeWindow.Designer.cs b/mRemoteNG/UI/Window/ConnectionTreeWindow.Designer.cs index b293ffb23..74a644252 100644 --- a/mRemoteNG/UI/Window/ConnectionTreeWindow.Designer.cs +++ b/mRemoteNG/UI/Window/ConnectionTreeWindow.Designer.cs @@ -168,7 +168,7 @@ namespace mRemoteNG.UI.Window this.txtSearch.TabIndex = 30; this.txtSearch.TabStop = false; this.txtSearch.Text = "Search"; - this.txtSearch.TextChanged += new System.EventHandler(this.txtSearch_TextChanged); + this.txtSearch.TextChanged += new System.EventHandler(this.TxtSearch_TextChanged); this.txtSearch.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TxtSearch_KeyDown); // // tableLayoutPanel1 diff --git a/mRemoteNG/UI/Window/ConnectionTreeWindow.cs b/mRemoteNG/UI/Window/ConnectionTreeWindow.cs index 72f2ff3c8..1f43923d9 100644 --- a/mRemoteNG/UI/Window/ConnectionTreeWindow.cs +++ b/mRemoteNG/UI/Window/ConnectionTreeWindow.cs @@ -102,7 +102,7 @@ namespace mRemoteNG.UI.Window if (!_themeManager.ThemingActive) return; - var activeTheme = _themeManager.ActiveTheme; + ThemeInfo activeTheme = _themeManager.ActiveTheme; vsToolStripExtender.SetStyle(msMain, activeTheme.Version, activeTheme.Theme); vsToolStripExtender.SetStyle(ConnectionTree.ContextMenuStrip, activeTheme.Version, activeTheme.Theme); @@ -137,7 +137,7 @@ namespace mRemoteNG.UI.Window private void SetTreePostSetupActions() { - var actions = new List + List actions = new() { new PreviouslyOpenedFolderExpander(), new RootNodeExpander() @@ -151,8 +151,8 @@ namespace mRemoteNG.UI.Window private void SetConnectionTreeClickHandlers() { - var singleClickHandlers = new List>(); - var doubleClickHandlers = new List> + List> singleClickHandlers = new(); + List> doubleClickHandlers = new() { new ExpandNodeClickHandler(ConnectionTree) }; @@ -178,8 +178,7 @@ namespace mRemoteNG.UI.Window } ConnectionTree.ConnectionTreeModel = connectionsLoadedEventArgs.NewConnectionTreeModel; - ConnectionTree.SelectedObject = - connectionsLoadedEventArgs.NewConnectionTreeModel.RootNodes.OfType().FirstOrDefault(); + ConnectionTree.SelectedObject = connectionsLoadedEventArgs.NewConnectionTreeModel.RootNodes.OfType().FirstOrDefault(); } #endregion @@ -212,14 +211,14 @@ namespace mRemoteNG.UI.Window mMenFavorites.Click += (sender, args) => { mMenFavorites.DropDownItems.Clear(); - var rootNodes = Runtime.ConnectionsService.ConnectionTreeModel.RootNodes; - var favoritesList = new List(); + List rootNodes = Runtime.ConnectionsService.ConnectionTreeModel.RootNodes; + List favoritesList = new(); - foreach (var node in rootNodes) + foreach (ContainerInfo node in rootNodes) { - foreach (var containerInfo in Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveFavoriteChildList(node)) + foreach (ConnectionInfo containerInfo in Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveFavoriteChildList(node)) { - var favoriteMenuItem = new ToolStripMenuItem + ToolStripMenuItem favoriteMenuItem = new() { Text = containerInfo.Name, Tag = containerInfo, @@ -271,14 +270,14 @@ namespace mRemoteNG.UI.Window break; case Keys.Up: { - var match = ConnectionTree.NodeSearcher.PreviousMatch(); + ConnectionInfo match = ConnectionTree.NodeSearcher.PreviousMatch(); JumpToNode(match); e.Handled = true; break; } case Keys.Down: { - var match = ConnectionTree.NodeSearcher.NextMatch(); + ConnectionInfo match = ConnectionTree.NodeSearcher.NextMatch(); JumpToNode(match); e.Handled = true; break; @@ -294,7 +293,7 @@ namespace mRemoteNG.UI.Window } } - private void txtSearch_TextChanged(object sender, EventArgs e) + private void TxtSearch_TextChanged(object sender, EventArgs e) { ApplyFiltering(); } diff --git a/mRemoteNG/UI/Window/ConnectionWindow.cs b/mRemoteNG/UI/Window/ConnectionWindow.cs index b9d529163..766bba6ae 100644 --- a/mRemoteNG/UI/Window/ConnectionWindow.cs +++ b/mRemoteNG/UI/Window/ConnectionWindow.cs @@ -129,7 +129,7 @@ namespace mRemoteNG.UI.Window titleText = titleText.Replace("&", "&&"); - var conTab = new ConnectionTab + ConnectionTab conTab = new() { Tag = connectionInfo, DockAreas = DockAreas.Document | DockAreas.Float, @@ -160,16 +160,16 @@ namespace mRemoteNG.UI.Window public void ReconnectAll(IConnectionInitiator initiator) { - var controlList = new List(); + List controlList = new(); try { - foreach (var dockContent in connDock.DocumentsToArray()) + foreach (IDockContent dockContent in connDock.DocumentsToArray()) { - var tab = (ConnectionTab)dockContent; + ConnectionTab tab = (ConnectionTab)dockContent; controlList.Add((InterfaceControl)tab.Tag); } - foreach (var iControl in controlList) + foreach (InterfaceControl iControl in controlList) { iControl.Protocol.Close(); initiator.OpenConnection(iControl.Info, ConnectionInfo.Force.DoNotJump); @@ -287,7 +287,7 @@ namespace mRemoteNG.UI.Window Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple & connDock.Documents.Count() > 1)) { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, + DialogResult result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string .Format(Language.ConfirmCloseConnectionPanelMainInstruction, Text), "", "", "", @@ -308,9 +308,9 @@ namespace mRemoteNG.UI.Window try { - foreach (var dockContent in connDock.Documents.ToArray()) + foreach (IDockContent dockContent in connDock.Documents.ToArray()) { - var tabP = (ConnectionTab)dockContent; + ConnectionTab tabP = (ConnectionTab)dockContent; if (tabP.Tag == null) continue; tabP.silentClose = true; tabP.Close(); @@ -342,7 +342,7 @@ namespace mRemoteNG.UI.Window private void ConnDockOnActiveContentChanged(object sender, EventArgs e) { - var ic = GetInterfaceControl(); + InterfaceControl ic = GetInterfaceControl(); if (ic?.Info == null) return; FrmMain.Default.SelectedConnection = ic.Info; } @@ -355,7 +355,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (interfaceControl == null) return; if (interfaceControl.Protocol is ISupportsViewOnly viewOnly) @@ -370,7 +370,7 @@ namespace mRemoteNG.UI.Window if (interfaceControl.Info.Protocol == ProtocolType.RDP) { - var rdp = (RdpProtocol)interfaceControl.Protocol; + RdpProtocol rdp = (RdpProtocol)interfaceControl.Protocol; cmenTabFullscreen.Visible = true; cmenTabFullscreen.Checked = rdp.Fullscreen; cmenTabSmartSize.Visible = true; @@ -384,7 +384,7 @@ namespace mRemoteNG.UI.Window if (interfaceControl.Info.Protocol == ProtocolType.VNC) { - var vnc = (ProtocolVNC)interfaceControl.Protocol; + ProtocolVNC vnc = (ProtocolVNC)interfaceControl.Protocol; cmenTabSendSpecialKeys.Visible = true; cmenTabSmartSize.Visible = true; cmenTabStartChat.Visible = true; @@ -423,7 +423,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); switch (interfaceControl.Protocol) { @@ -442,7 +442,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (interfaceControl == null) return; if (interfaceControl.Info.Protocol == ProtocolType.SSH1 | @@ -461,11 +461,11 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (interfaceControl == null) return; Windows.Show(WindowType.SSHTransfer); - var connectionInfo = interfaceControl.Info; + ConnectionInfo connectionInfo = interfaceControl.Info; Windows.SshtransferForm.Hostname = connectionInfo.Hostname; Windows.SshtransferForm.Username = connectionInfo.Username; @@ -482,8 +482,8 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); - var vnc = interfaceControl?.Protocol as ProtocolVNC; + InterfaceControl interfaceControl = GetInterfaceControl(); + ProtocolVNC vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.StartFileTransfer(); } catch (Exception ex) @@ -496,7 +496,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (!(interfaceControl?.Protocol is ISupportsViewOnly viewOnly)) return; @@ -513,8 +513,8 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); - var vnc = interfaceControl?.Protocol as ProtocolVNC; + InterfaceControl interfaceControl = GetInterfaceControl(); + ProtocolVNC vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.StartChat(); } catch (Exception ex) @@ -527,8 +527,8 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); - var vnc = interfaceControl?.Protocol as ProtocolVNC; + InterfaceControl interfaceControl = GetInterfaceControl(); + ProtocolVNC vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.RefreshScreen(); } catch (Exception ex) @@ -541,8 +541,8 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); - var vnc = interfaceControl?.Protocol as ProtocolVNC; + InterfaceControl interfaceControl = GetInterfaceControl(); + ProtocolVNC vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.SendSpecialKeys(keys); } catch (Exception ex) @@ -555,8 +555,8 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); - var rdp = interfaceControl?.Protocol as RdpProtocol; + InterfaceControl interfaceControl = GetInterfaceControl(); + RdpProtocol rdp = interfaceControl?.Protocol as RdpProtocol; rdp?.ToggleFullscreen(); } catch (Exception ex) @@ -570,8 +570,8 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); - var puttyBase = interfaceControl?.Protocol as PuttyBase; + InterfaceControl interfaceControl = GetInterfaceControl(); + PuttyBase puttyBase = interfaceControl?.Protocol as PuttyBase; puttyBase?.ShowSettingsDialog(); } catch (Exception ex) @@ -589,15 +589,15 @@ namespace mRemoteNG.UI.Window //clean up. since new items are added below, we have to dispose of any previous items first if (cmenTabExternalApps.DropDownItems.Count > 0) { - for (var i = cmenTabExternalApps.DropDownItems.Count - 1; i >= 0; i--) + for (int i = cmenTabExternalApps.DropDownItems.Count - 1; i >= 0; i--) cmenTabExternalApps.DropDownItems[i].Dispose(); cmenTabExternalApps.DropDownItems.Clear(); } //add ext apps - foreach (var externalTool in Runtime.ExternalToolsService.ExternalTools) + foreach (ExternalTool externalTool in Runtime.ExternalToolsService.ExternalTools) { - var nItem = new ToolStripMenuItem + ToolStripMenuItem nItem = new() { Text = externalTool.DisplayName, Tag = externalTool, @@ -621,7 +621,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); externalTool.Start(interfaceControl?.Info); } catch (Exception ex) @@ -633,7 +633,7 @@ namespace mRemoteNG.UI.Window private void CloseTabMenu() { - var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + ConnectionTab selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; if (selectedTab == null) return; try @@ -648,11 +648,11 @@ namespace mRemoteNG.UI.Window private void CloseOtherTabs() { - var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + ConnectionTab selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; if (selectedTab == null) return; if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple) { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, + DialogResult result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.ConfirmCloseConnectionOthersInstruction, selectedTab.TabText), "", "", "", Language.CheckboxDoNotShowThisMessageAgain, @@ -669,9 +669,9 @@ namespace mRemoteNG.UI.Window } } - foreach (var dockContent in connDock.DocumentsToArray()) + foreach (IDockContent dockContent in connDock.DocumentsToArray()) { - var tab = (ConnectionTab)dockContent; + ConnectionTab tab = (ConnectionTab)dockContent; if (selectedTab != tab) { tab.Close(); @@ -683,15 +683,15 @@ namespace mRemoteNG.UI.Window { try { - var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + ConnectionTab selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; if (selectedTab == null) return; - var dockPane = selectedTab.Pane; + DockPane dockPane = selectedTab.Pane; - var pastTabToKeepAlive = false; - var connectionsToClose = new List(); - foreach (var dockContent in dockPane.Contents) + bool pastTabToKeepAlive = false; + List connectionsToClose = new(); + foreach (IDockContent dockContent in dockPane.Contents) { - var tab = (ConnectionTab)dockContent; + ConnectionTab tab = (ConnectionTab)dockContent; if (pastTabToKeepAlive) connectionsToClose.Add(tab); @@ -699,7 +699,7 @@ namespace mRemoteNG.UI.Window pastTabToKeepAlive = true; } - foreach (var tab in connectionsToClose) + foreach (ConnectionTab tab in connectionsToClose) { tab.Close(); } @@ -714,7 +714,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (interfaceControl == null) return; Runtime.ConnectionInitiator.OpenConnection(interfaceControl.Info, ConnectionInfo.Force.DoNotJump); } @@ -728,7 +728,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (interfaceControl == null) { Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "Reconnect (UI.Window.ConnectionWindow) failed. Could not find InterfaceControl."); @@ -748,12 +748,12 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = GetInterfaceControl(); + InterfaceControl interfaceControl = GetInterfaceControl(); if (interfaceControl == null) return; - using (var frmInputBox = new FrmInputBox(Language.NewTitle, Language.NewTitle, + using (FrmInputBox frmInputBox = new(Language.NewTitle, Language.NewTitle, ((ConnectionTab)interfaceControl.Parent).TabText)) { - var dr = frmInputBox.ShowDialog(); + DialogResult dr = frmInputBox.ShowDialog(); if (dr != DialogResult.OK) return; if (!string.IsNullOrEmpty(frmInputBox.returnValue)) ((ConnectionTab)interfaceControl.Parent).TabText = frmInputBox.returnValue.Replace("&", "&&"); @@ -771,7 +771,7 @@ namespace mRemoteNG.UI.Window public void Prot_Event_Closed(object sender) { - var protocolBase = sender as ProtocolBase; + ProtocolBase protocolBase = sender as ProtocolBase; if (!(protocolBase?.InterfaceControl.Parent is ConnectionTab tabPage)) return; if (tabPage.Disposing || tabPage.IsDisposed) return; tabPage.protocolClose = true; diff --git a/mRemoteNG/UI/Window/ErrorAndInfoWindow.cs b/mRemoteNG/UI/Window/ErrorAndInfoWindow.cs index 7e47784b1..bf72c8801 100644 --- a/mRemoteNG/UI/Window/ErrorAndInfoWindow.cs +++ b/mRemoteNG/UI/Window/ErrorAndInfoWindow.cs @@ -217,8 +217,8 @@ namespace mRemoteNG.UI.Window return; } - var sItem = lvErrorCollector.SelectedItems[0]; - var eMsg = (Message)sItem.Tag; + ListViewItem sItem = lvErrorCollector.SelectedItems[0]; + Message eMsg = (Message)sItem.Tag; switch (eMsg.Class) { case MessageClass.DebugMsg: @@ -339,7 +339,7 @@ namespace mRemoteNG.UI.Window items = lvErrorCollector.Items; } - var stringBuilder = new StringBuilder(); + StringBuilder stringBuilder = new(); stringBuilder.AppendLine("----------"); lvErrorCollector.BeginUpdate(); diff --git a/mRemoteNG/UI/Window/ExternalToolsWindow.cs b/mRemoteNG/UI/Window/ExternalToolsWindow.cs index 9a61cf02c..717f73f1a 100644 --- a/mRemoteNG/UI/Window/ExternalToolsWindow.cs +++ b/mRemoteNG/UI/Window/ExternalToolsWindow.cs @@ -30,7 +30,7 @@ namespace mRemoteNG.UI.Window _themeManager = ThemeManager.getInstance(); _themeManager.ThemeChanged += ApplyTheme; _externalAppsSaver = new ExternalAppsSaver(); - _currentlySelectedExternalTools = new FullyObservableCollection(); + _currentlySelectedExternalTools = []; _currentlySelectedExternalTools.CollectionUpdated += CurrentlySelectedExternalToolsOnCollectionUpdated; BrowseButton.Height = FilenameTextBox.Height; BrowseWorkingDir.Height = WorkingDirTextBox.Height; @@ -120,7 +120,7 @@ namespace mRemoteNG.UI.Window { try { - foreach (var externalTool in _currentlySelectedExternalTools) + foreach (ExternalTool externalTool in _currentlySelectedExternalTools) { externalTool.Start(); } @@ -133,7 +133,7 @@ namespace mRemoteNG.UI.Window private void UpdateEditorControls() { - var selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); + ExternalTool selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); DisplayNameTextBox.Text = selectedTool?.DisplayName; FilenameTextBox.Text = selectedTool?.FileName; @@ -152,7 +152,7 @@ namespace mRemoteNG.UI.Window _currentlySelectedExternalTools.AddRange(ToolsListObjView.SelectedObjects.OfType()); PropertiesGroupBox.Enabled = _currentlySelectedExternalTools.Count == 1; - var atleastOneToolSelected = _currentlySelectedExternalTools.Count > 0; + bool atleastOneToolSelected = _currentlySelectedExternalTools.Count > 0; DeleteToolMenuItem.Enabled = atleastOneToolSelected; DeleteToolToolstripButton.Enabled = atleastOneToolSelected; LaunchToolMenuItem.Enabled = atleastOneToolSelected; @@ -181,7 +181,7 @@ namespace mRemoteNG.UI.Window { try { - var externalTool = new ExternalTool(Language.ExternalToolDefaultName); + ExternalTool externalTool = new(Language.ExternalToolDefaultName); Runtime.ExternalToolsService.ExternalTools.Add(externalTool); UpdateToolsListObjView(); ToolsListObjView.SelectedObject = externalTool; @@ -211,17 +211,17 @@ namespace mRemoteNG.UI.Window MessageBoxIcon.Question) != DialogResult.Yes) return; - foreach (var externalTool in _currentlySelectedExternalTools) + foreach (ExternalTool externalTool in _currentlySelectedExternalTools) { Runtime.ExternalToolsService.ExternalTools.Remove(externalTool); } - var firstDeletedNode = _currentlySelectedExternalTools.FirstOrDefault(); - var oldSelectedIndex = ToolsListObjView.IndexOf(firstDeletedNode); + ExternalTool firstDeletedNode = _currentlySelectedExternalTools.FirstOrDefault(); + int oldSelectedIndex = ToolsListObjView.IndexOf(firstDeletedNode); _currentlySelectedExternalTools.Clear(); UpdateToolsListObjView(); - var maxIndex = ToolsListObjView.GetItemCount() - 1; + int maxIndex = ToolsListObjView.GetItemCount() - 1; ToolsListObjView.SelectedIndex = oldSelectedIndex <= maxIndex ? oldSelectedIndex : maxIndex; @@ -263,7 +263,7 @@ namespace mRemoteNG.UI.Window private void PropertyControl_ChangedOrLostFocus(object sender, EventArgs e) { - var selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); + ExternalTool selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); if (selectedTool == null) return; @@ -292,13 +292,13 @@ namespace mRemoteNG.UI.Window { try { - using (var browseDialog = new OpenFileDialog()) + using (OpenFileDialog browseDialog = new()) { browseDialog.Filter = string.Join("|", Language.FilterApplication, "*.exe", Language.FilterAll, "*.*"); if (browseDialog.ShowDialog() != DialogResult.OK) return; - var selectedItem = _currentlySelectedExternalTools.FirstOrDefault(); + ExternalTool selectedItem = _currentlySelectedExternalTools.FirstOrDefault(); if (selectedItem == null) return; selectedItem.FileName = browseDialog.FileName; @@ -315,11 +315,11 @@ namespace mRemoteNG.UI.Window { try { - using (var browseDialog = new FolderBrowserDialog()) + using (FolderBrowserDialog browseDialog = new()) { if (browseDialog.ShowDialog() != DialogResult.OK) return; - var selectedItem = _currentlySelectedExternalTools.FirstOrDefault(); + ExternalTool selectedItem = _currentlySelectedExternalTools.FirstOrDefault(); if (selectedItem == null) return; selectedItem.WorkingDir = browseDialog.SelectedPath; diff --git a/mRemoteNG/UI/Window/PortScanWindow.cs b/mRemoteNG/UI/Window/PortScanWindow.cs index d0b2cc814..7b2ab32b9 100644 --- a/mRemoteNG/UI/Window/PortScanWindow.cs +++ b/mRemoteNG/UI/Window/PortScanWindow.cs @@ -28,7 +28,7 @@ namespace mRemoteNG.UI.Window WindowType = WindowType.PortScan; DockPnl = new DockContent(); ApplyTheme(); - var display = new DisplayProperties(); + DisplayProperties display = new(); btnScan.Image = display.ScaleImage(btnScan.Image); } @@ -154,7 +154,7 @@ namespace mRemoteNG.UI.Window private void btnImport_Click(object sender, EventArgs e) { - var protocol = + ProtocolType protocol = (ProtocolType)Enum.Parse(typeof(ProtocolType), Convert.ToString(cbProtocol.SelectedItem), true); importSelectedHosts(protocol); } @@ -195,8 +195,8 @@ namespace mRemoteNG.UI.Window SwitchButtonText(); olvHosts.Items.Clear(); - var ipAddressStart = IPAddress.Parse(ipStart.Text); - var ipAddressEnd = IPAddress.Parse(ipEnd.Text); + IPAddress ipAddressStart = IPAddress.Parse(ipStart.Text); + IPAddress ipAddressEnd = IPAddress.Parse(ipEnd.Text); if (!ngCheckFirstPort.Checked && !ngCheckLastPort.Checked) _portScanner = new PortScanner(ipAddressStart, ipAddressEnd, (int)portStart.Value, @@ -279,7 +279,7 @@ namespace mRemoteNG.UI.Window private void importSelectedHosts(ProtocolType protocol) { - var hosts = new List(); + List hosts = new(); foreach (ScanHost host in olvHosts.SelectedObjects) { hosts.Add(host); @@ -292,7 +292,7 @@ namespace mRemoteNG.UI.Window return; } - var destinationContainer = GetDestinationContainerForImportedHosts(); + ContainerInfo destinationContainer = GetDestinationContainerForImportedHosts(); Import.ImportFromPortScan(hosts, protocol, destinationContainer); } @@ -302,7 +302,7 @@ namespace mRemoteNG.UI.Window /// private ContainerInfo GetDestinationContainerForImportedHosts() { - var selectedNode = Windows.TreeForm.SelectedNode + ConnectionInfo selectedNode = Windows.TreeForm.SelectedNode ?? Windows.TreeForm.ConnectionTree.ConnectionTreeModel.RootNodes.OfType() .First(); @@ -312,7 +312,7 @@ namespace mRemoteNG.UI.Window .First(); // if the selected node is a connection, use its parent container - var selectedTreeNodeAsContainer = selectedNode as ContainerInfo ?? selectedNode.Parent; + ContainerInfo selectedTreeNodeAsContainer = selectedNode as ContainerInfo ?? selectedNode.Parent; return selectedTreeNodeAsContainer; } diff --git a/mRemoteNG/UI/Window/SSHTransferWindow.cs b/mRemoteNG/UI/Window/SSHTransferWindow.cs index 33c2f82e3..db4761def 100644 --- a/mRemoteNG/UI/Window/SSHTransferWindow.cs +++ b/mRemoteNG/UI/Window/SSHTransferWindow.cs @@ -42,7 +42,7 @@ namespace mRemoteNG.UI.Window private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = - new System.ComponentModel.ComponentResourceManager(typeof(SSHTransferWindow)); + new(typeof(SSHTransferWindow)); grpFiles = new MrngGroupBox(); lblLocalFile = new MrngLabel(); txtLocalFile = new MrngTextBox(); @@ -352,7 +352,7 @@ namespace mRemoteNG.UI.Window ApplyTheme(); ApplyLanguage(); Icon = Resources.ImageConverter.GetImageAsIcon(Properties.Resources.SyncArrow_16x); - var display = new DisplayProperties(); + DisplayProperties display = new(); btnTransfer.Image = display.ScaleImage(btnTransfer.Image); } @@ -411,7 +411,7 @@ namespace mRemoteNG.UI.Window break; } - var t = new Thread(StartTransferBG); + Thread t = new(StartTransferBG); t.SetApartmentState(ApartmentState.STA); t.IsBackground = true; t.Start(); @@ -432,10 +432,10 @@ namespace mRemoteNG.UI.Window private void ScpClt_Uploading(object sender, Renci.SshNet.Common.ScpUploadEventArgs e) { // If the file size is over 2 gigs, convert to kb. This means we'll support a 2TB file. - var max = e.Size > int.MaxValue ? Convert.ToInt32(e.Size / 1024) : Convert.ToInt32(e.Size); + int max = e.Size > int.MaxValue ? Convert.ToInt32(e.Size / 1024) : Convert.ToInt32(e.Size); // yes, compare to size since that's the total/original file size - var cur = e.Size > int.MaxValue ? Convert.ToInt32(e.Uploaded / 1024) : Convert.ToInt32(e.Uploaded); + int cur = e.Size > int.MaxValue ? Convert.ToInt32(e.Uploaded / 1024) : Convert.ToInt32(e.Uploaded); SshTransfer_Progress(cur, max); } @@ -452,14 +452,14 @@ namespace mRemoteNG.UI.Window // SftpClient is Asynchronous, so we need to wait here after the upload and handle the status directly since no status events are raised. if (st.Protocol == SecureTransfer.SSHTransferProtocol.SFTP) { - var fi = new FileInfo(st.SrcFile); + FileInfo fi = new(st.SrcFile); while (!st.asyncResult.IsCompleted) { - var max = fi.Length > int.MaxValue + int max = fi.Length > int.MaxValue ? Convert.ToInt32(fi.Length / 1024) : Convert.ToInt32(fi.Length); - var cur = fi.Length > int.MaxValue + int cur = fi.Length > int.MaxValue ? Convert.ToInt32(st.asyncResult.UploadedBytes / 1024) : Convert.ToInt32(st.asyncResult.UploadedBytes); SshTransfer_Progress(cur, max); diff --git a/mRemoteNG/UI/Window/UltraVNCWindow.cs b/mRemoteNG/UI/Window/UltraVNCWindow.cs index 4cb51fd1f..5afe1e812 100644 --- a/mRemoteNG/UI/Window/UltraVNCWindow.cs +++ b/mRemoteNG/UI/Window/UltraVNCWindow.cs @@ -19,7 +19,7 @@ namespace mRemoteNG.UI.Window private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = - new System.ComponentModel.ComponentResourceManager(typeof(UltraVNCWindow)); + new(typeof(UltraVNCWindow)); this.tsMain = new System.Windows.Forms.ToolStrip(); this.btnDisconnect = new System.Windows.Forms.ToolStripButton(); this.pnlContainer = new System.Windows.Forms.Panel(); diff --git a/mRemoteNG/UI/Window/UpdateWindow.cs b/mRemoteNG/UI/Window/UpdateWindow.cs index 25c52a397..397fdc2cc 100644 --- a/mRemoteNG/UI/Window/UpdateWindow.cs +++ b/mRemoteNG/UI/Window/UpdateWindow.cs @@ -85,7 +85,7 @@ namespace mRemoteNG.UI.Window private void pbUpdateImage_Click(object sender, EventArgs e) { - var linkUri = pbUpdateImage.Tag as Uri; + Uri linkUri = pbUpdateImage.Tag as Uri; if (linkUri == null || linkUri.IsFile || linkUri.IsUnc || linkUri.IsLoopback) { return; @@ -135,7 +135,7 @@ namespace mRemoteNG.UI.Window lblStatus.ForeColor = Color.OrangeRed; SetVisibilityOfUpdateControls(true); - var updateInfo = _appUpdate.CurrentUpdateInfo; + UpdateInfo updateInfo = _appUpdate.CurrentUpdateInfo; lblLatestVersion.Text = updateInfo.Version.ToString(); lblLatestVersionLabel.Visible = true; lblLatestVersion.Visible = true; @@ -153,7 +153,7 @@ namespace mRemoteNG.UI.Window try { - var changeLog = await _appUpdate.GetChangeLogAsync(); + string changeLog = await _appUpdate.GetChangeLogAsync(); txtChangeLog.Text = changeLog.Replace("\n", Environment.NewLine); } catch (Exception ex) @@ -169,7 +169,7 @@ namespace mRemoteNG.UI.Window lblStatus.ForeColor = Color.ForestGreen; if (_appUpdate.CurrentUpdateInfo == null) return; - var updateInfo = _appUpdate.CurrentUpdateInfo; + UpdateInfo updateInfo = _appUpdate.CurrentUpdateInfo; if (!updateInfo.IsValid || updateInfo.Version == null) return; lblLatestVersion.Text = updateInfo.Version.ToString(); lblLatestVersionLabel.Visible = true; diff --git a/mRemoteNG/UI/WindowList.cs b/mRemoteNG/UI/WindowList.cs index bf254c6ba..b66ad85f5 100644 --- a/mRemoteNG/UI/WindowList.cs +++ b/mRemoteNG/UI/WindowList.cs @@ -43,7 +43,7 @@ namespace mRemoteNG.UI public void AddRange(BaseWindow[] uiWindow) { - foreach (var uW in uiWindow) + foreach (BaseWindow uW in uiWindow) { List.Add(uW); } @@ -57,7 +57,7 @@ namespace mRemoteNG.UI public BaseWindow FromString(string uiWindow) { CleanUp(); - for (var i = 0; i < List.Count; i++) + for (int i = 0; i < List.Count; i++) { if (this[i].Text == uiWindow.Replace("&", "&&")) { @@ -73,7 +73,7 @@ namespace mRemoteNG.UI private void CleanUp() { - for (var i = 0; i <= List.Count - 1; i++) + for (int i = 0; i <= List.Count - 1; i++) { if (i > List.Count - 1) { @@ -81,7 +81,7 @@ namespace mRemoteNG.UI return; } - var baseWindow = List[i] as BaseWindow; + BaseWindow baseWindow = List[i] as BaseWindow; if (baseWindow != null && !baseWindow.IsDisposed) continue; List.RemoveAt(i); CleanUp(); @@ -93,7 +93,7 @@ namespace mRemoteNG.UI { try { - var objectIndex = List.IndexOf(Index); + int objectIndex = List.IndexOf(Index); return IndexByNumber(objectIndex); } catch (ArgumentOutOfRangeException e) diff --git a/mRemoteNG/mRemoteNG.csproj b/mRemoteNG/mRemoteNG.csproj index ed72d159a..b9a241f66 100644 --- a/mRemoteNG/mRemoteNG.csproj +++ b/mRemoteNG/mRemoteNG.csproj @@ -86,37 +86,37 @@ - + - + - - + + - + - + - - + + - + @@ -494,7 +494,7 @@ - + diff --git a/mRemoteNGInstaller/Installer/Filters/Harvest_Filter.xslt b/mRemoteNGInstaller/Installer/Filters/Harvest_Filter.xslt index 8f63dffb3..c8540fac9 100644 --- a/mRemoteNGInstaller/Installer/Filters/Harvest_Filter.xslt +++ b/mRemoteNGInstaller/Installer/Filters/Harvest_Filter.xslt @@ -14,7 +14,7 @@ xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"> - + \ No newline at end of file diff --git a/mRemoteNGInstaller/Installer/Fragments/FilesFragment.wxs b/mRemoteNGInstaller/Installer/Fragments/FilesFragment.wxs index 974969e6b..6bf379442 100644 --- a/mRemoteNGInstaller/Installer/Fragments/FilesFragment.wxs +++ b/mRemoteNGInstaller/Installer/Fragments/FilesFragment.wxs @@ -78,12 +78,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -105,6 +135,9 @@ + + + @@ -147,18 +180,30 @@ + + + + + + + + + + + + @@ -189,6 +234,9 @@ + + + @@ -357,6 +405,9 @@ + + + @@ -481,6 +532,16 @@ + + + + + + + + + + @@ -526,4 +587,9 @@ + + + + + \ No newline at end of file diff --git a/mRemoteNGSpecs/StepDefinitions/CredentialRepositoryListSteps.cs b/mRemoteNGSpecs/StepDefinitions/CredentialRepositoryListSteps.cs index 8f9c1f8ea..a79485e9e 100644 --- a/mRemoteNGSpecs/StepDefinitions/CredentialRepositoryListSteps.cs +++ b/mRemoteNGSpecs/StepDefinitions/CredentialRepositoryListSteps.cs @@ -10,7 +10,7 @@ namespace mRemoteNGSpecs.StepDefinitions public class CredentialRepositoryListSteps { private CredentialRepositoryList _credentialRepositoryList; - private readonly XmlCredentialRepoBuilder _credentialRepoUtilities = new XmlCredentialRepoBuilder(); + private readonly XmlCredentialRepoBuilder _credentialRepoUtilities = new(); [Given(@"I have a credential repository list")] public void GivenIHaveACredentialRepositoryList() diff --git a/mRemoteNGSpecs/mRemoteNGSpecs.csproj b/mRemoteNGSpecs/mRemoteNGSpecs.csproj index b7277a19b..4f7f0c9b3 100644 --- a/mRemoteNGSpecs/mRemoteNGSpecs.csproj +++ b/mRemoteNGSpecs/mRemoteNGSpecs.csproj @@ -2,7 +2,7 @@ WinExe - net6.0-windows + net6.0-windows10.0.22621.0 enable true x64 @@ -17,14 +17,14 @@ - - - - + + + + - - - + + + diff --git a/mRemoteNGTests/ListViewTester.cs b/mRemoteNGTests/ListViewTester.cs index e82265a80..ad5140e2b 100644 --- a/mRemoteNGTests/ListViewTester.cs +++ b/mRemoteNGTests/ListViewTester.cs @@ -147,7 +147,7 @@ namespace mRemoteNGTests /// public bool SelectedItemsMatch(string[] matches) { - ArrayList matchList = new ArrayList(matches); + ArrayList matchList = new(matches); if (matchList.Count != Properties.SelectedItems.Count) { diff --git a/mRemoteNGTests/TestHelpers/Randomizer.cs b/mRemoteNGTests/TestHelpers/Randomizer.cs index d66f3f804..69bd7dd22 100644 --- a/mRemoteNGTests/TestHelpers/Randomizer.cs +++ b/mRemoteNGTests/TestHelpers/Randomizer.cs @@ -8,7 +8,7 @@ namespace mRemoteNGTests.TestHelpers { internal static class Randomizer { - private static readonly Random Random = new Random(); + private static readonly Random Random = new(); internal static string RandomString(params string[] excludedStrings) { diff --git a/mRemoteNGTests/Tools/Registry/WindowsRegistryKeyTests.cs b/mRemoteNGTests/Tools/Registry/WindowsRegistryKeyTests.cs index 717b82397..dad5b54d6 100644 --- a/mRemoteNGTests/Tools/Registry/WindowsRegistryKeyTests.cs +++ b/mRemoteNGTests/Tools/Registry/WindowsRegistryKeyTests.cs @@ -257,8 +257,10 @@ namespace mRemoteNGTests.Tools.Registry Value = "Big Bang" }; - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" }; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" } + }; StrKey.ConvertFromWindowsRegistryKey(TestKey); Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true)); @@ -277,8 +279,10 @@ namespace mRemoteNGTests.Tools.Registry Value = "ig ang" }; - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" }; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" } + }; StrKey.ConvertFromWindowsRegistryKey(TestKey); Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true)); @@ -297,9 +301,11 @@ namespace mRemoteNGTests.Tools.Registry Value = "BiG BAng" }; - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = new[] { "BiG BAng", "Big Bang Theory", "The Big Bang Theory" }; - StrKey.IsCaseSensitiveValidation = true; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = new[] { "BiG BAng", "Big Bang Theory", "The Big Bang Theory" }, + IsCaseSensitiveValidation = true + }; StrKey.ConvertFromWindowsRegistryKey(TestKey); Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true)); @@ -318,9 +324,11 @@ namespace mRemoteNGTests.Tools.Registry Value = "BiG BAng" }; - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" }; - StrKey.IsCaseSensitiveValidation = true; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" }, + IsCaseSensitiveValidation = true + }; StrKey.ConvertFromWindowsRegistryKey(TestKey); Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true)); @@ -339,8 +347,10 @@ namespace mRemoteNGTests.Tools.Registry Value = "ig ang" }; - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" }; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" } + }; StrKey.ConvertFromWindowsRegistryKey(TestKey); Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true)); @@ -360,8 +370,10 @@ namespace mRemoteNGTests.Tools.Registry Value = "ig ang" }; - WindowsRegistryKeyString StrKey = new(); - StrKey.AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" }; + WindowsRegistryKeyString StrKey = new() + { + AllowedValues = new[] { "Big Bang", "Big Bang Theory", "The Big Bang Theory" } + }; StrKey.ConvertFromWindowsRegistryKey(TestKey, "Big Bang Theory"); Assert.That(StrKey.IsKeyPresent, Is.EqualTo(true)); diff --git a/mRemoteNGTests/UI/Forms/OptionsFormTests.cs b/mRemoteNGTests/UI/Forms/OptionsFormTests.cs index 297503ad8..2b964cb4b 100644 --- a/mRemoteNGTests/UI/Forms/OptionsFormTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsFormTests.cs @@ -30,7 +30,7 @@ namespace mRemoteNGTests.UI.Forms [Test] public void ListViewContainsOptionsPages() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items.Count, Is.EqualTo(12)); } } diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAdvancedPageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAdvancedPageTests.cs index 2ea555810..c779f8479 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAdvancedPageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAdvancedPageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void AdvancedPageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[10].Text, Does.Match("Advanced")); } [Test] public void AdvancedIconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[10].ImageList, Is.Not.Null); } [Test] public void SelectingAdvancedPageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("Advanced"); CheckBox checkboxTester = _optionsForm.FindControl("chkAutomaticReconnect"); diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAppearancePageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAppearancePageTests.cs index 8fe8234ec..4b4429c51 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAppearancePageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsAppearancePageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void AppearancePageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[1].Text, Does.Match("Appearance")); } [Test] public void IconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[1].ImageList, Is.Not.Null); } [Test] public void SelectingAppearancePageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("Appearance"); CheckBox checkboxTester = _optionsForm.FindControl("chkShowSystemTrayIcon"); Assert.That(checkboxTester.Text, Does.Match("show notification area icon")); diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsConnectionsPageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsConnectionsPageTests.cs index 5ce461c89..a06d82656 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsConnectionsPageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsConnectionsPageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void ConnectionsPageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[2].Text, Does.Match("Connections")); } [Test] public void ConnectionsIconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[2].ImageList, Is.Not.Null); } [Test] public void SelectingConnectionsPageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("Connections"); CheckBox checkboxTester = _optionsForm.FindControl("chkSingleClickOnConnectionOpensIt"); Assert.That(checkboxTester.Text, Does.Match("Single click on connection")); diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsSQLPageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsSQLPageTests.cs index 3cf1d64cd..c084988bf 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsSQLPageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsSQLPageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void SQLPageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[6].Text, Does.Match("SQL Server")); } [Test] public void SQLIconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[6].ImageList, Is.Not.Null); } [Test] public void SelectingSQLPageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("SQL Server"); CheckBox checkboxTester = _optionsForm.FindControl("chkUseSQLServer"); Assert.That(checkboxTester.Text, Does.Match("Use SQL")); diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsStartupExitPageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsStartupExitPageTests.cs index e62a3ffc3..8e1648431 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsStartupExitPageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsStartupExitPageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void StartupExitPageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[0].Text, Does.Match("Startup/Exit")); } [Test] public void IconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[0].ImageList, Is.Not.Null); } [Test] public void SelectingStartupExitPageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("Startup/Exit"); CheckBox checkboxTester = _optionsForm.FindControl("chkSaveConsOnExit"); Assert.That(checkboxTester.Text, Does.Match("Save connections")); diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsTabsPanelPageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsTabsPanelPageTests.cs index 67e13515a..7d79e7d7e 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsTabsPanelPageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsTabsPanelPageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void TabsPanelPageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[3].Text, Does.Match("Tabs & Panels")); } [Test] public void TabsPanelIconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[3].ImageList, Is.Not.Null); } [Test] public void SelectingTabsPanelPageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("Tabs & Panels"); CheckBox checkboxTester = _optionsForm.FindControl("chkAlwaysShowPanelTabs"); Assert.That(checkboxTester.Text, Does.Match("Always show panel tabs")); diff --git a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsThemePageTests.cs b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsThemePageTests.cs index 323af78e9..c8fdf9152 100644 --- a/mRemoteNGTests/UI/Forms/OptionsPages/OptionsThemePageTests.cs +++ b/mRemoteNGTests/UI/Forms/OptionsPages/OptionsThemePageTests.cs @@ -12,21 +12,21 @@ namespace mRemoteNGTests.UI.Forms.OptionsPages [Test] public void ThemePageLinkExistsInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[8].Text, Does.Match("Theme")); } [Test] public void ThemeIconShownInListView() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); Assert.That(listViewTester.Items[8].ImageList, Is.Not.Null); } [Test] public void SelectingThemePageLoadsSettings() { - ListViewTester listViewTester = new ListViewTester("lstOptionPages", _optionsForm); + ListViewTester listViewTester = new("lstOptionPages", _optionsForm); listViewTester.Select("Theme"); Button buttonTester = _optionsForm.FindControl