diff --git a/.gitignore b/.gitignore index 4485ecca..18a38611 100644 --- a/.gitignore +++ b/.gitignore @@ -283,9 +283,6 @@ Installer Projects/Installer/Fragments/HelpFilesFragment.wxs InstallerProjects/Installer/Fragments/FilesFragment.wxs InstallerProjects/Installer/Resources/License.rtf -# user preference: .editorconfig - http://editorconfig.org/ -.editorconfig - # gh-pages info runlocal.bat /_site \ No newline at end of file diff --git a/CHANGELOG.TXT b/CHANGELOG.TXT index d19bed2c..d5e5fe45 100644 --- a/CHANGELOG.TXT +++ b/CHANGELOG.TXT @@ -10,9 +10,12 @@ Features/Enhancements: #951: Added property to Enable/Disable Clipboard Sharing for RDP connections #928: Add context menu items to 'Close all but this' and 'Close all tabs to the right' #765: Port Scan Issues (single port scan option now available) +#155: Replace MagicLibrary with DockPanelSuite +#154: MR-139: Close Button on Each Tab - new default theme has a close button on each tab Fixes: ------ +#1248: RemoveMagicLib Bugs - various bugs that cropped up as a result of removing magiclib #1245: Options form takes nearly 3 seconds to appear when Theming is active #1240: Theming problem with NGNumericUpDown #1238: Connection panel not translated until opened for the first time diff --git a/Tools/appveyor_after_build.ps1 b/Tools/appveyor_after_build.ps1 index ec81233c..ab85ebd0 100644 --- a/Tools/appveyor_after_build.ps1 +++ b/Tools/appveyor_after_build.ps1 @@ -32,7 +32,7 @@ if ($ConfigurationName -eq "Release Portable") { Write-Output "Creating portable ZIP file $($PortableZip)" Remove-Item -Force $PortableZip -ErrorAction SilentlyContinue - & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $PortableZip "mRemoteV1\bin\package\*.*" + & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $PortableZip ".\mRemoteV1\bin\package\*.*" } else { Write-Output "We will not zip anything - this isnt a portable release build." diff --git a/Tools/cert/CodeSigning_Cert_mRemoteNG_DigiCert.p12.enc b/Tools/cert/CodeSigning_Cert_mRemoteNG_DigiCert.p12.enc new file mode 100644 index 00000000..38538259 Binary files /dev/null and b/Tools/cert/CodeSigning_Cert_mRemoteNG_DigiCert.p12.enc differ diff --git a/appveyor.yml b/appveyor.yml index a8474cb1..9370b432 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -13,7 +13,7 @@ install: - ps: >- date - C:\projects\mremoteng\mRemoteV1\Resources\CitrixReceiver.exe ENABLE_SSON="No" /silent /noreboot /EnableCEIP=false /AutoUpdateCheck=disabled /EnableTracing=false | out-null + mRemoteV1\Resources\CitrixReceiver.exe ENABLE_SSON="No" /silent /noreboot /EnableCEIP=false /AutoUpdateCheck=disabled /EnableTracing=false | out-null date before_build: @@ -28,7 +28,7 @@ build: parallel: true verbosity: normal after_build: -- ps: "if([string]::IsNullOrEmpty($Env:APPVEYOR_BUILD_FOLDER)) {\n Write-Output \"NOT running via Appveyor - Exiting\"\n Exit\n}\n\n$appvDir = $Env:APPVEYOR_BUILD_FOLDER\n\nWrite-Output \"Appveyor Build Dir: '$($appvDir)'\"\n$ConfigurationName = $Env:CONFIGURATION.Trim()\nWrite-Output \"Config Name (tirmmed): '$($ConfigurationName)'\"\n\n\n$SIGCHECK=\"Tools\\exes\\sigcheck.exe\"\n$SEVENZIP=\"Tools\\7zip\\7za.exe\"\n\nif ($ConfigurationName -eq \"Release Portable\") {\n Write-Output \"Packaging Release Portable ZIP\"\n \n $version = & $SIGCHECK /accepteula -q -n \"mRemoteV1\\bin\\$($ConfigurationName)\\mRemoteNG.exe\"\n\n Write-Output \"Version is $($version)\"\n\n $PortableZip=\"Release\\mRemoteNG-Portable-$($version).zip\"\n\n Remove-Item -Recurse \"mRemoteV1\\bin\\package\" -ErrorAction SilentlyContinue | Out-Null\n New-Item \"mRemoteV1\\bin\\package\" -ItemType \"directory\" | Out-Null\n \n Copy-Item \"mRemoteV1\\Resources\\PuTTYNG.exe\" -Destination \"mRemoteV1\\bin\\package\"\n\n Copy-Item \"mRemoteV1\\bin\\$ConfigurationName\\*\" -Destination \"mRemoteV1\\bin\\package\" -Recurse -Force \n Copy-Item \"*.txt\" -Destination \"mRemoteV1\\bin\\package\"\n\n Write-Output \"Creating portable ZIP file $($PortableZip)\"\n Remove-Item -Force $PortableZip -ErrorAction SilentlyContinue\n & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $PortableZip \"mRemoteV1\\bin\\package\\*.*\"\n}\nelse {\n Write-Output \"We will not zip anything - this isnt a portable release build.\"\n}\n\nWrite-Output \"\"\nWrite-Output \"\"\n\nif ($ConfigurationName -match \"Release\" -And $ConfigurationName -ne \"Release Installer\") {\n Write-Output \"Packaging debug symbols\"\n \n $version = & $SIGCHECK /accepteula -q -n \"mRemoteV1\\bin\\$($ConfigurationName)\\mRemoteNG.exe\"\n\n Write-Output \"Version is $($version)\"\n\n if ($ConfigurationName -match \"Portable\") {\n $zipFilePrefix = \"mRemoteNG-Portable-symbols\"\n } else {\n $zipFilePrefix = \"mRemoteNG-symbols\"\n }\n\n $outputZipPath=\"Release\\$zipFilePrefix-$($version).zip\"\n\n Write-Output \"Creating debug symbols ZIP file $($outputZipPath)\"\n Remove-Item -Force $outputZipPath -ErrorAction SilentlyContinue\n $SymPath = (Join-Path -Path mRemoteV1\\bin\\$($ConfigurationName) -ChildPath \"*.pdb\")\n if(Test-Path \"$SymPath\") {\n & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $outputZipPath \"$SymPath\"\n } else {\n Write-Output \"No Debugging Symbols Found...\"\n }\n \n}\nelse {\n Write-Output \"We will not package debug symbols for this configuration $($ConfigurationName)\"\n}\n\nWrite-Output \"\"" +- ps: "if([string]::IsNullOrEmpty($Env:APPVEYOR_BUILD_FOLDER)) {\n Write-Output \"NOT running via Appveyor - Exiting\"\n Exit\n}\n\n$appvDir = $Env:APPVEYOR_BUILD_FOLDER\n\nWrite-Output \"Appveyor Build Dir: '$($appvDir)'\"\n$ConfigurationName = $Env:CONFIGURATION.Trim()\nWrite-Output \"Config Name (tirmmed): '$($ConfigurationName)'\"\n\n\n$SIGCHECK=\"Tools\\exes\\sigcheck.exe\"\n$SEVENZIP=\"Tools\\7zip\\7za.exe\"\n\nif ($ConfigurationName -eq \"Release Portable\") {\n Write-Output \"Packaging Release Portable ZIP\"\n \n $version = & $SIGCHECK /accepteula -q -n \"mRemoteV1\\bin\\$($ConfigurationName)\\mRemoteNG.exe\"\n\n Write-Output \"Version is $($version)\"\n\n $PortableZip=\"Release\\mRemoteNG-Portable-$($version).zip\"\n\n Remove-Item -Recurse \"mRemoteV1\\bin\\package\" -ErrorAction SilentlyContinue | Out-Null\n New-Item \"mRemoteV1\\bin\\package\" -ItemType \"directory\" | Out-Null\n \n Copy-Item \"mRemoteV1\\Resources\\PuTTYNG.exe\" -Destination \"mRemoteV1\\bin\\package\"\n\n Copy-Item \"mRemoteV1\\bin\\$ConfigurationName\\*\" -Destination \"mRemoteV1\\bin\\package\" -Recurse -Force \n Copy-Item \"*.txt\" -Destination \"mRemoteV1\\bin\\package\"\n\n Write-Output \"Creating portable ZIP file $($PortableZip)\"\n Remove-Item -Force $PortableZip -ErrorAction SilentlyContinue\n & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $PortableZip \".\\mRemoteV1\\bin\\package\\*.*\"\n}\nelse {\n Write-Output \"We will not zip anything - this isnt a portable release build.\"\n}\n\nWrite-Output \"\"\nWrite-Output \"\"\n\nif ($ConfigurationName -match \"Release\" -And $ConfigurationName -ne \"Release Installer\") {\n Write-Output \"Packaging debug symbols\"\n \n $version = & $SIGCHECK /accepteula -q -n \"mRemoteV1\\bin\\$($ConfigurationName)\\mRemoteNG.exe\"\n\n Write-Output \"Version is $($version)\"\n\n if ($ConfigurationName -match \"Portable\") {\n $zipFilePrefix = \"mRemoteNG-Portable-symbols\"\n } else {\n $zipFilePrefix = \"mRemoteNG-symbols\"\n }\n\n $outputZipPath=\"Release\\$zipFilePrefix-$($version).zip\"\n\n Write-Output \"Creating debug symbols ZIP file $($outputZipPath)\"\n Remove-Item -Force $outputZipPath -ErrorAction SilentlyContinue\n $SymPath = (Join-Path -Path mRemoteV1\\bin\\$($ConfigurationName) -ChildPath \"*.pdb\")\n if(Test-Path \"$SymPath\") {\n & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $outputZipPath \"$SymPath\"\n } else {\n Write-Output \"No Debugging Symbols Found...\"\n }\n \n}\nelse {\n Write-Output \"We will not package debug symbols for this configuration $($ConfigurationName)\"\n}\n\nWrite-Output \"\"" test: assemblies: only: diff --git a/appveyor_publish.yml b/appveyor_publish.yml new file mode 100644 index 00000000..d25aa074 --- /dev/null +++ b/appveyor_publish.yml @@ -0,0 +1,65 @@ +version: 1.76.{build} +pull_requests: + do_not_increment_build_number: true +environment: + cert_path: tools\cert\CodeSigning_Cert_mRemoteNG_DigiCert.p12 + cert_decrypt_pwd: + secure: QK1ldldzIUSVA0u+OtbHixPmsXHAO9ksOKcyByq0FHM= + cert_pwd: + secure: Fni66m2OgoTxjRzahUNUUNHl5gGwTXLvXIMQYiOMqX8= +image: Visual Studio 2017 +configuration: +- Release Portable +- Release +- Release Installer +platform: x86 +shallow_clone: true +clone_depth: 1 +install: +- ps: >- + iex ((New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/appveyor/secure-file/master/install.ps1')) + + date + + mRemoteV1\Resources\CitrixReceiver.exe ENABLE_SSON="No" /silent /noreboot /EnableCEIP=false /AutoUpdateCheck=disabled /EnableTracing=false | out-null + + date +before_build: +- cmd: >- + echo %TIME% + + nuget restore + + echo %TIME% + + appveyor-tools\secure-file -decrypt %cert_path%.enc -secret %cert_decrypt_pwd% +build_script: + - cmd: msbuild mRemoteV1.sln /t:Clean,Build /p:Configuration="Release Portable" /p:Platform=x86 /p:CertPath="%APPVEYOR_BUILD_FOLDER%\%cert_path%" /p:CertPassword=%cert_pwd% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" +for: + - + matrix: + only: + - configuration: "Release Installer" + build_script: + - cmd: msbuild mRemoteV1.sln /t:Clean,Build /p:Configuration="Release Installer" /p:Platform=x86 /p:CertPath="%APPVEYOR_BUILD_FOLDER%\%cert_path%" /p:CertPassword=%cert_pwd% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" + - + matrix: + only: + - configuration: Release + build_script: + - cmd: msbuild mRemoteV1.sln /t:Clean,Build /p:Configuration="Release" /p:Platform=x86 /p:CertPath="%APPVEYOR_BUILD_FOLDER%\%cert_path%" /p:CertPassword=%cert_pwd% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" +after_build: +- ps: "if([string]::IsNullOrEmpty($Env:APPVEYOR_BUILD_FOLDER)) {\n Write-Output \"NOT running via Appveyor - Exiting\"\n Exit\n}\n\n$appvDir = $Env:APPVEYOR_BUILD_FOLDER\n\nWrite-Output \"Appveyor Build Dir: '$($appvDir)'\"\n$ConfigurationName = $Env:CONFIGURATION.Trim()\nWrite-Output \"Config Name (tirmmed): '$($ConfigurationName)'\"\n\n\n$SIGCHECK=\"Tools\\exes\\sigcheck.exe\"\n$SEVENZIP=\"Tools\\7zip\\7za.exe\"\n\nif ($ConfigurationName -eq \"Release Portable\") {\n Write-Output \"Packaging Release Portable ZIP\"\n \n $version = & $SIGCHECK /accepteula -q -n \"mRemoteV1\\bin\\$($ConfigurationName)\\mRemoteNG.exe\"\n\n Write-Output \"Version is $($version)\"\n\n $PortableZip=\"Release\\mRemoteNG-Portable-$($version).zip\"\n\n Remove-Item -Recurse \"mRemoteV1\\bin\\package\" -ErrorAction SilentlyContinue | Out-Null\n New-Item \"mRemoteV1\\bin\\package\" -ItemType \"directory\" | Out-Null\n \n Copy-Item \"mRemoteV1\\Resources\\PuTTYNG.exe\" -Destination \"mRemoteV1\\bin\\package\"\n\n Copy-Item \"mRemoteV1\\bin\\$ConfigurationName\\*\" -Destination \"mRemoteV1\\bin\\package\" -Recurse -Force \n Copy-Item \"*.txt\" -Destination \"mRemoteV1\\bin\\package\"\n\n Write-Output \"Creating portable ZIP file $($PortableZip)\"\n Remove-Item -Force $PortableZip -ErrorAction SilentlyContinue\n & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $PortableZip \".\\mRemoteV1\\bin\\package\\*.*\"\n}\nelse {\n Write-Output \"We will not zip anything - this isnt a portable release build.\"\n}\n\nWrite-Output \"\"\nWrite-Output \"\"\n\nif ($ConfigurationName -match \"Release\" -And $ConfigurationName -ne \"Release Installer\") {\n Write-Output \"Packaging debug symbols\"\n \n $version = & $SIGCHECK /accepteula -q -n \"mRemoteV1\\bin\\$($ConfigurationName)\\mRemoteNG.exe\"\n\n Write-Output \"Version is $($version)\"\n\n if ($ConfigurationName -match \"Portable\") {\n $zipFilePrefix = \"mRemoteNG-Portable-symbols\"\n } else {\n $zipFilePrefix = \"mRemoteNG-symbols\"\n }\n\n $outputZipPath=\"Release\\$zipFilePrefix-$($version).zip\"\n\n Write-Output \"Creating debug symbols ZIP file $($outputZipPath)\"\n Remove-Item -Force $outputZipPath -ErrorAction SilentlyContinue\n $SymPath = (Join-Path -Path mRemoteV1\\bin\\$($ConfigurationName) -ChildPath \"*.pdb\")\n if(Test-Path \"$SymPath\") {\n & $SEVENZIP a -bt -bd -bb1 -mx=9 -tzip -y -r $outputZipPath \"$SymPath\"\n } else {\n Write-Output \"No Debugging Symbols Found...\"\n }\n \n}\nelse {\n Write-Output \"We will not package debug symbols for this configuration $($ConfigurationName)\"\n}\n\nWrite-Output \"\"" +test: + assemblies: + only: + - mRemoteNGTests\bin\$(configuration)\mRemoteNGTests.dll +artifacts: +- path: Release\*.msi + name: mRemoteNG-installer.msi +- path: Release\mRemoteNG-Portable-1.*.zip + name: mRemoteNG-portable.zip +- path: Release\mRemoteNG-Portable-symbols*.zip + name: mRemoteNG-Portable-symbols.zip +- path: Release\mRemoteNG-symbols*.zip + name: mRemoteNG-symbols.zip \ No newline at end of file diff --git a/mRemoteNG.Specs/App.config b/mRemoteNG.Specs/App.config index 7695b838..902fa1f5 100644 --- a/mRemoteNG.Specs/App.config +++ b/mRemoteNG.Specs/App.config @@ -7,7 +7,7 @@ - + diff --git a/mRemoteNGTests/Connection/Protocol/IntegratedProgramTests.cs b/mRemoteNGTests/Connection/Protocol/IntegratedProgramTests.cs index 9c82b320..3ca439d3 100644 --- a/mRemoteNGTests/Connection/Protocol/IntegratedProgramTests.cs +++ b/mRemoteNGTests/Connection/Protocol/IntegratedProgramTests.cs @@ -52,8 +52,8 @@ namespace mRemoteNGTests.Connection.Protocol private InterfaceControl BuildInterfaceControl(string extAppName, ProtocolBase sut) { var connectionWindow = new ConnectionWindow(new DockContent()); - var connectionInfo = new ConnectionInfo {ExtApp = extAppName}; - return new InterfaceControl(connectionWindow, sut, connectionInfo); + var connectionInfo = new ConnectionInfo {ExtApp = extAppName, Protocol = ProtocolType.IntApp}; + return new InterfaceControl(connectionWindow, sut, connectionInfo); } } } \ No newline at end of file diff --git a/mRemoteV1/.editorconfig b/mRemoteV1/.editorconfig new file mode 100644 index 00000000..6071b846 --- /dev/null +++ b/mRemoteV1/.editorconfig @@ -0,0 +1,44 @@ +# top-most EditorConfig file +root = true + +[*] +end_of_line = crlf +indent_style = space + +[*.xml] +indent_size = 4 + +[*.cs] +indent_size = 4 +trim_trailing_whitespace = true +charset = utf-8-bom + +# Organize usings +dotnet_sort_system_directives_first = true + +# this. preferences +dotnet_style_qualification_for_field = false:none +dotnet_style_qualification_for_property = false:none +dotnet_style_qualification_for_method = false:none +dotnet_style_qualification_for_event = false:none + +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false \ No newline at end of file diff --git a/mRemoteV1/App/CompatibilityChecker.cs b/mRemoteV1/App/CompatibilityChecker.cs index c26af6cd..a5a4d281 100644 --- a/mRemoteV1/App/CompatibilityChecker.cs +++ b/mRemoteV1/App/CompatibilityChecker.cs @@ -1,11 +1,11 @@ using Microsoft.Win32; using mRemoteNG.App.Info; -using mRemoteNG.UI.Forms; using mRemoteNG.UI.TaskDialog; using System; using System.Diagnostics; using System.Windows.Forms; using mRemoteNG.Messages; +using mRemoteNG.UI.Forms; namespace mRemoteNG.App { @@ -19,13 +19,38 @@ namespace mRemoteNG.App private static void CheckFipsPolicy(MessageCollector messageCollector) { + if (Settings.Default.OverrideFIPSCheck) + { + messageCollector.AddMessage(MessageClass.InformationMsg, "OverrideFIPSCheck is set. Will skip check...", + true); + return; + } + messageCollector.AddMessage(MessageClass.InformationMsg, "Checking FIPS Policy...", true); if (!FipsPolicyEnabledForServer2003() && !FipsPolicyEnabledForServer2008AndNewer()) return; - var errorText = string.Format(Language.strErrorFipsPolicyIncompatible, GeneralAppInfo.ProductName, - GeneralAppInfo.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); + + var errorText = string.Format(Language.strErrorFipsPolicyIncompatible, GeneralAppInfo.ProductName); messageCollector.AddMessage(MessageClass.ErrorMsg, errorText, true); - MessageBox.Show(FrmMain.Default, errorText); - Environment.Exit(1); + + //About to pop up a message, let's not block it... + FrmSplashScreen.getInstance().Close(); + + var ShouldIStayOrShouldIGo = CTaskDialog.MessageBox(Application.ProductName, + Language.strCompatibilityProblemDetected, errorText, "", + "", + Language.strCheckboxDoNotShowThisMessageAgain, + ETaskDialogButtons.OkCancel, ESysIcons.Warning, + ESysIcons.Warning); + if (CTaskDialog.VerificationChecked && ShouldIStayOrShouldIGo == DialogResult.OK) + { + messageCollector.AddMessage(MessageClass.ErrorMsg, "User requests that FIPS check be overridden", true); + Settings.Default.OverrideFIPSCheck = true; + Settings.Default.Save(); + return; + } + + if (ShouldIStayOrShouldIGo == DialogResult.Cancel) + Environment.Exit(1); } private static bool FipsPolicyEnabledForServer2003() @@ -39,7 +64,8 @@ namespace mRemoteNG.App private static bool FipsPolicyEnabledForServer2008AndNewer() { - var regKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\Lsa\\FIPSAlgorithmPolicy"); + var regKey = + Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\Lsa\\FIPSAlgorithmPolicy"); var fipsPolicy = regKey?.GetValue("Enabled"); if (fipsPolicy == null) return false; fipsPolicy = Convert.ToInt32(fipsPolicy); @@ -64,9 +90,14 @@ namespace mRemoteNG.App } if (proccesses.Length <= 0) return; - CTaskDialog.MessageBox(Application.ProductName, Language.strCompatibilityProblemDetected, string.Format(Language.strCompatibilityLenovoAutoScrollUtilityDetected, Application.ProductName), "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.Ok, ESysIcons.Warning, ESysIcons.Warning); + CTaskDialog.MessageBox(Application.ProductName, Language.strCompatibilityProblemDetected, + string.Format(Language.strCompatibilityLenovoAutoScrollUtilityDetected, + Application.ProductName), "", + "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.Ok, + ESysIcons.Warning, + ESysIcons.Warning); if (CTaskDialog.VerificationChecked) Settings.Default.CompatibilityWarnLenovoAutoScrollUtility = false; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/App/Export.cs b/mRemoteV1/App/Export.cs index 1bb2d7be..a973e2ae 100644 --- a/mRemoteV1/App/Export.cs +++ b/mRemoteV1/App/Export.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Windows.Forms; using mRemoteNG.Config.Connections; @@ -17,92 +17,100 @@ using mRemoteNG.UI.Forms; namespace mRemoteNG.App { - public static class Export - { + public static class Export + { public static void ExportToFile(ConnectionInfo selectedNode, IConnectionTreeModel connectionTreeModel) - { - try - { - var saveFilter = new SaveFilter(); - - using (var exportForm = new ExportForm()) - { - if (selectedNode?.GetTreeNodeType() == TreeNodeType.Container) - exportForm.SelectedFolder = selectedNode as ContainerInfo; - else if (selectedNode?.GetTreeNodeType() == TreeNodeType.Connection) - { - if (selectedNode.Parent.GetTreeNodeType() == TreeNodeType.Container) - exportForm.SelectedFolder = selectedNode.Parent; - exportForm.SelectedConnection = selectedNode; - } - - if (exportForm.ShowDialog(FrmMain.Default) != DialogResult.OK) - return; + { + try + { + var saveFilter = new SaveFilter(); - ConnectionInfo exportTarget; - switch (exportForm.Scope) - { - case ExportForm.ExportScope.SelectedFolder: - exportTarget = exportForm.SelectedFolder; - break; + using (var exportForm = new ExportForm()) + { + if (selectedNode?.GetTreeNodeType() == TreeNodeType.Container) + exportForm.SelectedFolder = selectedNode as ContainerInfo; + else if (selectedNode?.GetTreeNodeType() == TreeNodeType.Connection) + { + if (selectedNode.Parent.GetTreeNodeType() == TreeNodeType.Container) + exportForm.SelectedFolder = selectedNode.Parent; + exportForm.SelectedConnection = selectedNode; + } + + if (exportForm.ShowDialog(FrmMain.Default) != DialogResult.OK) + return; + + ConnectionInfo exportTarget; + switch (exportForm.Scope) + { + case ExportForm.ExportScope.SelectedFolder: + exportTarget = exportForm.SelectedFolder; + break; case ExportForm.ExportScope.SelectedConnection: - exportTarget = exportForm.SelectedConnection; - break; - default: - exportTarget = connectionTreeModel.RootNodes.First(node => node is RootNodeInfo); - break; - } - - saveFilter.SaveUsername = exportForm.IncludeUsername; - saveFilter.SavePassword = exportForm.IncludePassword; - saveFilter.SaveDomain = exportForm.IncludeDomain; - saveFilter.SaveInheritance = exportForm.IncludeInheritance; - saveFilter.SaveCredentialId = exportForm.IncludeAssignedCredential; - - SaveExportFile(exportForm.FileName, exportForm.SaveFormat, saveFilter, exportTarget); - } - - } - catch (Exception ex) - { + exportTarget = exportForm.SelectedConnection; + break; + default: + exportTarget = connectionTreeModel.RootNodes.First(node => node is RootNodeInfo); + break; + } + + saveFilter.SaveUsername = exportForm.IncludeUsername; + saveFilter.SavePassword = exportForm.IncludePassword; + saveFilter.SaveDomain = exportForm.IncludeDomain; + saveFilter.SaveInheritance = exportForm.IncludeInheritance; + saveFilter.SaveCredentialId = exportForm.IncludeAssignedCredential; + + SaveExportFile(exportForm.FileName, exportForm.SaveFormat, saveFilter, exportTarget); + } + } + catch (Exception ex) + { Runtime.MessageCollector.AddExceptionMessage("App.Export.ExportToFile() failed.", ex); - } - } - - private static void SaveExportFile(string fileName, SaveFormat saveFormat, SaveFilter saveFilter, ConnectionInfo exportTarget) - { - try - { - ISerializer serializer; - switch (saveFormat) - { - case SaveFormat.mRXML: + } + } + + private static void SaveExportFile(string fileName, + SaveFormat saveFormat, + SaveFilter saveFilter, + ConnectionInfo exportTarget) + { + try + { + ISerializer serializer; + switch (saveFormat) + { + case SaveFormat.mRXML: var cryptographyProvider = new CryptoProviderFactoryFromSettings().Build(); - var rootNode = exportTarget.GetRootParent() as RootNodeInfo; + var rootNode = exportTarget.GetRootParent() as RootNodeInfo; var connectionNodeSerializer = new XmlConnectionNodeSerializer27( - cryptographyProvider, - rootNode?.PasswordString.ConvertToSecureString() ?? new RootNodeInfo(RootNodeType.Connection).PasswordString.ConvertToSecureString(), - saveFilter); - serializer = new XmlConnectionsSerializer(cryptographyProvider, connectionNodeSerializer); - break; - case SaveFormat.mRCSV: + cryptographyProvider, + rootNode?.PasswordString + .ConvertToSecureString() ?? + new RootNodeInfo(RootNodeType + .Connection) + .PasswordString + .ConvertToSecureString(), + saveFilter); + serializer = new XmlConnectionsSerializer(cryptographyProvider, connectionNodeSerializer); + break; + case SaveFormat.mRCSV: serializer = new CsvConnectionsSerializerMremotengFormat(saveFilter, Runtime.CredentialService.RepositoryList); break; - default: - throw new ArgumentOutOfRangeException(nameof(saveFormat), saveFormat, null); - } - var serializedData = serializer.Serialize(exportTarget); - var fileDataProvider = new FileDataProvider(fileName); + default: + throw new ArgumentOutOfRangeException(nameof(saveFormat), saveFormat, null); + } + + var serializedData = serializer.Serialize(exportTarget); + var fileDataProvider = new FileDataProvider(fileName); fileDataProvider.Save(serializedData); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace($"Export.SaveExportFile(\"{fileName}\") failed.", ex); - } - finally - { - Runtime.ConnectionsService.RemoteConnectionsSyncronizer?.Enable(); - } - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace($"Export.SaveExportFile(\"{fileName}\") failed.", ex); + } + finally + { + Runtime.ConnectionsService.RemoteConnectionsSyncronizer?.Enable(); + } + } + } } \ No newline at end of file diff --git a/mRemoteV1/App/Import.cs b/mRemoteV1/App/Import.cs index c700e3e0..4235c49b 100644 --- a/mRemoteV1/App/Import.cs +++ b/mRemoteV1/App/Import.cs @@ -45,8 +45,10 @@ namespace mRemoteNG.App } catch (Exception ex) { - MessageBox.Show(string.Format(Language.strImportFileFailedContent, fileName), Language.strImportFileFailedMainInstruction, - MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); + MessageBox.Show(string.Format(Language.strImportFileFailedContent, fileName), + Language.strImportFileFailedMainInstruction, + MessageBoxButtons.OK, MessageBoxIcon.Exclamation, + MessageBoxDefaultButton.Button1); Runtime.MessageCollector.AddExceptionMessage("Unable to import file.", ex); } } @@ -60,7 +62,9 @@ namespace mRemoteNG.App } } - public static void ImportFromActiveDirectory(string ldapPath, ContainerInfo importDestinationContainer, bool importSubOu) + public static void ImportFromActiveDirectory(string ldapPath, + ContainerInfo importDestinationContainer, + bool importSubOu) { try { @@ -73,7 +77,9 @@ namespace mRemoteNG.App } } - public static void ImportFromPortScan(IEnumerable hosts, ProtocolType protocol, ContainerInfo importDestinationContainer) + public static void ImportFromPortScan(IEnumerable hosts, + ProtocolType protocol, + ContainerInfo importDestinationContainer) { try { diff --git a/mRemoteV1/App/Info/ConnectionsFileInfo.cs b/mRemoteV1/App/Info/ConnectionsFileInfo.cs index 6017865f..36793e36 100644 --- a/mRemoteV1/App/Info/ConnectionsFileInfo.cs +++ b/mRemoteV1/App/Info/ConnectionsFileInfo.cs @@ -1,6 +1,6 @@ namespace mRemoteNG.App.Info { - public static class ConnectionsFileInfo + public static class ConnectionsFileInfo { public static readonly string DefaultConnectionsPath = SettingsFileInfo.SettingsPath; public static readonly string DefaultConnectionsFile = "confCons.xml"; diff --git a/mRemoteV1/App/Info/GeneralAppInfo.cs b/mRemoteV1/App/Info/GeneralAppInfo.cs index 17977389..fe424beb 100644 --- a/mRemoteV1/App/Info/GeneralAppInfo.cs +++ b/mRemoteV1/App/Info/GeneralAppInfo.cs @@ -9,46 +9,53 @@ using static System.Environment; namespace mRemoteNG.App.Info { - public static class GeneralAppInfo - { - public const string UrlHome = "https://www.mremoteng.org/"; - public const string UrlDonate = "https://mremoteng.org/contribute/"; - public const string UrlForum = "https://www.reddit.com/r/mRemoteNG/"; - public const string UrlBugs = "https://bugs.mremoteng.org/"; - public static string ApplicationVersion = Application.ProductVersion; + public static class GeneralAppInfo + { + public const string UrlHome = "https://www.mremoteng.org/"; + public const string UrlDonate = "https://mremoteng.org/contribute/"; + public const string UrlForum = "https://www.reddit.com/r/mRemoteNG/"; + public const string UrlBugs = "https://bugs.mremoteng.org/"; + public static 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"; - public static string UserAgent - { - get - { - var details = new List - { - "compatible", - OSVersion.Platform == PlatformID.Win32NT - ? $"Windows NT {OSVersion.Version.Major}.{OSVersion.Version.Minor}" - : OSVersion.VersionString - }; - if (Is64BitProcess) - { - details.Add("WOW64"); - } - details.Add(Thread.CurrentThread.CurrentUICulture.Name); - details.Add($".NET CLR {Environment.Version}"); - var detailsString = string.Join("; ", details.ToArray()); - - return $"Mozilla/5.0 ({detailsString}) {ProductName}/{ApplicationVersion}"; - } - } - public static Version GetApplicationVersion() - { - Version v; - System.Version.TryParse(ApplicationVersion, out v); - return v; - } - } + 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"; + + public static string UserAgent + { + get + { + var details = new List + { + "compatible", + OSVersion.Platform == PlatformID.Win32NT + ? $"Windows NT {OSVersion.Version.Major}.{OSVersion.Version.Minor}" + : OSVersion.VersionString + }; + if (Is64BitProcess) + { + details.Add("WOW64"); + } + + details.Add(Thread.CurrentThread.CurrentUICulture.Name); + details.Add($".NET CLR {Environment.Version}"); + var detailsString = string.Join("; ", details.ToArray()); + + return $"Mozilla/5.0 ({detailsString}) {ProductName}/{ApplicationVersion}"; + } + } + + public static Version GetApplicationVersion() + { + System.Version.TryParse(ApplicationVersion, out var v); + return v; + } + } } \ No newline at end of file diff --git a/mRemoteV1/App/Info/SettingsFileInfo.cs b/mRemoteV1/App/Info/SettingsFileInfo.cs index a91d9497..e6007b9f 100644 --- a/mRemoteV1/App/Info/SettingsFileInfo.cs +++ b/mRemoteV1/App/Info/SettingsFileInfo.cs @@ -8,13 +8,22 @@ namespace mRemoteNG.App.Info { public static class SettingsFileInfo { - private static readonly string ExePath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(ConnectionInfo))?.Location); + private static readonly string ExePath = + Path.GetDirectoryName(Assembly.GetAssembly(typeof(ConnectionInfo))?.Location); + + public static string SettingsPath => + Runtime.IsPortableEdition + ? ExePath + : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + Application.ProductName; - public static string SettingsPath => Runtime.IsPortableEdition ? ExePath : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + Application.ProductName; public static string LayoutFileName { get; } = "pnlLayout.xml"; public static string ExtAppsFilesName { get; } = "extApps.xml"; public static string ThemesFileName { get; } = "Themes.xml"; - public static string ThemeFolder { get; } = SettingsPath != null ? Path.Combine(SettingsPath, "Themes") : String.Empty; - public static string InstalledThemeFolder { get; } = ExePath != null ? Path.Combine(ExePath, "Themes") : String.Empty; + + public static string ThemeFolder { get; } = + SettingsPath != null ? Path.Combine(SettingsPath, "Themes") : String.Empty; + + public static string InstalledThemeFolder { get; } = + ExePath != null ? Path.Combine(ExePath, "Themes") : String.Empty; } } \ No newline at end of file diff --git a/mRemoteV1/App/Info/UpdateChannelInfo.cs b/mRemoteV1/App/Info/UpdateChannelInfo.cs index e3b3f4e2..c5f3ec46 100644 --- a/mRemoteV1/App/Info/UpdateChannelInfo.cs +++ b/mRemoteV1/App/Info/UpdateChannelInfo.cs @@ -1,4 +1,5 @@ using System; + // ReSharper disable InconsistentNaming namespace mRemoteNG.App.Info @@ -27,7 +28,9 @@ namespace mRemoteNG.App.Info private static string GetChannelFileName(string channel) { - return Runtime.IsPortableEdition ? GetChannelFileNamePortableEdition(channel) : GetChannelFileNameNormalEdition(channel); + return Runtime.IsPortableEdition + ? GetChannelFileNamePortableEdition(channel) + : GetChannelFileNameNormalEdition(channel); } private static string GetChannelFileNameNormalEdition(string channel) @@ -62,7 +65,8 @@ namespace mRemoteNG.App.Info private static Uri GetUpdateTxtUri(string channel) { - return new Uri(new Uri(Settings.Default.UpdateAddress), new Uri(GetChannelFileName(channel), UriKind.Relative)); + return new Uri(new Uri(Settings.Default.UpdateAddress), + new Uri(GetChannelFileName(channel), UriKind.Relative)); } private static bool IsValidChannel(string s) diff --git a/mRemoteV1/App/Initialization/ConnectionIconLoader.cs b/mRemoteV1/App/Initialization/ConnectionIconLoader.cs index f9282ff8..b9267f63 100644 --- a/mRemoteV1/App/Initialization/ConnectionIconLoader.cs +++ b/mRemoteV1/App/Initialization/ConnectionIconLoader.cs @@ -11,7 +11,7 @@ namespace mRemoteNG.App.Initialization public ConnectionIconLoader(string folderPath) { - if(string.IsNullOrEmpty(folderPath)) + if (string.IsNullOrEmpty(folderPath)) throw new ArgumentException($"{nameof(folderPath)} must be a valid folder path."); _path = folderPath; diff --git a/mRemoteV1/App/Initialization/CredsAndConsSetup.cs b/mRemoteV1/App/Initialization/CredsAndConsSetup.cs index 14cfdbe1..77c5ad2b 100644 --- a/mRemoteV1/App/Initialization/CredsAndConsSetup.cs +++ b/mRemoteV1/App/Initialization/CredsAndConsSetup.cs @@ -14,7 +14,8 @@ namespace mRemoteNG.App.Initialization { connectionsOnEdit.Subscribe(connectionsService); - if (Settings.Default.FirstStart && !Settings.Default.LoadConsFromCustomLocation && !File.Exists(connectionsService.GetStartupConnectionFileName())) + if (Settings.Default.FirstStart && !Settings.Default.LoadConsFromCustomLocation && + !File.Exists(connectionsService.GetStartupConnectionFileName())) connectionsService.NewConnectionsFile(connectionsService.GetStartupConnectionFileName()); credentialService.LoadRepositoryList(); diff --git a/mRemoteV1/App/Initialization/MessageCollectorSetup.cs b/mRemoteV1/App/Initialization/MessageCollectorSetup.cs index 5f110cc7..faf6a394 100644 --- a/mRemoteV1/App/Initialization/MessageCollectorSetup.cs +++ b/mRemoteV1/App/Initialization/MessageCollectorSetup.cs @@ -8,7 +8,8 @@ namespace mRemoteNG.App.Initialization { public class MessageCollectorSetup { - public static void SetupMessageCollector(MessageCollector messageCollector, IList messageWriterList) + public static void SetupMessageCollector(MessageCollector messageCollector, + IList messageWriterList) { messageCollector.CollectionChanged += (o, args) => { @@ -37,34 +38,37 @@ namespace mRemoteNG.App.Initialization private static IMessageWriter BuildTextLogMessageWriter() { return new MessageTypeFilterDecorator( - new LogMessageTypeFilteringOptions(), - new TextLogMessageWriter(Logger.Instance) - ); + new LogMessageTypeFilteringOptions(), + new TextLogMessageWriter(Logger.Instance) + ); } private static IMessageWriter BuildNotificationPanelMessageWriter() { - return new OnlyLogMessageFilter( - new MessageTypeFilterDecorator( - new NotificationPanelMessageFilteringOptions(), - new MessageFocusDecorator( - Windows.ErrorsForm, - new NotificationPanelSwitchOnMessageFilteringOptions(), - new NotificationPanelMessageWriter(Windows.ErrorsForm) - ) - ) - ); + new MessageTypeFilterDecorator( + new + NotificationPanelMessageFilteringOptions(), + new MessageFocusDecorator( + Windows.ErrorsForm, + new + NotificationPanelSwitchOnMessageFilteringOptions(), + new + NotificationPanelMessageWriter(Windows + .ErrorsForm) + ) + ) + ); } private static IMessageWriter BuildPopupMessageWriter() { return new OnlyLogMessageFilter( - new MessageTypeFilterDecorator( - new PopupMessageFilteringOptions(), - new PopupMessageWriter() - ) - ); + new MessageTypeFilterDecorator( + new PopupMessageFilteringOptions(), + new PopupMessageWriter() + ) + ); } } } \ No newline at end of file diff --git a/mRemoteV1/App/Initialization/StartupDataLogger.cs b/mRemoteV1/App/Initialization/StartupDataLogger.cs index e5ea3a23..d4bc791e 100644 --- a/mRemoteV1/App/Initialization/StartupDataLogger.cs +++ b/mRemoteV1/App/Initialization/StartupDataLogger.cs @@ -43,7 +43,8 @@ namespace mRemoteNG.App.Initialization try { - foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary=True").Get()) + foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary=True") + .Get()) { var managementObject = (ManagementObject)o; osVersion = Convert.ToString(managementObject.GetPropertyValue("Caption")).Trim(); @@ -54,6 +55,7 @@ namespace mRemoteNG.App.Initialization { _messageCollector.AddExceptionMessage("Error retrieving operating system information from WMI.", ex); } + var osData = string.Join(" ", osVersion, servicePack); return osData; } @@ -65,6 +67,7 @@ namespace mRemoteNG.App.Initialization { servicePack = $"Service Pack {servicePackNumber}"; } + return servicePack; } @@ -73,7 +76,8 @@ namespace mRemoteNG.App.Initialization var architecture = string.Empty; try { - foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_Processor WHERE DeviceID=\'CPU0\'").Get()) + foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_Processor WHERE DeviceID=\'CPU0\'") + .Get()) { var managementObject = (ManagementObject)o; var addressWidth = Convert.ToInt32(managementObject.GetPropertyValue("AddressWidth")); @@ -84,6 +88,7 @@ namespace mRemoteNG.App.Initialization { _messageCollector.AddExceptionMessage("Error retrieving operating system address width from WMI.", ex); } + return architecture; } @@ -110,7 +115,8 @@ namespace mRemoteNG.App.Initialization private void LogCultureData() { - var data = $"System Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}"; + var data = + $"System Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}"; _messageCollector.AddMessage(MessageClass.InformationMsg, data, true); } } diff --git a/mRemoteV1/App/Logger.cs b/mRemoteV1/App/Logger.cs index 4031e058..b39fffb4 100644 --- a/mRemoteV1/App/Logger.cs +++ b/mRemoteV1/App/Logger.cs @@ -4,11 +4,12 @@ using System.Windows.Forms; using log4net; using log4net.Appender; using log4net.Config; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.App { - public class Logger + public class Logger { public static readonly Logger Instance = new Logger(); @@ -42,6 +43,7 @@ namespace mRemoteNG.App fileAppender.File = path; fileAppender.ActivateOptions(); } + Log = LogManager.GetLogger("Logger"); } @@ -56,7 +58,8 @@ namespace mRemoteNG.App private static string GetLogPathNormalEdition() { - return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.ProductName); + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + Application.ProductName); } private static string GetLogPathPortableEdition() diff --git a/mRemoteV1/App/NativeMethods.cs b/mRemoteV1/App/NativeMethods.cs index aaac65bd..0e15954b 100644 --- a/mRemoteV1/App/NativeMethods.cs +++ b/mRemoteV1/App/NativeMethods.cs @@ -4,6 +4,7 @@ using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Text; +#pragma warning disable 649 #pragma warning disable 169 namespace mRemoteNG.App @@ -11,33 +12,41 @@ namespace mRemoteNG.App public static class NativeMethods { #region Functions + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool AppendMenu(IntPtr hMenu, int uFlags, IntPtr uIDNewItem, string lpNewItem); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr CreatePopupMenu(); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle); - + internal static extern IntPtr FindWindowEx(IntPtr parentHandle, + IntPtr childAfter, + string lclassName, + string windowTitle); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr GetForegroundWindow(); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern bool InsertMenu(IntPtr hMenu, int uPosition, int uFlags, IntPtr uIDNewItem, string lpNewItem); - + internal static extern bool InsertMenu(IntPtr hMenu, + int uPosition, + int uFlags, + IntPtr uIDNewItem, + string lpNewItem); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int IsIconic(IntPtr hWnd); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool MoveWindow(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam); @@ -54,31 +63,38 @@ namespace mRemoteNG.App internal static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, string lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr SendMessage([In] IntPtr hWnd, [In] uint msg, [Out] StringBuilder wParam, [In] IntPtr lParam); + internal static extern IntPtr SendMessage([In] IntPtr hWnd, + [In] uint msg, + [Out] StringBuilder wParam, + [In] IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool SetForegroundWindow(IntPtr hWnd); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern bool SetMenuItemBitmaps(IntPtr hMenu, int uPosition, int uFlags, IntPtr hBitmapUnchecked, IntPtr hBitmapChecked); - + internal static extern bool SetMenuItemBitmaps(IntPtr hMenu, + int uPosition, + int uFlags, + IntPtr hBitmapUnchecked, + IntPtr hBitmapChecked); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int ShowWindow(IntPtr hWnd, int nCmdShow); - + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr WindowFromPoint(Point point); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount); + internal static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int GetDlgCtrlID(IntPtr hwndCtl); @@ -92,9 +108,11 @@ namespace mRemoteNG.App [DllImport("kernel32", SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal static extern bool CloseHandle(IntPtr handle); + #endregion #region Structures + [StructLayout(LayoutKind.Sequential)] internal struct WINDOWPOS { @@ -130,60 +148,71 @@ namespace mRemoteNG.App public long right; public long bottom; } + #endregion #region Helpers + public static int MAKELONG(int wLow, int wHigh) { return wLow | wHigh << 16; } - + public static int MAKELPARAM(ref int wLow, ref int wHigh) { return MAKELONG(wLow, wHigh); } - + public static int LOWORD(int value) { return value & 0xFFFF; } - + public static int LOWORD(IntPtr value) { return LOWORD(value.ToInt32()); } - + public static int HIWORD(int value) { return value >> 16; } - + public static int HIWORD(IntPtr value) { return HIWORD(value.ToInt32()); } + #endregion #region Constants + public const int TRUE = 1; #region GetWindowLong + public const int GWL_STYLE = (-16); + #endregion #region AppendMenu / ModifyMenu / DeleteMenu / RemoveMenu + public const int MF_BYCOMMAND = 0x0; public const int MF_BYPOSITION = 0x400; public const int MF_STRING = 0x0; public const int MF_POPUP = 0x10; public const int MF_SEPARATOR = 0x800; + #endregion #region WM_LBUTTONDOWN / WM_LBUTTONUP + public const int MK_LBUTTON = 0x1; + #endregion #region ShowWindow + public const uint SW_HIDE = 0; public const uint SW_SHOWNORMAL = 1; public const uint SW_SHOWMINIMIZED = 2; @@ -195,9 +224,11 @@ namespace mRemoteNG.App public const uint SW_SHOWMINNOACTIVE = 7; public const uint SW_SHOWNA = 8; public const uint SW_RESTORE = 9; + #endregion #region SetWindowPos / WM_WINDOWPOSCHANGING / WM_WINDOWPOSCHANGED + /// /// Retains the current size (ignores the cx and cy parameters). /// @@ -269,12 +300,12 @@ namespace mRemoteNG.App public const int SWP_NOCLIENTMOVE = 0x1000; /// - /// Prevents generation of the WM_SYNCPAINT message. + /// Prevents generation of the WM_SYNCPAINT message. /// public const int SWP_DEFERERASE = 0x2000; /// - /// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. + /// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. /// public const int SWP_ASYNCWINDOWPOS = 0x4000; @@ -282,15 +313,19 @@ namespace mRemoteNG.App /// /// public const int SWP_STATECHANGED = 0x8000; + #endregion #region Window Placement Flags (WPF) + public const uint WPF_SETMINPOSITION = 0x1; public const uint WPF_RESTORETOMAXIMIZED = 0x2; public const uint WPF_ASYNCWINDOWPLACEMENT = 0x4; + #endregion #region WM_ACTIVATE + /// /// /// @@ -303,14 +338,16 @@ namespace mRemoteNG.App /// /// Sent to both the window being activated and the window being deactivated. - /// If the windows use the same input queue, the message is sent synchronously, first to the window procedure of the - /// top-level window being deactivated, then to the window procedure of the top-level window being activated. If the + /// If the windows use the same input queue, the message is sent synchronously, first to the window procedure of the + /// top-level window being deactivated, then to the window procedure of the top-level window being activated. If the /// windows use different input queues, the message is sent asynchronously, so the window is activated immediately. /// public const int WA_CLICKACTIVE = 0x2; + #endregion #region Window Messages + /// /// Sent when an application requests that a window be created by calling the CreateWindowEx or CreateWindow function. (The message is sent before the function returns.) The window procedure of the new window receives this message after the window is created, but before the window becomes visible. /// @@ -332,7 +369,7 @@ namespace mRemoteNG.App public const int WM_SETTEXT = 0xC; /// - /// Copies the text that corresponds to a window into a buffer provided by the caller. + /// Copies the text that corresponds to a window into a buffer provided by the caller. /// public const int WM_GETTEXT = 0xD; @@ -347,7 +384,7 @@ namespace mRemoteNG.App public const int WM_ACTIVATEAPP = 0x1C; /// - /// Sent to a window if the mouse causes the cursor to move within a window and mouse input is not captured. + /// Sent to a window if the mouse causes the cursor to move within a window and mouse input is not captured. /// public const int WM_SETCURSOR = 0x20; @@ -372,12 +409,12 @@ namespace mRemoteNG.App public const int WM_WINDOWPOSCHANGED = 0x47; /// - /// Posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed. + /// Posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed. /// public const int WM_KEYDOWN = 0x100; /// - /// Posted to the window with the keyboard focus when a nonsystem key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed, or a keyboard key that is pressed when a window has the keyboard focus. + /// Posted to the window with the keyboard focus when a nonsystem key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed, or a keyboard key that is pressed when a window has the keyboard focus. /// public const int WM_KEYUP = 0x101; @@ -432,7 +469,7 @@ namespace mRemoteNG.App public const int WM_MBUTTONUP = 0x208; /// - /// Posted when the user presses the first or second X button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse. + /// Posted when the user presses the first or second X button while the cursor is in the client area of a window. If the mouse is not captured, the message is posted to the window beneath the cursor. Otherwise, the message is posted to the window that has captured the mouse. /// public const int WM_XBUTTONDOWN = 0x20B; @@ -447,47 +484,56 @@ namespace mRemoteNG.App public const int WM_PARENTNOTIFY = 0x210; /// - /// Sent one time to a window after it enters the moving or sizing modal loop. The window enters the moving or sizing modal loop when the user clicks the window's title bar or sizing border, or when the window passes the WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the message specifies the SC_MOVE or SC_SIZE value. The operation is complete when DefWindowProc returns. + /// Sent one time to a window after it enters the moving or sizing modal loop. The window enters the moving or sizing modal loop when the user clicks the window's title bar or sizing border, or when the window passes the WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the message specifies the SC_MOVE or SC_SIZE value. The operation is complete when DefWindowProc returns. /// public const int WM_ENTERSIZEMOVE = 0x231; /// - /// Sent one time to a window, after it has exited the moving or sizing modal loop. The window enters the moving or sizing modal loop when the user clicks the window's title bar or sizing border, or when the window passes the WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the message specifies the SC_MOVE or SC_SIZE value. The operation is complete when DefWindowProc returns. + /// Sent one time to a window, after it has exited the moving or sizing modal loop. The window enters the moving or sizing modal loop when the user clicks the window's title bar or sizing border, or when the window passes the WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the message specifies the SC_MOVE or SC_SIZE value. The operation is complete when DefWindowProc returns. /// public const int WM_EXITSIZEMOVE = 0x232; /// - /// Sent to the first window in the clipboard viewer chain when the content of the clipboard changes. This enables a clipboard viewer window to display the new content of the clipboard. + /// Sent to the first window in the clipboard viewer chain when the content of the clipboard changes. This enables a clipboard viewer window to display the new content of the clipboard. /// public const int WM_DRAWCLIPBOARD = 0x308; /// - /// Sent to the first window in the clipboard viewer chain when a window is being removed from the chain. + /// Sent to the first window in the clipboard viewer chain when a window is being removed from the chain. /// public const int WM_CHANGECBCHAIN = 0x30D; + #endregion #region Window Styles + public const int WS_MAXIMIZE = 0x1000000; public const int WS_VISIBLE = 0x10000000; public const int WS_CHILD = 0x40000000; public const int WS_EX_MDICHILD = 0x40; + #endregion #region Virtual Key Codes + public const int VK_CONTROL = 0x11; public const int VK_C = 0x67; + #endregion #region EM + public const uint ECM_FIRST = 0x1500; public const uint EM_SETCUEBANNER = ECM_FIRST + 1; public const uint EM_GETCUEBANNER = ECM_FIRST + 2; + #endregion #region LB + public const int LB_ERR = -1; public const int LB_SELECTSTRING = 0x18C; + #endregion #region TCM diff --git a/mRemoteV1/App/ProgramRoot.cs b/mRemoteV1/App/ProgramRoot.cs index b2fcd4a7..5906d2e0 100644 --- a/mRemoteV1/App/ProgramRoot.cs +++ b/mRemoteV1/App/ProgramRoot.cs @@ -67,9 +67,12 @@ namespace mRemoteNG.App var currentProcess = Process.GetCurrentProcess(); foreach (var enumeratedProcess in Process.GetProcessesByName(currentProcess.ProcessName)) { - if (enumeratedProcess.Id != currentProcess.Id && enumeratedProcess.MainModule.FileName == currentProcess.MainModule.FileName && enumeratedProcess.MainWindowHandle != IntPtr.Zero) + if (enumeratedProcess.Id != currentProcess.Id && + enumeratedProcess.MainModule.FileName == currentProcess.MainModule.FileName && + enumeratedProcess.MainWindowHandle != IntPtr.Zero) windowHandle = enumeratedProcess.MainWindowHandle; } + return windowHandle; } diff --git a/mRemoteV1/App/Runtime.cs b/mRemoteV1/App/Runtime.cs index 6aa27f0b..f404ae22 100644 --- a/mRemoteV1/App/Runtime.cs +++ b/mRemoteV1/App/Runtime.cs @@ -40,11 +40,16 @@ namespace mRemoteNG.App public static MessageCollector MessageCollector { get; } = new MessageCollector(); public static NotificationAreaIcon NotificationAreaIcon { get; set; } public static ExternalToolsService ExternalToolsService { get; } = new ExternalToolsService(); - public static SecureString EncryptionKey { get; set; } = new RootNodeInfo(RootNodeType.Connection).PasswordString.ConvertToSecureString(); + + public static SecureString EncryptionKey { get; set; } = + new RootNodeInfo(RootNodeType.Connection).PasswordString.ConvertToSecureString(); + public static CredentialService CredentialService { get; } = new CredentialServiceFactory().Build(); + public static ConnectionsService ConnectionsService { get; } = new ConnectionsService(PuttySessionsManager.Instance, CredentialService); #region Connections Loading/Saving + public static void LoadConnectionsAsync() { var t = new Thread(LoadConnectionsBGd); @@ -105,8 +110,14 @@ namespace mRemoteNG.App if (Settings.Default.UseSQLServer) { MessageCollector.AddExceptionMessage(Language.strLoadFromSqlFailed, ex); - var commandButtons = string.Join("|", Language.strCommandTryAgain, Language.strCommandOpenConnectionFile, string.Format(Language.strCommandExitProgram, Application.ProductName)); - CTaskDialog.ShowCommandBox(Application.ProductName, Language.strLoadFromSqlFailed, Language.strLoadFromSqlFailedContent, MiscTools.GetExceptionMessageRecursive(ex), "", "", commandButtons, false, ESysIcons.Error, ESysIcons.Error); + var commandButtons = string.Join("|", Language.strCommandTryAgain, + Language.strCommandOpenConnectionFile, + string.Format(Language.strCommandExitProgram, + Application.ProductName)); + CTaskDialog.ShowCommandBox(Application.ProductName, Language.strLoadFromSqlFailed, + Language.strLoadFromSqlFailedContent, + MiscTools.GetExceptionMessageRecursive(ex), "", "", + commandButtons, false, ESysIcons.Error, ESysIcons.Error); switch (CTaskDialog.CommandButtonResult) { case 0: @@ -121,9 +132,13 @@ namespace mRemoteNG.App return; } } + if (ex is FileNotFoundException && !withDialog) { - MessageCollector.AddExceptionMessage(string.Format(Language.strConnectionsFileCouldNotBeLoadedNew, connectionFileName), ex, MessageClass.InformationMsg); + MessageCollector.AddExceptionMessage( + string.Format(Language.strConnectionsFileCouldNotBeLoadedNew, + connectionFileName), ex, + MessageClass.InformationMsg); string[] commandButtons = { @@ -139,13 +154,13 @@ namespace mRemoteNG.App try { CTaskDialog.ShowTaskDialogBox( - GeneralAppInfo.ProductName, - Language.ConnectionFileNotFound, - "", "", "", "", "", - string.Join(" | ", commandButtons), - ETaskDialogButtons.None, - ESysIcons.Question, - ESysIcons.Question); + GeneralAppInfo.ProductName, + Language.ConnectionFileNotFound, + "", "", "", "", "", + string.Join(" | ", commandButtons), + ETaskDialogButtons.None, + ESysIcons.Question, + ESysIcons.Question); switch (CTaskDialog.CommandButtonResult) { @@ -166,17 +181,24 @@ namespace mRemoteNG.App Application.Exit(); answered = true; break; - } + } } catch (Exception exc) { - MessageCollector.AddExceptionMessage(string.Format(Language.strConnectionsFileCouldNotBeLoadedNew, connectionFileName), exc, MessageClass.InformationMsg); + MessageCollector.AddExceptionMessage( + string + .Format(Language.strConnectionsFileCouldNotBeLoadedNew, + connectionFileName), exc, + MessageClass.InformationMsg); } } + return; } - MessageCollector.AddExceptionStackTrace(string.Format(Language.strConnectionsFileCouldNotBeLoaded, connectionFileName), ex); + MessageCollector.AddExceptionStackTrace( + string.Format(Language.strConnectionsFileCouldNotBeLoaded, + connectionFileName), ex); if (connectionFileName != ConnectionsService.GetStartupConnectionFileName()) { LoadConnections(withDialog); @@ -184,12 +206,16 @@ namespace mRemoteNG.App else { MessageBox.Show(FrmMain.Default, - string.Format(Language.strErrorStartupConnectionFileLoad, Environment.NewLine, Application.ProductName, ConnectionsService.GetStartupConnectionFileName(), MiscTools.GetExceptionMessageRecursive(ex)), - @"Could not load startup file.", MessageBoxButtons.OK, MessageBoxIcon.Error); + string.Format(Language.strErrorStartupConnectionFileLoad, Environment.NewLine, + Application.ProductName, + ConnectionsService.GetStartupConnectionFileName(), + MiscTools.GetExceptionMessageRecursive(ex)), + @"Could not load startup file.", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/App/Shutdown.cs b/mRemoteV1/App/Shutdown.cs index 56977bba..817d451a 100644 --- a/mRemoteV1/App/Shutdown.cs +++ b/mRemoteV1/App/Shutdown.cs @@ -5,6 +5,7 @@ using System.Windows.Forms; using mRemoteNG.Config.Putty; using mRemoteNG.UI.Controls; using mRemoteNG.UI.Forms; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.App @@ -25,7 +26,10 @@ namespace mRemoteNG.App ProgramRoot.CloseSingletonInstanceMutex(); } - public static void Cleanup(Control quickConnectToolStrip, ExternalToolsToolStrip externalToolsToolStrip, MultiSshToolStrip multiSshToolStrip, FrmMain frmMain) + public static void Cleanup(Control quickConnectToolStrip, + ExternalToolsToolStrip externalToolsToolStrip, + MultiSshToolStrip multiSshToolStrip, + FrmMain frmMain) { try { @@ -58,9 +62,13 @@ namespace mRemoteNG.App Runtime.ConnectionsService.SaveConnections(); } - private static void SaveSettings(Control quickConnectToolStrip, ExternalToolsToolStrip externalToolsToolStrip, MultiSshToolStrip multiSshToolStrip, FrmMain frmMain) + private static void SaveSettings(Control quickConnectToolStrip, + ExternalToolsToolStrip externalToolsToolStrip, + MultiSshToolStrip multiSshToolStrip, + FrmMain frmMain) { - Config.Settings.SettingsSaver.SaveSettings(quickConnectToolStrip, externalToolsToolStrip, multiSshToolStrip, frmMain); + Config.Settings.SettingsSaver.SaveSettings(quickConnectToolStrip, externalToolsToolStrip, multiSshToolStrip, + frmMain); } private static void UnregisterBrowsers() diff --git a/mRemoteV1/App/Startup.cs b/mRemoteV1/App/Startup.cs index 77b62b94..531190bf 100644 --- a/mRemoteV1/App/Startup.cs +++ b/mRemoteV1/App/Startup.cs @@ -37,15 +37,16 @@ namespace mRemoteNG.App public void InitializeProgram(MessageCollector messageCollector) { - Debug.Print("---------------------------" + Environment.NewLine + "[START] - " + Convert.ToString(DateTime.Now, CultureInfo.InvariantCulture)); + Debug.Print("---------------------------" + Environment.NewLine + "[START] - " + + Convert.ToString(DateTime.Now, CultureInfo.InvariantCulture)); var startupLogger = new StartupDataLogger(messageCollector); startupLogger.LogStartupData(); CompatibilityChecker.CheckCompatibility(messageCollector); ParseCommandLineArgs(messageCollector); IeBrowserEmulation.Register(); _connectionIconLoader.GetConnectionIcons(); - DefaultConnectionInfo.Instance.LoadFrom(Settings.Default, a=>"ConDefault"+a); - DefaultConnectionInheritance.Instance.LoadFrom(Settings.Default, a=>"InhDefault"+a); + DefaultConnectionInfo.Instance.LoadFrom(Settings.Default, a => "ConDefault" + a); + DefaultConnectionInheritance.Instance.LoadFrom(Settings.Default, a => "InhDefault" + a); } private static void ParseCommandLineArgs(MessageCollector messageCollector) @@ -59,7 +60,8 @@ namespace mRemoteNG.App messageCollector.AddMessage(MessageClass.DebugMsg, "Determining if we need a database syncronizer"); if (!Settings.Default.UseSQLServer) return; messageCollector.AddMessage(MessageClass.DebugMsg, "Creating database syncronizer"); - Runtime.ConnectionsService.RemoteConnectionsSyncronizer = new RemoteConnectionsSyncronizer(new SqlConnectionsUpdateChecker()); + Runtime.ConnectionsService.RemoteConnectionsSyncronizer = + new RemoteConnectionsSyncronizer(new SqlConnectionsUpdateChecker()); Runtime.ConnectionsService.RemoteConnectionsSyncronizer.Enable(); } @@ -74,7 +76,12 @@ namespace mRemoteNG.App return; } - var nextUpdateCheck = Convert.ToDateTime(Settings.Default.CheckForUpdatesLastCheck.Add(TimeSpan.FromDays(Convert.ToDouble(Settings.Default.CheckForUpdatesFrequencyDays)))); + var nextUpdateCheck = + Convert.ToDateTime(Settings.Default.CheckForUpdatesLastCheck.Add( + TimeSpan + .FromDays(Convert.ToDouble(Settings + .Default + .CheckForUpdatesFrequencyDays)))); if (!Settings.Default.UpdatePending && DateTime.UtcNow < nextUpdateCheck) { return; @@ -100,6 +107,7 @@ namespace mRemoteNG.App { return; } + if (e.Error != null) { throw e.Error; diff --git a/mRemoteV1/App/SupportedCultures.cs b/mRemoteV1/App/SupportedCultures.cs index 37ebc34a..1ee52261 100644 --- a/mRemoteV1/App/SupportedCultures.cs +++ b/mRemoteV1/App/SupportedCultures.cs @@ -10,7 +10,7 @@ namespace mRemoteNG.App { [Serializable] public sealed class SupportedCultures : Dictionary - { + { private static SupportedCultures _Instance; private static SupportedCultures SingletonInstance @@ -19,7 +19,7 @@ namespace mRemoteNG.App } - private SupportedCultures() + private SupportedCultures() { foreach (var CultureName in Settings.Default.SupportedUICultures.Split(',')) { @@ -30,7 +30,8 @@ namespace mRemoteNG.App } catch (Exception ex) { - Debug.Print($"An exception occurred while adding the culture {CultureName} to the list of supported cultures. {ex.StackTrace}"); + Debug.Print( + $"An exception occurred while adding the culture {CultureName} to the list of supported cultures. {ex.StackTrace}"); } } } @@ -41,51 +42,52 @@ namespace mRemoteNG.App throw new NotImplementedException(); } - public static bool IsNameSupported(string CultureName) - { - return SingletonInstance.ContainsKey(CultureName); - } - - public static bool IsNativeNameSupported(string CultureNativeName) - { - return SingletonInstance.ContainsValue(CultureNativeName); - } - - public static string get_CultureName(string CultureNativeName) - { - var Names = new string[SingletonInstance.Count + 1]; - var NativeNames = new string[SingletonInstance.Count + 1]; + public static bool IsNameSupported(string CultureName) + { + return SingletonInstance.ContainsKey(CultureName); + } + + public static bool IsNativeNameSupported(string CultureNativeName) + { + return SingletonInstance.ContainsValue(CultureNativeName); + } + + public static string get_CultureName(string CultureNativeName) + { + var Names = new string[SingletonInstance.Count + 1]; + var NativeNames = new string[SingletonInstance.Count + 1]; SingletonInstance.Keys.CopyTo(Names, 0); SingletonInstance.Values.CopyTo(NativeNames, 0); - - for (var Index = 0; Index <= SingletonInstance.Count; Index++) - { - if (NativeNames[Index] == CultureNativeName) - { - return Names[Index]; - } - } - - throw (new KeyNotFoundException()); - } - - public static string get_CultureNativeName(string CultureName) - { - return SingletonInstance[CultureName]; - } - + + for (var Index = 0; Index <= SingletonInstance.Count; Index++) + { + if (NativeNames[Index] == CultureNativeName) + { + return Names[Index]; + } + } + + throw (new KeyNotFoundException()); + } + + public static string get_CultureNativeName(string CultureName) + { + return SingletonInstance[CultureName]; + } + public static List CultureNativeNames - { - get - { - var ValueList = new List(); - foreach (var Value in SingletonInstance.Values) - { - ValueList.Add(Value); - } - return ValueList; - } - } - } + { + get + { + var ValueList = new List(); + foreach (var Value in SingletonInstance.Values) + { + ValueList.Add(Value); + } + + return ValueList; + } + } + } } \ No newline at end of file diff --git a/mRemoteV1/App/Update/AppUpdater.cs b/mRemoteV1/App/Update/AppUpdater.cs index 2e728291..3532a596 100644 --- a/mRemoteV1/App/Update/AppUpdater.cs +++ b/mRemoteV1/App/Update/AppUpdater.cs @@ -10,8 +10,9 @@ using System.Security.Cryptography; #if !PORTABLE using mRemoteNG.Tools; -#else +#else using System.Windows.Forms; + #endif // ReSharper disable ArrangeAccessorOwnerBody @@ -66,7 +67,12 @@ namespace mRemoteNG.App.Update SetProxySettings(shouldWeUseProxy, proxyAddress, port, useAuthentication, username, password); } - public void SetProxySettings(bool useProxy, string address, int port, bool useAuthentication, string username, string password) + public void SetProxySettings(bool useProxy, + string address, + int port, + bool useAuthentication, + string username, + string password) { if (useProxy && !string.IsNullOrEmpty(address)) { @@ -107,7 +113,8 @@ namespace mRemoteNG.App.Update { if (CurrentUpdateInfo == null || !CurrentUpdateInfo.IsValid) { - throw new InvalidOperationException("CurrentUpdateInfo is not valid. GetUpdateInfoAsync() must be called before calling GetChangeLogAsync()."); + throw new InvalidOperationException( + "CurrentUpdateInfo is not valid. GetUpdateInfoAsync() must be called before calling GetChangeLogAsync()."); } if (IsGetChangeLogRunning) @@ -131,27 +138,29 @@ namespace mRemoteNG.App.Update if (CurrentUpdateInfo == null || !CurrentUpdateInfo.IsValid) { throw new InvalidOperationException( - "CurrentUpdateInfo is not valid. GetUpdateInfoAsync() must be called before calling DownloadUpdateAsync()."); + "CurrentUpdateInfo is not valid. GetUpdateInfoAsync() must be called before calling DownloadUpdateAsync()."); } #if !PORTABLE - CurrentUpdateInfo.UpdateFilePath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetRandomFileName(), "msi")); + CurrentUpdateInfo.UpdateFilePath = + Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetRandomFileName(), "msi")); #else - var sfd = new SaveFileDialog - { - InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), + var sfd = new SaveFileDialog + { + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), FileName = CurrentUpdateInfo.FileName, - RestoreDirectory = true - }; - if (sfd.ShowDialog() == DialogResult.OK) - { + RestoreDirectory = true + }; + if (sfd.ShowDialog() == DialogResult.OK) + { CurrentUpdateInfo.UpdateFilePath = sfd.FileName; } - else - { - return; - } + else + { + return; + } #endif - DownloadUpdateWebClient.DownloadFileAsync(CurrentUpdateInfo.DownloadAddress, CurrentUpdateInfo.UpdateFilePath); + DownloadUpdateWebClient.DownloadFileAsync(CurrentUpdateInfo.DownloadAddress, + CurrentUpdateInfo.UpdateFilePath); } #endregion @@ -191,7 +200,9 @@ namespace mRemoteNG.App.Update } private static DownloadStringCompletedEventArgs NewDownloadStringCompletedEventArgs(string result, - Exception exception, bool cancelled, object userToken) + Exception exception, + bool cancelled, + object userToken) { var type = typeof(DownloadStringCompletedEventArgs); const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; @@ -201,7 +212,7 @@ namespace mRemoteNG.App.Update if (constructor == null) return null; - return (DownloadStringCompletedEventArgs) constructor.Invoke(arguments); + return (DownloadStringCompletedEventArgs)constructor.Invoke(arguments); } private DownloadStringCompletedEventArgs DownloadString(Uri address) @@ -326,11 +337,13 @@ namespace mRemoteNG.App.Update { add { - GetUpdateInfoCompletedEventEvent = (AsyncCompletedEventHandler)Delegate.Combine(GetUpdateInfoCompletedEventEvent, value); + GetUpdateInfoCompletedEventEvent = + (AsyncCompletedEventHandler)Delegate.Combine(GetUpdateInfoCompletedEventEvent, value); } remove { - GetUpdateInfoCompletedEventEvent = (AsyncCompletedEventHandler)Delegate.Remove(GetUpdateInfoCompletedEventEvent, value); + GetUpdateInfoCompletedEventEvent = + (AsyncCompletedEventHandler)Delegate.Remove(GetUpdateInfoCompletedEventEvent, value); } } @@ -340,11 +353,13 @@ namespace mRemoteNG.App.Update { add { - GetChangeLogCompletedEventEvent = (AsyncCompletedEventHandler)Delegate.Combine(GetChangeLogCompletedEventEvent, value); + GetChangeLogCompletedEventEvent = + (AsyncCompletedEventHandler)Delegate.Combine(GetChangeLogCompletedEventEvent, value); } remove { - GetChangeLogCompletedEventEvent = (AsyncCompletedEventHandler)Delegate.Remove(GetChangeLogCompletedEventEvent, value); + GetChangeLogCompletedEventEvent = + (AsyncCompletedEventHandler)Delegate.Remove(GetChangeLogCompletedEventEvent, value); } } @@ -354,11 +369,15 @@ namespace mRemoteNG.App.Update { add { - DownloadUpdateProgressChangedEventEvent = (DownloadProgressChangedEventHandler)Delegate.Combine(DownloadUpdateProgressChangedEventEvent, value); + DownloadUpdateProgressChangedEventEvent = + (DownloadProgressChangedEventHandler)Delegate.Combine(DownloadUpdateProgressChangedEventEvent, + value); } remove { - DownloadUpdateProgressChangedEventEvent = (DownloadProgressChangedEventHandler)Delegate.Remove(DownloadUpdateProgressChangedEventEvent, value); + DownloadUpdateProgressChangedEventEvent = + (DownloadProgressChangedEventHandler)Delegate.Remove(DownloadUpdateProgressChangedEventEvent, + value); } } @@ -368,11 +387,13 @@ namespace mRemoteNG.App.Update { add { - DownloadUpdateCompletedEventEvent = (AsyncCompletedEventHandler)Delegate.Combine(DownloadUpdateCompletedEventEvent, value); + DownloadUpdateCompletedEventEvent = + (AsyncCompletedEventHandler)Delegate.Combine(DownloadUpdateCompletedEventEvent, value); } remove { - DownloadUpdateCompletedEventEvent = (AsyncCompletedEventHandler)Delegate.Remove(DownloadUpdateCompletedEventEvent, value); + DownloadUpdateCompletedEventEvent = + (AsyncCompletedEventHandler)Delegate.Remove(DownloadUpdateCompletedEventEvent, value); } } diff --git a/mRemoteV1/App/Update/UpdateFile.cs b/mRemoteV1/App/Update/UpdateFile.cs index b5ea64e6..fae08418 100644 --- a/mRemoteV1/App/Update/UpdateFile.cs +++ b/mRemoteV1/App/Update/UpdateFile.cs @@ -7,12 +7,16 @@ namespace mRemoteNG.App.Update public class UpdateFile { #region Public Properties + // ReSharper disable MemberCanBePrivate.Local // ReSharper disable once MemberCanBePrivate.Global - public Dictionary Items { get; } = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + public Dictionary Items { get; } = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + #endregion #region Public Methods + public UpdateFile(string content) { FromString(content); @@ -24,8 +28,8 @@ namespace mRemoteNG.App.Update { if (string.IsNullOrEmpty(content)) return; - char[] keyValueSeparators = { ':', '=' }; - char[] commentCharacters = { '#', ';', '\'' }; + char[] keyValueSeparators = {':', '='}; + char[] commentCharacters = {'#', ';', '\''}; // no separators means no valid update data... if (content.Trim().IndexOfAny(keyValueSeparators) == -1) return; @@ -47,7 +51,7 @@ namespace mRemoteNG.App.Update continue; // make sure we have valid data in both parts before adding to the collection. If either part is empty, then it's not valid data. - if(string.IsNullOrEmpty(parts[0].Trim()) || string.IsNullOrEmpty(parts[1].Trim())) + if (string.IsNullOrEmpty(parts[0].Trim()) || string.IsNullOrEmpty(parts[1].Trim())) continue; Items.Add(parts[0].Trim(), parts[1].Trim()); @@ -83,13 +87,14 @@ namespace mRemoteNG.App.Update { var value = GetString("dURL"); var sv = value.Split('/'); - return sv[sv.Length-1]; + return sv[sv.Length - 1]; } public string GetChecksum(string key = "Checksum") { return GetString(key).Replace(" ", "").ToUpperInvariant(); } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/App/Update/UpdateInfo.cs b/mRemoteV1/App/Update/UpdateInfo.cs index 9255ef16..0d2ad4c6 100644 --- a/mRemoteV1/App/Update/UpdateInfo.cs +++ b/mRemoteV1/App/Update/UpdateInfo.cs @@ -1,4 +1,5 @@ using System; + // ReSharper disable UnusedAutoPropertyAccessor.Local namespace mRemoteNG.App.Update @@ -43,6 +44,7 @@ namespace mRemoteNG.App.Update newInfo.Checksum = updateFile.GetChecksum(); newInfo.IsValid = newInfo.CheckIfValid(); } + return newInfo; } @@ -50,11 +52,11 @@ namespace mRemoteNG.App.Update { if (string.IsNullOrEmpty(Version.ToString())) return false; - if(string.IsNullOrEmpty(DownloadAddress.AbsoluteUri)) + if (string.IsNullOrEmpty(DownloadAddress.AbsoluteUri)) return false; if (string.IsNullOrEmpty(ChangeLogAddress.AbsoluteUri)) return false; -#if false +#if false if (string.IsNullOrEmpty(ImageAddress.AbsoluteUri)) return false; if (string.IsNullOrEmpty(ImageLinkAddress.AbsoluteUri)) diff --git a/mRemoteV1/App/Windows.cs b/mRemoteV1/App/Windows.cs index 6304b75b..d4ec8c9a 100644 --- a/mRemoteV1/App/Windows.cs +++ b/mRemoteV1/App/Windows.cs @@ -31,7 +31,6 @@ namespace mRemoteNG.App internal static SSHTransferWindow SshtransferForm { get; private set; } = new SSHTransferWindow(); - public static void Show(WindowType windowType) { try @@ -55,6 +54,7 @@ namespace mRemoteNG.App { optionsForm.ShowDialog(dockPanel); } + break; case WindowType.SSHTransfer: if (SshtransferForm == null || SshtransferForm.IsDisposed) @@ -90,7 +90,8 @@ namespace mRemoteNG.App _ultravncscForm.Show(dockPanel); break; case WindowType.ComponentsCheck: - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Showing ComponentsCheck window", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Showing ComponentsCheck window", true); if (_componentscheckForm == null || _componentscheckForm.IsDisposed) _componentscheckForm = new ComponentsCheckWindow(); _componentscheckForm.Show(dockPanel); diff --git a/mRemoteV1/Config/ConfirmCloseEnum.cs b/mRemoteV1/Config/ConfirmCloseEnum.cs index b990822a..ff4e615e 100644 --- a/mRemoteV1/Config/ConfirmCloseEnum.cs +++ b/mRemoteV1/Config/ConfirmCloseEnum.cs @@ -1,11 +1,11 @@ namespace mRemoteNG.Config { - public enum ConfirmCloseEnum - { - Unspecified = 0, - Never = 1, - Exit = 2, - Multiple = 3, - All = 4 - } + public enum ConfirmCloseEnum + { + Unspecified = 0, + Never = 1, + Exit = 2, + Multiple = 3, + All = 4 + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Connections/ConnectionsSavedEventArgs.cs b/mRemoteV1/Config/Connections/ConnectionsSavedEventArgs.cs index 279adeec..a0067946 100644 --- a/mRemoteV1/Config/Connections/ConnectionsSavedEventArgs.cs +++ b/mRemoteV1/Config/Connections/ConnectionsSavedEventArgs.cs @@ -10,7 +10,10 @@ namespace mRemoteNG.Config.Connections public bool UsingDatabase { get; } public string ConnectionFileName { get; } - public ConnectionsSavedEventArgs(IConnectionTreeModel modelThatWasSaved, bool previouslyUsingDatabase, bool usingDatabase, string connectionFileName) + public ConnectionsSavedEventArgs(IConnectionTreeModel modelThatWasSaved, + bool previouslyUsingDatabase, + bool usingDatabase, + string connectionFileName) { if (modelThatWasSaved == null) throw new ArgumentNullException(nameof(modelThatWasSaved)); diff --git a/mRemoteV1/Config/Connections/Multiuser/ConnectionsUpdateAvailableEventArgs.cs b/mRemoteV1/Config/Connections/Multiuser/ConnectionsUpdateAvailableEventArgs.cs index 4440d03c..589bd4db 100644 --- a/mRemoteV1/Config/Connections/Multiuser/ConnectionsUpdateAvailableEventArgs.cs +++ b/mRemoteV1/Config/Connections/Multiuser/ConnectionsUpdateAvailableEventArgs.cs @@ -3,7 +3,8 @@ using mRemoteNG.Config.DatabaseConnectors; namespace mRemoteNG.Config.Connections.Multiuser { - public delegate void ConnectionsUpdateAvailableEventHandler(object sender, ConnectionsUpdateAvailableEventArgs args); + public delegate void + ConnectionsUpdateAvailableEventHandler(object sender, ConnectionsUpdateAvailableEventArgs args); public class ConnectionsUpdateAvailableEventArgs : EventArgs { diff --git a/mRemoteV1/Config/Connections/Multiuser/RemoteConnectionsSyncronizer.cs b/mRemoteV1/Config/Connections/Multiuser/RemoteConnectionsSyncronizer.cs index b336ad2d..c2545f98 100644 --- a/mRemoteV1/Config/Connections/Multiuser/RemoteConnectionsSyncronizer.cs +++ b/mRemoteV1/Config/Connections/Multiuser/RemoteConnectionsSyncronizer.cs @@ -27,7 +27,8 @@ namespace mRemoteNG.Config.Connections.Multiuser { _updateChecker.UpdateCheckStarted += OnUpdateCheckStarted; _updateChecker.UpdateCheckFinished += OnUpdateCheckFinished; - _updateChecker.ConnectionsUpdateAvailable += (sender, args) => ConnectionsUpdateAvailable?.Invoke(sender, args); + _updateChecker.ConnectionsUpdateAvailable += + (sender, args) => ConnectionsUpdateAvailable?.Invoke(sender, args); _updateTimer.Elapsed += (sender, args) => _updateChecker.IsUpdateAvailableAsync(); ConnectionsUpdateAvailable += Load; } @@ -81,6 +82,7 @@ namespace mRemoteNG.Config.Connections.Multiuser Dispose(true); GC.SuppressFinalize(this); } + private void Dispose(bool itIsSafeToAlsoFreeManagedObjects) { if (!itIsSafeToAlsoFreeManagedObjects) return; diff --git a/mRemoteV1/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs b/mRemoteV1/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs index af3ab56f..66d8978e 100644 --- a/mRemoteV1/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs +++ b/mRemoteV1/Config/Connections/Multiuser/SqlConnectionsUpdateChecker.cs @@ -48,9 +48,11 @@ namespace mRemoteNG.Config.Connections { _sqlConnector.Connect(); } - catch(Exception e) + catch (Exception e) { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "Unable to connect to Sql DB to check for updates." + Environment.NewLine + e.Message, true); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "Unable to connect to Sql DB to check for updates." + + Environment.NewLine + e.Message, true); } } @@ -63,7 +65,9 @@ namespace mRemoteNG.Config.Connections private bool CheckIfIAmTheLastOneUpdated(DateTime lastUpdateInDb) { - DateTime lastSqlUpdateWithoutMilliseconds = new DateTime(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), LastUpdateTime.Kind); + DateTime lastSqlUpdateWithoutMilliseconds = + new DateTime(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), + LastUpdateTime.Kind); return lastUpdateInDb == lastSqlUpdateWithoutMilliseconds; } @@ -80,20 +84,25 @@ namespace mRemoteNG.Config.Connections } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "Error executing Sql query to get updates from the DB." + Environment.NewLine + ex.Message, true); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "Error executing Sql query to get updates from the DB." + + Environment.NewLine + ex.Message, true); } + _lastDatabaseUpdateTime = lastUpdateInDb; return lastUpdateInDb; } public event EventHandler UpdateCheckStarted; + private void RaiseUpdateCheckStartedEvent() { UpdateCheckStarted?.Invoke(this, EventArgs.Empty); } public event UpdateCheckFinishedEventHandler UpdateCheckFinished; + private void RaiseUpdateCheckFinishedEvent(bool updateAvailable) { var args = new ConnectionsUpdateCheckFinishedEventArgs {UpdateAvailable = updateAvailable}; @@ -101,6 +110,7 @@ namespace mRemoteNG.Config.Connections } public event ConnectionsUpdateAvailableEventHandler ConnectionsUpdateAvailable; + private void RaiseConnectionsUpdateAvailableEvent() { Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, "Remote connection update is available"); diff --git a/mRemoteV1/Config/Connections/SaveConnectionsOnEdit.cs b/mRemoteV1/Config/Connections/SaveConnectionsOnEdit.cs index 58a1a9a0..229759ee 100644 --- a/mRemoteV1/Config/Connections/SaveConnectionsOnEdit.cs +++ b/mRemoteV1/Config/Connections/SaveConnectionsOnEdit.cs @@ -23,12 +23,15 @@ namespace mRemoteNG.Config.Connections _connectionsService = null; } - private void ConnectionTreeModelOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) + private void ConnectionTreeModelOnPropertyChanged(object sender, + PropertyChangedEventArgs propertyChangedEventArgs) { SaveConnectionOnEdit(propertyChangedEventArgs.PropertyName); } - private void ConnectionTreeModelOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) + private void ConnectionTreeModelOnCollectionChanged(object sender, + NotifyCollectionChangedEventArgs + notifyCollectionChangedEventArgs) { SaveConnectionOnEdit(); } diff --git a/mRemoteV1/Config/Connections/SaveFormat.cs b/mRemoteV1/Config/Connections/SaveFormat.cs index 0ca1d9b0..fa577f41 100644 --- a/mRemoteV1/Config/Connections/SaveFormat.cs +++ b/mRemoteV1/Config/Connections/SaveFormat.cs @@ -7,4 +7,4 @@ mRCSV, SQL } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Connections/SqlConnectionsLoader.cs b/mRemoteV1/Config/Connections/SqlConnectionsLoader.cs index f24442d9..56e36a75 100644 --- a/mRemoteV1/Config/Connections/SqlConnectionsLoader.cs +++ b/mRemoteV1/Config/Connections/SqlConnectionsLoader.cs @@ -19,17 +19,20 @@ namespace mRemoteNG.Config.Connections { public class SqlConnectionsLoader : IConnectionsLoader { - private readonly IDeserializer> _localConnectionPropertiesDeserializer; + private readonly IDeserializer> + _localConnectionPropertiesDeserializer; + private readonly IDataProvider _dataProvider; public Func> AuthenticationRequestor { get; set; } = () => MiscTools.PasswordDialog("", false); public SqlConnectionsLoader( - IDeserializer> localConnectionPropertiesDeserializer, + IDeserializer> localConnectionPropertiesDeserializer, IDataProvider dataProvider) { - _localConnectionPropertiesDeserializer = localConnectionPropertiesDeserializer.ThrowIfNull(nameof(localConnectionPropertiesDeserializer)); + _localConnectionPropertiesDeserializer = + localConnectionPropertiesDeserializer.ThrowIfNull(nameof(localConnectionPropertiesDeserializer)); _dataProvider = dataProvider.ThrowIfNull(nameof(dataProvider)); } @@ -60,7 +63,9 @@ namespace mRemoteNG.Config.Connections 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()); + var authenticated = + authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword + .ConvertToSecureString()); if (authenticated) return authenticator.LastAuthenticatedPassword; @@ -74,10 +79,10 @@ namespace mRemoteNG.Config.Connections rootNode .GetRecursiveChildList() - .Join(localConnectionProperties, - con => con.ConstantID, - locals => locals.ConnectionId, - (con, locals) => new {Connection = con, LocalProperties = locals}) + .Join(localConnectionProperties, + con => con.ConstantID, + locals => locals.ConnectionId, + (con, locals) => new {Connection = con, LocalProperties = locals}) .ForEach(x => { x.Connection.PleaseConnect = x.LocalProperties.Connected; diff --git a/mRemoteV1/Config/Connections/SqlConnectionsSaver.cs b/mRemoteV1/Config/Connections/SqlConnectionsSaver.cs index 74186b37..ca05a2a1 100644 --- a/mRemoteV1/Config/Connections/SqlConnectionsSaver.cs +++ b/mRemoteV1/Config/Connections/SqlConnectionsSaver.cs @@ -29,10 +29,10 @@ namespace mRemoteNG.Config.Connections private readonly ISerializer, string> _localPropertiesSerializer; private readonly IDataProvider _dataProvider; - public SqlConnectionsSaver( - SaveFilter saveFilter, - ISerializer, string> localPropertieSerializer, - IDataProvider localPropertiesDataProvider) + public SqlConnectionsSaver(SaveFilter saveFilter, + ISerializer, string> + localPropertieSerializer, + IDataProvider localPropertiesDataProvider) { if (saveFilter == null) throw new ArgumentNullException(nameof(saveFilter)); @@ -49,14 +49,15 @@ namespace mRemoteNG.Config.Connections if (PropertyIsLocalOnly(propertyNameTrigger)) { - Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, - $"Property {propertyNameTrigger} is local only. Not saving to database."); + Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, + $"Property {propertyNameTrigger} is local only. Not saving to database."); return; } if (SqlUserIsReadOnly()) { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Trying to save connection tree but the SQL read only checkbox is checked, aborting!"); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Trying to save connection tree but the SQL read only checkbox is checked, aborting!"); return; } @@ -69,7 +70,8 @@ namespace mRemoteNG.Config.Connections if (!databaseVersionVerifier.VerifyDatabaseVersion(metaData.ConfVersion)) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strErrorConnectionListSaveFailed); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strErrorConnectionListSaveFailed); return; } @@ -137,22 +139,25 @@ namespace mRemoteNG.Config.Connections { sqlQuery = new SqlCommand( - "INSERT INTO tblRoot (Name, Export, Protected, ConfVersion) VALUES(\'" + - MiscTools.PrepareValueForDB(rootTreeNode.Name) + "\', 0, \'" + strProtected + "\'," + - ConnectionsFileInfo.ConnectionFileVersion.ToString(CultureInfo.InvariantCulture) + ")", - sqlDatabaseConnector.SqlConnection); + "INSERT INTO tblRoot (Name, Export, Protected, ConfVersion) VALUES(\'" + + MiscTools.PrepareValueForDB(rootTreeNode.Name) + "\', 0, \'" + strProtected + "\'," + + ConnectionsFileInfo.ConnectionFileVersion.ToString(CultureInfo.InvariantCulture) + + ")", + sqlDatabaseConnector.SqlConnection); sqlQuery.ExecuteNonQuery(); } else { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"UpdateRootNodeTable: rootTreeNode was null. Could not insert!"); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + $"UpdateRootNodeTable: rootTreeNode was null. Could not insert!"); } } private void UpdateConnectionsTable(RootNodeInfo rootTreeNode, SqlDatabaseConnector sqlDatabaseConnector) { var cryptoProvider = new LegacyRijndaelCryptographyProvider(); - var serializer = new DataTableSerializer(_saveFilter, cryptoProvider, rootTreeNode.PasswordString.ConvertToSecureString()); + var serializer = new DataTableSerializer(_saveFilter, cryptoProvider, + rootTreeNode.PasswordString.ConvertToSecureString()); var dataTable = serializer.Serialize(rootTreeNode); var dataProvider = new SqlDataProvider(sqlDatabaseConnector); @@ -165,14 +170,16 @@ namespace mRemoteNG.Config.Connections { var sqlQuery = new SqlCommand("DELETE FROM tblUpdate", sqlDatabaseConnector.SqlConnection); sqlQuery.ExecuteNonQuery(); - sqlQuery = new SqlCommand("INSERT INTO tblUpdate (LastUpdate) VALUES(\'" + MiscTools.DBDate(DateTime.Now) + "\')", sqlDatabaseConnector.SqlConnection); + sqlQuery = new SqlCommand( + "INSERT INTO tblUpdate (LastUpdate) VALUES(\'" + MiscTools.DBDate(DateTime.Now) + + "\')", + sqlDatabaseConnector.SqlConnection); sqlQuery.ExecuteNonQuery(); } private bool SqlUserIsReadOnly() { return mRemoteNG.Settings.Default.SQLReadOnly; - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Connections/XmlConnectionsLoader.cs b/mRemoteV1/Config/Connections/XmlConnectionsLoader.cs index 2b064737..5eeedc00 100644 --- a/mRemoteV1/Config/Connections/XmlConnectionsLoader.cs +++ b/mRemoteV1/Config/Connections/XmlConnectionsLoader.cs @@ -59,4 +59,4 @@ namespace mRemoteNG.Config.Connections return password; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Connections/XmlConnectionsSaver.cs b/mRemoteV1/Config/Connections/XmlConnectionsSaver.cs index 7548f5ce..47aa229d 100644 --- a/mRemoteV1/Config/Connections/XmlConnectionsSaver.cs +++ b/mRemoteV1/Config/Connections/XmlConnectionsSaver.cs @@ -33,13 +33,17 @@ namespace mRemoteNG.Config.Connections { var cryptographyProvider = new CryptoProviderFactoryFromSettings().Build(); var connectionNodeSerializer = new XmlConnectionNodeSerializer27( - cryptographyProvider, - connectionTreeModel.RootNodes.OfType().First().PasswordString.ConvertToSecureString(), - _saveFilter); - var xmlConnectionsSerializer = new XmlConnectionsSerializer(cryptographyProvider, connectionNodeSerializer) - { - UseFullEncryption = mRemoteNG.Settings.Default.EncryptCompleteConnectionsFile - }; + cryptographyProvider, + connectionTreeModel + .RootNodes.OfType() + .First().PasswordString + .ConvertToSecureString(), + _saveFilter); + var xmlConnectionsSerializer = + new XmlConnectionsSerializer(cryptographyProvider, connectionNodeSerializer) + { + UseFullEncryption = mRemoteNG.Settings.Default.EncryptCompleteConnectionsFile + }; var xml = xmlConnectionsSerializer.Serialize(connectionTreeModel); var fileDataProvider = new FileDataProviderWithRollingBackup(_connectionFileName); @@ -51,4 +55,4 @@ namespace mRemoteNG.Config.Connections } } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/CredentialRecordLoader.cs b/mRemoteV1/Config/CredentialRecordLoader.cs index 8fe6d83e..f74525bd 100644 --- a/mRemoteV1/Config/CredentialRecordLoader.cs +++ b/mRemoteV1/Config/CredentialRecordLoader.cs @@ -13,7 +13,8 @@ namespace mRemoteNG.Config private readonly IDataProvider _dataProvider; private readonly ISecureDeserializer> _deserializer; - public CredentialRecordLoader(IDataProvider dataProvider, ISecureDeserializer> deserializer) + public CredentialRecordLoader(IDataProvider dataProvider, + ISecureDeserializer> deserializer) { if (dataProvider == null) throw new ArgumentNullException(nameof(dataProvider)); diff --git a/mRemoteV1/Config/CredentialRecordSaver.cs b/mRemoteV1/Config/CredentialRecordSaver.cs index 9a9b52d7..5f7d70ae 100644 --- a/mRemoteV1/Config/CredentialRecordSaver.cs +++ b/mRemoteV1/Config/CredentialRecordSaver.cs @@ -13,7 +13,8 @@ namespace mRemoteNG.Config private readonly IDataProvider _dataProvider; private readonly ISecureSerializer, string> _serializer; - public CredentialRecordSaver(IDataProvider dataProvider, ISecureSerializer, string> serializer) + public CredentialRecordSaver(IDataProvider dataProvider, + ISecureSerializer, string> serializer) { if (dataProvider == null) throw new ArgumentNullException(nameof(dataProvider)); diff --git a/mRemoteV1/Config/DataProviders/FileBackupCreator.cs b/mRemoteV1/Config/DataProviders/FileBackupCreator.cs index 25b09b98..453eaeaf 100644 --- a/mRemoteV1/Config/DataProviders/FileBackupCreator.cs +++ b/mRemoteV1/Config/DataProviders/FileBackupCreator.cs @@ -14,12 +14,14 @@ namespace mRemoteNG.Config.DataProviders if (WeDontNeedToBackup(fileName)) return; - var backupFileName = string.Format(mRemoteNG.Settings.Default.BackupFileNameFormat, fileName, DateTime.Now); + var backupFileName = + string.Format(mRemoteNG.Settings.Default.BackupFileNameFormat, fileName, DateTime.Now); File.Copy(fileName, backupFileName); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage(Language.strConnectionsFileBackupFailed, ex, MessageClass.WarningMsg); + Runtime.MessageCollector.AddExceptionMessage(Language.strConnectionsFileBackupFailed, ex, + MessageClass.WarningMsg); throw; } } diff --git a/mRemoteV1/Config/DataProviders/FileBackupPruner.cs b/mRemoteV1/Config/DataProviders/FileBackupPruner.cs index 5572a345..a85ce1f9 100644 --- a/mRemoteV1/Config/DataProviders/FileBackupPruner.cs +++ b/mRemoteV1/Config/DataProviders/FileBackupPruner.cs @@ -20,8 +20,8 @@ namespace mRemoteNG.Config.DataProviders return; var filesToDelete = files - .OrderByDescending(s => s) - .Skip(maxBackupsToKeep); + .OrderByDescending(s => s) + .Skip(maxBackupsToKeep); foreach (var file in filesToDelete) { diff --git a/mRemoteV1/Config/DataProviders/FileDataProvider.cs b/mRemoteV1/Config/DataProviders/FileDataProvider.cs index 9a36c7f8..7cc85276 100644 --- a/mRemoteV1/Config/DataProviders/FileDataProvider.cs +++ b/mRemoteV1/Config/DataProviders/FileDataProvider.cs @@ -19,14 +19,14 @@ namespace mRemoteNG.Config.DataProviders var fileContents = ""; try { - if (!File.Exists(FilePath)) - { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, $"Could not load file. File does not exist '{FilePath}'"); - return ""; - } - fileContents = File.ReadAllText(FilePath); } + catch (FileNotFoundException ex) + { + Runtime.MessageCollector.AddExceptionStackTrace( + $"Could not load file. File does not exist '{FilePath}'", + ex); + } catch (Exception ex) { Runtime.MessageCollector.AddExceptionStackTrace($"Failed to load file {FilePath}", ex); diff --git a/mRemoteV1/Config/DataProviders/IDataProvider.cs b/mRemoteV1/Config/DataProviders/IDataProvider.cs index 1f665f17..b6e52988 100644 --- a/mRemoteV1/Config/DataProviders/IDataProvider.cs +++ b/mRemoteV1/Config/DataProviders/IDataProvider.cs @@ -1,5 +1,4 @@ - -namespace mRemoteNG.Config.DataProviders +namespace mRemoteNG.Config.DataProviders { public interface IDataProvider { diff --git a/mRemoteV1/Config/DataProviders/SqlDataProvider.cs b/mRemoteV1/Config/DataProviders/SqlDataProvider.cs index cb70977c..4b8cbe69 100644 --- a/mRemoteV1/Config/DataProviders/SqlDataProvider.cs +++ b/mRemoteV1/Config/DataProviders/SqlDataProvider.cs @@ -34,7 +34,8 @@ namespace mRemoteNG.Config.DataProviders { if (SqlUserIsReadOnly()) { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Trying to save connections but the SQL read only checkbox is checked, aborting!"); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Trying to save connections but the SQL read only checkbox is checked, aborting!"); return; } @@ -62,7 +63,6 @@ namespace mRemoteNG.Config.DataProviders private bool SqlUserIsReadOnly() { return mRemoteNG.Settings.Default.SQLReadOnly; - } } } \ No newline at end of file diff --git a/mRemoteV1/Config/DatabaseConnectors/ConnectionTestResult.cs b/mRemoteV1/Config/DatabaseConnectors/ConnectionTestResult.cs index 0426a2cd..23bcbbb5 100644 --- a/mRemoteV1/Config/DatabaseConnectors/ConnectionTestResult.cs +++ b/mRemoteV1/Config/DatabaseConnectors/ConnectionTestResult.cs @@ -8,4 +8,4 @@ CredentialsRejected, UnknownError } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/DatabaseConnectors/DatabaseConnectorFactory.cs b/mRemoteV1/Config/DatabaseConnectors/DatabaseConnectorFactory.cs index f8e8a149..39d7bcf4 100644 --- a/mRemoteV1/Config/DatabaseConnectors/DatabaseConnectorFactory.cs +++ b/mRemoteV1/Config/DatabaseConnectors/DatabaseConnectorFactory.cs @@ -15,4 +15,4 @@ namespace mRemoteNG.Config.DatabaseConnectors return new SqlDatabaseConnector(sqlHost, sqlCatalog, sqlUsername, sqlPassword); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnectionTester.cs b/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnectionTester.cs index 69c43375..2100920a 100644 --- a/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnectionTester.cs +++ b/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnectionTester.cs @@ -9,7 +9,10 @@ namespace mRemoteNG.Config.DatabaseConnectors /// public class SqlDatabaseConnectionTester { - public async Task TestConnectivity(string server, string database, string username, string password) + public async Task TestConnectivity(string server, + string database, + string username, + string password) { using (var sqlConnector = new SqlDatabaseConnector(server, database, username, password)) { @@ -35,4 +38,4 @@ namespace mRemoteNG.Config.DatabaseConnectors } } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnector.cs b/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnector.cs index 6aaeb413..e55bfb0a 100644 --- a/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnector.cs +++ b/mRemoteV1/Config/DatabaseConnectors/SqlDatabaseConnector.cs @@ -8,7 +8,7 @@ namespace mRemoteNG.Config.DatabaseConnectors { public class SqlDatabaseConnector : IDatabaseConnector { - public SqlConnection SqlConnection { get; private set; } = default(SqlConnection); + public SqlConnection SqlConnection { get; private set; } = default(SqlConnection); private string _sqlConnectionString = ""; private readonly string _sqlHost; private readonly string _sqlCatalog; @@ -45,7 +45,8 @@ namespace mRemoteNG.Config.DatabaseConnectors private void BuildSqlConnectionStringWithCustomCredentials() { - _sqlConnectionString = $"Data Source={_sqlHost};Initial Catalog={_sqlCatalog};User Id={_sqlUsername};Password={_sqlPassword}"; + _sqlConnectionString = + $"Data Source={_sqlHost};Initial Catalog={_sqlCatalog};User Id={_sqlUsername};Password={_sqlPassword}"; } private void BuildSqlConnectionStringWithDefaultCredentials() @@ -77,6 +78,7 @@ namespace mRemoteNG.Config.DatabaseConnectors { Dispose(true); } + private void Dispose(bool itIsSafeToFreeManagedObjects) { if (!itIsSafeToFreeManagedObjects) return; diff --git a/mRemoteV1/Config/Import/ActiveDirectoryImporter.cs b/mRemoteV1/Config/Import/ActiveDirectoryImporter.cs index 9c59b385..32b1e9d9 100644 --- a/mRemoteV1/Config/Import/ActiveDirectoryImporter.cs +++ b/mRemoteV1/Config/Import/ActiveDirectoryImporter.cs @@ -7,29 +7,29 @@ using mRemoteNG.Tools; namespace mRemoteNG.Config.Import { - public class ActiveDirectoryImporter : IConnectionImporter - { + public class ActiveDirectoryImporter : IConnectionImporter + { public void Import(string ldapPath, ContainerInfo destinationContainer) { Import(ldapPath, destinationContainer, false); } - public static void Import(string ldapPath, ContainerInfo destinationContainer, bool importSubOu) - { - try - { - ldapPath.ThrowIfNullOrEmpty(nameof(ldapPath)); - var deserializer = new ActiveDirectoryDeserializer(ldapPath, importSubOu); - var connectionTreeModel = deserializer.Deserialize(); + public static void Import(string ldapPath, ContainerInfo destinationContainer, bool importSubOu) + { + try + { + ldapPath.ThrowIfNullOrEmpty(nameof(ldapPath)); + var deserializer = new ActiveDirectoryDeserializer(ldapPath, importSubOu); + var connectionTreeModel = deserializer.Deserialize(); var importedRootNode = connectionTreeModel.RootNodes.First(); if (importedRootNode == null) return; var childrenToAdd = importedRootNode.Children.ToArray(); destinationContainer.AddChildRange(childrenToAdd); } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("Config.Import.ActiveDirectory.Import() failed.", ex); - } - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("Config.Import.ActiveDirectory.Import() failed.", ex); + } + } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Import/MRemoteNGCsvImporter.cs b/mRemoteV1/Config/Import/MRemoteNGCsvImporter.cs index 3fe15c2f..810d0f84 100644 --- a/mRemoteV1/Config/Import/MRemoteNGCsvImporter.cs +++ b/mRemoteV1/Config/Import/MRemoteNGCsvImporter.cs @@ -20,7 +20,8 @@ namespace mRemoteNG.Config.Import } if (!File.Exists(filePath)) - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"Unable to import file. File does not exist. Path: {filePath}"); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + $"Unable to import file. File does not exist. Path: {filePath}"); var dataProvider = new FileDataProvider(filePath); var xmlString = dataProvider.Load(); @@ -34,7 +35,7 @@ namespace mRemoteNG.Config.Import }; credentialImportForm.ShowDialog(); - var rootImportContainer = new ContainerInfo { Name = Path.GetFileNameWithoutExtension(filePath) }; + var rootImportContainer = new ContainerInfo {Name = Path.GetFileNameWithoutExtension(filePath)}; rootImportContainer.AddChildRange(serializationResult.ConnectionRecords); destinationContainer.AddChild(rootImportContainer); } diff --git a/mRemoteV1/Config/Import/MRemoteNGXmlImporter.cs b/mRemoteV1/Config/Import/MRemoteNGXmlImporter.cs index 19a62964..5a014e06 100644 --- a/mRemoteV1/Config/Import/MRemoteNGXmlImporter.cs +++ b/mRemoteV1/Config/Import/MRemoteNGXmlImporter.cs @@ -10,28 +10,29 @@ using mRemoteNG.Messages; namespace mRemoteNG.Config.Import { - // ReSharper disable once InconsistentNaming - public class MRemoteNGXmlImporter : IConnectionImporter - { - public void Import(string fileName, ContainerInfo destinationContainer) - { - if (fileName == null) - { + // ReSharper disable once InconsistentNaming + public class MRemoteNGXmlImporter : IConnectionImporter + { + public void Import(string fileName, ContainerInfo destinationContainer) + { + if (fileName == null) + { Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "Unable to import file. File path is null."); return; } - if(!File.Exists(fileName)) - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"Unable to import file. File does not exist. Path: {fileName}"); + if (!File.Exists(fileName)) + 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 dataProvider = new FileDataProvider(fileName); + var xmlString = dataProvider.Load(); + var xmlConnectionsDeserializer = new XmlConnectionsDeserializer(); var serializationResult = xmlConnectionsDeserializer.Deserialize(xmlString, true); - var rootImportContainer = new ContainerInfo { Name = Path.GetFileNameWithoutExtension(fileName) }; + var rootImportContainer = new ContainerInfo {Name = Path.GetFileNameWithoutExtension(fileName)}; rootImportContainer.AddChildRange(serializationResult.ConnectionRecords); - destinationContainer.AddChild(rootImportContainer); + destinationContainer.AddChild(rootImportContainer); } - } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Import/PortScanImporter.cs b/mRemoteV1/Config/Import/PortScanImporter.cs index aa0c9442..738710f1 100644 --- a/mRemoteV1/Config/Import/PortScanImporter.cs +++ b/mRemoteV1/Config/Import/PortScanImporter.cs @@ -8,18 +8,18 @@ using mRemoteNG.Tools; namespace mRemoteNG.Config.Import { - public class PortScanImporter : IConnectionImporter> - { - private readonly ProtocolType _targetProtocolType; + public class PortScanImporter : IConnectionImporter> + { + private readonly ProtocolType _targetProtocolType; - public PortScanImporter(ProtocolType targetProtocolType) - { - _targetProtocolType = targetProtocolType; - } + public PortScanImporter(ProtocolType targetProtocolType) + { + _targetProtocolType = targetProtocolType; + } public void Import(IEnumerable hosts, ContainerInfo destinationContainer) - { - var deserializer = new PortScanDeserializer(_targetProtocolType); + { + var deserializer = new PortScanDeserializer(_targetProtocolType); var connectionTreeModel = deserializer.Deserialize(hosts); var importedRootNode = connectionTreeModel.RootNodes.First(); @@ -27,5 +27,5 @@ namespace mRemoteNG.Config.Import var childrenToAdd = importedRootNode.Children.ToArray(); destinationContainer.AddChildRange(childrenToAdd); } - } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Import/PuttyConnectionManagerImporter.cs b/mRemoteV1/Config/Import/PuttyConnectionManagerImporter.cs index 3f20f813..b6a9358f 100644 --- a/mRemoteV1/Config/Import/PuttyConnectionManagerImporter.cs +++ b/mRemoteV1/Config/Import/PuttyConnectionManagerImporter.cs @@ -5,10 +5,10 @@ using mRemoteNG.Container; namespace mRemoteNG.Config.Import { - public class PuttyConnectionManagerImporter : IConnectionImporter - { + public class PuttyConnectionManagerImporter : IConnectionImporter + { public void Import(string filePath, ContainerInfo destinationContainer) - { + { var dataProvider = new FileDataProvider(filePath); var xmlContent = dataProvider.Load(); @@ -17,5 +17,5 @@ namespace mRemoteNG.Config.Import destinationContainer.AddChildRange(serializationResult.ConnectionRecords); } - } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Import/RemoteDesktopConnectionImporter.cs b/mRemoteV1/Config/Import/RemoteDesktopConnectionImporter.cs index fbea3414..a0a763f3 100644 --- a/mRemoteV1/Config/Import/RemoteDesktopConnectionImporter.cs +++ b/mRemoteV1/Config/Import/RemoteDesktopConnectionImporter.cs @@ -7,10 +7,10 @@ using mRemoteNG.Container; namespace mRemoteNG.Config.Import { - public class RemoteDesktopConnectionImporter : IConnectionImporter - { + public class RemoteDesktopConnectionImporter : IConnectionImporter + { public void Import(string fileName, ContainerInfo destinationContainer) - { + { var dataProvider = new FileDataProvider(fileName); var content = dataProvider.Load(); @@ -18,10 +18,10 @@ namespace mRemoteNG.Config.Import var serializationResult = deserializer.Deserialize(content); var importedConnection = serializationResult.ConnectionRecords.FirstOrDefault(); - + if (importedConnection == null) return; importedConnection.Name = Path.GetFileNameWithoutExtension(fileName); destinationContainer.AddChild(importedConnection); - } + } } } \ No newline at end of file diff --git a/mRemoteV1/Config/Import/RemoteDesktopConnectionManagerImporter.cs b/mRemoteV1/Config/Import/RemoteDesktopConnectionManagerImporter.cs index a7f173b2..ab709c84 100644 --- a/mRemoteV1/Config/Import/RemoteDesktopConnectionManagerImporter.cs +++ b/mRemoteV1/Config/Import/RemoteDesktopConnectionManagerImporter.cs @@ -5,10 +5,10 @@ using mRemoteNG.Container; namespace mRemoteNG.Config.Import { - public class RemoteDesktopConnectionManagerImporter : IConnectionImporter - { - public void Import(string filePath, ContainerInfo destinationContainer) - { + public class RemoteDesktopConnectionManagerImporter : IConnectionImporter + { + public void Import(string filePath, ContainerInfo destinationContainer) + { var dataProvider = new FileDataProvider(filePath); var fileContent = dataProvider.Load(); @@ -17,5 +17,5 @@ namespace mRemoteNG.Config.Import destinationContainer.AddChildRange(serializationResult.ConnectionRecords); } - } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Putty/AbstractPuttySessionsProvider.cs b/mRemoteV1/Config/Putty/AbstractPuttySessionsProvider.cs index 2c5d55c6..38da3533 100644 --- a/mRemoteV1/Config/Putty/AbstractPuttySessionsProvider.cs +++ b/mRemoteV1/Config/Putty/AbstractPuttySessionsProvider.cs @@ -5,37 +5,42 @@ using System.Web; using mRemoteNG.Connection; using mRemoteNG.Tree.Root; using System.Text; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Config.Putty { public abstract class AbstractPuttySessionsProvider - { + { public virtual RootPuttySessionsNodeInfo RootInfo { get; } = new RootPuttySessionsNodeInfo(); + protected virtual List Sessions { get { return RootInfo.Children.OfType().ToList(); } } - #region Public Methods + #region Public Methods + public abstract string[] GetSessionNames(bool raw = false); - public abstract PuttySessionInfo GetSession(string sessionName); - - public virtual IEnumerable GetSessions() - { - var sessionNamesFromProvider = GetSessionNames(true); + public abstract PuttySessionInfo GetSession(string sessionName); + + public virtual IEnumerable GetSessions() + { + var sessionNamesFromProvider = GetSessionNames(true); foreach (var sessionName in GetSessionNamesToAdd(sessionNamesFromProvider)) - { - var sessionInfo = GetSession(sessionName); - AddSession(sessionInfo); - } - foreach (var session in GetSessionToRemove(sessionNamesFromProvider)) - { - RemoveSession(session); - } + { + var sessionInfo = GetSession(sessionName); + AddSession(sessionInfo); + } + + foreach (var session in GetSessionToRemove(sessionNamesFromProvider)) + { + RemoveSession(session); + } + RootInfo.SortRecursive(); - return Sessions; - } + return Sessions; + } private IEnumerable GetSessionNamesToAdd(IEnumerable sessionNamesFromProvider) { @@ -47,7 +52,9 @@ namespace mRemoteNG.Config.Putty private IEnumerable GetSessionToRemove(IEnumerable sessionNamesFromProvider) { var currentlyKnownSessionNames = Sessions.Select(session => session.Name); - var normalizedSessionNames = sessionNamesFromProvider.Select(name => HttpUtility.UrlDecode(name, Encoding.GetEncoding("iso-8859-1"))); + var normalizedSessionNames = + sessionNamesFromProvider.Select(name => + HttpUtility.UrlDecode(name, Encoding.GetEncoding("iso-8859-1"))); var sessionNamesToRemove = currentlyKnownSessionNames.Except(normalizedSessionNames); return Sessions.Where(session => sessionNamesToRemove.Contains(session.Name)); } @@ -57,29 +64,43 @@ namespace mRemoteNG.Config.Putty if (string.IsNullOrEmpty(sessionInfo?.Name) || Sessions.Any(child => child.Name == sessionInfo.Name)) return; RootInfo.AddChild(sessionInfo); - RaisePuttySessionCollectionChangedEvent(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, sessionInfo)); + RaisePuttySessionCollectionChangedEvent( + new + NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, + sessionInfo)); } protected virtual void RemoveSession(PuttySessionInfo sessionInfo) { if (!Sessions.Contains(sessionInfo)) return; RootInfo.RemoveChild(sessionInfo); - RaisePuttySessionCollectionChangedEvent(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, sessionInfo)); + RaisePuttySessionCollectionChangedEvent( + new + NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, + sessionInfo)); } - - public virtual void StartWatcher() { } - - public virtual void StopWatcher() { } + + public virtual void StartWatcher() + { + } + + public virtual void StopWatcher() + { + } + #endregion - - public delegate void PuttySessionChangedEventHandler(object sender, PuttySessionChangedEventArgs e); + + public delegate void PuttySessionChangedEventHandler(object sender, PuttySessionChangedEventArgs e); + public event PuttySessionChangedEventHandler PuttySessionChanged; - protected virtual void RaiseSessionChangedEvent(PuttySessionChangedEventArgs args) - { + + protected virtual void RaiseSessionChangedEvent(PuttySessionChangedEventArgs args) + { PuttySessionChanged?.Invoke(this, args); - } + } public event NotifyCollectionChangedEventHandler PuttySessionsCollectionChanged; + protected void RaisePuttySessionCollectionChangedEvent(NotifyCollectionChangedEventArgs args) { PuttySessionsCollectionChanged?.Invoke(this, args); diff --git a/mRemoteV1/Config/Putty/PuttySessionsManager.cs b/mRemoteV1/Config/Putty/PuttySessionsManager.cs index 72e9a1ce..4286e60d 100644 --- a/mRemoteV1/Config/Putty/PuttySessionsManager.cs +++ b/mRemoteV1/Config/Putty/PuttySessionsManager.cs @@ -3,74 +3,80 @@ using System.Collections.Specialized; using System.ComponentModel; using mRemoteNG.Tools; using mRemoteNG.Tree.Root; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Config.Putty { public class PuttySessionsManager - { + { public static PuttySessionsManager Instance { get; } = new PuttySessionsManager(); private readonly List _providers = new List(); + public IEnumerable Providers { get { return _providers; } } - public List RootPuttySessionsNodes { get; } = new List(); + public List RootPuttySessionsNodes { get; } = new List(); - private PuttySessionsManager() - { - AddProvider(new PuttySessionsRegistryProvider()); + private PuttySessionsManager() + { + AddProvider(new PuttySessionsRegistryProvider()); AddProvider(new PuttySessionsXmingProvider()); - } + } #region Public Methods - public void AddSessions() - { - foreach (var provider in Providers) - { - AddSessionsFromProvider(provider); - } - } - private void AddSessionsFromProvider(AbstractPuttySessionsProvider puttySessionProvider) - { - puttySessionProvider.ThrowIfNull(nameof(puttySessionProvider)); + public void AddSessions() + { + foreach (var provider in Providers) + { + AddSessionsFromProvider(provider); + } + } + + private void AddSessionsFromProvider(AbstractPuttySessionsProvider puttySessionProvider) + { + puttySessionProvider.ThrowIfNull(nameof(puttySessionProvider)); var rootTreeNode = puttySessionProvider.RootInfo; - puttySessionProvider.GetSessions(); + puttySessionProvider.GetSessions(); if (!RootPuttySessionsNodes.Contains(rootTreeNode) && rootTreeNode.HasChildren()) RootPuttySessionsNodes.Add(rootTreeNode); rootTreeNode.SortRecursive(); } - - public void StartWatcher() - { - foreach (var provider in Providers) - { - provider.StartWatcher(); - provider.PuttySessionChanged += PuttySessionChanged; - } - } - - public void StopWatcher() - { - foreach (var provider in Providers) - { - provider.StopWatcher(); - provider.PuttySessionChanged -= PuttySessionChanged; - } - } + + public void StartWatcher() + { + foreach (var provider in Providers) + { + provider.StartWatcher(); + provider.PuttySessionChanged += PuttySessionChanged; + } + } + + public void StopWatcher() + { + foreach (var provider in Providers) + { + provider.StopWatcher(); + provider.PuttySessionChanged -= PuttySessionChanged; + } + } public void AddProvider(AbstractPuttySessionsProvider newProvider) { if (_providers.Contains(newProvider)) return; _providers.Add(newProvider); newProvider.PuttySessionsCollectionChanged += RaisePuttySessionCollectionChangedEvent; - RaiseSessionProvidersCollectionChangedEvent(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newProvider)); + RaiseSessionProvidersCollectionChangedEvent( + new + NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, + newProvider)); } public void AddProviders(IEnumerable newProviders) @@ -84,48 +90,58 @@ namespace mRemoteNG.Config.Putty if (!_providers.Contains(providerToRemove)) return; _providers.Remove(providerToRemove); providerToRemove.PuttySessionsCollectionChanged -= RaisePuttySessionCollectionChangedEvent; - RaiseSessionProvidersCollectionChangedEvent(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, providerToRemove)); + RaiseSessionProvidersCollectionChangedEvent( + new + NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, + providerToRemove)); } public void PuttySessionChanged(object sender, PuttySessionChangedEventArgs e) - { - AddSessions(); - } + { + AddSessions(); + } + #endregion #region Private Methods - private string[] GetSessionNames(bool raw = false) - { - var sessionNames = new List(); - foreach (var provider in Providers) - { - if (!IsProviderEnabled(provider)) - { - continue; - } - sessionNames.AddRange(provider.GetSessionNames(raw)); - } - return sessionNames.ToArray(); - } - - private bool IsProviderEnabled(AbstractPuttySessionsProvider puttySessionsProvider) - { + + private string[] GetSessionNames(bool raw = false) + { + var sessionNames = new List(); + foreach (var provider in Providers) + { + if (!IsProviderEnabled(provider)) + { + continue; + } + + sessionNames.AddRange(provider.GetSessionNames(raw)); + } + + return sessionNames.ToArray(); + } + + private bool IsProviderEnabled(AbstractPuttySessionsProvider puttySessionsProvider) + { var enabled = true; - if (PuttyTypeDetector.GetPuttyType() == PuttyTypeDetector.PuttyType.Xming) - { - if (puttySessionsProvider is PuttySessionsRegistryProvider) - enabled = false; - } - else - { - if (puttySessionsProvider is PuttySessionsXmingProvider) - enabled = false; - } - return enabled; - } + if (PuttyTypeDetector.GetPuttyType() == PuttyTypeDetector.PuttyType.Xming) + { + if (puttySessionsProvider is PuttySessionsRegistryProvider) + enabled = false; + } + else + { + if (puttySessionsProvider is PuttySessionsXmingProvider) + enabled = false; + } + + return enabled; + } + #endregion - + #region Public Classes + public class SessionList : StringConverter { public static string[] Names @@ -134,29 +150,32 @@ namespace mRemoteNG.Config.Putty } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - return new StandardValuesCollection(Names); - } - - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) - { - return true; - } - - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } + { + return new StandardValuesCollection(Names); + } + + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { + return true; + } + + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { + return true; + } } + #endregion public event NotifyCollectionChangedEventHandler PuttySessionsCollectionChanged; + protected void RaisePuttySessionCollectionChangedEvent(object sender, NotifyCollectionChangedEventArgs args) { PuttySessionsCollectionChanged?.Invoke(sender, args); } public event NotifyCollectionChangedEventHandler SessionProvidersCollectionChanged; + protected void RaiseSessionProvidersCollectionChangedEvent(NotifyCollectionChangedEventArgs args) { SessionProvidersCollectionChanged?.Invoke(this, args); diff --git a/mRemoteV1/Config/Putty/PuttySessionsRegistryProvider.cs b/mRemoteV1/Config/Putty/PuttySessionsRegistryProvider.cs index 07c2bf37..3e03c817 100644 --- a/mRemoteV1/Config/Putty/PuttySessionsRegistryProvider.cs +++ b/mRemoteV1/Config/Putty/PuttySessionsRegistryProvider.cs @@ -14,30 +14,34 @@ using System.Web; namespace mRemoteNG.Config.Putty { public class PuttySessionsRegistryProvider : AbstractPuttySessionsProvider - { + { private const string PuttySessionsKey = "Software\\SimonTatham\\PuTTY\\Sessions"; private static ManagementEventWatcher _eventWatcher; #region Public Methods - public override string[] GetSessionNames(bool raw = false) - { + + public override string[] GetSessionNames(bool raw = false) + { var sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey); - if (sessionsKey == null) return new string[] {}; + if (sessionsKey == null) return new string[] { }; var sessionNames = new List(); - foreach (var sessionName in sessionsKey.GetSubKeyNames()) - { - sessionNames.Add(raw ? sessionName : HttpUtility.UrlDecode(sessionName.Replace("+", "%2B"), Encoding.GetEncoding("iso-8859-1"))); - } - - if (raw && !sessionNames.Contains("Default%20Settings")) - sessionNames.Insert(0, "Default%20Settings"); - else if (!raw && !sessionNames.Contains("Default Settings")) - sessionNames.Insert(0, "Default Settings"); - - return sessionNames.ToArray(); - } - + foreach (var sessionName in sessionsKey.GetSubKeyNames()) + { + sessionNames.Add(raw + ? sessionName + : HttpUtility.UrlDecode(sessionName.Replace("+", "%2B"), + Encoding.GetEncoding("iso-8859-1"))); + } + + if (raw && !sessionNames.Contains("Default%20Settings")) + sessionNames.Insert(0, "Default%20Settings"); + else if (!raw && !sessionNames.Contains("Default Settings")) + sessionNames.Insert(0, "Default Settings"); + + return sessionNames.ToArray(); + } + public override PuttySessionInfo GetSession(string sessionName) { if (string.IsNullOrEmpty(sessionName)) @@ -45,36 +49,36 @@ namespace mRemoteNG.Config.Putty var sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey); var sessionKey = sessionsKey?.OpenSubKey(sessionName); - if (sessionKey == null) return null; + if (sessionKey == null) return null; sessionName = HttpUtility.UrlDecode(sessionName.Replace("+", "%2B"), Encoding.GetEncoding("iso-8859-1")); - - var sessionInfo = new PuttySessionInfo - { - PuttySession = sessionName, - Name = sessionName, - Hostname = sessionKey.GetValue("HostName")?.ToString() ?? "", + + var sessionInfo = new PuttySessionInfo + { + PuttySession = sessionName, + Name = sessionName, + Hostname = sessionKey.GetValue("HostName")?.ToString() ?? "", // TODO: this should create a temp putty credential - Username = sessionKey.GetValue("UserName")?.ToString() ?? "" - }; + Username = sessionKey.GetValue("UserName")?.ToString() ?? "" + }; - var protocol = string.IsNullOrEmpty(sessionKey.GetValue("Protocol")?.ToString()) - ? "ssh" + var protocol = string.IsNullOrEmpty(sessionKey.GetValue("Protocol")?.ToString()) + ? "ssh" : sessionKey.GetValue("Protocol").ToString(); - switch (protocol.ToLowerInvariant()) - { - case "raw": - sessionInfo.Protocol = ProtocolType.RAW; - break; - case "rlogin": - sessionInfo.Protocol = ProtocolType.Rlogin; - break; - case "serial": - return null; - case "ssh": - int.TryParse(sessionKey.GetValue("SshProt")?.ToString(), out var sshVersion); + switch (protocol.ToLowerInvariant()) + { + case "raw": + sessionInfo.Protocol = ProtocolType.RAW; + break; + case "rlogin": + sessionInfo.Protocol = ProtocolType.Rlogin; + break; + case "serial": + return null; + case "ssh": + int.TryParse(sessionKey.GetValue("SshProt")?.ToString(), out var 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 @@ -83,53 +87,56 @@ namespace mRemoteNG.Config.Putty * default to SSH2 if any other value is received */ sessionInfo.Protocol = sshVersion == 1 || sshVersion == 0 ? ProtocolType.SSH1 : ProtocolType.SSH2; - break; - case "telnet": - sessionInfo.Protocol = ProtocolType.Telnet; - break; - default: - return null; - } + break; + case "telnet": + sessionInfo.Protocol = ProtocolType.Telnet; + break; + default: + return null; + } int.TryParse(sessionKey.GetValue("PortNumber")?.ToString(), out var portNumber); if (portNumber == default(int)) sessionInfo.SetDefaultPort(); else sessionInfo.Port = portNumber; - - return sessionInfo; - } - - public override void StartWatcher() - { - if (_eventWatcher != null) return; - - try - { + + return sessionInfo; + } + + public override void StartWatcher() + { + if (_eventWatcher != null) return; + + try + { var currentUserSid = WindowsIdentity.GetCurrent().User?.Value; var key = string.Join("\\", currentUserSid, PuttySessionsKey).Replace("\\", "\\\\"); - var query = new WqlEventQuery($"SELECT * FROM RegistryTreeChangeEvent WHERE Hive = \'HKEY_USERS\' AND RootPath = \'{key}\'"); - _eventWatcher = new ManagementEventWatcher(query); - _eventWatcher.EventArrived += OnManagementEventArrived; - _eventWatcher.Start(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("PuttySessions.Watcher.StartWatching() failed.", ex, MessageClass.WarningMsg); - } - } - - public override void StopWatcher() - { - if (_eventWatcher == null) return; - _eventWatcher.Stop(); - _eventWatcher.Dispose(); - } + var query = new WqlEventQuery( + $"SELECT * FROM RegistryTreeChangeEvent WHERE Hive = \'HKEY_USERS\' AND RootPath = \'{key}\'"); + _eventWatcher = new ManagementEventWatcher(query); + _eventWatcher.EventArrived += OnManagementEventArrived; + _eventWatcher.Start(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("PuttySessions.Watcher.StartWatching() failed.", ex, + MessageClass.WarningMsg); + } + } + + public override void StopWatcher() + { + if (_eventWatcher == null) return; + _eventWatcher.Stop(); + _eventWatcher.Dispose(); + } + #endregion - - private void OnManagementEventArrived(object sender, EventArrivedEventArgs e) - { - RaiseSessionChangedEvent(new PuttySessionChangedEventArgs()); - } + + private void OnManagementEventArrived(object sender, EventArrivedEventArgs e) + { + RaiseSessionChangedEvent(new PuttySessionChangedEventArgs()); + } } } \ No newline at end of file diff --git a/mRemoteV1/Config/Putty/PuttySessionsXmingProvider.cs b/mRemoteV1/Config/Putty/PuttySessionsXmingProvider.cs index 32557cf4..a55551f5 100644 --- a/mRemoteV1/Config/Putty/PuttySessionsXmingProvider.cs +++ b/mRemoteV1/Config/Putty/PuttySessionsXmingProvider.cs @@ -13,339 +13,374 @@ using System.Text.RegularExpressions; namespace mRemoteNG.Config.Putty { public class PuttySessionsXmingProvider : AbstractPuttySessionsProvider - { - public override RootPuttySessionsNodeInfo RootInfo { get; } = new RootPuttySessionsNodeInfo { Name = "Xming Putty Sessions" }; + { + public override RootPuttySessionsNodeInfo RootInfo { get; } = + new RootPuttySessionsNodeInfo {Name = "Xming Putty Sessions"}; + private const string RegistrySessionNameFormat = "{0} [registry]"; private const string RegistrySessionNamePattern = "(.*)\\ \\[registry\\]"; - private static readonly PuttySessionsRegistryProvider PuttySessionsRegistryProvider = new PuttySessionsRegistryProvider(); + + private static readonly PuttySessionsRegistryProvider PuttySessionsRegistryProvider = + new PuttySessionsRegistryProvider(); + private static FileSystemWatcher _eventWatcher; #region Public Methods - public override string[] GetSessionNames(bool raw = false) - { - var sessionsFolderPath = GetSessionsFolderPath(); - if (!Directory.Exists(sessionsFolderPath)) - { - return new string[] {}; - } + + public override string[] GetSessionNames(bool raw = false) + { + var sessionsFolderPath = GetSessionsFolderPath(); + if (!Directory.Exists(sessionsFolderPath)) + { + return new string[] { }; + } var sessionNames = new List(); - foreach (var sessionName in Directory.GetFiles(sessionsFolderPath)) - { - var sessionFileName = Path.GetFileName(sessionName); - // ReSharper disable once ConstantConditionalAccessQualifier - sessionNames.Add(raw ? sessionFileName : System.Web.HttpUtility.UrlDecode(sessionFileName?.Replace("+", "%2B"))); - } + foreach (var sessionName in Directory.GetFiles(sessionsFolderPath)) + { + var sessionFileName = Path.GetFileName(sessionName); + // ReSharper disable once ConstantConditionalAccessQualifier + sessionNames.Add(raw + ? sessionFileName + : System.Web.HttpUtility.UrlDecode(sessionFileName?.Replace("+", "%2B"))); + } - if (raw) - { - if (!sessionNames.Contains("Default%20Settings")) // Do not localize - { - sessionNames.Insert(0, "Default%20Settings"); - } - } - else - { - if (!sessionNames.Contains("Default Settings")) - { - sessionNames.Insert(0, "Default Settings"); - } - } + if (raw) + { + if (!sessionNames.Contains("Default%20Settings")) // Do not localize + { + sessionNames.Insert(0, "Default%20Settings"); + } + } + else + { + if (!sessionNames.Contains("Default Settings")) + { + sessionNames.Insert(0, "Default Settings"); + } + } - var registrySessionNames = PuttySessionsRegistryProvider.GetSessionNames(raw).Select(sessionName => string.Format(RegistrySessionNameFormat, sessionName)).ToList(); + var registrySessionNames = PuttySessionsRegistryProvider.GetSessionNames(raw) + .Select(sessionName => + string + .Format(RegistrySessionNameFormat, + sessionName)).ToList(); - sessionNames.AddRange(registrySessionNames); - sessionNames.Sort(); - - return sessionNames.ToArray(); - } - - public override PuttySessionInfo GetSession(string sessionName) - { + sessionNames.AddRange(registrySessionNames); + sessionNames.Sort(); + + return sessionNames.ToArray(); + } + + public override PuttySessionInfo GetSession(string sessionName) + { var registrySessionName = GetRegistrySessionName(sessionName); - if (!string.IsNullOrEmpty(registrySessionName)) - { - return ModifyRegistrySessionInfo(PuttySessionsRegistryProvider.GetSession(registrySessionName)); - } + if (!string.IsNullOrEmpty(registrySessionName)) + { + return ModifyRegistrySessionInfo(PuttySessionsRegistryProvider.GetSession(registrySessionName)); + } var sessionsFolderPath = GetSessionsFolderPath(); - if (!Directory.Exists(sessionsFolderPath)) - { - return null; - } + if (!Directory.Exists(sessionsFolderPath)) + { + return null; + } var sessionFile = Path.Combine(sessionsFolderPath, sessionName); - if (!File.Exists(sessionFile)) - { - return null; - } - - sessionName = System.Web.HttpUtility.UrlDecode(sessionName.Replace("+", "%2B")); + if (!File.Exists(sessionFile)) + { + return null; + } + + sessionName = System.Web.HttpUtility.UrlDecode(sessionName.Replace("+", "%2B")); var sessionFileReader = new SessionFileReader(sessionFile); - var sessionInfo = new PuttySessionInfo - { - PuttySession = sessionName, - Name = sessionName, - Hostname = sessionFileReader.GetValue("HostName"), + var sessionInfo = new PuttySessionInfo + { + PuttySession = sessionName, + Name = sessionName, + Hostname = sessionFileReader.GetValue("HostName"), // TODO: this should create a temp putty credential Username = sessionFileReader.GetValue("UserName") - }; - var protocol = sessionFileReader.GetValue("Protocol") ?? "ssh"; - switch (protocol.ToLowerInvariant()) - { - case "raw": - sessionInfo.Protocol = ProtocolType.RAW; - break; - case "rlogin": - sessionInfo.Protocol = ProtocolType.Rlogin; - break; - case "serial": - return null; - case "ssh": - object sshVersionObject = sessionFileReader.GetValue("SshProt"); - if (sshVersionObject != null) - { - var sshVersion = Convert.ToInt32(sshVersionObject); - sessionInfo.Protocol = sshVersion >= 2 ? ProtocolType.SSH2 : ProtocolType.SSH1; - } - else - { - sessionInfo.Protocol = ProtocolType.SSH2; - } - break; - case "telnet": - sessionInfo.Protocol = ProtocolType.Telnet; - break; - default: - return null; - } - sessionInfo.Port = Convert.ToInt32(sessionFileReader.GetValue("PortNumber")); - - return sessionInfo; - } - - public override void StartWatcher() - { - if (_eventWatcher != null) - { - return; - } - - try - { + }; + var protocol = sessionFileReader.GetValue("Protocol") ?? "ssh"; + switch (protocol.ToLowerInvariant()) + { + case "raw": + sessionInfo.Protocol = ProtocolType.RAW; + break; + case "rlogin": + sessionInfo.Protocol = ProtocolType.Rlogin; + break; + case "serial": + return null; + case "ssh": + object sshVersionObject = sessionFileReader.GetValue("SshProt"); + if (sshVersionObject != null) + { + var sshVersion = Convert.ToInt32(sshVersionObject); + sessionInfo.Protocol = sshVersion >= 2 ? ProtocolType.SSH2 : ProtocolType.SSH1; + } + else + { + sessionInfo.Protocol = ProtocolType.SSH2; + } + + break; + case "telnet": + sessionInfo.Protocol = ProtocolType.Telnet; + break; + default: + return null; + } + + sessionInfo.Port = Convert.ToInt32(sessionFileReader.GetValue("PortNumber")); + + return sessionInfo; + } + + public override void StartWatcher() + { + if (_eventWatcher != null) + { + return; + } + + try + { var sessionsFolderPath = GetSessionsFolderPath(); - if (!Directory.Exists(sessionsFolderPath)) - { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, $"XmingPortablePuttySessions.Watcher.StartWatching() failed: '{sessionsFolderPath}' does not exist.", true); - return; - } + if (!Directory.Exists(sessionsFolderPath)) + { + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + $"XmingPortablePuttySessions.Watcher.StartWatching() failed: '{sessionsFolderPath}' does not exist.", + true); + return; + } + + _eventWatcher = new FileSystemWatcher(sessionsFolderPath) + { + NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite + }; + _eventWatcher.Changed += OnFileSystemEventArrived; + _eventWatcher.Created += OnFileSystemEventArrived; + _eventWatcher.Deleted += OnFileSystemEventArrived; + _eventWatcher.Renamed += OnFileSystemEventArrived; + _eventWatcher.EnableRaisingEvents = true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + "XmingPortablePuttySessions.Watcher.StartWatching() failed.", + ex, MessageClass.WarningMsg); + } + } + + public override void StopWatcher() + { + PuttySessionsRegistryProvider.StopWatcher(); + PuttySessionsRegistryProvider.PuttySessionChanged -= OnRegistrySessionChanged; + + if (_eventWatcher == null) + { + return; + } + + _eventWatcher.EnableRaisingEvents = false; + _eventWatcher.Dispose(); + } - _eventWatcher = new FileSystemWatcher(sessionsFolderPath) - { - NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite - }; - _eventWatcher.Changed += OnFileSystemEventArrived; - _eventWatcher.Created += OnFileSystemEventArrived; - _eventWatcher.Deleted += OnFileSystemEventArrived; - _eventWatcher.Renamed += OnFileSystemEventArrived; - _eventWatcher.EnableRaisingEvents = true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("XmingPortablePuttySessions.Watcher.StartWatching() failed.", ex, MessageClass.WarningMsg); - } - } - - public override void StopWatcher() - { - PuttySessionsRegistryProvider.StopWatcher(); - PuttySessionsRegistryProvider.PuttySessionChanged -= OnRegistrySessionChanged; - - if (_eventWatcher == null) - { - return; - } - _eventWatcher.EnableRaisingEvents = false; - _eventWatcher.Dispose(); - } #endregion - + #region Private Methods - private static string GetPuttyConfPath() - { - var puttyPath = mRemoteNG.Settings.Default.UseCustomPuttyPath ? mRemoteNG.Settings.Default.CustomPuttyPath : App.Info.GeneralAppInfo.PuttyPath; - puttyPath = Path.GetDirectoryName(puttyPath); + + private static string GetPuttyConfPath() + { + var puttyPath = mRemoteNG.Settings.Default.UseCustomPuttyPath + ? mRemoteNG.Settings.Default.CustomPuttyPath + : App.Info.GeneralAppInfo.PuttyPath; + puttyPath = Path.GetDirectoryName(puttyPath); return string.IsNullOrEmpty(puttyPath) ? null : Path.Combine(puttyPath, "putty.conf"); - } - - private static string GetSessionsFolderPath() - { + } + + private static string GetSessionsFolderPath() + { var puttyConfPath = GetPuttyConfPath(); var sessionFileReader = new PuttyConfFileReader(puttyConfPath); var basePath = Environment.ExpandEnvironmentVariables(sessionFileReader.GetValue("sshk&sess")); - return Path.Combine(basePath, "sessions"); - } - - private static string GetRegistrySessionName(string sessionName) - { + return Path.Combine(basePath, "sessions"); + } + + private static string GetRegistrySessionName(string sessionName) + { var regex = new Regex(RegistrySessionNamePattern); var matches = regex.Matches(sessionName); - if (matches.Count < 1) - { - return string.Empty; - } + if (matches.Count < 1) + { + return string.Empty; + } var groups = matches[0].Groups; - return groups.Count < 1 ? string.Empty : groups[1].Value; - } - - private static PuttySessionInfo ModifyRegistrySessionInfo(PuttySessionInfo sessionInfo) - { - if (sessionInfo == null) - return null; + return groups.Count < 1 ? string.Empty : groups[1].Value; + } + + private static PuttySessionInfo ModifyRegistrySessionInfo(PuttySessionInfo sessionInfo) + { + if (sessionInfo == null) + return null; + + sessionInfo.Name = string.Format(RegistrySessionNameFormat, sessionInfo.Name); + sessionInfo.PuttySession = string.Format(RegistrySessionNameFormat, sessionInfo.PuttySession); + return sessionInfo; + } + + private void OnFileSystemEventArrived(object sender, FileSystemEventArgs e) + { + RaiseSessionChangedEvent(new PuttySessionChangedEventArgs()); + } + + private void OnRegistrySessionChanged(object sender, PuttySessionChangedEventArgs e) + { + RaiseSessionChangedEvent(new PuttySessionChangedEventArgs()); + } - sessionInfo.Name = string.Format(RegistrySessionNameFormat, sessionInfo.Name); - sessionInfo.PuttySession = string.Format(RegistrySessionNameFormat, sessionInfo.PuttySession); - return sessionInfo; - } - - private void OnFileSystemEventArrived(object sender, FileSystemEventArgs e) - { - RaiseSessionChangedEvent(new PuttySessionChangedEventArgs()); - } - - private void OnRegistrySessionChanged(object sender, PuttySessionChangedEventArgs e) - { - RaiseSessionChangedEvent(new PuttySessionChangedEventArgs()); - } #endregion - + #region Private Classes - private class PuttyConfFileReader - { - public PuttyConfFileReader(string puttyConfFile) - { - _puttyConfFile = puttyConfFile; - } - - private string _puttyConfFile; - private bool _configurationLoaded; - private Dictionary _configuration = new Dictionary(); - - private void LoadConfiguration() - { - _configurationLoaded = true; - try - { - if (!File.Exists(_puttyConfFile)) - { - return; - } - using (var streamReader = new StreamReader(_puttyConfFile)) - { - do - { - var line = streamReader.ReadLine(); - if (line == null) - { - break; - } - line = line.Trim(); - if (line == string.Empty) - { - continue; // Blank line - } - if (line.Substring(0, 1) == ";") - { - continue; // Comment - } + + private class PuttyConfFileReader + { + public PuttyConfFileReader(string puttyConfFile) + { + _puttyConfFile = puttyConfFile; + } + + private string _puttyConfFile; + private bool _configurationLoaded; + private Dictionary _configuration = new Dictionary(); + + private void LoadConfiguration() + { + _configurationLoaded = true; + try + { + if (!File.Exists(_puttyConfFile)) + { + return; + } + + using (var streamReader = new StreamReader(_puttyConfFile)) + { + do + { + var line = streamReader.ReadLine(); + if (line == null) + { + break; + } + + line = line.Trim(); + if (line == string.Empty) + { + continue; // Blank line + } + + if (line.Substring(0, 1) == ";") + { + continue; // Comment + } + var parts = line.Split(new[] {'='}, 2); - if (parts.Length < 2) - { - continue; - } - if (_configuration.ContainsKey(parts[0])) - { - continue; // As per http://www.straightrunning.com/XmingNotes/portableputty.php only first entry is used - } - _configuration.Add(parts[0], parts[1]); - } while (true); - } - - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("PuttyConfFileReader.LoadConfiguration() failed.", ex); - } - } - - public string GetValue(string setting) - { - if (!_configurationLoaded) - { - LoadConfiguration(); - } - return !_configuration.ContainsKey(setting) ? string.Empty : _configuration[setting]; - } - } - - private class SessionFileReader - { - public SessionFileReader(string sessionFile) - { - _sessionFile = sessionFile; - } - - private string _sessionFile; - private bool _sessionInfoLoaded; - private Dictionary _sessionInfo = new Dictionary(); - - private void LoadSessionInfo() - { - _sessionInfoLoaded = true; - try - { - if (!File.Exists(_sessionFile)) - { - return; - } - using (var streamReader = new StreamReader(_sessionFile)) - { - do - { - var line = streamReader.ReadLine(); - if (line == null) - { - break; - } + if (parts.Length < 2) + { + continue; + } + + if (_configuration.ContainsKey(parts[0])) + { + continue; // As per http://www.straightrunning.com/XmingNotes/portableputty.php only first entry is used + } + + _configuration.Add(parts[0], parts[1]); + } while (true); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("PuttyConfFileReader.LoadConfiguration() failed.", ex); + } + } + + public string GetValue(string setting) + { + if (!_configurationLoaded) + { + LoadConfiguration(); + } + + return !_configuration.ContainsKey(setting) ? string.Empty : _configuration[setting]; + } + } + + private class SessionFileReader + { + public SessionFileReader(string sessionFile) + { + _sessionFile = sessionFile; + } + + private string _sessionFile; + private bool _sessionInfoLoaded; + private Dictionary _sessionInfo = new Dictionary(); + + private void LoadSessionInfo() + { + _sessionInfoLoaded = true; + try + { + if (!File.Exists(_sessionFile)) + { + return; + } + + using (var streamReader = new StreamReader(_sessionFile)) + { + do + { + var line = streamReader.ReadLine(); + if (line == null) + { + break; + } + var parts = line.Split('\\'); - if (parts.Length < 2) - { - continue; - } - _sessionInfo.Add(parts[0], parts[1]); - } while (true); - } - - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("SessionFileReader.LoadSessionInfo() failed.", ex); - } - } - - public string GetValue(string setting) - { - if (!_sessionInfoLoaded) - { - LoadSessionInfo(); - } - return !_sessionInfo.ContainsKey(setting) ? string.Empty : _sessionInfo[setting]; - } - } + if (parts.Length < 2) + { + continue; + } + + _sessionInfo.Add(parts[0], parts[1]); + } while (true); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("SessionFileReader.LoadSessionInfo() failed.", ex); + } + } + + public string GetValue(string setting) + { + if (!_sessionInfoLoaded) + { + LoadSessionInfo(); + } + + return !_sessionInfo.ContainsKey(setting) ? string.Empty : _sessionInfo[setting]; + } + } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs index 42275d29..6bb924b8 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsDeserializerMremotengFormat.cs @@ -21,7 +21,7 @@ namespace mRemoteNG.Config.Serializers.Csv { public SerializationResult Deserialize(string serializedData) { - var lines = serializedData.Split(new []{"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries); + var lines = serializedData.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries); var csvHeaders = new List(); // used to map a connectioninfo to it's parent's GUID var parentMapping = new Dictionary(); @@ -72,9 +72,9 @@ namespace mRemoteNG.Config.Serializers.Csv // search for parent in the list by GUID var parent = parentMapping - .Keys - .OfType() - .FirstOrDefault(info => info.ConstantID == node.Value); + .Keys + .OfType() + .FirstOrDefault(info => info.ConstantID == node.Value); if (parent != null) { @@ -92,7 +92,7 @@ namespace mRemoteNG.Config.Serializers.Csv private ConnectionInfo ParseConnectionInfo(IList headers, string[] connectionCsv) { var nodeType = headers.Contains("NodeType") - ? (TreeNodeType)Enum.Parse(typeof(TreeNodeType), connectionCsv[headers.IndexOf("NodeType")], true) + ? (TreeNodeType)Enum.Parse(typeof(TreeNodeType), connectionCsv[headers.IndexOf("NodeType")], true) : TreeNodeType.Connection; var nodeId = headers.Contains("Id") @@ -104,7 +104,8 @@ namespace mRemoteNG.Config.Serializers.Csv : new ContainerInfo(nodeId); connectionRecord.Name = headers.Contains("Name") ? connectionCsv[headers.IndexOf("Name")] : ""; - connectionRecord.Description = headers.Contains("Description") ? connectionCsv[headers.IndexOf("Description")] : ""; + connectionRecord.Description = + headers.Contains("Description") ? connectionCsv[headers.IndexOf("Description")] : ""; connectionRecord.Icon = headers.Contains("Icon") ? connectionCsv[headers.IndexOf("Icon")] : ""; connectionRecord.Panel = headers.Contains("Panel") ? connectionCsv[headers.IndexOf("Panel")] : ""; @@ -119,20 +120,40 @@ namespace mRemoteNG.Config.Serializers.Csv connectionRecord.Domain = headers.Contains("Domain") ? connectionCsv[headers.IndexOf("Domain")] : ""; connectionRecord.Hostname = headers.Contains("Hostname") ? connectionCsv[headers.IndexOf("Hostname")] : ""; - connectionRecord.PuttySession = headers.Contains("PuttySession") ? connectionCsv[headers.IndexOf("PuttySession")] : ""; - connectionRecord.LoadBalanceInfo = headers.Contains("LoadBalanceInfo") ? connectionCsv[headers.IndexOf("LoadBalanceInfo")] : ""; - connectionRecord.PreExtApp = headers.Contains("PreExtApp") ? connectionCsv[headers.IndexOf("PreExtApp")] : ""; - connectionRecord.PostExtApp = headers.Contains("PostExtApp") ? connectionCsv[headers.IndexOf("PostExtApp")] : ""; - connectionRecord.MacAddress = headers.Contains("MacAddress") ? connectionCsv[headers.IndexOf("MacAddress")] : ""; - connectionRecord.UserField = headers.Contains("UserField") ? connectionCsv[headers.IndexOf("UserField")] : ""; + connectionRecord.PuttySession = + headers.Contains("PuttySession") ? connectionCsv[headers.IndexOf("PuttySession")] : ""; + connectionRecord.LoadBalanceInfo = headers.Contains("LoadBalanceInfo") + ? connectionCsv[headers.IndexOf("LoadBalanceInfo")] + : ""; + connectionRecord.PreExtApp = + headers.Contains("PreExtApp") ? connectionCsv[headers.IndexOf("PreExtApp")] : ""; + connectionRecord.PostExtApp = + headers.Contains("PostExtApp") ? connectionCsv[headers.IndexOf("PostExtApp")] : ""; + connectionRecord.MacAddress = + headers.Contains("MacAddress") ? connectionCsv[headers.IndexOf("MacAddress")] : ""; + connectionRecord.UserField = + headers.Contains("UserField") ? connectionCsv[headers.IndexOf("UserField")] : ""; connectionRecord.ExtApp = headers.Contains("ExtApp") ? connectionCsv[headers.IndexOf("ExtApp")] : ""; - connectionRecord.VNCProxyUsername = headers.Contains("VNCProxyUsername") ? connectionCsv[headers.IndexOf("VNCProxyUsername")] : ""; - connectionRecord.VNCProxyPassword = headers.Contains("VNCProxyPassword") ? connectionCsv[headers.IndexOf("VNCProxyPassword")] : ""; - connectionRecord.RDGatewayUsername = headers.Contains("RDGatewayUsername") ? connectionCsv[headers.IndexOf("RDGatewayUsername")] : ""; - connectionRecord.RDGatewayPassword = headers.Contains("RDGatewayPassword") ? connectionCsv[headers.IndexOf("RDGatewayPassword")] : ""; - connectionRecord.RDGatewayDomain = headers.Contains("RDGatewayDomain") ? connectionCsv[headers.IndexOf("RDGatewayDomain")] : ""; - connectionRecord.VNCProxyIP = headers.Contains("VNCProxyIP") ? connectionCsv[headers.IndexOf("VNCProxyIP")] : ""; - connectionRecord.RDGatewayHostname = headers.Contains("RDGatewayHostname") ? connectionCsv[headers.IndexOf("RDGatewayHostname")] : ""; + connectionRecord.VNCProxyUsername = headers.Contains("VNCProxyUsername") + ? connectionCsv[headers.IndexOf("VNCProxyUsername")] + : ""; + connectionRecord.VNCProxyPassword = headers.Contains("VNCProxyPassword") + ? connectionCsv[headers.IndexOf("VNCProxyPassword")] + : ""; + connectionRecord.RDGatewayUsername = headers.Contains("RDGatewayUsername") + ? connectionCsv[headers.IndexOf("RDGatewayUsername")] + : ""; + connectionRecord.RDGatewayPassword = headers.Contains("RDGatewayPassword") + ? connectionCsv[headers.IndexOf("RDGatewayPassword")] + : ""; + connectionRecord.RDGatewayDomain = headers.Contains("RDGatewayDomain") + ? connectionCsv[headers.IndexOf("RDGatewayDomain")] + : ""; + connectionRecord.VNCProxyIP = + headers.Contains("VNCProxyIP") ? connectionCsv[headers.IndexOf("VNCProxyIP")] : ""; + connectionRecord.RDGatewayHostname = headers.Contains("RDGatewayHostname") + ? connectionCsv[headers.IndexOf("RDGatewayHostname")] + : ""; if (headers.Contains("CredentialId")) { @@ -247,6 +268,7 @@ namespace mRemoteNG.Config.Serializers.Csv if (bool.TryParse(connectionCsv[headers.IndexOf("RedirectPrinters")], out bool value)) connectionRecord.RedirectPrinters = value; } + if (headers.Contains("RedirectClipboard")) { if (bool.TryParse(connectionCsv[headers.IndexOf("RedirectClipboard")], out bool value)) @@ -332,6 +354,7 @@ namespace mRemoteNG.Config.Serializers.Csv } #region Inheritance + if (headers.Contains("InheritCacheBitmaps")) { if (bool.TryParse(connectionCsv[headers.IndexOf("InheritCacheBitmaps")], out bool value)) @@ -622,7 +645,8 @@ namespace mRemoteNG.Config.Serializers.Csv if (headers.Contains("InheritRDGatewayUseConnectionCredentials")) { - if (bool.TryParse(connectionCsv[headers.IndexOf("InheritRDGatewayUseConnectionCredentials")], out bool value)) + if (bool.TryParse(connectionCsv[headers.IndexOf("InheritRDGatewayUseConnectionCredentials")], + out var value)) connectionRecord.Inheritance.RDGatewayUseConnectionCredentials = value; } diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs index 069a1214..aa5a1641 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Csv/CsvConnectionsSerializerMremotengFormat.cs @@ -11,14 +11,15 @@ using System.Text; namespace mRemoteNG.Config.Serializers.Csv { - public class CsvConnectionsSerializerMremotengFormat : ISerializer + public class CsvConnectionsSerializerMremotengFormat : ISerializer { private readonly SaveFilter _saveFilter; private readonly ICredentialRepositoryList _credentialRepositoryList; public Version Version { get; } = new Version(2, 7); - public CsvConnectionsSerializerMremotengFormat(SaveFilter saveFilter, ICredentialRepositoryList credentialRepositoryList) + public CsvConnectionsSerializerMremotengFormat(SaveFilter saveFilter, + ICredentialRepositoryList credentialRepositoryList) { saveFilter.ThrowIfNull(nameof(saveFilter)); credentialRepositoryList.ThrowIfNull(nameof(credentialRepositoryList)); @@ -106,52 +107,52 @@ namespace mRemoteNG.Config.Serializers.Csv .Append(FormatForCsv(con.CredentialRecordId)); sb.Append(FormatForCsv(con.Hostname)) - .Append(FormatForCsv(con.Protocol)) - .Append(FormatForCsv(con.PuttySession)) - .Append(FormatForCsv(con.Port)) - .Append(FormatForCsv(con.UseConsoleSession)) - .Append(FormatForCsv(con.UseCredSsp)) - .Append(FormatForCsv(con.RenderingEngine)) - .Append(FormatForCsv(con.ICAEncryptionStrength)) - .Append(FormatForCsv(con.RDPAuthenticationLevel)) - .Append(FormatForCsv(con.LoadBalanceInfo)) - .Append(FormatForCsv(con.Colors)) - .Append(FormatForCsv(con.Resolution)) - .Append(FormatForCsv(con.AutomaticResize)) - .Append(FormatForCsv(con.DisplayWallpaper)) - .Append(FormatForCsv(con.DisplayThemes)) - .Append(FormatForCsv(con.EnableFontSmoothing)) - .Append(FormatForCsv(con.EnableDesktopComposition)) - .Append(FormatForCsv(con.CacheBitmaps)) - .Append(FormatForCsv(con.RedirectDiskDrives)) - .Append(FormatForCsv(con.RedirectPorts)) - .Append(FormatForCsv(con.RedirectPrinters)) - .Append(FormatForCsv(con.RedirectClipboard)) - .Append(FormatForCsv(con.RedirectSmartCards)) - .Append(FormatForCsv(con.RedirectSound)) - .Append(FormatForCsv(con.RedirectKeys)) - .Append(FormatForCsv(con.PreExtApp)) - .Append(FormatForCsv(con.PostExtApp)) - .Append(FormatForCsv(con.MacAddress)) - .Append(FormatForCsv(con.UserField)) - .Append(FormatForCsv(con.ExtApp)) - .Append(FormatForCsv(con.VNCCompression)) - .Append(FormatForCsv(con.VNCEncoding)) - .Append(FormatForCsv(con.VNCAuthMode)) - .Append(FormatForCsv(con.VNCProxyType)) - .Append(FormatForCsv(con.VNCProxyIP)) - .Append(FormatForCsv(con.VNCProxyPort)) - .Append(FormatForCsv(con.VNCProxyUsername)) - .Append(FormatForCsv(con.VNCProxyPassword)) - .Append(FormatForCsv(con.VNCColors)) - .Append(FormatForCsv(con.VNCSmartSizeMode)) - .Append(FormatForCsv(con.VNCViewOnly)) - .Append(FormatForCsv(con.RDGatewayUsageMethod)) - .Append(FormatForCsv(con.RDGatewayHostname)) - .Append(FormatForCsv(con.RDGatewayUseConnectionCredentials)) - .Append(FormatForCsv(con.RDGatewayUsername)) - .Append(FormatForCsv(con.RDGatewayPassword)) - .Append(FormatForCsv(con.RDGatewayDomain)); + .Append(FormatForCsv(con.Protocol)) + .Append(FormatForCsv(con.PuttySession)) + .Append(FormatForCsv(con.Port)) + .Append(FormatForCsv(con.UseConsoleSession)) + .Append(FormatForCsv(con.UseCredSsp)) + .Append(FormatForCsv(con.RenderingEngine)) + .Append(FormatForCsv(con.ICAEncryptionStrength)) + .Append(FormatForCsv(con.RDPAuthenticationLevel)) + .Append(FormatForCsv(con.LoadBalanceInfo)) + .Append(FormatForCsv(con.Colors)) + .Append(FormatForCsv(con.Resolution)) + .Append(FormatForCsv(con.AutomaticResize)) + .Append(FormatForCsv(con.DisplayWallpaper)) + .Append(FormatForCsv(con.DisplayThemes)) + .Append(FormatForCsv(con.EnableFontSmoothing)) + .Append(FormatForCsv(con.EnableDesktopComposition)) + .Append(FormatForCsv(con.CacheBitmaps)) + .Append(FormatForCsv(con.RedirectDiskDrives)) + .Append(FormatForCsv(con.RedirectPorts)) + .Append(FormatForCsv(con.RedirectPrinters)) + .Append(FormatForCsv(con.RedirectClipboard)) + .Append(FormatForCsv(con.RedirectSmartCards)) + .Append(FormatForCsv(con.RedirectSound)) + .Append(FormatForCsv(con.RedirectKeys)) + .Append(FormatForCsv(con.PreExtApp)) + .Append(FormatForCsv(con.PostExtApp)) + .Append(FormatForCsv(con.MacAddress)) + .Append(FormatForCsv(con.UserField)) + .Append(FormatForCsv(con.ExtApp)) + .Append(FormatForCsv(con.VNCCompression)) + .Append(FormatForCsv(con.VNCEncoding)) + .Append(FormatForCsv(con.VNCAuthMode)) + .Append(FormatForCsv(con.VNCProxyType)) + .Append(FormatForCsv(con.VNCProxyIP)) + .Append(FormatForCsv(con.VNCProxyPort)) + .Append(FormatForCsv(con.VNCProxyUsername)) + .Append(FormatForCsv(con.VNCProxyPassword)) + .Append(FormatForCsv(con.VNCColors)) + .Append(FormatForCsv(con.VNCSmartSizeMode)) + .Append(FormatForCsv(con.VNCViewOnly)) + .Append(FormatForCsv(con.RDGatewayUsageMethod)) + .Append(FormatForCsv(con.RDGatewayHostname)) + .Append(FormatForCsv(con.RDGatewayUseConnectionCredentials)) + .Append(FormatForCsv(con.RDGatewayUsername)) + .Append(FormatForCsv(con.RDGatewayPassword)) + .Append(FormatForCsv(con.RDGatewayDomain)); if (!_saveFilter.SaveInheritance) diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableDeserializer.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableDeserializer.cs index 0129d72e..c7949cb3 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableDeserializer.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableDeserializer.cs @@ -51,20 +51,21 @@ namespace mRemoteNG.Config.Serializers.MsSql break; } } + return nodeList; } private ConnectionInfo DeserializeConnectionInfo(DataRow row) { - var connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString(); - var connectionInfo = new ConnectionInfo(connectionId); + var connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString(); + var connectionInfo = new ConnectionInfo(connectionId); PopulateConnectionInfoFromDataRow(row, connectionInfo); return connectionInfo; } private ContainerInfo DeserializeContainerInfo(DataRow row) { - var containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString(); + var containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString(); var containerInfo = new ContainerInfo(containerId); PopulateConnectionInfoFromDataRow(row, containerInfo); return containerInfo; @@ -96,14 +97,22 @@ namespace mRemoteNG.Config.Serializers.MsSql connectionInfo.Port = (int)dataRow["Port"]; connectionInfo.UseConsoleSession = (bool)dataRow["ConnectToConsole"]; connectionInfo.UseCredSsp = (bool)dataRow["UseCredSsp"]; - connectionInfo.RenderingEngine = (HTTPBase.RenderingEngine)Enum.Parse(typeof(HTTPBase.RenderingEngine), (string)dataRow["RenderingEngine"]); - connectionInfo.ICAEncryptionStrength = (IcaProtocol.EncryptionStrength)Enum.Parse(typeof(IcaProtocol.EncryptionStrength), (string)dataRow["ICAEncryptionStrength"]); - connectionInfo.RDPAuthenticationLevel = (RdpProtocol.AuthenticationLevel)Enum.Parse(typeof(RdpProtocol.AuthenticationLevel), (string)dataRow["RDPAuthenticationLevel"]); + connectionInfo.RenderingEngine = (HTTPBase.RenderingEngine)Enum.Parse(typeof(HTTPBase.RenderingEngine), + (string)dataRow["RenderingEngine"]); + connectionInfo.ICAEncryptionStrength = + (IcaProtocol.EncryptionStrength)Enum.Parse(typeof(IcaProtocol.EncryptionStrength), + (string)dataRow["ICAEncryptionStrength"]); + connectionInfo.RDPAuthenticationLevel = + (RdpProtocol.AuthenticationLevel)Enum.Parse(typeof(RdpProtocol.AuthenticationLevel), + (string)dataRow["RDPAuthenticationLevel"]); connectionInfo.RDPMinutesToIdleTimeout = (int)dataRow["RDPMinutesToIdleTimeout"]; connectionInfo.RDPAlertIdleTimeout = (bool)dataRow["RDPAlertIdleTimeout"]; connectionInfo.LoadBalanceInfo = (string)dataRow["LoadBalanceInfo"]; - connectionInfo.Colors = (RdpProtocol.RDPColors)Enum.Parse(typeof(RdpProtocol.RDPColors) ,(string)dataRow["Colors"]); - connectionInfo.Resolution = (RdpProtocol.RDPResolutions)Enum.Parse(typeof(RdpProtocol.RDPResolutions), (string)dataRow["Resolution"]); + connectionInfo.Colors = + (RdpProtocol.RDPColors)Enum.Parse(typeof(RdpProtocol.RDPColors), (string)dataRow["Colors"]); + connectionInfo.Resolution = + (RdpProtocol.RDPResolutions)Enum.Parse(typeof(RdpProtocol.RDPResolutions), + (string)dataRow["Resolution"]); connectionInfo.AutomaticResize = (bool)dataRow["AutomaticResize"]; connectionInfo.DisplayWallpaper = (bool)dataRow["DisplayWallpaper"]; connectionInfo.DisplayThemes = (bool)dataRow["DisplayThemes"]; @@ -115,28 +124,44 @@ namespace mRemoteNG.Config.Serializers.MsSql connectionInfo.RedirectPrinters = (bool)dataRow["RedirectPrinters"]; connectionInfo.RedirectClipboard = (bool)dataRow["RedirectClipboard"]; connectionInfo.RedirectSmartCards = (bool)dataRow["RedirectSmartCards"]; - connectionInfo.RedirectSound = (RdpProtocol.RDPSounds)Enum.Parse(typeof(RdpProtocol.RDPSounds), (string)dataRow["RedirectSound"]); - connectionInfo.SoundQuality = (RdpProtocol.RDPSoundQuality)Enum.Parse(typeof(RdpProtocol.RDPSoundQuality), (string)dataRow["SoundQuality"]); + connectionInfo.RedirectSound = + (RdpProtocol.RDPSounds)Enum.Parse(typeof(RdpProtocol.RDPSounds), (string)dataRow["RedirectSound"]); + connectionInfo.SoundQuality = (RdpProtocol.RDPSoundQuality)Enum.Parse(typeof(RdpProtocol.RDPSoundQuality), + (string)dataRow["SoundQuality"]); connectionInfo.RedirectKeys = (bool)dataRow["RedirectKeys"]; connectionInfo.PreExtApp = (string)dataRow["PreExtApp"]; connectionInfo.PostExtApp = (string)dataRow["PostExtApp"]; connectionInfo.MacAddress = (string)dataRow["MacAddress"]; connectionInfo.UserField = (string)dataRow["UserField"]; connectionInfo.ExtApp = (string)dataRow["ExtApp"]; - connectionInfo.VNCCompression = (ProtocolVNC.Compression)Enum.Parse(typeof(ProtocolVNC.Compression), (string)dataRow["VNCCompression"]); - connectionInfo.VNCEncoding = (ProtocolVNC.Encoding)Enum.Parse(typeof(ProtocolVNC.Encoding) ,(string)dataRow["VNCEncoding"]); - connectionInfo.VNCAuthMode = (ProtocolVNC.AuthMode)Enum.Parse(typeof(ProtocolVNC.AuthMode), (string)dataRow["VNCAuthMode"]); - connectionInfo.VNCProxyType = (ProtocolVNC.ProxyType)Enum.Parse(typeof(ProtocolVNC.ProxyType), (string)dataRow["VNCProxyType"]); + connectionInfo.VNCCompression = (ProtocolVNC.Compression)Enum.Parse(typeof(ProtocolVNC.Compression), + (string)dataRow["VNCCompression"]); + connectionInfo.VNCEncoding = + (ProtocolVNC.Encoding)Enum.Parse(typeof(ProtocolVNC.Encoding), (string)dataRow["VNCEncoding"]); + connectionInfo.VNCAuthMode = + (ProtocolVNC.AuthMode)Enum.Parse(typeof(ProtocolVNC.AuthMode), (string)dataRow["VNCAuthMode"]); + connectionInfo.VNCProxyType = + (ProtocolVNC.ProxyType)Enum.Parse(typeof(ProtocolVNC.ProxyType), (string)dataRow["VNCProxyType"]); connectionInfo.VNCProxyIP = (string)dataRow["VNCProxyIP"]; connectionInfo.VNCProxyPort = (int)dataRow["VNCProxyPort"]; connectionInfo.VNCProxyUsername = (string)dataRow["VNCProxyUsername"]; connectionInfo.VNCProxyPassword = DecryptValue((string)dataRow["VNCProxyPassword"]); - connectionInfo.VNCColors = (ProtocolVNC.Colors)Enum.Parse(typeof(ProtocolVNC.Colors), (string)dataRow["VNCColors"]); - connectionInfo.VNCSmartSizeMode = (ProtocolVNC.SmartSizeMode)Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), (string)dataRow["VNCSmartSizeMode"]); + connectionInfo.VNCColors = + (ProtocolVNC.Colors)Enum.Parse(typeof(ProtocolVNC.Colors), (string)dataRow["VNCColors"]); + connectionInfo.VNCSmartSizeMode = (ProtocolVNC.SmartSizeMode)Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), + (string)dataRow + ["VNCSmartSizeMode"]); connectionInfo.VNCViewOnly = (bool)dataRow["VNCViewOnly"]; - connectionInfo.RDGatewayUsageMethod = (RdpProtocol.RDGatewayUsageMethod)Enum.Parse(typeof(RdpProtocol.RDGatewayUsageMethod), (string)dataRow["RDGatewayUsageMethod"]); + connectionInfo.RDGatewayUsageMethod = + (RdpProtocol.RDGatewayUsageMethod)Enum.Parse(typeof(RdpProtocol.RDGatewayUsageMethod), + (string)dataRow["RDGatewayUsageMethod"]); connectionInfo.RDGatewayHostname = (string)dataRow["RDGatewayHostname"]; - connectionInfo.RDGatewayUseConnectionCredentials = (RdpProtocol.RDGatewayUseConnectionCredentials)Enum.Parse(typeof(RdpProtocol.RDGatewayUseConnectionCredentials), (string)dataRow["RDGatewayUseConnectionCredentials"]); + connectionInfo.RDGatewayUseConnectionCredentials = + (RdpProtocol.RDGatewayUseConnectionCredentials)Enum.Parse( + typeof(RdpProtocol. + RDGatewayUseConnectionCredentials), + (string)dataRow + ["RDGatewayUseConnectionCredentials"]); connectionInfo.RDGatewayUsername = (string)dataRow["RDGatewayUsername"]; connectionInfo.RDGatewayPassword = DecryptValue((string)dataRow["RDGatewayPassword"]); connectionInfo.RDGatewayDomain = (string)dataRow["RDGatewayDomain"]; @@ -189,7 +214,8 @@ namespace mRemoteNG.Config.Serializers.MsSql connectionInfo.Inheritance.VNCViewOnly = (bool)dataRow["InheritVNCViewOnly"]; connectionInfo.Inheritance.RDGatewayUsageMethod = (bool)dataRow["InheritRDGatewayUsageMethod"]; connectionInfo.Inheritance.RDGatewayHostname = (bool)dataRow["InheritRDGatewayHostname"]; - connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = (bool)dataRow["InheritRDGatewayUseConnectionCredentials"]; + connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = + (bool)dataRow["InheritRDGatewayUseConnectionCredentials"]; connectionInfo.Inheritance.RDGatewayUsername = (bool)dataRow["InheritRDGatewayUsername"]; connectionInfo.Inheritance.RDGatewayPassword = (bool)dataRow["InheritRDGatewayPassword"]; connectionInfo.Inheritance.RDGatewayDomain = (bool)dataRow["InheritRDGatewayDomain"]; diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableSerializer.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableSerializer.cs index eb38e6c0..be249173 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableSerializer.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/DataTableSerializer.cs @@ -12,7 +12,7 @@ using System.Security; namespace mRemoteNG.Config.Serializers.MsSql { - public class DataTableSerializer : ISerializer + public class DataTableSerializer : ISerializer { private readonly ICryptographyProvider _cryptographyProvider; private readonly SecureString _encryptionKey; @@ -23,7 +23,9 @@ namespace mRemoteNG.Config.Serializers.MsSql public Version Version { get; } = new Version(2, 7); - public DataTableSerializer(SaveFilter saveFilter, ICryptographyProvider cryptographyProvider, SecureString encryptionKey) + public DataTableSerializer(SaveFilter saveFilter, + ICryptographyProvider cryptographyProvider, + SecureString encryptionKey) { _saveFilter = saveFilter.ThrowIfNull(nameof(saveFilter)); _cryptographyProvider = cryptographyProvider.ThrowIfNull(nameof(cryptographyProvider)); @@ -187,7 +189,7 @@ namespace mRemoteNG.Config.Serializers.MsSql private void SetPrimaryKey(DataTable dataTable) { - dataTable.PrimaryKey = new[] { dataTable.Columns["ConstantID"] }; + dataTable.PrimaryKey = new[] {dataTable.Columns["ConstantID"]}; } private void SerializeNodesRecursive(ConnectionInfo connectionInfo) @@ -255,14 +257,16 @@ namespace mRemoteNG.Config.Serializers.MsSql dataRow["VNCProxyIP"] = connectionInfo.VNCProxyIP; dataRow["VNCProxyPort"] = connectionInfo.VNCProxyPort; dataRow["VNCProxyUsername"] = connectionInfo.VNCProxyUsername; - dataRow["VNCProxyPassword"] = _cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, _encryptionKey); + dataRow["VNCProxyPassword"] = + _cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, _encryptionKey); dataRow["VNCColors"] = connectionInfo.VNCColors; dataRow["VNCSmartSizeMode"] = connectionInfo.VNCSmartSizeMode; dataRow["VNCViewOnly"] = connectionInfo.VNCViewOnly; dataRow["RDGatewayUsageMethod"] = connectionInfo.RDGatewayUsageMethod; dataRow["RDGatewayHostname"] = connectionInfo.RDGatewayHostname; dataRow["RDGatewayUseConnectionCredentials"] = connectionInfo.RDGatewayUseConnectionCredentials; - dataRow["RDGatewayUsername"] = _cryptographyProvider.Encrypt(connectionInfo.RDGatewayUsername, _encryptionKey); + dataRow["RDGatewayUsername"] = + _cryptographyProvider.Encrypt(connectionInfo.RDGatewayUsername, _encryptionKey); dataRow["RDGatewayPassword"] = connectionInfo.RDGatewayPassword; dataRow["RDGatewayDomain"] = connectionInfo.RDGatewayDomain; if (_saveFilter.SaveInheritance) @@ -315,7 +319,8 @@ namespace mRemoteNG.Config.Serializers.MsSql dataRow["InheritVNCViewOnly"] = connectionInfo.Inheritance.VNCViewOnly; dataRow["InheritRDGatewayUsageMethod"] = connectionInfo.Inheritance.RDGatewayUsageMethod; dataRow["InheritRDGatewayHostname"] = connectionInfo.Inheritance.RDGatewayHostname; - dataRow["InheritRDGatewayUseConnectionCredentials"] = connectionInfo.Inheritance.RDGatewayUseConnectionCredentials; + dataRow["InheritRDGatewayUseConnectionCredentials"] = + connectionInfo.Inheritance.RDGatewayUseConnectionCredentials; dataRow["InheritRDGatewayUsername"] = connectionInfo.Inheritance.RDGatewayUsername; dataRow["InheritRDGatewayPassword"] = connectionInfo.Inheritance.RDGatewayPassword; dataRow["InheritRDGatewayDomain"] = connectionInfo.Inheritance.RDGatewayDomain; @@ -375,6 +380,7 @@ namespace mRemoteNG.Config.Serializers.MsSql dataRow["InheritRDGatewayPassword"] = false; dataRow["InheritRDGatewayDomain"] = false; } + _dataTable.Rows.Add(dataRow); } } diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesModel.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesModel.cs index f8cdb35f..696c6070 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesModel.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesModel.cs @@ -17,4 +17,4 @@ /// public bool Expanded { get; set; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesXmlSerializer.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesXmlSerializer.cs index da76a8dc..3af6108d 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesXmlSerializer.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/LocalConnectionPropertiesXmlSerializer.cs @@ -8,8 +8,8 @@ using System.Xml.Linq; namespace mRemoteNG.Config.Serializers.MsSql { - public class LocalConnectionPropertiesXmlSerializer : - ISerializer, string>, + public class LocalConnectionPropertiesXmlSerializer : + ISerializer, string>, IDeserializer> { public Version Version { get; } = new Version(1, 0); @@ -17,10 +17,10 @@ namespace mRemoteNG.Config.Serializers.MsSql public string Serialize(IEnumerable models) { var localConnections = models - .Select(m => new XElement("Node", - new XAttribute("ConnectionId", m.ConnectionId), - new XAttribute("Connected", m.Connected), - new XAttribute("Expanded", m.Expanded))); + .Select(m => new XElement("Node", + new XAttribute("ConnectionId", m.ConnectionId), + new XAttribute("Connected", m.Connected), + new XAttribute("Expanded", m.Expanded))); var root = new XElement("LocalConnections", localConnections); var xdoc = new XDocument(new XDeclaration("1.0", "utf-8", null), root); @@ -34,20 +34,21 @@ namespace mRemoteNG.Config.Serializers.MsSql var xdoc = XDocument.Parse(serializedData); return xdoc - .Descendants("Node") - .Where(e => e.Attribute("ConnectionId") != null) - .Select(e => new LocalConnectionPropertiesModel - { - ConnectionId = e.Attribute("ConnectionId")?.Value, - Connected = bool.Parse(e.Attribute("Connected")?.Value ?? "False"), - Expanded = bool.Parse(e.Attribute("Expanded")?.Value ?? "False") - }); + .Descendants("Node") + .Where(e => e.Attribute("ConnectionId") != null) + .Select(e => new LocalConnectionPropertiesModel + { + ConnectionId = e.Attribute("ConnectionId")?.Value, + Connected = bool.Parse(e.Attribute("Connected")?.Value ?? "False"), + Expanded = bool.Parse(e.Attribute("Expanded")?.Value ?? "False") + }); } private static string WriteXmlToString(XNode xmlDocument) { string xmlString; - var xmlWriterSettings = new XmlWriterSettings { Indent = true, IndentChars = " ", Encoding = Encoding.UTF8 }; + var xmlWriterSettings = new XmlWriterSettings + {Indent = true, IndentChars = " ", Encoding = Encoding.UTF8}; var memoryStream = new MemoryStream(); using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings)) { @@ -57,7 +58,8 @@ namespace mRemoteNG.Config.Serializers.MsSql memoryStream.Seek(0, SeekOrigin.Begin); xmlString = streamReader.ReadToEnd(); } + return xmlString; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlConnectionListMetaData.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlConnectionListMetaData.cs index 12e8ce86..98d61ae4 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlConnectionListMetaData.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlConnectionListMetaData.cs @@ -10,4 +10,4 @@ namespace mRemoteNG.Config.Serializers.MsSql public bool Export { get; set; } public Version ConfVersion { get; set; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlDatabaseMetaDataRetriever.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlDatabaseMetaDataRetriever.cs index 8c97292d..2bfa7ef6 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlDatabaseMetaDataRetriever.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/MsSql/SqlDatabaseMetaDataRetriever.cs @@ -29,7 +29,8 @@ namespace mRemoteNG.Config.Serializers.MsSql Name = sqlDataReader["Name"] as string ?? "", Protected = sqlDataReader["Protected"] as string ?? "", Export = (bool)sqlDataReader["Export"], - ConfVersion = new Version(Convert.ToString(sqlDataReader["confVersion"], CultureInfo.InvariantCulture)) + ConfVersion = + new Version(Convert.ToString(sqlDataReader["confVersion"], CultureInfo.InvariantCulture)) }; } catch (Exception ex) @@ -42,6 +43,7 @@ namespace mRemoteNG.Config.Serializers.MsSql if (sqlDataReader != null && !sqlDataReader.IsClosed) sqlDataReader.Close(); } + return metaData; } } diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs index 591f1291..7ccaa95f 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer26.cs @@ -8,7 +8,7 @@ using System.Xml.Linq; namespace mRemoteNG.Config.Serializers.Xml { // ReSharper disable once InconsistentNaming - public class XmlConnectionNodeSerializer26 : ISerializer + public class XmlConnectionNodeSerializer26 : ISerializer { private readonly ICryptographyProvider _cryptographyProvider; private readonly SecureString _encryptionKey; @@ -16,7 +16,9 @@ namespace mRemoteNG.Config.Serializers.Xml public Version Version { get; } = new Version(2, 6); - public XmlConnectionNodeSerializer26(ICryptographyProvider cryptographyProvider, SecureString encryptionKey, SaveFilter saveFilter) + public XmlConnectionNodeSerializer26(ICryptographyProvider cryptographyProvider, + SecureString encryptionKey, + SaveFilter saveFilter) { if (cryptographyProvider == null) throw new ArgumentNullException(nameof(cryptographyProvider)); @@ -52,15 +54,16 @@ namespace mRemoteNG.Config.Serializers.Xml // TODO: remove element.Add(_saveFilter.SaveUsername - ? new XAttribute("Username", connectionInfo.Username) - : new XAttribute("Username", "")); + ? new XAttribute("Username", connectionInfo.Username) + : new XAttribute("Username", "")); element.Add(_saveFilter.SaveDomain - ? new XAttribute("Domain", connectionInfo.Domain) - : new XAttribute("Domain", "")); + ? new XAttribute("Domain", connectionInfo.Domain) + : new XAttribute("Domain", "")); if (_saveFilter.SavePassword && !connectionInfo.Inheritance.Password) - element.Add(new XAttribute("Password", _cryptographyProvider.Encrypt(connectionInfo.Password, _encryptionKey))); + element.Add(new XAttribute("Password", + _cryptographyProvider.Encrypt(connectionInfo.Password, _encryptionKey))); else element.Add(new XAttribute("Password", "")); @@ -68,31 +71,42 @@ namespace mRemoteNG.Config.Serializers.Xml element.Add(new XAttribute("Protocol", connectionInfo.Protocol)); element.Add(new XAttribute("PuttySession", connectionInfo.PuttySession)); element.Add(new XAttribute("Port", connectionInfo.Port)); - element.Add(new XAttribute("ConnectToConsole", connectionInfo.UseConsoleSession.ToString().ToLowerInvariant())); + element.Add(new XAttribute("ConnectToConsole", + connectionInfo.UseConsoleSession.ToString().ToLowerInvariant())); element.Add(new XAttribute("UseCredSsp", connectionInfo.UseCredSsp.ToString().ToLowerInvariant())); element.Add(new XAttribute("RenderingEngine", connectionInfo.RenderingEngine)); element.Add(new XAttribute("ICAEncryptionStrength", connectionInfo.ICAEncryptionStrength)); element.Add(new XAttribute("RDPAuthenticationLevel", connectionInfo.RDPAuthenticationLevel)); element.Add(new XAttribute("RDPMinutesToIdleTimeout", connectionInfo.RDPMinutesToIdleTimeout)); - element.Add(new XAttribute("RDPAlertIdleTimeout", connectionInfo.RDPAlertIdleTimeout.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RDPAlertIdleTimeout", + connectionInfo.RDPAlertIdleTimeout.ToString().ToLowerInvariant())); element.Add(new XAttribute("LoadBalanceInfo", connectionInfo.LoadBalanceInfo)); element.Add(new XAttribute("Colors", connectionInfo.Colors)); element.Add(new XAttribute("Resolution", connectionInfo.Resolution)); - element.Add(new XAttribute("AutomaticResize", connectionInfo.AutomaticResize.ToString().ToLowerInvariant())); - element.Add(new XAttribute("DisplayWallpaper", connectionInfo.DisplayWallpaper.ToString().ToLowerInvariant())); + element.Add(new XAttribute("AutomaticResize", + connectionInfo.AutomaticResize.ToString().ToLowerInvariant())); + element.Add(new XAttribute("DisplayWallpaper", + connectionInfo.DisplayWallpaper.ToString().ToLowerInvariant())); element.Add(new XAttribute("DisplayThemes", connectionInfo.DisplayThemes.ToString().ToLowerInvariant())); - element.Add(new XAttribute("EnableFontSmoothing", connectionInfo.EnableFontSmoothing.ToString().ToLowerInvariant())); - element.Add(new XAttribute("EnableDesktopComposition", connectionInfo.EnableDesktopComposition.ToString().ToLowerInvariant())); + element.Add(new XAttribute("EnableFontSmoothing", + connectionInfo.EnableFontSmoothing.ToString().ToLowerInvariant())); + element.Add(new XAttribute("EnableDesktopComposition", + connectionInfo.EnableDesktopComposition.ToString().ToLowerInvariant())); element.Add(new XAttribute("CacheBitmaps", connectionInfo.CacheBitmaps.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectDiskDrives", connectionInfo.RedirectDiskDrives.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectDiskDrives", + connectionInfo.RedirectDiskDrives.ToString().ToLowerInvariant())); element.Add(new XAttribute("RedirectPorts", connectionInfo.RedirectPorts.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectPrinters", connectionInfo.RedirectPrinters.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectClipboard", connectionInfo.RedirectClipboard.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectSmartCards", connectionInfo.RedirectSmartCards.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectPrinters", + connectionInfo.RedirectPrinters.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectClipboard", + connectionInfo.RedirectClipboard.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectSmartCards", + connectionInfo.RedirectSmartCards.ToString().ToLowerInvariant())); element.Add(new XAttribute("RedirectSound", connectionInfo.RedirectSound.ToString())); element.Add(new XAttribute("SoundQuality", connectionInfo.SoundQuality.ToString())); element.Add(new XAttribute("RedirectKeys", connectionInfo.RedirectKeys.ToString().ToLowerInvariant())); - element.Add(new XAttribute("Connected", (connectionInfo.OpenConnections.Count > 0).ToString().ToLowerInvariant())); + element.Add(new XAttribute("Connected", + (connectionInfo.OpenConnections.Count > 0).ToString().ToLowerInvariant())); element.Add(new XAttribute("PreExtApp", connectionInfo.PreExtApp)); element.Add(new XAttribute("PostExtApp", connectionInfo.PostExtApp)); element.Add(new XAttribute("MacAddress", connectionInfo.MacAddress)); @@ -106,93 +120,163 @@ namespace mRemoteNG.Config.Serializers.Xml element.Add(new XAttribute("VNCProxyPort", connectionInfo.VNCProxyPort)); element.Add(_saveFilter.SaveUsername - ? new XAttribute("VNCProxyUsername", connectionInfo.VNCProxyUsername) - : new XAttribute("VNCProxyUsername", "")); + ? new XAttribute("VNCProxyUsername", connectionInfo.VNCProxyUsername) + : new XAttribute("VNCProxyUsername", "")); element.Add(_saveFilter.SavePassword - ? new XAttribute("VNCProxyPassword", - _cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, _encryptionKey)) - : new XAttribute("VNCProxyPassword", "")); + ? new XAttribute("VNCProxyPassword", + _cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, + _encryptionKey)) + : new XAttribute("VNCProxyPassword", "")); element.Add(new XAttribute("VNCColors", connectionInfo.VNCColors)); element.Add(new XAttribute("VNCSmartSizeMode", connectionInfo.VNCSmartSizeMode)); element.Add(new XAttribute("VNCViewOnly", connectionInfo.VNCViewOnly.ToString().ToLowerInvariant())); element.Add(new XAttribute("RDGatewayUsageMethod", connectionInfo.RDGatewayUsageMethod)); element.Add(new XAttribute("RDGatewayHostname", connectionInfo.RDGatewayHostname)); - element.Add(new XAttribute("RDGatewayUseConnectionCredentials", connectionInfo.RDGatewayUseConnectionCredentials)); + element.Add(new XAttribute("RDGatewayUseConnectionCredentials", + connectionInfo.RDGatewayUseConnectionCredentials)); element.Add(_saveFilter.SaveUsername - ? new XAttribute("RDGatewayUsername", connectionInfo.RDGatewayUsername) - : new XAttribute("RDGatewayUsername", "")); + ? new XAttribute("RDGatewayUsername", connectionInfo.RDGatewayUsername) + : new XAttribute("RDGatewayUsername", "")); element.Add(_saveFilter.SavePassword - ? new XAttribute("RDGatewayPassword", - _cryptographyProvider.Encrypt(connectionInfo.RDGatewayPassword, _encryptionKey)) - : new XAttribute("RDGatewayPassword", "")); + ? new XAttribute("RDGatewayPassword", + _cryptographyProvider.Encrypt(connectionInfo.RDGatewayPassword, + _encryptionKey)) + : new XAttribute("RDGatewayPassword", "")); element.Add(_saveFilter.SaveDomain - ? new XAttribute("RDGatewayDomain", connectionInfo.RDGatewayDomain) - : new XAttribute("RDGatewayDomain", "")); + ? new XAttribute("RDGatewayDomain", connectionInfo.RDGatewayDomain) + : new XAttribute("RDGatewayDomain", "")); } private void SetInheritanceAttributes(XContainer element, IInheritable connectionInfo) { if (_saveFilter.SaveInheritance) { - element.Add(new XAttribute("InheritCacheBitmaps", connectionInfo.Inheritance.CacheBitmaps.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritColors", connectionInfo.Inheritance.Colors.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritDescription", connectionInfo.Inheritance.Description.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritDisplayThemes", connectionInfo.Inheritance.DisplayThemes.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritDisplayWallpaper", connectionInfo.Inheritance.DisplayWallpaper.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritEnableFontSmoothing", connectionInfo.Inheritance.EnableFontSmoothing.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritEnableDesktopComposition", connectionInfo.Inheritance.EnableDesktopComposition.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritDomain", connectionInfo.Inheritance.Domain.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritIcon", connectionInfo.Inheritance.Icon.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritPanel", connectionInfo.Inheritance.Panel.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritPassword", connectionInfo.Inheritance.Password.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritPort", connectionInfo.Inheritance.Port.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritProtocol", connectionInfo.Inheritance.Protocol.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritPuttySession", connectionInfo.Inheritance.PuttySession.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRedirectDiskDrives", connectionInfo.Inheritance.RedirectDiskDrives.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRedirectKeys", connectionInfo.Inheritance.RedirectKeys.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRedirectPorts", connectionInfo.Inheritance.RedirectPorts.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRedirectPrinters", connectionInfo.Inheritance.RedirectPrinters.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRedirectSmartCards", connectionInfo.Inheritance.RedirectSmartCards.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRedirectSound", connectionInfo.Inheritance.RedirectSound.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritSoundQuality", connectionInfo.Inheritance.SoundQuality.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritResolution", connectionInfo.Inheritance.Resolution.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritAutomaticResize", connectionInfo.Inheritance.AutomaticResize.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritUseConsoleSession", connectionInfo.Inheritance.UseConsoleSession.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritUseCredSsp", connectionInfo.Inheritance.UseCredSsp.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRenderingEngine", connectionInfo.Inheritance.RenderingEngine.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritUsername", connectionInfo.Inheritance.Username.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritICAEncryptionStrength", connectionInfo.Inheritance.ICAEncryptionStrength.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDPAuthenticationLevel", connectionInfo.Inheritance.RDPAuthenticationLevel.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDPMinutesToIdleTimeout", connectionInfo.Inheritance.RDPMinutesToIdleTimeout.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDPAlertIdleTimeout", connectionInfo.Inheritance.RDPAlertIdleTimeout.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritLoadBalanceInfo", connectionInfo.Inheritance.LoadBalanceInfo.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritPreExtApp", connectionInfo.Inheritance.PreExtApp.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritPostExtApp", connectionInfo.Inheritance.PostExtApp.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritMacAddress", connectionInfo.Inheritance.MacAddress.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritUserField", connectionInfo.Inheritance.UserField.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritExtApp", connectionInfo.Inheritance.ExtApp.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCCompression", connectionInfo.Inheritance.VNCCompression.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCEncoding", connectionInfo.Inheritance.VNCEncoding.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCAuthMode", connectionInfo.Inheritance.VNCAuthMode.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCProxyType", connectionInfo.Inheritance.VNCProxyType.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCProxyIP", connectionInfo.Inheritance.VNCProxyIP.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCProxyPort", connectionInfo.Inheritance.VNCProxyPort.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCProxyUsername", connectionInfo.Inheritance.VNCProxyUsername.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCProxyPassword", connectionInfo.Inheritance.VNCProxyPassword.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCColors", connectionInfo.Inheritance.VNCColors.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCSmartSizeMode", connectionInfo.Inheritance.VNCSmartSizeMode.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritVNCViewOnly", connectionInfo.Inheritance.VNCViewOnly.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDGatewayUsageMethod", connectionInfo.Inheritance.RDGatewayUsageMethod.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDGatewayHostname", connectionInfo.Inheritance.RDGatewayHostname.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDGatewayUseConnectionCredentials", connectionInfo.Inheritance.RDGatewayUseConnectionCredentials.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDGatewayUsername", connectionInfo.Inheritance.RDGatewayUsername.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDGatewayPassword", connectionInfo.Inheritance.RDGatewayPassword.ToString().ToLowerInvariant())); - element.Add(new XAttribute("InheritRDGatewayDomain", connectionInfo.Inheritance.RDGatewayDomain.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritCacheBitmaps", + connectionInfo.Inheritance.CacheBitmaps.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritColors", + connectionInfo.Inheritance.Colors.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritDescription", + connectionInfo.Inheritance.Description.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritDisplayThemes", + connectionInfo.Inheritance.DisplayThemes.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritDisplayWallpaper", + connectionInfo.Inheritance.DisplayWallpaper.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritEnableFontSmoothing", + connectionInfo + .Inheritance.EnableFontSmoothing.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritEnableDesktopComposition", + connectionInfo + .Inheritance.EnableDesktopComposition.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritDomain", + connectionInfo.Inheritance.Domain.ToString().ToLowerInvariant())); + element.Add( + new XAttribute("InheritIcon", + connectionInfo.Inheritance.Icon.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritPanel", + connectionInfo.Inheritance.Panel.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritPassword", + connectionInfo.Inheritance.Password.ToString().ToLowerInvariant())); + element.Add( + new XAttribute("InheritPort", + connectionInfo.Inheritance.Port.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritProtocol", + connectionInfo.Inheritance.Protocol.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritPuttySession", + connectionInfo.Inheritance.PuttySession.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRedirectDiskDrives", + connectionInfo + .Inheritance.RedirectDiskDrives.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRedirectKeys", + connectionInfo.Inheritance.RedirectKeys.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRedirectPorts", + connectionInfo.Inheritance.RedirectPorts.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRedirectPrinters", + connectionInfo.Inheritance.RedirectPrinters.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRedirectSmartCards", + connectionInfo + .Inheritance.RedirectSmartCards.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRedirectSound", + connectionInfo.Inheritance.RedirectSound.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritSoundQuality", + connectionInfo.Inheritance.SoundQuality.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritResolution", + connectionInfo.Inheritance.Resolution.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritAutomaticResize", + connectionInfo.Inheritance.AutomaticResize.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritUseConsoleSession", + connectionInfo.Inheritance.UseConsoleSession.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritUseCredSsp", + connectionInfo.Inheritance.UseCredSsp.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRenderingEngine", + connectionInfo.Inheritance.RenderingEngine.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritUsername", + connectionInfo.Inheritance.Username.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritICAEncryptionStrength", + connectionInfo + .Inheritance.ICAEncryptionStrength.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDPAuthenticationLevel", + connectionInfo + .Inheritance.RDPAuthenticationLevel.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDPMinutesToIdleTimeout", + connectionInfo + .Inheritance.RDPMinutesToIdleTimeout.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDPAlertIdleTimeout", + connectionInfo + .Inheritance.RDPAlertIdleTimeout.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritLoadBalanceInfo", + connectionInfo.Inheritance.LoadBalanceInfo.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritPreExtApp", + connectionInfo.Inheritance.PreExtApp.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritPostExtApp", + connectionInfo.Inheritance.PostExtApp.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritMacAddress", + connectionInfo.Inheritance.MacAddress.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritUserField", + connectionInfo.Inheritance.UserField.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritExtApp", + connectionInfo.Inheritance.ExtApp.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCCompression", + connectionInfo.Inheritance.VNCCompression.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCEncoding", + connectionInfo.Inheritance.VNCEncoding.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCAuthMode", + connectionInfo.Inheritance.VNCAuthMode.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCProxyType", + connectionInfo.Inheritance.VNCProxyType.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCProxyIP", + connectionInfo.Inheritance.VNCProxyIP.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCProxyPort", + connectionInfo.Inheritance.VNCProxyPort.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCProxyUsername", + connectionInfo.Inheritance.VNCProxyUsername.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCProxyPassword", + connectionInfo.Inheritance.VNCProxyPassword.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCColors", + connectionInfo.Inheritance.VNCColors.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCSmartSizeMode", + connectionInfo.Inheritance.VNCSmartSizeMode.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritVNCViewOnly", + connectionInfo.Inheritance.VNCViewOnly.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDGatewayUsageMethod", + connectionInfo + .Inheritance.RDGatewayUsageMethod.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDGatewayHostname", + connectionInfo.Inheritance.RDGatewayHostname.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDGatewayUseConnectionCredentials", + connectionInfo + .Inheritance.RDGatewayUseConnectionCredentials.ToString() + .ToLowerInvariant())); + element.Add(new XAttribute("InheritRDGatewayUsername", + connectionInfo.Inheritance.RDGatewayUsername.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDGatewayPassword", + connectionInfo.Inheritance.RDGatewayPassword.ToString().ToLowerInvariant())); + element.Add(new XAttribute("InheritRDGatewayDomain", + connectionInfo.Inheritance.RDGatewayDomain.ToString().ToLowerInvariant())); } else { @@ -214,7 +298,7 @@ namespace mRemoteNG.Config.Serializers.Xml element.Add(new XAttribute("InheritRedirectDiskDrives", falseString)); element.Add(new XAttribute("InheritRedirectKeys", falseString)); element.Add(new XAttribute("InheritRedirectPorts", falseString)); - element.Add(new XAttribute("InheritRedirectPrinters", falseString)); + element.Add(new XAttribute("InheritRedirectPrinters", falseString)); element.Add(new XAttribute("InheritRedirectSmartCards", falseString)); element.Add(new XAttribute("InheritRedirectSound", falseString)); element.Add(new XAttribute("InheritSoundQuality", falseString)); diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs index 10b231d1..c86d3a45 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionNodeSerializer27.cs @@ -10,7 +10,7 @@ using mRemoteNG.Tools; namespace mRemoteNG.Config.Serializers.Xml { // ReSharper disable once InconsistentNaming - public class XmlConnectionNodeSerializer27 : ISerializer + public class XmlConnectionNodeSerializer27 : ISerializer { private readonly ICryptographyProvider _cryptographyProvider; private readonly SecureString _encryptionKey; @@ -18,7 +18,9 @@ namespace mRemoteNG.Config.Serializers.Xml public Version Version { get; } = new Version(2, 7); - public XmlConnectionNodeSerializer27(ICryptographyProvider cryptographyProvider, SecureString encryptionKey, SaveFilter saveFilter) + public XmlConnectionNodeSerializer27(ICryptographyProvider cryptographyProvider, + SecureString encryptionKey, + SaveFilter saveFilter) { _cryptographyProvider = cryptographyProvider.ThrowIfNull(nameof(cryptographyProvider)); _encryptionKey = encryptionKey.ThrowIfNull(nameof(encryptionKey)); @@ -50,31 +52,42 @@ namespace mRemoteNG.Config.Serializers.Xml element.Add(new XAttribute("Protocol", connectionInfo.Protocol)); element.Add(new XAttribute("PuttySession", connectionInfo.PuttySession)); element.Add(new XAttribute("Port", connectionInfo.Port)); - element.Add(new XAttribute("ConnectToConsole", connectionInfo.UseConsoleSession.ToString().ToLowerInvariant())); + element.Add(new XAttribute("ConnectToConsole", + connectionInfo.UseConsoleSession.ToString().ToLowerInvariant())); element.Add(new XAttribute("UseCredSsp", connectionInfo.UseCredSsp.ToString().ToLowerInvariant())); element.Add(new XAttribute("RenderingEngine", connectionInfo.RenderingEngine)); element.Add(new XAttribute("ICAEncryptionStrength", connectionInfo.ICAEncryptionStrength)); element.Add(new XAttribute("RDPAuthenticationLevel", connectionInfo.RDPAuthenticationLevel)); element.Add(new XAttribute("RDPMinutesToIdleTimeout", connectionInfo.RDPMinutesToIdleTimeout)); - element.Add(new XAttribute("RDPAlertIdleTimeout", connectionInfo.RDPAlertIdleTimeout.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RDPAlertIdleTimeout", + connectionInfo.RDPAlertIdleTimeout.ToString().ToLowerInvariant())); element.Add(new XAttribute("LoadBalanceInfo", connectionInfo.LoadBalanceInfo)); element.Add(new XAttribute("Colors", connectionInfo.Colors)); element.Add(new XAttribute("Resolution", connectionInfo.Resolution)); - element.Add(new XAttribute("AutomaticResize", connectionInfo.AutomaticResize.ToString().ToLowerInvariant())); - element.Add(new XAttribute("DisplayWallpaper", connectionInfo.DisplayWallpaper.ToString().ToLowerInvariant())); + element.Add(new XAttribute("AutomaticResize", + connectionInfo.AutomaticResize.ToString().ToLowerInvariant())); + element.Add(new XAttribute("DisplayWallpaper", + connectionInfo.DisplayWallpaper.ToString().ToLowerInvariant())); element.Add(new XAttribute("DisplayThemes", connectionInfo.DisplayThemes.ToString().ToLowerInvariant())); - element.Add(new XAttribute("EnableFontSmoothing", connectionInfo.EnableFontSmoothing.ToString().ToLowerInvariant())); - element.Add(new XAttribute("EnableDesktopComposition", connectionInfo.EnableDesktopComposition.ToString().ToLowerInvariant())); + element.Add(new XAttribute("EnableFontSmoothing", + connectionInfo.EnableFontSmoothing.ToString().ToLowerInvariant())); + element.Add(new XAttribute("EnableDesktopComposition", + connectionInfo.EnableDesktopComposition.ToString().ToLowerInvariant())); element.Add(new XAttribute("CacheBitmaps", connectionInfo.CacheBitmaps.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectDiskDrives", connectionInfo.RedirectDiskDrives.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectDiskDrives", + connectionInfo.RedirectDiskDrives.ToString().ToLowerInvariant())); element.Add(new XAttribute("RedirectPorts", connectionInfo.RedirectPorts.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectPrinters", connectionInfo.RedirectPrinters.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectClipboard", connectionInfo.RedirectClipboard.ToString().ToLowerInvariant())); - element.Add(new XAttribute("RedirectSmartCards", connectionInfo.RedirectSmartCards.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectPrinters", + connectionInfo.RedirectPrinters.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectClipboard", + connectionInfo.RedirectClipboard.ToString().ToLowerInvariant())); + element.Add(new XAttribute("RedirectSmartCards", + connectionInfo.RedirectSmartCards.ToString().ToLowerInvariant())); element.Add(new XAttribute("RedirectSound", connectionInfo.RedirectSound.ToString())); element.Add(new XAttribute("SoundQuality", connectionInfo.SoundQuality.ToString())); element.Add(new XAttribute("RedirectKeys", connectionInfo.RedirectKeys.ToString().ToLowerInvariant())); - element.Add(new XAttribute("Connected", (connectionInfo.OpenConnections.Count > 0).ToString().ToLowerInvariant())); + element.Add(new XAttribute("Connected", + (connectionInfo.OpenConnections.Count > 0).ToString().ToLowerInvariant())); element.Add(new XAttribute("PreExtApp", connectionInfo.PreExtApp)); element.Add(new XAttribute("PostExtApp", connectionInfo.PostExtApp)); element.Add(new XAttribute("MacAddress", connectionInfo.MacAddress)); @@ -88,33 +101,36 @@ namespace mRemoteNG.Config.Serializers.Xml element.Add(new XAttribute("VNCProxyPort", connectionInfo.VNCProxyPort)); element.Add(_saveFilter.SaveUsername - ? new XAttribute("VNCProxyUsername", connectionInfo.VNCProxyUsername) - : new XAttribute("VNCProxyUsername", "")); + ? new XAttribute("VNCProxyUsername", connectionInfo.VNCProxyUsername) + : new XAttribute("VNCProxyUsername", "")); element.Add(_saveFilter.SavePassword - ? new XAttribute("VNCProxyPassword", - _cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, _encryptionKey)) - : new XAttribute("VNCProxyPassword", "")); + ? new XAttribute("VNCProxyPassword", + _cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, + _encryptionKey)) + : new XAttribute("VNCProxyPassword", "")); element.Add(new XAttribute("VNCColors", connectionInfo.VNCColors)); element.Add(new XAttribute("VNCSmartSizeMode", connectionInfo.VNCSmartSizeMode)); element.Add(new XAttribute("VNCViewOnly", connectionInfo.VNCViewOnly.ToString().ToLowerInvariant())); element.Add(new XAttribute("RDGatewayUsageMethod", connectionInfo.RDGatewayUsageMethod)); element.Add(new XAttribute("RDGatewayHostname", connectionInfo.RDGatewayHostname)); - element.Add(new XAttribute("RDGatewayUseConnectionCredentials", connectionInfo.RDGatewayUseConnectionCredentials)); + element.Add(new XAttribute("RDGatewayUseConnectionCredentials", + connectionInfo.RDGatewayUseConnectionCredentials)); element.Add(_saveFilter.SaveUsername - ? new XAttribute("RDGatewayUsername", connectionInfo.RDGatewayUsername) - : new XAttribute("RDGatewayUsername", "")); + ? new XAttribute("RDGatewayUsername", connectionInfo.RDGatewayUsername) + : new XAttribute("RDGatewayUsername", "")); element.Add(_saveFilter.SavePassword - ? new XAttribute("RDGatewayPassword", - _cryptographyProvider.Encrypt(connectionInfo.RDGatewayPassword, _encryptionKey)) - : new XAttribute("RDGatewayPassword", "")); + ? new XAttribute("RDGatewayPassword", + _cryptographyProvider.Encrypt(connectionInfo.RDGatewayPassword, + _encryptionKey)) + : new XAttribute("RDGatewayPassword", "")); element.Add(_saveFilter.SaveDomain - ? new XAttribute("RDGatewayDomain", connectionInfo.RDGatewayDomain) - : new XAttribute("RDGatewayDomain", "")); + ? new XAttribute("RDGatewayDomain", connectionInfo.RDGatewayDomain) + : new XAttribute("RDGatewayDomain", "")); } private void SetInheritanceAttributes(XContainer element, IInheritable connectionInfo) @@ -194,8 +210,8 @@ namespace mRemoteNG.Config.Serializers.Xml element.Add(new XAttribute("InheritRedirectDiskDrives", falseString)); element.Add(new XAttribute("InheritRedirectKeys", falseString)); element.Add(new XAttribute("InheritRedirectPorts", falseString)); - element.Add(new XAttribute("InheritRedirectPrinters", falseString)); - element.Add(new XAttribute("InheritRedirectClipboard", falseString)); + element.Add(new XAttribute("InheritRedirectPrinters", falseString)); + element.Add(new XAttribute("InheritRedirectClipboard", falseString)); element.Add(new XAttribute("InheritRedirectSmartCards", falseString)); element.Add(new XAttribute("InheritRedirectSound", falseString)); element.Add(new XAttribute("InheritSoundQuality", falseString)); diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs index a9b7cebd..a59e97fc 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDeserializer.cs @@ -101,7 +101,9 @@ namespace mRemoteNG.Config.Serializers.Xml private void ValidateConnectionFileVersion() { if (_xmlDocument.DocumentElement != null && _xmlDocument.DocumentElement.HasAttribute("ConfVersion")) - _confVersion = Convert.ToDouble(_xmlDocument.DocumentElement.Attributes["ConfVersion"].Value.Replace(",", "."), CultureInfo.InvariantCulture); + _confVersion = + Convert.ToDouble(_xmlDocument.DocumentElement.Attributes["ConfVersion"].Value.Replace(",", "."), + CultureInfo.InvariantCulture); else Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, Language.strOldConffile); @@ -113,19 +115,22 @@ namespace mRemoteNG.Config.Serializers.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 - ); + 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 RootNodeInfo InitializeRootNode(XmlElement connectionsRootElement) @@ -179,7 +184,7 @@ namespace mRemoteNG.Config.Serializers.Xml break; case TreeNodeType.Container: var containerInfo = new ContainerInfo(); - + if (_confVersion >= 0.9) containerInfo.CopyFrom(GetConnectionInfoFromXml(xmlNode, credentialMap)); if (_confVersion >= 0.8) @@ -208,10 +213,10 @@ namespace mRemoteNG.Config.Serializers.Xml if (xmlnode?.Attributes == null) return null; - var connectionId = xmlnode.GetAttributeAsString("Id"); + var connectionId = xmlnode.GetAttributeAsString("Id"); if (string.IsNullOrWhiteSpace(connectionId)) connectionId = Guid.NewGuid().ToString(); - var connectionInfo = new ConnectionInfo(connectionId); + var connectionInfo = new ConnectionInfo(connectionId); try { @@ -274,7 +279,7 @@ namespace mRemoteNG.Config.Serializers.Xml { if (_confVersion < 0.7) { - connectionInfo.Port = xmlnode.GetAttributeAsBool("UseVNC") + connectionInfo.Port = xmlnode.GetAttributeAsBool("UseVNC") ? xmlnode.GetAttributeAsInt("VNCPort") : xmlnode.GetAttributeAsInt("RDPPort"); } @@ -290,6 +295,7 @@ namespace mRemoteNG.Config.Serializers.Xml else connectionInfo.Port = (int)RdpProtocol.Defaults.Port; } + connectionInfo.UseConsoleSession = false; } @@ -303,7 +309,7 @@ namespace mRemoteNG.Config.Serializers.Xml else { connectionInfo.RedirectDiskDrives = false; - connectionInfo.RedirectPrinters = false; + connectionInfo.RedirectPrinters = false; connectionInfo.RedirectPorts = false; connectionInfo.RedirectSmartCards = false; } @@ -368,14 +374,17 @@ namespace mRemoteNG.Config.Serializers.Xml connectionInfo.Inheritance.Port = xmlnode.GetAttributeAsBool("InheritPort"); connectionInfo.Inheritance.Protocol = xmlnode.GetAttributeAsBool("InheritProtocol"); connectionInfo.Inheritance.PuttySession = xmlnode.GetAttributeAsBool("InheritPuttySession"); - connectionInfo.Inheritance.RedirectDiskDrives = xmlnode.GetAttributeAsBool("InheritRedirectDiskDrives"); + connectionInfo.Inheritance.RedirectDiskDrives = + xmlnode.GetAttributeAsBool("InheritRedirectDiskDrives"); connectionInfo.Inheritance.RedirectKeys = xmlnode.GetAttributeAsBool("InheritRedirectKeys"); connectionInfo.Inheritance.RedirectPorts = xmlnode.GetAttributeAsBool("InheritRedirectPorts"); connectionInfo.Inheritance.RedirectPrinters = xmlnode.GetAttributeAsBool("InheritRedirectPrinters"); - connectionInfo.Inheritance.RedirectSmartCards = xmlnode.GetAttributeAsBool("InheritRedirectSmartCards"); + connectionInfo.Inheritance.RedirectSmartCards = + xmlnode.GetAttributeAsBool("InheritRedirectSmartCards"); connectionInfo.Inheritance.RedirectSound = xmlnode.GetAttributeAsBool("InheritRedirectSound"); connectionInfo.Inheritance.Resolution = xmlnode.GetAttributeAsBool("InheritResolution"); - connectionInfo.Inheritance.UseConsoleSession = xmlnode.GetAttributeAsBool("InheritUseConsoleSession"); + connectionInfo.Inheritance.UseConsoleSession = + xmlnode.GetAttributeAsBool("InheritUseConsoleSession"); if (!Runtime.UseCredentialManager || _confVersion <= 2.6) // 1.3 - 2.6 { @@ -383,6 +392,7 @@ namespace mRemoteNG.Config.Serializers.Xml connectionInfo.Inheritance.Password = xmlnode.GetAttributeAsBool("InheritPassword"); connectionInfo.Inheritance.Username = xmlnode.GetAttributeAsBool("InheritUsername"); } + connectionInfo.Icon = xmlnode.GetAttributeAsString("Icon"); connectionInfo.Panel = xmlnode.GetAttributeAsString("Panel"); } @@ -401,8 +411,10 @@ namespace mRemoteNG.Config.Serializers.Xml if (_confVersion >= 1.6) { - connectionInfo.ICAEncryptionStrength = xmlnode.GetAttributeAsEnum("ICAEncryptionStrength"); - connectionInfo.Inheritance.ICAEncryptionStrength = xmlnode.GetAttributeAsBool("InheritICAEncryptionStrength"); + connectionInfo.ICAEncryptionStrength = + xmlnode.GetAttributeAsEnum("ICAEncryptionStrength"); + connectionInfo.Inheritance.ICAEncryptionStrength = + xmlnode.GetAttributeAsBool("InheritICAEncryptionStrength"); connectionInfo.PreExtApp = xmlnode.GetAttributeAsString("PreExtApp"); connectionInfo.PostExtApp = xmlnode.GetAttributeAsString("PostExtApp"); connectionInfo.Inheritance.PreExtApp = xmlnode.GetAttributeAsBool("InheritPreExtApp"); @@ -411,16 +423,19 @@ namespace mRemoteNG.Config.Serializers.Xml if (_confVersion >= 1.7) { - connectionInfo.VNCCompression = xmlnode.GetAttributeAsEnum("VNCCompression"); + connectionInfo.VNCCompression = + xmlnode.GetAttributeAsEnum("VNCCompression"); connectionInfo.VNCEncoding = xmlnode.GetAttributeAsEnum("VNCEncoding"); connectionInfo.VNCAuthMode = xmlnode.GetAttributeAsEnum("VNCAuthMode"); connectionInfo.VNCProxyType = xmlnode.GetAttributeAsEnum("VNCProxyType"); connectionInfo.VNCProxyIP = xmlnode.GetAttributeAsString("VNCProxyIP"); connectionInfo.VNCProxyPort = xmlnode.GetAttributeAsInt("VNCProxyPort"); connectionInfo.VNCProxyUsername = xmlnode.GetAttributeAsString("VNCProxyUsername"); - connectionInfo.VNCProxyPassword = _decryptor.Decrypt(xmlnode.GetAttributeAsString("VNCProxyPassword")); + connectionInfo.VNCProxyPassword = + _decryptor.Decrypt(xmlnode.GetAttributeAsString("VNCProxyPassword")); connectionInfo.VNCColors = xmlnode.GetAttributeAsEnum("VNCColors"); - connectionInfo.VNCSmartSizeMode = xmlnode.GetAttributeAsEnum("VNCSmartSizeMode"); + connectionInfo.VNCSmartSizeMode = + xmlnode.GetAttributeAsEnum("VNCSmartSizeMode"); connectionInfo.VNCViewOnly = xmlnode.GetAttributeAsBool("VNCViewOnly"); connectionInfo.Inheritance.VNCCompression = xmlnode.GetAttributeAsBool("InheritVNCCompression"); connectionInfo.Inheritance.VNCEncoding = xmlnode.GetAttributeAsBool("InheritVNCEncoding"); @@ -437,13 +452,16 @@ namespace mRemoteNG.Config.Serializers.Xml if (_confVersion >= 1.8) { - connectionInfo.RDPAuthenticationLevel = xmlnode.GetAttributeAsEnum("RDPAuthenticationLevel"); - connectionInfo.Inheritance.RDPAuthenticationLevel = xmlnode.GetAttributeAsBool("InheritRDPAuthenticationLevel"); + connectionInfo.RDPAuthenticationLevel = + xmlnode.GetAttributeAsEnum("RDPAuthenticationLevel"); + connectionInfo.Inheritance.RDPAuthenticationLevel = + xmlnode.GetAttributeAsBool("InheritRDPAuthenticationLevel"); } if (_confVersion >= 1.9) { - connectionInfo.RenderingEngine = xmlnode.GetAttributeAsEnum("RenderingEngine"); + connectionInfo.RenderingEngine = + xmlnode.GetAttributeAsEnum("RenderingEngine"); connectionInfo.MacAddress = xmlnode.GetAttributeAsString("MacAddress"); connectionInfo.Inheritance.RenderingEngine = xmlnode.GetAttributeAsBool("InheritRenderingEngine"); connectionInfo.Inheritance.MacAddress = xmlnode.GetAttributeAsBool("InheritMacAddress"); @@ -464,19 +482,28 @@ namespace mRemoteNG.Config.Serializers.Xml if (_confVersion >= 2.2) { // Get settings - connectionInfo.RDGatewayUsageMethod = xmlnode.GetAttributeAsEnum("RDGatewayUsageMethod"); + connectionInfo.RDGatewayUsageMethod = + xmlnode.GetAttributeAsEnum("RDGatewayUsageMethod"); connectionInfo.RDGatewayHostname = xmlnode.GetAttributeAsString("RDGatewayHostname"); - connectionInfo.RDGatewayUseConnectionCredentials = xmlnode.GetAttributeAsEnum("RDGatewayUseConnectionCredentials"); + connectionInfo.RDGatewayUseConnectionCredentials = + xmlnode.GetAttributeAsEnum( + "RDGatewayUseConnectionCredentials"); connectionInfo.RDGatewayUsername = xmlnode.GetAttributeAsString("RDGatewayUsername"); - connectionInfo.RDGatewayPassword = _decryptor.Decrypt(xmlnode.GetAttributeAsString("RDGatewayPassword")); + connectionInfo.RDGatewayPassword = + _decryptor.Decrypt(xmlnode.GetAttributeAsString("RDGatewayPassword")); connectionInfo.RDGatewayDomain = xmlnode.GetAttributeAsString("RDGatewayDomain"); // Get inheritance settings - connectionInfo.Inheritance.RDGatewayUsageMethod = xmlnode.GetAttributeAsBool("InheritRDGatewayUsageMethod"); - connectionInfo.Inheritance.RDGatewayHostname = xmlnode.GetAttributeAsBool("InheritRDGatewayHostname"); - connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = xmlnode.GetAttributeAsBool("InheritRDGatewayUseConnectionCredentials"); - connectionInfo.Inheritance.RDGatewayUsername = xmlnode.GetAttributeAsBool("InheritRDGatewayUsername"); - connectionInfo.Inheritance.RDGatewayPassword = xmlnode.GetAttributeAsBool("InheritRDGatewayPassword"); + connectionInfo.Inheritance.RDGatewayUsageMethod = + xmlnode.GetAttributeAsBool("InheritRDGatewayUsageMethod"); + connectionInfo.Inheritance.RDGatewayHostname = + xmlnode.GetAttributeAsBool("InheritRDGatewayHostname"); + connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = + xmlnode.GetAttributeAsBool("InheritRDGatewayUseConnectionCredentials"); + connectionInfo.Inheritance.RDGatewayUsername = + xmlnode.GetAttributeAsBool("InheritRDGatewayUsername"); + connectionInfo.Inheritance.RDGatewayPassword = + xmlnode.GetAttributeAsBool("InheritRDGatewayPassword"); connectionInfo.Inheritance.RDGatewayDomain = xmlnode.GetAttributeAsBool("InheritRDGatewayDomain"); } @@ -487,8 +514,10 @@ namespace mRemoteNG.Config.Serializers.Xml connectionInfo.EnableDesktopComposition = xmlnode.GetAttributeAsBool("EnableDesktopComposition"); // Get inheritance settings - connectionInfo.Inheritance.EnableFontSmoothing = xmlnode.GetAttributeAsBool("InheritEnableFontSmoothing"); - connectionInfo.Inheritance.EnableDesktopComposition = xmlnode.GetAttributeAsBool("InheritEnableDesktopComposition"); + connectionInfo.Inheritance.EnableFontSmoothing = + xmlnode.GetAttributeAsBool("InheritEnableFontSmoothing"); + connectionInfo.Inheritance.EnableDesktopComposition = + xmlnode.GetAttributeAsBool("InheritEnableDesktopComposition"); } if (_confVersion >= 2.4) @@ -507,14 +536,18 @@ namespace mRemoteNG.Config.Serializers.Xml if (_confVersion >= 2.6) { - connectionInfo.SoundQuality = xmlnode.GetAttributeAsEnum("SoundQuality"); + connectionInfo.SoundQuality = + xmlnode.GetAttributeAsEnum("SoundQuality"); connectionInfo.Inheritance.SoundQuality = xmlnode.GetAttributeAsBool("InheritSoundQuality"); connectionInfo.RDPMinutesToIdleTimeout = xmlnode.GetAttributeAsInt("RDPMinutesToIdleTimeout"); - connectionInfo.Inheritance.RDPMinutesToIdleTimeout = xmlnode.GetAttributeAsBool("InheritRDPMinutesToIdleTimeout"); + connectionInfo.Inheritance.RDPMinutesToIdleTimeout = + xmlnode.GetAttributeAsBool("InheritRDPMinutesToIdleTimeout"); connectionInfo.RDPAlertIdleTimeout = xmlnode.GetAttributeAsBool("RDPAlertIdleTimeout"); - connectionInfo.Inheritance.RDPAlertIdleTimeout = xmlnode.GetAttributeAsBool("InheritRDPAlertIdleTimeout"); + connectionInfo.Inheritance.RDPAlertIdleTimeout = + xmlnode.GetAttributeAsBool("InheritRDPAlertIdleTimeout"); } - if(_confVersion >= 2.7) + + if (_confVersion >= 2.7) { connectionInfo.RedirectClipboard = xmlnode.GetAttributeAsBool("RedirectClipboard"); connectionInfo.Inheritance.RedirectClipboard = xmlnode.GetAttributeAsBool("InheritRedirectClipboard"); @@ -528,7 +561,10 @@ namespace mRemoteNG.Config.Serializers.Xml } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strGetConnectionInfoFromXmlFailed, connectionInfo.Name, ConnectionFileName, ex.Message)); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + string.Format(Language.strGetConnectionInfoFromXmlFailed, + connectionInfo.Name, ConnectionFileName, + ex.Message)); } return connectionInfo; diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs index 95c35d4b..acdde98c 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsDocumentCompiler.cs @@ -16,7 +16,8 @@ namespace mRemoteNG.Config.Serializers.Xml private SecureString _encryptionKey; private readonly ISerializer _connectionNodeSerializer; - public XmlConnectionsDocumentCompiler(ICryptographyProvider cryptographyProvider, ISerializer connectionNodeSerializer) + public XmlConnectionsDocumentCompiler(ICryptographyProvider cryptographyProvider, + ISerializer connectionNodeSerializer) { if (cryptographyProvider == null) throw new ArgumentNullException(nameof(cryptographyProvider)); @@ -43,7 +44,9 @@ namespace mRemoteNG.Config.Serializers.Xml var xmlDeclaration = new XDeclaration("1.0", "utf-8", null); var xmlDocument = new XDocument(xmlDeclaration, rootElement); if (fullFileEncryption) - xmlDocument = new XmlConnectionsDocumentEncryptor(_cryptographyProvider).EncryptDocument(xmlDocument, _encryptionKey); + xmlDocument = + new XmlConnectionsDocumentEncryptor(_cryptographyProvider).EncryptDocument(xmlDocument, + _encryptionKey); return xmlDocument; } @@ -55,6 +58,7 @@ namespace mRemoteNG.Config.Serializers.Xml newElement = CompileConnectionInfoNode(serializationTarget); parentElement.Add(newElement); } + var serializationTargetAsContainer = serializationTarget as ContainerInfo; if (serializationTargetAsContainer == null) return; foreach (var child in serializationTargetAsContainer.Children) @@ -79,7 +83,8 @@ namespace mRemoteNG.Config.Serializers.Xml private XElement CompileRootNode(RootNodeInfo rootNodeInfo, bool fullFileEncryption) { var rootNodeSerializer = new XmlRootNodeSerializer(); - return rootNodeSerializer.SerializeRootNodeInfo(rootNodeInfo, _cryptographyProvider, _connectionNodeSerializer.Version, fullFileEncryption); + return rootNodeSerializer.SerializeRootNodeInfo(rootNodeInfo, _cryptographyProvider, + _connectionNodeSerializer.Version, fullFileEncryption); } private XElement CompileConnectionInfoNode(ConnectionInfo connectionInfo) diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs index 4ad97746..ee372c79 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlConnectionsSerializer.cs @@ -20,7 +20,8 @@ namespace mRemoteNG.Config.Serializers.Xml public Version Version => _connectionNodeSerializer.Version; public bool UseFullEncryption { get; set; } - public XmlConnectionsSerializer(ICryptographyProvider cryptographyProvider, ISerializer connectionNodeSerializer) + public XmlConnectionsSerializer(ICryptographyProvider cryptographyProvider, + ISerializer connectionNodeSerializer) { _cryptographyProvider = cryptographyProvider; _connectionNodeSerializer = connectionNodeSerializer; @@ -42,7 +43,8 @@ namespace mRemoteNG.Config.Serializers.Xml var xml = ""; try { - var documentCompiler = new XmlConnectionsDocumentCompiler(_cryptographyProvider, _connectionNodeSerializer); + var documentCompiler = + new XmlConnectionsDocumentCompiler(_cryptographyProvider, _connectionNodeSerializer); var xmlDocument = documentCompiler.CompileDocument(serializationTarget, UseFullEncryption); xml = WriteXmlToString(xmlDocument); } @@ -50,13 +52,15 @@ namespace mRemoteNG.Config.Serializers.Xml { Runtime.MessageCollector.AddExceptionStackTrace("SaveToXml failed", ex); } + return xml; } private static string WriteXmlToString(XNode xmlDocument) { string xmlString; - var xmlWriterSettings = new XmlWriterSettings { Indent = true, IndentChars = " ", Encoding = Encoding.UTF8 }; + var xmlWriterSettings = new XmlWriterSettings + {Indent = true, IndentChars = " ", Encoding = Encoding.UTF8}; var memoryStream = new MemoryStream(); using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings)) { @@ -66,6 +70,7 @@ namespace mRemoteNG.Config.Serializers.Xml memoryStream.Seek(0, SeekOrigin.Begin); xmlString = streamReader.ReadToEnd(); } + return xmlString; } } diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs index 71ecbff7..06520b1c 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlExtensions.cs @@ -17,7 +17,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml if (string.IsNullOrWhiteSpace(value)) return defaultValue; - return bool.TryParse(value, out var valueAsBool) + return bool.TryParse(value, out var valueAsBool) ? valueAsBool : defaultValue; } @@ -28,8 +28,8 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml if (string.IsNullOrWhiteSpace(value)) return defaultValue; - return int.TryParse(value, out var valueAsBool) - ? valueAsBool + return int.TryParse(value, out var valueAsBool) + ? valueAsBool : defaultValue; } @@ -45,4 +45,4 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml : defaultValue; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs index 9a9f9af9..75a4391e 100644 --- a/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs +++ b/mRemoteV1/Config/Serializers/ConnectionSerializers/Xml/XmlRootNodeSerializer.cs @@ -7,27 +7,28 @@ namespace mRemoteNG.Config.Serializers.Xml { public class XmlRootNodeSerializer { - public XElement SerializeRootNodeInfo( - RootNodeInfo rootNodeInfo, - ICryptographyProvider cryptographyProvider, - Version version, - bool fullFileEncryption = false) + public XElement SerializeRootNodeInfo(RootNodeInfo rootNodeInfo, + ICryptographyProvider cryptographyProvider, + Version version, + bool fullFileEncryption = false) { XNamespace xmlNamespace = "http://mremoteng.org"; var element = new XElement(xmlNamespace + "Connections"); - element.Add(new XAttribute(XNamespace.Xmlns+"mrng", xmlNamespace)); + 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")); - element.Add(new XAttribute(XName.Get("EncryptionEngine"), cryptographyProvider.CipherEngine)); + element.Add(new XAttribute(XName.Get("Export"), "false")); + element.Add(new XAttribute(XName.Get("EncryptionEngine"), cryptographyProvider.CipherEngine)); element.Add(new XAttribute(XName.Get("BlockCipherMode"), cryptographyProvider.CipherMode)); element.Add(new XAttribute(XName.Get("KdfIterations"), cryptographyProvider.KeyDerivationIterations)); - element.Add(new XAttribute(XName.Get("FullFileEncryption"), fullFileEncryption.ToString().ToLowerInvariant())); + element.Add(new XAttribute(XName.Get("FullFileEncryption"), + fullFileEncryption.ToString().ToLowerInvariant())); element.Add(CreateProtectedAttribute(rootNodeInfo, cryptographyProvider)); element.Add(new XAttribute(XName.Get("ConfVersion"), version.ToString(2))); return element; } - private XAttribute CreateProtectedAttribute(RootNodeInfo rootNodeInfo, ICryptographyProvider cryptographyProvider) + private XAttribute CreateProtectedAttribute(RootNodeInfo rootNodeInfo, + ICryptographyProvider cryptographyProvider) { var attribute = new XAttribute(XName.Get("Protected"), ""); var plainText = rootNodeInfo.Password ? "ThisIsProtected" : "ThisIsNotProtected"; diff --git a/mRemoteV1/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs b/mRemoteV1/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs index 79365228..ea755999 100644 --- a/mRemoteV1/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs +++ b/mRemoteV1/Config/Serializers/CredentialProviderSerializer/CredentialRepositoryListSerializer.cs @@ -13,14 +13,14 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer { var xmlDocument = new XDocument(new XDeclaration("1.0", "utf-8", null)); var rootElement = new XElement("CredentialRepositories", - from provider in credentialProviderCatalog - select new XElement("CredentialRepository", - new XAttribute("Id", provider.Config.Id), - new XAttribute("TypeName", provider.Config.TypeName), - new XAttribute("Title", provider.Config.Title), - new XAttribute("Source", provider.Config.Source) - ) - ); + from provider in credentialProviderCatalog + select new XElement("CredentialRepository", + new XAttribute("Id", provider.Config.Id), + new XAttribute("TypeName", provider.Config.TypeName), + new XAttribute("Title", provider.Config.Title), + new XAttribute("Source", provider.Config.Source) + ) + ); xmlDocument.Add(rootElement); var declaration = xmlDocument.Declaration.ToString(); var documentBody = xmlDocument.ToString(); diff --git a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs index 3e6d5854..a89ea755 100644 --- a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs +++ b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordDecryptorDecorator.cs @@ -12,7 +12,8 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer { private readonly IDeserializer> _baseDeserializer; - public XmlCredentialPasswordDecryptorDecorator(IDeserializer> baseDeserializer) + public XmlCredentialPasswordDecryptorDecorator( + IDeserializer> baseDeserializer) { if (baseDeserializer == null) throw new ArgumentNullException(nameof(baseDeserializer)); @@ -39,10 +40,13 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer var decryptedPassword = cryptoProvider.Decrypt(passwordAttribute.Value, key); passwordAttribute.SetValue(decryptedPassword); } + return xdoc.ToString(); } - private void DecryptAuthHeader(XElement rootElement, ICryptographyProvider cryptographyProvider, SecureString key) + private void DecryptAuthHeader(XElement rootElement, + ICryptographyProvider cryptographyProvider, + SecureString key) { var authAttribute = rootElement.Attribute("Auth"); if (authAttribute == null) diff --git a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs index 8fc38ed8..6b3db03c 100644 --- a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs +++ b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialPasswordEncryptorDecorator.cs @@ -12,7 +12,9 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer private readonly ISerializer, string> _baseSerializer; private readonly ICryptographyProvider _cryptographyProvider; - public XmlCredentialPasswordEncryptorDecorator(ICryptographyProvider cryptographyProvider, ISerializer, string> baseSerializer) + public XmlCredentialPasswordEncryptorDecorator(ICryptographyProvider cryptographyProvider, + ISerializer, string> + baseSerializer) { if (baseSerializer == null) throw new ArgumentNullException(nameof(baseSerializer)); @@ -45,6 +47,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer var encryptedPassword = _cryptographyProvider.Encrypt(passwordAttribute.Value, encryptionKey); passwordAttribute.Value = encryptedPassword; } + return xdoc.Declaration + Environment.NewLine + xdoc; } @@ -53,7 +56,9 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer xdoc.Root?.SetAttributeValue("EncryptionEngine", _cryptographyProvider.CipherEngine); xdoc.Root?.SetAttributeValue("BlockCipherMode", _cryptographyProvider.CipherMode); xdoc.Root?.SetAttributeValue("KdfIterations", _cryptographyProvider.KeyDerivationIterations); - xdoc.Root?.SetAttributeValue("Auth", _cryptographyProvider.Encrypt(RandomGenerator.RandomString(20), encryptionKey)); + xdoc.Root?.SetAttributeValue("Auth", + _cryptographyProvider.Encrypt(RandomGenerator.RandomString(20), + encryptionKey)); } } } \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs index 7a7fe0d9..3f071a9d 100644 --- a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs +++ b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordDeserializer.cs @@ -19,13 +19,14 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer ValidateSchemaVersion(rootElement); var credentials = from element in xdoc.Descendants("Credential") - select new CredentialRecord(Guid.Parse(element.Attribute("Id")?.Value ?? Guid.NewGuid().ToString())) - { - Title = element.Attribute("Title")?.Value ?? "", - Username = element.Attribute("Username")?.Value ?? "", - Password = element.Attribute("Password")?.Value.ConvertToSecureString(), - Domain = element.Attribute("Domain")?.Value ?? "" - }; + select new CredentialRecord(Guid.Parse(element.Attribute("Id")?.Value ?? + Guid.NewGuid().ToString())) + { + Title = element.Attribute("Title")?.Value ?? "", + Username = element.Attribute("Username")?.Value ?? "", + Password = element.Attribute("Password")?.Value.ConvertToSecureString(), + Domain = element.Attribute("Domain")?.Value ?? "" + }; return credentials.ToArray(); } @@ -33,7 +34,8 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer { var 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}"); + throw new Exception( + $"The schema version of this document is not supported by this class. Document Version: {docSchemaVersion} Supported Version: {SchemaVersion}"); } } } \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs index 01d2e0e1..eb421b27 100644 --- a/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs +++ b/mRemoteV1/Config/Serializers/CredentialSerializer/XmlCredentialRecordSerializer.cs @@ -14,18 +14,20 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer public string Serialize(IEnumerable credentialRecords) { var xdoc = new XDocument( - new XElement("Credentials", - new XAttribute("SchemaVersion", Version.ToString(2)), - from r in credentialRecords - select new XElement("Credential", - new XAttribute("Id", r.Id), - new XAttribute("Title", r.Title), - new XAttribute("Username", r.Username), - new XAttribute("Domain", r.Domain), - new XAttribute("Password", r.Password.ConvertToUnsecureString()) - ) - ) - ) + new XElement("Credentials", + new XAttribute("SchemaVersion", Version.ToString(2)), + from r in credentialRecords + select new XElement("Credential", + new XAttribute("Id", r.Id), + new XAttribute("Title", r.Title), + new XAttribute("Username", r.Username), + new XAttribute("Domain", r.Domain), + new XAttribute("Password", + r.Password + .ConvertToUnsecureString()) + ) + ) + ) { Declaration = new XDeclaration("1.0", "utf-8", null) }; diff --git a/mRemoteV1/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs b/mRemoteV1/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs index d9789f0f..a042aa21 100644 --- a/mRemoteV1/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs +++ b/mRemoteV1/Config/Serializers/MiscSerializers/ActiveDirectoryDeserializer.cs @@ -55,7 +55,7 @@ namespace mRemoteNG.Config.Serializers ldapSearcher.SearchRoot = new DirectoryEntry(ldapPath); ldapSearcher.Filter = ldapFilter; ldapSearcher.SearchScope = SearchScope.OneLevel; - ldapSearcher.PropertiesToLoad.AddRange(new[] { "securityEquals", "cn", "objectClass" }); + ldapSearcher.PropertiesToLoad.AddRange(new[] {"securityEquals", "cn", "objectClass"}); var ldapResults = ldapSearcher.FindAll(); foreach (SearchResult ldapResult in ldapResults) @@ -65,7 +65,7 @@ namespace mRemoteNG.Config.Serializers if (directoryEntry.Properties["objectClass"].Contains("organizationalUnit")) { // check/continue here so we don't create empty connection objects - if(!_importSubOu) continue; + if (!_importSubOu) continue; // TODO - this is a circular call. A deserializer should not call an importer ActiveDirectoryImporter.Import(ldapResult.Path, parentContainer, _importSubOu); @@ -79,7 +79,8 @@ namespace mRemoteNG.Config.Serializers } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("Config.Import.ActiveDirectory.ImportComputers() failed.", ex); + Runtime.MessageCollector.AddExceptionMessage("Config.Import.ActiveDirectory.ImportComputers() failed.", + ex); } } diff --git a/mRemoteV1/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs b/mRemoteV1/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs index 81e3ac25..43d65b25 100644 --- a/mRemoteV1/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs +++ b/mRemoteV1/Config/Serializers/MiscSerializers/PuttyConnectionManagerDeserializer.cs @@ -75,16 +75,19 @@ namespace mRemoteNG.Config.Serializers { throw (new FileFormatException($"Unrecognized root node type ({xmlNodeType}).")); } + break; case "container": if (string.Compare(xmlNodeType, "folder", StringComparison.OrdinalIgnoreCase) != 0) { throw (new FileFormatException($"Unrecognized root node type ({xmlNodeType}).")); } + break; default: // ReSharper disable once LocalizableElement - throw (new ArgumentException("Argument must be either a root or a container node.", nameof(xmlNode))); + throw (new ArgumentException("Argument must be either a root or a container node.", + nameof(xmlNode))); } } diff --git a/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs b/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs index b2d25ca9..20ad5b25 100644 --- a/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs +++ b/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionDeserializer.cs @@ -18,7 +18,7 @@ namespace mRemoteNG.Config.Serializers foreach (var line in rdcFileContent.Split(Environment.NewLine.ToCharArray())) { - var parts = line.Split(new[] { ':' }, 3); + var parts = line.Split(new[] {':'}, 3); if (parts.Length < 3) { continue; @@ -90,12 +90,15 @@ namespace mRemoteNG.Config.Serializers connectionInfo.Colors = RdpProtocol.RDPColors.Colors32Bit; break; } + break; case "bitmapcachepersistenable": connectionInfo.CacheBitmaps = value == "1"; break; case "screen mode id": - connectionInfo.Resolution = value == "2" ? RdpProtocol.RDPResolutions.Fullscreen : RdpProtocol.RDPResolutions.FitToWindow; + connectionInfo.Resolution = value == "2" + ? RdpProtocol.RDPResolutions.Fullscreen + : RdpProtocol.RDPResolutions.FitToWindow; break; case "connect to console": connectionInfo.UseConsoleSession = value == "1"; @@ -140,6 +143,7 @@ namespace mRemoteNG.Config.Serializers connectionInfo.RedirectSound = RdpProtocol.RDPSounds.DoNotPlay; break; } + break; case "loadbalanceinfo": connectionInfo.LoadBalanceInfo = value; diff --git a/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs b/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs index 21274f2e..856c67d5 100644 --- a/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs +++ b/mRemoteV1/Config/Serializers/MiscSerializers/RemoteDesktopConnectionManagerDeserializer.cs @@ -125,6 +125,7 @@ namespace mRemoteNG.Config.Serializers // Program Version 2.2 wraps all setting inside the Properties tags containerPropertiesNode = containerPropertiesNode.SelectSingleNode("./properties"); } + var newContainer = new ContainerInfo(); var connectionInfo = ConnectionInfoFromXml(containerPropertiesNode); newContainer.CopyFrom(connectionInfo); @@ -134,8 +135,10 @@ namespace mRemoteNG.Config.Serializers // Program Version 2.7 wraps these properties containerPropertiesNode = containerPropertiesNode.SelectSingleNode("./properties"); } + newContainer.Name = containerPropertiesNode?.SelectSingleNode("./name")?.InnerText ?? Language.strNewFolder; - newContainer.IsExpanded = bool.Parse(containerPropertiesNode?.SelectSingleNode("./expanded")?.InnerText ?? "false"); + newContainer.IsExpanded = + bool.Parse(containerPropertiesNode?.SelectSingleNode("./expanded")?.InnerText ?? "false"); return newContainer; } @@ -145,9 +148,11 @@ namespace mRemoteNG.Config.Serializers var propertiesNode = xmlNode.SelectSingleNode("./properties"); - if (_schemaVersion == 1) propertiesNode = xmlNode; // Version 2.2 defines the container name at the root instead + if (_schemaVersion == 1) + propertiesNode = xmlNode; // Version 2.2 defines the container name at the root instead connectionInfo.Hostname = propertiesNode?.SelectSingleNode("./name")?.InnerText ?? ""; - connectionInfo.Name = propertiesNode?.SelectSingleNode("./displayName")?.InnerText ?? connectionInfo.Hostname; + connectionInfo.Name = + propertiesNode?.SelectSingleNode("./displayName")?.InnerText ?? connectionInfo.Hostname; connectionInfo.Description = propertiesNode?.SelectSingleNode("./comment")?.InnerText ?? string.Empty; var logonCredentialsNode = xmlNode.SelectSingleNode("./logonCredentials"); @@ -161,7 +166,8 @@ namespace mRemoteNG.Config.Serializers var connectionSettingsNode = xmlNode.SelectSingleNode("./connectionSettings"); if (connectionSettingsNode?.Attributes?["inherit"]?.Value == "None") { - connectionInfo.UseConsoleSession = bool.Parse(connectionSettingsNode.SelectSingleNode("./connectToConsole")?.InnerText ?? "false"); + connectionInfo.UseConsoleSession = + bool.Parse(connectionSettingsNode.SelectSingleNode("./connectToConsole")?.InnerText ?? "false"); // ./startProgram // ./workingDir connectionInfo.Port = Convert.ToInt32(connectionSettingsNode.SelectSingleNode("./port")?.InnerText); @@ -175,7 +181,10 @@ namespace mRemoteNG.Config.Serializers var gatewaySettingsNode = xmlNode.SelectSingleNode("./gatewaySettings"); if (gatewaySettingsNode?.Attributes?["inherit"]?.Value == "None") { - connectionInfo.RDGatewayUsageMethod = gatewaySettingsNode.SelectSingleNode("./enabled")?.InnerText == "True" ? RdpProtocol.RDGatewayUsageMethod.Always : RdpProtocol.RDGatewayUsageMethod.Never; + connectionInfo.RDGatewayUsageMethod = + gatewaySettingsNode.SelectSingleNode("./enabled")?.InnerText == "True" + ? RdpProtocol.RDGatewayUsageMethod.Always + : RdpProtocol.RDGatewayUsageMethod.Never; connectionInfo.RDGatewayHostname = gatewaySettingsNode.SelectSingleNode("./hostName")?.InnerText; connectionInfo.RDGatewayUsername = gatewaySettingsNode.SelectSingleNode("./userName")?.InnerText; @@ -225,7 +234,8 @@ namespace mRemoteNG.Config.Serializers var colorDepth = remoteDesktopNode.SelectSingleNode("./colorDepth")?.InnerText; if (colorDepth != null) - connectionInfo.Colors = (RdpProtocol.RDPColors)Enum.Parse(typeof(RdpProtocol.RDPColors), colorDepth); + connectionInfo.Colors = + (RdpProtocol.RDPColors)Enum.Parse(typeof(RdpProtocol.RDPColors), colorDepth); } else { @@ -274,11 +284,16 @@ namespace mRemoteNG.Config.Serializers } // ./redirectClipboard - connectionInfo.RedirectDiskDrives = bool.Parse(localResourcesNode?.SelectSingleNode("./redirectDrives")?.InnerText ?? "false"); - connectionInfo.RedirectPorts = bool.Parse(localResourcesNode?.SelectSingleNode("./redirectPorts")?.InnerText ?? "false"); - connectionInfo.RedirectPrinters = bool.Parse(localResourcesNode?.SelectSingleNode("./redirectPrinters")?.InnerText ?? "false"); - connectionInfo.RedirectSmartCards = bool.Parse(localResourcesNode?.SelectSingleNode("./redirectSmartCards")?.InnerText ?? "false"); - connectionInfo.RedirectClipboard = bool.Parse(localResourcesNode?.SelectSingleNode("./redirectClipboard")?.InnerText ?? "false"); + connectionInfo.RedirectDiskDrives = + bool.Parse(localResourcesNode?.SelectSingleNode("./redirectDrives")?.InnerText ?? "false"); + connectionInfo.RedirectPorts = + bool.Parse(localResourcesNode?.SelectSingleNode("./redirectPorts")?.InnerText ?? "false"); + connectionInfo.RedirectPrinters = + bool.Parse(localResourcesNode?.SelectSingleNode("./redirectPrinters")?.InnerText ?? "false"); + connectionInfo.RedirectSmartCards = + bool.Parse(localResourcesNode?.SelectSingleNode("./redirectSmartCards")?.InnerText ?? "false"); + connectionInfo.RedirectClipboard = + bool.Parse(localResourcesNode?.SelectSingleNode("./redirectClipboard")?.InnerText ?? "false"); } else { @@ -354,7 +369,8 @@ namespace mRemoteNG.Config.Serializers try { - var plaintextData = ProtectedData.Unprotect(Convert.FromBase64String(ciphertext), new byte[] { }, DataProtectionScope.LocalMachine); + var plaintextData = ProtectedData.Unprotect(Convert.FromBase64String(ciphertext), new byte[] { }, + DataProtectionScope.LocalMachine); return Encoding.Unicode.GetString(plaintextData).ConvertToSecureString(); } catch (Exception /*ex*/) diff --git a/mRemoteV1/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs b/mRemoteV1/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs index 232914b0..607512c8 100644 --- a/mRemoteV1/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs +++ b/mRemoteV1/Config/Serializers/Versioning/SqlDatabaseVersionVerifier.cs @@ -36,7 +36,7 @@ namespace mRemoteNG.Config.Serializers.Versioning new SqlVersion23To24Upgrader(_sqlDatabaseConnector), new SqlVersion24To25Upgrader(_sqlDatabaseConnector), new SqlVersion25To26Upgrader(_sqlDatabaseConnector), - new SqlVersion26To27Upgrader(_sqlDatabaseConnector), + new SqlVersion26To27Upgrader(_sqlDatabaseConnector), }; foreach (var upgrader in dbUpgraders) @@ -52,11 +52,16 @@ namespace mRemoteNG.Config.Serializers.Versioning isVerified = true; if (isVerified == false) - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, string.Format(Language.strErrorBadDatabaseVersion, databaseVersion, GeneralAppInfo.ProductName)); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + string.Format(Language.strErrorBadDatabaseVersion, + databaseVersion, + GeneralAppInfo.ProductName)); } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strErrorVerifyDatabaseVersionFailed, ex.Message)); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + string.Format(Language.strErrorVerifyDatabaseVersionFailed, + ex.Message)); } return isVerified; diff --git a/mRemoteV1/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs b/mRemoteV1/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs index cf0e8865..5f8cbbad 100644 --- a/mRemoteV1/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs +++ b/mRemoteV1/Config/Serializers/Versioning/SqlVersion22To23Upgrader.cs @@ -25,7 +25,8 @@ namespace mRemoteNG.Config.Serializers.Versioning public Version Upgrade() { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.2 to version 2.3."); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Upgrading database from version 2.2 to version 2.3."); const string sqlText = @" ALTER TABLE tblCons ADD EnableFontSmoothing bit NOT NULL DEFAULT 0, diff --git a/mRemoteV1/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs b/mRemoteV1/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs index 03085c8a..535dad23 100644 --- a/mRemoteV1/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs +++ b/mRemoteV1/Config/Serializers/Versioning/SqlVersion23To24Upgrader.cs @@ -25,7 +25,8 @@ namespace mRemoteNG.Config.Serializers.Versioning public Version Upgrade() { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.3 to version 2.4."); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Upgrading database from version 2.3 to version 2.4."); const string sqlText = @" ALTER TABLE tblCons ADD UseCredSsp bit NOT NULL DEFAULT 1, diff --git a/mRemoteV1/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs b/mRemoteV1/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs index 704fd8cf..b51615db 100644 --- a/mRemoteV1/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs +++ b/mRemoteV1/Config/Serializers/Versioning/SqlVersion24To25Upgrader.cs @@ -25,7 +25,8 @@ namespace mRemoteNG.Config.Serializers.Versioning public Version Upgrade() { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.4 to version 2.5."); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Upgrading database from version 2.4 to version 2.5."); const string sqlText = @" ALTER TABLE tblCons ADD LoadBalanceInfo varchar (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, diff --git a/mRemoteV1/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs b/mRemoteV1/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs index 7e6e232c..cfde93f0 100644 --- a/mRemoteV1/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs +++ b/mRemoteV1/Config/Serializers/Versioning/SqlVersion25To26Upgrader.cs @@ -25,7 +25,8 @@ namespace mRemoteNG.Config.Serializers.Versioning public Version Upgrade() { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.5 to version 2.6."); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Upgrading database from version 2.5 to version 2.6."); const string sqlText = @" ALTER TABLE tblCons ADD RDPMinutesToIdleTimeout int NOT NULL DEFAULT 0, diff --git a/mRemoteV1/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs b/mRemoteV1/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs index e0022589..431bc65a 100644 --- a/mRemoteV1/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs +++ b/mRemoteV1/Config/Serializers/Versioning/SqlVersion26To27Upgrader.cs @@ -25,7 +25,8 @@ namespace mRemoteNG.Config.Serializers.Versioning public Version Upgrade() { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.6 to version 2.7."); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "Upgrading database from version 2.6 to version 2.7."); const string sqlText = @" ALTER TABLE tblCons ADD RedirectClipboard bit NOT NULL DEFAULT 0, @@ -39,4 +40,4 @@ UPDATE tblRoot return new Version(2, 7); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Config/Serializers/XmlConnectionsDecryptor.cs b/mRemoteV1/Config/Serializers/XmlConnectionsDecryptor.cs index efa0683a..80332729 100644 --- a/mRemoteV1/Config/Serializers/XmlConnectionsDecryptor.cs +++ b/mRemoteV1/Config/Serializers/XmlConnectionsDecryptor.cs @@ -29,7 +29,9 @@ namespace mRemoteNG.Config.Serializers _rootNodeInfo = rootNodeInfo; } - public XmlConnectionsDecryptor(BlockCipherEngines blockCipherEngine, BlockCipherModes blockCipherMode, RootNodeInfo rootNodeInfo) + public XmlConnectionsDecryptor(BlockCipherEngines blockCipherEngine, + BlockCipherModes blockCipherMode, + RootNodeInfo rootNodeInfo) { _cryptographyProvider = new CryptoProviderFactory(blockCipherEngine, blockCipherMode).Build(); _rootNodeInfo = rootNodeInfo; @@ -37,7 +39,9 @@ namespace mRemoteNG.Config.Serializers public string Decrypt(string plainText) { - return plainText == "" ? "" : _cryptographyProvider.Decrypt(plainText, _rootNodeInfo.PasswordString.ConvertToSecureString()); + return plainText == "" + ? "" + : _cryptographyProvider.Decrypt(plainText, _rootNodeInfo.PasswordString.ConvertToSecureString()); } public string LegacyFullFileDecrypt(string xml) @@ -50,7 +54,8 @@ namespace mRemoteNG.Config.Serializers try { - decryptedContent = _cryptographyProvider.Decrypt(xml, _rootNodeInfo.PasswordString.ConvertToSecureString()); + decryptedContent = + _cryptographyProvider.Decrypt(xml, _rootNodeInfo.PasswordString.ConvertToSecureString()); notDecr = decryptedContent == xml; } catch (Exception) @@ -62,7 +67,8 @@ namespace mRemoteNG.Config.Serializers { if (Authenticate(xml, _rootNodeInfo.PasswordString.ConvertToSecureString())) { - decryptedContent = _cryptographyProvider.Decrypt(xml, _rootNodeInfo.PasswordString.ConvertToSecureString()); + decryptedContent = + _cryptographyProvider.Decrypt(xml, _rootNodeInfo.PasswordString.ConvertToSecureString()); notDecr = false; } @@ -82,12 +88,17 @@ namespace mRemoteNG.Config.Serializers var connectionsFileIsNotEncrypted = false; try { - connectionsFileIsNotEncrypted = _cryptographyProvider.Decrypt(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()) == "ThisIsNotProtected"; + connectionsFileIsNotEncrypted = + _cryptographyProvider.Decrypt(protectedString, + _rootNodeInfo.PasswordString.ConvertToSecureString()) == + "ThisIsNotProtected"; } catch (EncryptionException) { } - return connectionsFileIsNotEncrypted || Authenticate(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()); + + return connectionsFileIsNotEncrypted || + Authenticate(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()); } private bool Authenticate(string cipherText, SecureString password) diff --git a/mRemoteV1/Config/Settings/DockPanelLayoutLoader.cs b/mRemoteV1/Config/Settings/DockPanelLayoutLoader.cs index d431a3d1..4995384d 100644 --- a/mRemoteV1/Config/Settings/DockPanelLayoutLoader.cs +++ b/mRemoteV1/Config/Settings/DockPanelLayoutLoader.cs @@ -36,7 +36,8 @@ namespace mRemoteNG.Config.Settings } #if !PORTABLE - var oldPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\" + GeneralAppInfo.ProductName + "\\" + SettingsFileInfo.LayoutFileName; + var oldPath = + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\" + GeneralAppInfo.ProductName + "\\" + SettingsFileInfo.LayoutFileName; #endif var newPath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName; if (File.Exists(newPath)) diff --git a/mRemoteV1/Config/Settings/DockPanelLayoutSaver.cs b/mRemoteV1/Config/Settings/DockPanelLayoutSaver.cs index 9779a7bd..f5e2aae0 100644 --- a/mRemoteV1/Config/Settings/DockPanelLayoutSaver.cs +++ b/mRemoteV1/Config/Settings/DockPanelLayoutSaver.cs @@ -14,7 +14,8 @@ namespace mRemoteNG.Config.Settings private readonly ISerializer _dockPanelSerializer; private readonly IDataProvider _dataProvider; - public DockPanelLayoutSaver(ISerializer dockPanelSerializer, IDataProvider dataProvider) + public DockPanelLayoutSaver(ISerializer dockPanelSerializer, + IDataProvider dataProvider) { if (dockPanelSerializer == null) throw new ArgumentNullException(nameof(dockPanelSerializer)); diff --git a/mRemoteV1/Config/Settings/DockPanelLayoutSerializer.cs b/mRemoteV1/Config/Settings/DockPanelLayoutSerializer.cs index 0ee7d3c3..e8e4be84 100644 --- a/mRemoteV1/Config/Settings/DockPanelLayoutSerializer.cs +++ b/mRemoteV1/Config/Settings/DockPanelLayoutSerializer.cs @@ -23,6 +23,7 @@ namespace mRemoteNG.Config.Settings memoryStream.Position = 0; xdoc = XDocument.Load(memoryStream, LoadOptions.SetBaseUri); } + return $"{xdoc.Declaration}{Environment.NewLine}{xdoc}"; } } diff --git a/mRemoteV1/Config/Settings/ExternalAppsLoader.cs b/mRemoteV1/Config/Settings/ExternalAppsLoader.cs index ee064507..a81d4b09 100644 --- a/mRemoteV1/Config/Settings/ExternalAppsLoader.cs +++ b/mRemoteV1/Config/Settings/ExternalAppsLoader.cs @@ -16,7 +16,9 @@ namespace mRemoteNG.Config.Settings private readonly MessageCollector _messageCollector; private readonly ExternalToolsToolStrip _externalToolsToolStrip; - public ExternalAppsLoader(FrmMain mainForm, MessageCollector messageCollector, ExternalToolsToolStrip externalToolsToolStrip) + public ExternalAppsLoader(FrmMain mainForm, + MessageCollector messageCollector, + ExternalToolsToolStrip externalToolsToolStrip) { if (mainForm == null) throw new ArgumentNullException(nameof(mainForm)); @@ -34,13 +36,15 @@ namespace mRemoteNG.Config.Settings public void LoadExternalAppsFromXML() { #if !PORTABLE - var oldPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GeneralAppInfo.ProductName, SettingsFileInfo.ExtAppsFilesName); + var 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(); if (File.Exists(newPath)) { - _messageCollector.AddMessage(MessageClass.InformationMsg, $"Loading External Apps from: {newPath}", true); + _messageCollector.AddMessage(MessageClass.InformationMsg, $"Loading External Apps from: {newPath}", + true); xDom.Load(newPath); } #if !PORTABLE @@ -53,13 +57,15 @@ namespace mRemoteNG.Config.Settings #endif else { - _messageCollector.AddMessage(MessageClass.WarningMsg, "Loading External Apps failed: Could not FIND file!"); + _messageCollector.AddMessage(MessageClass.WarningMsg, + "Loading External Apps failed: Could not FIND file!"); return; } if (xDom.DocumentElement == null) { - _messageCollector.AddMessage(MessageClass.WarningMsg, "Loading External Apps failed: Could not LOAD file!"); + _messageCollector.AddMessage(MessageClass.WarningMsg, + "Loading External Apps failed: Could not LOAD file!"); return; } @@ -93,7 +99,9 @@ namespace mRemoteNG.Config.Settings extA.ShowOnToolbar = bool.Parse(xEl.Attributes["ShowOnToolbar"].Value); } - _messageCollector.AddMessage(MessageClass.InformationMsg, $"Adding External App: {extA.DisplayName} {extA.FileName} {extA.Arguments}", true); + _messageCollector.AddMessage(MessageClass.InformationMsg, + $"Adding External App: {extA.DisplayName} {extA.FileName} {extA.Arguments}", + true); Runtime.ExternalToolsService.ExternalTools.Add(extA); } diff --git a/mRemoteV1/Config/Settings/ExternalAppsSaver.cs b/mRemoteV1/Config/Settings/ExternalAppsSaver.cs index 243f330a..000cc4c2 100644 --- a/mRemoteV1/Config/Settings/ExternalAppsSaver.cs +++ b/mRemoteV1/Config/Settings/ExternalAppsSaver.cs @@ -22,7 +22,7 @@ namespace mRemoteNG.Config.Settings var xmlTextWriter = new XmlTextWriter(SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.ExtAppsFilesName, - Encoding.UTF8) + Encoding.UTF8) { Formatting = Formatting.Indented, Indentation = 4 diff --git a/mRemoteV1/Config/Settings/Providers/ChooseProvider.cs b/mRemoteV1/Config/Settings/Providers/ChooseProvider.cs index 10a1a342..8a58cf8d 100644 --- a/mRemoteV1/Config/Settings/Providers/ChooseProvider.cs +++ b/mRemoteV1/Config/Settings/Providers/ChooseProvider.cs @@ -9,5 +9,6 @@ namespace mRemoteNG.Config.Settings.Providers #else public class ChooseProvider : LocalFileSettingsProvider #endif - { } + { + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Settings/Providers/PortableSettingsProvider.cs b/mRemoteV1/Config/Settings/Providers/PortableSettingsProvider.cs index 51349b26..fa79921f 100644 --- a/mRemoteV1/Config/Settings/Providers/PortableSettingsProvider.cs +++ b/mRemoteV1/Config/Settings/Providers/PortableSettingsProvider.cs @@ -21,7 +21,7 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -// https://raw.githubusercontent.com/crdx/PortableSettingsProvider +// https://github.com/crdx/PortableSettingsProvider // using System; @@ -31,6 +31,7 @@ using System.Windows.Forms; using System.Collections.Specialized; using System.Xml; using System.IO; + //using mRemoteNG.App; namespace mRemoteNG.Config.Settings.Providers @@ -43,7 +44,9 @@ namespace mRemoteNG.Config.Settings.Providers private const string _className = "PortableSettingsProvider"; private XmlDocument _xmlDocument; - private string _filePath => Path.Combine(Path.GetDirectoryName(Application.ExecutablePath) ?? throw new InvalidOperationException(), $"{ApplicationName}.settings"); + private string _filePath => + Path.Combine(Path.GetDirectoryName(Application.ExecutablePath) ?? throw new InvalidOperationException(), + $"{ApplicationName}.settings"); private XmlNode _localSettingsNode => GetSettingsNode(_localSettingsNodeName); @@ -63,7 +66,7 @@ namespace mRemoteNG.Config.Settings.Providers } catch (Exception /*ex*/) { - // This casues hundreds of unit tests to fail for some reason... + // This causes hundreds of unit tests to fail for some reason... //Runtime.MessageCollector.AddExceptionStackTrace("PortableSettingsProvider: Error getting XML", ex); } @@ -109,7 +112,8 @@ namespace mRemoteNG.Config.Settings.Providers } } - public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) + public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, + SettingsPropertyCollection collection) { var values = new SettingsPropertyValueCollection(); diff --git a/mRemoteV1/Config/Settings/SettingsLoader.cs b/mRemoteV1/Config/Settings/SettingsLoader.cs index a730dac6..6e250a5b 100644 --- a/mRemoteV1/Config/Settings/SettingsLoader.cs +++ b/mRemoteV1/Config/Settings/SettingsLoader.cs @@ -16,25 +16,24 @@ using mRemoteNG.UI.Forms; namespace mRemoteNG.Config.Settings { public class SettingsLoader - { + { private readonly ExternalAppsLoader _externalAppsLoader; private readonly MessageCollector _messageCollector; - private readonly MenuStrip _mainMenu; + private readonly MenuStrip _mainMenu; private readonly QuickConnectToolStrip _quickConnectToolStrip; private readonly ExternalToolsToolStrip _externalToolsToolStrip; - private readonly MultiSshToolStrip _multiSshToolStrip; + private readonly MultiSshToolStrip _multiSshToolStrip; private FrmMain MainForm { get; } - public SettingsLoader( - FrmMain mainForm, - MessageCollector messageCollector, - QuickConnectToolStrip quickConnectToolStrip, - ExternalToolsToolStrip externalToolsToolStrip, - MultiSshToolStrip multiSshToolStrip, - MenuStrip mainMenu) - { + public SettingsLoader(FrmMain mainForm, + MessageCollector messageCollector, + QuickConnectToolStrip quickConnectToolStrip, + ExternalToolsToolStrip externalToolsToolStrip, + MultiSshToolStrip multiSshToolStrip, + MenuStrip mainMenu) + { if (mainForm == null) throw new ArgumentNullException(nameof(mainForm)); if (messageCollector == null) @@ -45,45 +44,46 @@ namespace mRemoteNG.Config.Settings throw new ArgumentNullException(nameof(externalToolsToolStrip)); if (multiSshToolStrip == null) throw new ArgumentNullException(nameof(multiSshToolStrip)); - if (mainMenu == null) - throw new ArgumentNullException(nameof(mainMenu)); + if (mainMenu == null) + throw new ArgumentNullException(nameof(mainMenu)); MainForm = mainForm; - _messageCollector = messageCollector; - _quickConnectToolStrip = quickConnectToolStrip; - _externalToolsToolStrip = externalToolsToolStrip; - _multiSshToolStrip = multiSshToolStrip; - _mainMenu = mainMenu; - _externalAppsLoader = new ExternalAppsLoader(MainForm, messageCollector, _externalToolsToolStrip); + _messageCollector = messageCollector; + _quickConnectToolStrip = quickConnectToolStrip; + _externalToolsToolStrip = externalToolsToolStrip; + _multiSshToolStrip = multiSshToolStrip; + _mainMenu = mainMenu; + _externalAppsLoader = new ExternalAppsLoader(MainForm, messageCollector, _externalToolsToolStrip); } - + #region Public Methods + public void LoadSettings() - { - try - { + { + try + { EnsureSettingsAreSavedInNewestVersion(); - SetSupportedCulture(); + SetSupportedCulture(); SetApplicationWindowPositionAndSize(); SetKioskMode(); SetPuttyPath(); SetShowSystemTrayIcon(); SetAutoSave(); - LoadExternalAppsFromXml(); + LoadExternalAppsFromXml(); SetAlwaysShowPanelTabs(); - - if (mRemoteNG.Settings.Default.ResetToolbars) + + if (mRemoteNG.Settings.Default.ResetToolbars) SetToolbarsDefault(); - else + else LoadToolbarsFromSettings(); - } - catch (Exception ex) - { + } + catch (Exception ex) + { _messageCollector.AddExceptionMessage("Loading settings failed", ex); - } - } + } + } private static void SetAlwaysShowPanelTabs() { @@ -91,14 +91,15 @@ namespace mRemoteNG.Config.Settings FrmMain.Default.pnlDock.DocumentStyle = DocumentStyle.DockingWindow; } - private void SetSupportedCulture() { if (mRemoteNG.Settings.Default.OverrideUICulture == "" || !SupportedCultures.IsNameSupported(mRemoteNG.Settings.Default.OverrideUICulture)) return; Thread.CurrentThread.CurrentUICulture = new CultureInfo(mRemoteNG.Settings.Default.OverrideUICulture); - _messageCollector.AddMessage(MessageClass.InformationMsg, $"Override Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}", true); + _messageCollector.AddMessage(MessageClass.InformationMsg, + $"Override Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}", + true); } private void SetApplicationWindowPositionAndSize() @@ -163,7 +164,9 @@ namespace mRemoteNG.Config.Settings private static void SetPuttyPath() { - PuttyBase.PuttyPath = mRemoteNG.Settings.Default.UseCustomPuttyPath ? mRemoteNG.Settings.Default.CustomPuttyPath : GeneralAppInfo.PuttyPath; + PuttyBase.PuttyPath = mRemoteNG.Settings.Default.UseCustomPuttyPath + ? mRemoteNG.Settings.Default.CustomPuttyPath + : GeneralAppInfo.PuttyPath; } private void EnsureSettingsAreSavedInNewestVersion() @@ -183,6 +186,7 @@ namespace mRemoteNG.Config.Settings { _messageCollector.AddExceptionMessage("Settings.Upgrade() failed", ex); } + mRemoteNG.Settings.Default.DoUpgrade = false; // Clear pending update flag @@ -191,21 +195,21 @@ namespace mRemoteNG.Config.Settings mRemoteNG.Settings.Default.UpdatePending = false; } - private void SetToolbarsDefault() - { - ToolStripPanelFromString("top").Join(_quickConnectToolStrip, new Point(300, 0)); + private void SetToolbarsDefault() + { + ToolStripPanelFromString("top").Join(_quickConnectToolStrip, new Point(300, 0)); _quickConnectToolStrip.Visible = true; - ToolStripPanelFromString("bottom").Join(_externalToolsToolStrip, new Point(3, 0)); + ToolStripPanelFromString("bottom").Join(_externalToolsToolStrip, new Point(3, 0)); _externalToolsToolStrip.Visible = false; - } + } - private void LoadToolbarsFromSettings() - { + private void LoadToolbarsFromSettings() + { ResetAllToolbarLocations(); - AddMainMenuPanel(); + AddMainMenuPanel(); AddExternalAppsPanel(); - AddQuickConnectPanel(); - AddMultiSshPanel(); + AddQuickConnectPanel(); + AddMultiSshPanel(); } /// @@ -213,74 +217,75 @@ namespace mRemoteNG.Config.Settings /// Since all toolbars start in this temp panel, no toolbar load /// can be blocked by pre-existing toolbars. /// - private void ResetAllToolbarLocations() - { - var tempToolStrip = new ToolStripPanel(); + private void ResetAllToolbarLocations() + { + var tempToolStrip = new ToolStripPanel(); tempToolStrip.Join(_mainMenu); - tempToolStrip.Join(_quickConnectToolStrip); - tempToolStrip.Join(_externalToolsToolStrip); - tempToolStrip.Join(_multiSshToolStrip); + tempToolStrip.Join(_quickConnectToolStrip); + tempToolStrip.Join(_externalToolsToolStrip); + tempToolStrip.Join(_multiSshToolStrip); } - private void AddMainMenuPanel() - { - SetToolstripGripStyle(_mainMenu); + private void AddMainMenuPanel() + { + SetToolstripGripStyle(_mainMenu); var toolStripPanel = ToolStripPanelFromString("top"); - toolStripPanel.Join(_mainMenu, new Point(3, 0)); + toolStripPanel.Join(_mainMenu, new Point(3, 0)); } - private void AddQuickConnectPanel() - { - SetToolstripGripStyle(_quickConnectToolStrip); + private void AddQuickConnectPanel() + { + SetToolstripGripStyle(_quickConnectToolStrip); _quickConnectToolStrip.Visible = mRemoteNG.Settings.Default.QuickyTBVisible; var toolStripPanel = ToolStripPanelFromString(mRemoteNG.Settings.Default.QuickyTBParentDock); toolStripPanel.Join(_quickConnectToolStrip, mRemoteNG.Settings.Default.QuickyTBLocation); - } - - private void AddExternalAppsPanel() - { - SetToolstripGripStyle(_externalToolsToolStrip); + } + + private void AddExternalAppsPanel() + { + SetToolstripGripStyle(_externalToolsToolStrip); _externalToolsToolStrip.Visible = mRemoteNG.Settings.Default.ExtAppsTBVisible; var toolStripPanel = ToolStripPanelFromString(mRemoteNG.Settings.Default.ExtAppsTBParentDock); toolStripPanel.Join(_externalToolsToolStrip, mRemoteNG.Settings.Default.ExtAppsTBLocation); - } + } - private void AddMultiSshPanel() - { - SetToolstripGripStyle(_multiSshToolStrip); - _multiSshToolStrip.Visible = mRemoteNG.Settings.Default.MultiSshToolbarVisible; + private void AddMultiSshPanel() + { + SetToolstripGripStyle(_multiSshToolStrip); + _multiSshToolStrip.Visible = mRemoteNG.Settings.Default.MultiSshToolbarVisible; var toolStripPanel = ToolStripPanelFromString(mRemoteNG.Settings.Default.MultiSshToolbarParentDock); toolStripPanel.Join(_multiSshToolStrip, mRemoteNG.Settings.Default.MultiSshToolbarLocation); - } - - private void SetToolstripGripStyle(ToolStrip toolbar) - { - toolbar.GripStyle = mRemoteNG.Settings.Default.LockToolbars - ? ToolStripGripStyle.Hidden - : ToolStripGripStyle.Visible; } - - private ToolStripPanel ToolStripPanelFromString(string panel) - { - switch (panel.ToLower()) - { - case "top": - return MainForm.tsContainer.TopToolStripPanel; - case "bottom": - return MainForm.tsContainer.BottomToolStripPanel; - case "left": - return MainForm.tsContainer.LeftToolStripPanel; - case "right": - return MainForm.tsContainer.RightToolStripPanel; - default: - return MainForm.tsContainer.TopToolStripPanel; - } - } - private void LoadExternalAppsFromXml() - { + private void SetToolstripGripStyle(ToolStrip toolbar) + { + toolbar.GripStyle = mRemoteNG.Settings.Default.LockToolbars + ? ToolStripGripStyle.Hidden + : ToolStripGripStyle.Visible; + } + + private ToolStripPanel ToolStripPanelFromString(string panel) + { + switch (panel.ToLower()) + { + case "top": + return MainForm.tsContainer.TopToolStripPanel; + case "bottom": + return MainForm.tsContainer.BottomToolStripPanel; + case "left": + return MainForm.tsContainer.LeftToolStripPanel; + case "right": + return MainForm.tsContainer.RightToolStripPanel; + default: + return MainForm.tsContainer.TopToolStripPanel; + } + } + + private void LoadExternalAppsFromXml() + { _externalAppsLoader.LoadExternalAppsFromXML(); } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Config/Settings/SettingsSaver.cs b/mRemoteV1/Config/Settings/SettingsSaver.cs index f41ed382..b8fe2b6b 100644 --- a/mRemoteV1/Config/Settings/SettingsSaver.cs +++ b/mRemoteV1/Config/Settings/SettingsSaver.cs @@ -11,11 +11,10 @@ namespace mRemoteNG.Config.Settings { public static class SettingsSaver { - public static void SaveSettings( - Control quickConnectToolStrip, - ExternalToolsToolStrip externalToolsToolStrip, - MultiSshToolStrip multiSshToolStrip, - FrmMain frmMain) + public static void SaveSettings(Control quickConnectToolStrip, + ExternalToolsToolStrip externalToolsToolStrip, + MultiSshToolStrip multiSshToolStrip, + FrmMain frmMain) { try { @@ -50,7 +49,7 @@ namespace mRemoteNG.Config.Settings SaveExternalAppsToolbarLocation(externalToolsToolStrip); SaveQuickConnectToolbarLocation(quickConnectToolStrip); SaveMultiSshToolbarLocation(multiSshToolStrip); - + mRemoteNG.Settings.Default.Save(); SaveDockPanelLayout(); @@ -100,9 +99,9 @@ namespace mRemoteNG.Config.Settings { var panelLayoutXmlFilePath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName; var panelLayoutSaver = new DockPanelLayoutSaver( - new DockPanelLayoutSerializer(), - new FileDataProvider(panelLayoutXmlFilePath) - ); + new DockPanelLayoutSerializer(), + new FileDataProvider(panelLayoutXmlFilePath) + ); panelLayoutSaver.Save(); } diff --git a/mRemoteV1/Connection/AbstractConnectionRecord.cs b/mRemoteV1/Connection/AbstractConnectionRecord.cs index 2b36fefd..8e7c394f 100644 --- a/mRemoteV1/Connection/AbstractConnectionRecord.cs +++ b/mRemoteV1/Connection/AbstractConnectionRecord.cs @@ -19,6 +19,7 @@ namespace mRemoteNG.Connection public abstract class AbstractConnectionRecord : INotifyPropertyChanged { #region Fields + private string _name; private string _description; private string _icon; @@ -85,10 +86,13 @@ namespace mRemoteNG.Connection private ProtocolVNC.Colors _vncColors; private ProtocolVNC.SmartSizeMode _vncSmartSizeMode; private bool _vncViewOnly; + #endregion #region Properties + #region Display + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), LocalizedAttributes.LocalizedDisplayName("strPropertyNameName"), LocalizedAttributes.LocalizedDescription("strPropertyDescriptionName")] @@ -99,8 +103,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameDescription"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDescription")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameDescription"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDescription")] public virtual string Description { get => GetPropertyValue("Description", _description); @@ -108,9 +112,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), - TypeConverter(typeof(ConnectionIcon)), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameIcon"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionIcon")] + TypeConverter(typeof(ConnectionIcon)), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameIcon"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionIcon")] public virtual string Icon { get => GetPropertyValue("Icon", _icon); @@ -118,19 +122,21 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), - LocalizedAttributes.LocalizedDisplayName("strPropertyNamePanel"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPanel")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNamePanel"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPanel")] public virtual string Panel { get => GetPropertyValue("Panel", _panel); set => SetField(ref _panel, value, "Panel"); } + #endregion #region Connection + [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 2), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameAddress"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAddress")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameAddress"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAddress")] public virtual string Hostname { get => _hostname.Trim(); @@ -138,8 +144,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 2), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameUsername"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUsername")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameUsername"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUsername")] [Obsolete("Use the CredentialRecord property")] [Browsable(false)] public virtual string Username @@ -149,9 +155,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 2), - LocalizedAttributes.LocalizedDisplayName("strPropertyNamePassword"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPassword"), - PasswordPropertyText(true)] + LocalizedAttributes.LocalizedDisplayName("strPropertyNamePassword"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPassword"), + PasswordPropertyText(true)] [Obsolete("Use the CredentialRecord property")] [Browsable(false)] public virtual string Password @@ -161,8 +167,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 2), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameDomain"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDomain")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameDomain"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDomain")] [Obsolete("Use the CredentialRecord property")] [Browsable(false)] public string Domain @@ -193,10 +199,11 @@ namespace mRemoteNG.Connection #endregion #region Protocol + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameProtocol"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionProtocol"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameProtocol"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionProtocol"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public virtual ProtocolType Protocol { get => GetPropertyValue("Protocol", _protocol); @@ -204,9 +211,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameExternalTool"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionExternalTool"), - TypeConverter(typeof(ExternalToolsTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameExternalTool"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionExternalTool"), + TypeConverter(typeof(ExternalToolsTypeConverter))] public string ExtApp { get => GetPropertyValue("ExtApp", _extApp); @@ -214,8 +221,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNamePort"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPort")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNamePort"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPort")] public virtual int Port { get => GetPropertyValue("Port", _port); @@ -223,9 +230,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNamePuttySession"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPuttySession"), - TypeConverter(typeof(Config.Putty.PuttySessionsManager.SessionList))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNamePuttySession"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPuttySession"), + TypeConverter(typeof(Config.Putty.PuttySessionsManager.SessionList))] public virtual string PuttySession { get => GetPropertyValue("PuttySession", _puttySession); @@ -233,9 +240,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameEncryptionStrength"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEncryptionStrength"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameEncryptionStrength"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEncryptionStrength"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public IcaProtocol.EncryptionStrength ICAEncryptionStrength { get => GetPropertyValue("ICAEncryptionStrength", _icaEncryption); @@ -243,9 +250,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameUseConsoleSession"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUseConsoleSession"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameUseConsoleSession"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUseConsoleSession"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool UseConsoleSession { get => GetPropertyValue("UseConsoleSession", _useConsoleSession); @@ -253,9 +260,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameAuthenticationLevel"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAuthenticationLevel"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameAuthenticationLevel"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAuthenticationLevel"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.AuthenticationLevel RDPAuthenticationLevel { get => GetPropertyValue("RDPAuthenticationLevel", _rdpAuthenticationLevel); @@ -263,23 +270,24 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDPMinutesToIdleTimeout"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDPMinutesToIdleTimeout")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDPMinutesToIdleTimeout"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDPMinutesToIdleTimeout")] public virtual int RDPMinutesToIdleTimeout { get => GetPropertyValue("RDPMinutesToIdleTimeout", _rdpMinutesToIdleTimeout); - set { - if(value < 0) + set + { + if (value < 0) value = 0; - else if(value > 240) + else if (value > 240) value = 240; SetField(ref _rdpMinutesToIdleTimeout, value, "RDPMinutesToIdleTimeout"); } } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDPAlertIdleTimeout"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDPAlertIdleTimeout")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDPAlertIdleTimeout"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDPAlertIdleTimeout")] public bool RDPAlertIdleTimeout { get => GetPropertyValue("RDPAlertIdleTimeout", _rdpAlertIdleTimeout); @@ -287,8 +295,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameLoadBalanceInfo"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionLoadBalanceInfo")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameLoadBalanceInfo"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionLoadBalanceInfo")] public string LoadBalanceInfo { get => GetPropertyValue("LoadBalanceInfo", _loadBalanceInfo).Trim(); @@ -296,9 +304,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRenderingEngine"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRenderingEngine"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRenderingEngine"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRenderingEngine"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public HTTPBase.RenderingEngine RenderingEngine { get => GetPropertyValue("RenderingEngine", _renderingEngine); @@ -306,21 +314,23 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 3), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameUseCredSsp"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUseCredSsp"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameUseCredSsp"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUseCredSsp"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool UseCredSsp { get => GetPropertyValue("UseCredSsp", _useCredSsp); set => SetField(ref _useCredSsp, value, "UseCredSsp"); } + #endregion #region RD Gateway + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 4), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayUsageMethod"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayUsageMethod"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayUsageMethod"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayUsageMethod"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.RDGatewayUsageMethod RDGatewayUsageMethod { get => GetPropertyValue("RDGatewayUsageMethod", _rdGatewayUsageMethod); @@ -328,8 +338,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 4), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayHostname"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayHostname")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayHostname"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayHostname")] public string RDGatewayHostname { get => GetPropertyValue("RDGatewayHostname", _rdGatewayHostname).Trim(); @@ -337,9 +347,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 4), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayUseConnectionCredentials"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayUseConnectionCredentials"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayUseConnectionCredentials"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayUseConnectionCredentials"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.RDGatewayUseConnectionCredentials RDGatewayUseConnectionCredentials { get => GetPropertyValue("RDGatewayUseConnectionCredentials", _rdGatewayUseConnectionCredentials); @@ -347,8 +357,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 4), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayUsername"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayUsername")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayUsername"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayUsername")] [Obsolete] public string RDGatewayUsername { @@ -357,9 +367,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 4), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayPassword"), - LocalizedAttributes.LocalizedDescription("strPropertyNameRDGatewayPassword"), - PasswordPropertyText(true)] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayPassword"), + LocalizedAttributes.LocalizedDescription("strPropertyNameRDGatewayPassword"), + PasswordPropertyText(true)] [Obsolete] public string RDGatewayPassword { @@ -368,21 +378,23 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 4), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayDomain"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayDomain")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRDGatewayDomain"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRDGatewayDomain")] [Obsolete] public string RDGatewayDomain { get => GetPropertyValue("RDGatewayDomain", _rdGatewayDomain).Trim(); set => SetField(ref _rdGatewayDomain, value?.Trim(), "RDGatewayDomain"); } + #endregion #region Appearance + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameResolution"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionResolution"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameResolution"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionResolution"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.RDPResolutions Resolution { get => GetPropertyValue("Resolution", _resolution); @@ -390,9 +402,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameAutomaticResize"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAutomaticResize"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameAutomaticResize"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAutomaticResize"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool AutomaticResize { get => GetPropertyValue("AutomaticResize", _automaticResize); @@ -400,9 +412,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameColors"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionColors"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameColors"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionColors"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.RDPColors Colors { get => GetPropertyValue("Colors", _colors); @@ -410,9 +422,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameCacheBitmaps"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionCacheBitmaps"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameCacheBitmaps"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionCacheBitmaps"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool CacheBitmaps { get => GetPropertyValue("CacheBitmaps", _cacheBitmaps); @@ -420,9 +432,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameDisplayWallpaper"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDisplayWallpaper"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameDisplayWallpaper"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDisplayWallpaper"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool DisplayWallpaper { get => GetPropertyValue("DisplayWallpaper", _displayWallpaper); @@ -430,9 +442,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameDisplayThemes"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDisplayThemes"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameDisplayThemes"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionDisplayThemes"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool DisplayThemes { get => GetPropertyValue("DisplayThemes", _displayThemes); @@ -440,9 +452,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameEnableFontSmoothing"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEnableFontSmoothing"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameEnableFontSmoothing"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEnableFontSmoothing"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool EnableFontSmoothing { get => GetPropertyValue("EnableFontSmoothing", _enableFontSmoothing); @@ -450,21 +462,23 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameEnableDesktopComposition"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEnableDesktopComposition"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameEnableDesktopComposition"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEnableDesktopComposition"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool EnableDesktopComposition { get => GetPropertyValue("EnableDesktopComposition", _enableDesktopComposition); set => SetField(ref _enableDesktopComposition, value, "EnableDesktopComposition"); } + #endregion #region Redirect + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectKeys"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectKeys"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectKeys"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectKeys"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RedirectKeys { get => GetPropertyValue("RedirectKeys", _redirectKeys); @@ -472,9 +486,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectDrives"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectDrives"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectDrives"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectDrives"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RedirectDiskDrives { get => GetPropertyValue("RedirectDiskDrives", _redirectDiskDrives); @@ -482,9 +496,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectPrinters"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectPrinters"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectPrinters"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectPrinters"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RedirectPrinters { get => GetPropertyValue("RedirectPrinters", _redirectPrinters); @@ -492,9 +506,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectClipboard"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectClipboard"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectClipboard"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectClipboard"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RedirectClipboard { get { return GetPropertyValue("RedirectClipboard", _redirectClipboard); } @@ -502,9 +516,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectPorts"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectPorts"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectPorts"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectPorts"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RedirectPorts { get => GetPropertyValue("RedirectPorts", _redirectPorts); @@ -512,9 +526,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectSmartCards"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectSmartCards"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectSmartCards"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectSmartCards"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RedirectSmartCards { get => GetPropertyValue("RedirectSmartCards", _redirectSmartCards); @@ -522,9 +536,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectSounds"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectSounds"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameRedirectSounds"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionRedirectSounds"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.RDPSounds RedirectSound { get => GetPropertyValue("RedirectSound", _redirectSound); @@ -532,24 +546,25 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 6), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameSoundQuality"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionSoundQuality"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameSoundQuality"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionSoundQuality"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public RdpProtocol.RDPSoundQuality SoundQuality { get => GetPropertyValue("SoundQuality", _soundQuality); set => SetField(ref _soundQuality, value, "SoundQuality"); } + #endregion #region Misc - [Browsable(false)] - public string ConstantID { get; /*set;*/ } + + [Browsable(false)] public string ConstantID { get; /*set;*/ } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameExternalToolBefore"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionExternalToolBefore"), - TypeConverter(typeof(ExternalToolsTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameExternalToolBefore"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionExternalToolBefore"), + TypeConverter(typeof(ExternalToolsTypeConverter))] public virtual string PreExtApp { get => GetPropertyValue("PreExtApp", _preExtApp); @@ -557,9 +572,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameExternalToolAfter"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionExternalToolAfter"), - TypeConverter(typeof(ExternalToolsTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameExternalToolAfter"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionExternalToolAfter"), + TypeConverter(typeof(ExternalToolsTypeConverter))] public virtual string PostExtApp { get => GetPropertyValue("PostExtApp", _postExtApp); @@ -567,8 +582,8 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameMACAddress"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionMACAddress")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameMACAddress"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionMACAddress")] public virtual string MacAddress { get => GetPropertyValue("MacAddress", _macAddress); @@ -576,21 +591,23 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameUser1"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUser1")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameUser1"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionUser1")] public virtual string UserField { get => GetPropertyValue("UserField", _userField); set => SetField(ref _userField, value, "UserField"); } + #endregion #region VNC + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameCompression"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionCompression"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameCompression"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionCompression"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public ProtocolVNC.Compression VNCCompression { get => GetPropertyValue("VNCCompression", _vncCompression); @@ -598,10 +615,10 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameEncoding"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEncoding"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameEncoding"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionEncoding"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public ProtocolVNC.Encoding VNCEncoding { get => GetPropertyValue("VNCEncoding", _vncEncoding); @@ -609,10 +626,10 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 2), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameAuthenticationMode"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAuthenticationMode"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameAuthenticationMode"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionAuthenticationMode"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public ProtocolVNC.AuthMode VNCAuthMode { get => GetPropertyValue("VNCAuthMode", _vncAuthMode); @@ -620,10 +637,10 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyType"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyType"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyType"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyType"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public ProtocolVNC.ProxyType VNCProxyType { get => GetPropertyValue("VNCProxyType", _vncProxyType); @@ -631,9 +648,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyAddress"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyAddress")] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyAddress"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyAddress")] public string VNCProxyIP { get => GetPropertyValue("VNCProxyIP", _vncProxyIp); @@ -641,9 +658,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyPort"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyPort")] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyPort"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyPort")] public int VNCProxyPort { get => GetPropertyValue("VNCProxyPort", _vncProxyPort); @@ -651,9 +668,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyUsername"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyUsername")] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyUsername"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyUsername")] [Obsolete] public string VNCProxyUsername { @@ -662,10 +679,10 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 7), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyPassword"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyPassword"), - PasswordPropertyText(true)] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameVNCProxyPassword"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionVNCProxyPassword"), + PasswordPropertyText(true)] [Obsolete] public string VNCProxyPassword { @@ -674,10 +691,10 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - Browsable(false), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameColors"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionColors"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + Browsable(false), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameColors"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionColors"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public ProtocolVNC.Colors VNCColors { get => GetPropertyValue("VNCColors", _vncColors); @@ -685,9 +702,9 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameSmartSizeMode"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionSmartSizeMode"), - TypeConverter(typeof(MiscTools.EnumTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameSmartSizeMode"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionSmartSizeMode"), + TypeConverter(typeof(MiscTools.EnumTypeConverter))] public ProtocolVNC.SmartSizeMode VNCSmartSizeMode { get => GetPropertyValue("VNCSmartSizeMode", _vncSmartSizeMode); @@ -695,21 +712,23 @@ namespace mRemoteNG.Connection } [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 5), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameViewOnly"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionViewOnly"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayName("strPropertyNameViewOnly"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionViewOnly"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool VNCViewOnly { get => GetPropertyValue("VNCViewOnly", _vncViewOnly); set => SetField(ref _vncViewOnly, value, "VNCViewOnly"); } - #endregion + #endregion - protected AbstractConnectionRecord(string uniqueId) - { - ConstantID = uniqueId.ThrowIfNullOrEmpty(nameof(uniqueId)); - } + #endregion + + protected AbstractConnectionRecord(string uniqueId) + { + ConstantID = uniqueId.ThrowIfNullOrEmpty(nameof(uniqueId)); + } protected virtual TPropertyType GetPropertyValue(string propertyName, TPropertyType value) { @@ -717,6 +736,7 @@ namespace mRemoteNG.Connection } public event PropertyChangedEventHandler PropertyChanged; + protected virtual void RaisePropertyChangedEvent(object sender, PropertyChangedEventArgs args) { PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs(args.PropertyName)); diff --git a/mRemoteV1/Connection/ConnectionIcon.cs b/mRemoteV1/Connection/ConnectionIcon.cs index fc4397c1..60bae3c1 100644 --- a/mRemoteV1/Connection/ConnectionIcon.cs +++ b/mRemoteV1/Connection/ConnectionIcon.cs @@ -6,43 +6,45 @@ using mRemoteNG.App.Info; namespace mRemoteNG.Connection { - public class ConnectionIcon : StringConverter - { - public static string[] Icons = {}; - - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - return new StandardValuesCollection(Icons); - } - - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) - { - return true; - } - - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } - - public static System.Drawing.Icon FromString(string iconName) - { - try - { - var iconPath = $"{GeneralAppInfo.HomePath}\\Icons\\{iconName}.ico"; - - if (System.IO.File.Exists(iconPath)) - { - var nI = new System.Drawing.Icon(iconPath); - return nI; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, - $"Couldn\'t get Icon from String" + Environment.NewLine + ex.Message); - } - return null; - } - } -} + public class ConnectionIcon : StringConverter + { + public static string[] Icons = { }; + + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + return new StandardValuesCollection(Icons); + } + + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { + return true; + } + + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { + return true; + } + + public static System.Drawing.Icon FromString(string iconName) + { + try + { + var iconPath = $"{GeneralAppInfo.HomePath}\\Icons\\{iconName}.ico"; + + if (System.IO.File.Exists(iconPath)) + { + var nI = new System.Drawing.Icon(iconPath); + return nI; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + $"Couldn\'t get Icon from String" + Environment.NewLine + + ex.Message); + } + + return null; + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/ConnectionInfo.cs b/mRemoteV1/Connection/ConnectionInfo.cs index 4f007de7..67e18b94 100644 --- a/mRemoteV1/Connection/ConnectionInfo.cs +++ b/mRemoteV1/Connection/ConnectionInfo.cs @@ -21,22 +21,18 @@ namespace mRemoteNG.Connection { [DefaultProperty("Name")] public class ConnectionInfo : AbstractConnectionRecord, IHasParent, IInheritable - { + { #region Public Properties - [Browsable(false)] - public ConnectionInfoInheritance Inheritance { get; set; } - [Browsable(false)] - public ProtocolList OpenConnections { get; protected set; } + [Browsable(false)] public ConnectionInfoInheritance Inheritance { get; set; } - [Browsable(false)] - public virtual bool IsContainer { get; set; } + [Browsable(false)] public ProtocolList OpenConnections { get; protected set; } - [Browsable(false)] - public bool IsDefault { get; set; } + [Browsable(false)] public virtual bool IsContainer { get; set; } - [Browsable(false)] - public ContainerInfo Parent { get; internal set; } + [Browsable(false)] public bool IsDefault { get; set; } + + [Browsable(false)] public ContainerInfo Parent { get; internal set; } //[Browsable(false)] //private int PositionID { get; set; } @@ -45,20 +41,20 @@ namespace mRemoteNG.Connection // ReSharper disable once UnusedAutoPropertyAccessor.Global public bool IsQuickConnect { get; set; } - [Browsable(false)] - public bool PleaseConnect { get; set; } - #endregion + [Browsable(false)] public bool PleaseConnect { get; set; } + + #endregion #region Constructors - public ConnectionInfo() - : this(Guid.NewGuid().ToString()) - { - } + public ConnectionInfo() + : this(Guid.NewGuid().ToString()) + { + } public ConnectionInfo(string uniqueId) - : base(uniqueId) - { + : base(uniqueId) + { SetTreeDisplayDefaults(); SetConnectionDefaults(); SetProtocolDefaults(); @@ -69,56 +65,59 @@ namespace mRemoteNG.Connection SetVncDefaults(); SetNonBrowsablePropertiesDefaults(); SetDefaults(); - } + } + #endregion - + #region Public Methods - public virtual ConnectionInfo Clone() - { - var newConnectionInfo = new ConnectionInfo(); + + public virtual ConnectionInfo Clone() + { + var newConnectionInfo = new ConnectionInfo(); newConnectionInfo.CopyFrom(this); - newConnectionInfo.Inheritance = Inheritance.Clone(); + newConnectionInfo.Inheritance = Inheritance.Clone(); newConnectionInfo.Inheritance.Parent = newConnectionInfo; return newConnectionInfo; - } + } - public void CopyFrom(ConnectionInfo sourceConnectionInfo) - { - var properties = GetType().BaseType?.GetProperties().Where(prop => prop.CanRead && prop.CanWrite); - if (properties == null) return; - foreach (var property in properties) - { - if (property.Name == nameof(Parent)) continue; - var remotePropertyValue = property.GetValue(sourceConnectionInfo, null); + public void CopyFrom(ConnectionInfo sourceConnectionInfo) + { + var properties = GetType().BaseType?.GetProperties().Where(prop => prop.CanRead && prop.CanWrite); + if (properties == null) return; + foreach (var property in properties) + { + if (property.Name == nameof(Parent)) continue; + var remotePropertyValue = property.GetValue(sourceConnectionInfo, null); property.SetValue(this, remotePropertyValue, null); - } + } + var clonedInheritance = sourceConnectionInfo.Inheritance.Clone(); clonedInheritance.Parent = this; Inheritance = clonedInheritance; } - public virtual TreeNodeType GetTreeNodeType() - { - return TreeNodeType.Connection; - } + public virtual TreeNodeType GetTreeNodeType() + { + return TreeNodeType.Connection; + } private void SetDefaults() - { - if (Port == 0) - { - SetDefaultPort(); - } - } - - public int GetDefaultPort() - { - return GetDefaultPort(Protocol); - } - - public void SetDefaultPort() - { - Port = GetDefaultPort(); - } + { + if (Port == 0) + { + SetDefaultPort(); + } + } + + public int GetDefaultPort() + { + return GetDefaultPort(Protocol); + } + + public void SetDefaultPort() + { + Port = GetDefaultPort(); + } protected virtual IEnumerable GetProperties(string[] excludedPropertyNames) { @@ -151,41 +150,45 @@ namespace mRemoteNG.Connection Parent?.RemoveChild(this); } - public ConnectionInfo GetRootParent() - { - return Parent != null ? Parent.GetRootParent() : this; - } + public ConnectionInfo GetRootParent() + { + return Parent != null ? Parent.GetRootParent() : this; + } - #endregion + #endregion #region Public Enumerations + [Flags()] public enum Force - { - None = 0, - UseConsoleSession = 1, - Fullscreen = 2, - DoNotJump = 4, - OverridePanel = 8, - DontUseConsoleSession = 16, - NoCredentials = 32 - } + { + None = 0, + UseConsoleSession = 1, + Fullscreen = 2, + DoNotJump = 4, + OverridePanel = 8, + DontUseConsoleSession = 16, + NoCredentials = 32 + } + #endregion - + #region Private Methods + protected override TPropertyType GetPropertyValue(string propertyName, TPropertyType value) { if (!ShouldThisPropertyBeInherited(propertyName)) return value; - var couldGetInheritedValue = TryGetInheritedPropertyValue(propertyName, out var inheritedValue); + var couldGetInheritedValue = + TryGetInheritedPropertyValue(propertyName, out var inheritedValue); return couldGetInheritedValue ? inheritedValue : value; } - private bool ShouldThisPropertyBeInherited(string propertyName) + private bool ShouldThisPropertyBeInherited(string propertyName) { return ParentIsValidInheritanceTarget() && IsInheritanceTurnedOnForThisProperty(propertyName); } @@ -199,7 +202,8 @@ namespace mRemoteNG.Connection { var inheritType = Inheritance.GetType(); var inheritPropertyInfo = inheritType.GetProperty(propertyName); - var inheritPropertyValue = inheritPropertyInfo != null && Convert.ToBoolean(inheritPropertyInfo.GetValue(Inheritance, null)); + var inheritPropertyValue = inheritPropertyInfo != null && + Convert.ToBoolean(inheritPropertyInfo.GetValue(Inheritance, null)); return inheritPropertyValue; } @@ -210,24 +214,26 @@ namespace mRemoteNG.Connection var connectionInfoType = Parent.GetType(); var parentPropertyInfo = connectionInfoType.GetProperty(propertyName); if (parentPropertyInfo == null) - throw new NullReferenceException($"Could not retrieve property data for property '{propertyName}' on parent node '{Parent?.Name}'"); + throw new NullReferenceException( + $"Could not retrieve property data for property '{propertyName}' on parent node '{Parent?.Name}'"); inheritedValue = (TPropertyType)parentPropertyInfo.GetValue(Parent, null); return true; } catch (Exception e) { - Runtime.MessageCollector.AddExceptionStackTrace($"Error retrieving inherited property '{propertyName}'", e); + Runtime.MessageCollector.AddExceptionStackTrace($"Error retrieving inherited property '{propertyName}'", + e); inheritedValue = default(TPropertyType); return false; } } - private static int GetDefaultPort(ProtocolType protocol) - { - try - { - // ReSharper disable once SwitchStatementMissingSomeCases + private static int GetDefaultPort(ProtocolType protocol) + { + try + { + // ReSharper disable once SwitchStatementMissingSomeCases switch (protocol) { case ProtocolType.RDP: @@ -253,14 +259,15 @@ namespace mRemoteNG.Connection case ProtocolType.IntApp: return (int)IntegratedProgram.Defaults.Port; } + return 0; - } - catch (Exception ex) - { + } + catch (Exception ex) + { Runtime.MessageCollector.AddExceptionMessage(Language.strConnectionSetDefaultPortFailed, ex); return 0; - } - } + } + } private void SetTreeDisplayDefaults() { @@ -281,31 +288,54 @@ namespace mRemoteNG.Connection ExtApp = Settings.Default.ConDefaultExtApp; Port = 0; PuttySession = Settings.Default.ConDefaultPuttySession; - ICAEncryptionStrength = (IcaProtocol.EncryptionStrength) Enum.Parse(typeof(IcaProtocol.EncryptionStrength), Settings.Default.ConDefaultICAEncryptionStrength); + ICAEncryptionStrength = (IcaProtocol.EncryptionStrength)Enum.Parse(typeof(IcaProtocol.EncryptionStrength), + Settings + .Default + .ConDefaultICAEncryptionStrength); UseConsoleSession = Settings.Default.ConDefaultUseConsoleSession; - RDPAuthenticationLevel = (RdpProtocol.AuthenticationLevel) Enum.Parse(typeof(RdpProtocol.AuthenticationLevel), Settings.Default.ConDefaultRDPAuthenticationLevel); + RDPAuthenticationLevel = (RdpProtocol.AuthenticationLevel)Enum.Parse( + typeof(RdpProtocol.AuthenticationLevel + ), + Settings + .Default + .ConDefaultRDPAuthenticationLevel); RDPMinutesToIdleTimeout = Settings.Default.ConDefaultRDPMinutesToIdleTimeout; RDPAlertIdleTimeout = Settings.Default.ConDefaultRDPAlertIdleTimeout; LoadBalanceInfo = Settings.Default.ConDefaultLoadBalanceInfo; - RenderingEngine = (HTTPBase.RenderingEngine) Enum.Parse(typeof(HTTPBase.RenderingEngine), Settings.Default.ConDefaultRenderingEngine); + RenderingEngine = (HTTPBase.RenderingEngine)Enum.Parse(typeof(HTTPBase.RenderingEngine), + Settings.Default.ConDefaultRenderingEngine); UseCredSsp = Settings.Default.ConDefaultUseCredSsp; } private void SetRdGatewayDefaults() { - RDGatewayUsageMethod = (RdpProtocol.RDGatewayUsageMethod) Enum.Parse(typeof(RdpProtocol.RDGatewayUsageMethod), Settings.Default.ConDefaultRDGatewayUsageMethod); + RDGatewayUsageMethod = (RdpProtocol.RDGatewayUsageMethod)Enum.Parse( + typeof(RdpProtocol.RDGatewayUsageMethod + ), + Settings + .Default + .ConDefaultRDGatewayUsageMethod); RDGatewayHostname = Settings.Default.ConDefaultRDGatewayHostname; - RDGatewayUseConnectionCredentials = (RdpProtocol.RDGatewayUseConnectionCredentials) Enum.Parse(typeof(RdpProtocol.RDGatewayUseConnectionCredentials), Settings.Default.ConDefaultRDGatewayUseConnectionCredentials); + RDGatewayUseConnectionCredentials = (RdpProtocol.RDGatewayUseConnectionCredentials)Enum.Parse( + typeof( + RdpProtocol + .RDGatewayUseConnectionCredentials + ), + Settings + .Default + .ConDefaultRDGatewayUseConnectionCredentials); RDGatewayUsername = Settings.Default.ConDefaultRDGatewayUsername; RDGatewayPassword = Settings.Default.ConDefaultRDGatewayPassword; RDGatewayDomain = Settings.Default.ConDefaultRDGatewayDomain; } - private void SetAppearanceDefaults() + private void SetAppearanceDefaults() { - Resolution = (RdpProtocol.RDPResolutions) Enum.Parse(typeof(RdpProtocol.RDPResolutions), Settings.Default.ConDefaultResolution); + Resolution = (RdpProtocol.RDPResolutions)Enum.Parse(typeof(RdpProtocol.RDPResolutions), + Settings.Default.ConDefaultResolution); AutomaticResize = Settings.Default.ConDefaultAutomaticResize; - Colors = (RdpProtocol.RDPColors) Enum.Parse(typeof(RdpProtocol.RDPColors), Settings.Default.ConDefaultColors); + Colors = (RdpProtocol.RDPColors)Enum.Parse(typeof(RdpProtocol.RDPColors), + Settings.Default.ConDefaultColors); CacheBitmaps = Settings.Default.ConDefaultCacheBitmaps; DisplayWallpaper = Settings.Default.ConDefaultDisplayWallpaper; DisplayThemes = Settings.Default.ConDefaultDisplayThemes; @@ -321,8 +351,10 @@ namespace mRemoteNG.Connection RedirectClipboard = Settings.Default.ConDefaultRedirectClipboard; RedirectPorts = Settings.Default.ConDefaultRedirectPorts; RedirectSmartCards = Settings.Default.ConDefaultRedirectSmartCards; - RedirectSound = (RdpProtocol.RDPSounds) Enum.Parse(typeof(RdpProtocol.RDPSounds), Settings.Default.ConDefaultRedirectSound); - SoundQuality = (RdpProtocol.RDPSoundQuality)Enum.Parse(typeof(RdpProtocol.RDPSoundQuality), Settings.Default.ConDefaultSoundQuality); + RedirectSound = (RdpProtocol.RDPSounds)Enum.Parse(typeof(RdpProtocol.RDPSounds), + Settings.Default.ConDefaultRedirectSound); + SoundQuality = (RdpProtocol.RDPSoundQuality)Enum.Parse(typeof(RdpProtocol.RDPSoundQuality), + Settings.Default.ConDefaultSoundQuality); } private void SetMiscDefaults() @@ -335,16 +367,22 @@ namespace mRemoteNG.Connection private void SetVncDefaults() { - VNCCompression = (ProtocolVNC.Compression) Enum.Parse(typeof(ProtocolVNC.Compression), Settings.Default.ConDefaultVNCCompression); - VNCEncoding = (ProtocolVNC.Encoding) Enum.Parse(typeof(ProtocolVNC.Encoding), Settings.Default.ConDefaultVNCEncoding); - VNCAuthMode = (ProtocolVNC.AuthMode) Enum.Parse(typeof(ProtocolVNC.AuthMode), Settings.Default.ConDefaultVNCAuthMode); - VNCProxyType = (ProtocolVNC.ProxyType) Enum.Parse(typeof(ProtocolVNC.ProxyType), Settings.Default.ConDefaultVNCProxyType); + VNCCompression = (ProtocolVNC.Compression)Enum.Parse(typeof(ProtocolVNC.Compression), + Settings.Default.ConDefaultVNCCompression); + VNCEncoding = + (ProtocolVNC.Encoding)Enum.Parse(typeof(ProtocolVNC.Encoding), Settings.Default.ConDefaultVNCEncoding); + VNCAuthMode = + (ProtocolVNC.AuthMode)Enum.Parse(typeof(ProtocolVNC.AuthMode), Settings.Default.ConDefaultVNCAuthMode); + VNCProxyType = (ProtocolVNC.ProxyType)Enum.Parse(typeof(ProtocolVNC.ProxyType), + Settings.Default.ConDefaultVNCProxyType); VNCProxyIP = Settings.Default.ConDefaultVNCProxyIP; VNCProxyPort = Settings.Default.ConDefaultVNCProxyPort; VNCProxyUsername = Settings.Default.ConDefaultVNCProxyUsername; VNCProxyPassword = Settings.Default.ConDefaultVNCProxyPassword; - VNCColors = (ProtocolVNC.Colors) Enum.Parse(typeof(ProtocolVNC.Colors), Settings.Default.ConDefaultVNCColors); - VNCSmartSizeMode = (ProtocolVNC.SmartSizeMode) Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), Settings.Default.ConDefaultVNCSmartSizeMode); + VNCColors = (ProtocolVNC.Colors)Enum.Parse(typeof(ProtocolVNC.Colors), + Settings.Default.ConDefaultVNCColors); + VNCSmartSizeMode = (ProtocolVNC.SmartSizeMode)Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), + Settings.Default.ConDefaultVNCSmartSizeMode); VNCViewOnly = Settings.Default.ConDefaultVNCViewOnly; } @@ -356,10 +394,12 @@ namespace mRemoteNG.Connection } private void SetNewOpenConnectionList() - { - OpenConnections = new ProtocolList(); - OpenConnections.CollectionChanged += (sender, args) => RaisePropertyChangedEvent(this, new PropertyChangedEventArgs("OpenConnections")); - } + { + OpenConnections = new ProtocolList(); + OpenConnections.CollectionChanged += (sender, args) => + RaisePropertyChangedEvent(this, new PropertyChangedEventArgs("OpenConnections")); + } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/Connection/ConnectionInfoInheritance.cs b/mRemoteV1/Connection/ConnectionInfoInheritance.cs index 7d7e212c..2ac14f3e 100644 --- a/mRemoteV1/Connection/ConnectionInfoInheritance.cs +++ b/mRemoteV1/Connection/ConnectionInfoInheritance.cs @@ -7,38 +7,48 @@ using mRemoteNG.Tools; namespace mRemoteNG.Connection { - public class ConnectionInfoInheritance - { + public class ConnectionInfoInheritance + { private ConnectionInfoInheritance _tempInheritanceStorage; #region Public Properties + #region General + [LocalizedAttributes.LocalizedCategory("strCategoryGeneral"), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAll"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAll"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAll"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAll"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool EverythingInherited - { - get { return EverythingIsInherited(); } + { + get { return EverythingIsInherited(); } set { SetAllValues(value); } - } + } + #endregion + #region Display - [LocalizedAttributes.LocalizedCategory("strCategoryDisplay", 2), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDescription"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDescription"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Description {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryDisplay", 2), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameIcon"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionIcon"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Icon {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryDisplay", 2), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePanel"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPanel"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Panel {get; set;} + + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay", 2), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDescription"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDescription"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Description { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay", 2), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameIcon"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionIcon"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Icon { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay", 2), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePanel"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPanel"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Panel { get; set; } + #endregion + #region Connection [LocalizedAttributes.LocalizedCategory(nameof(Language.strCategoryConnection), 3), LocalizedAttributes.LocalizedDisplayNameInherit(nameof(Language.strCategoryCredentials)), @@ -47,308 +57,370 @@ namespace mRemoteNG.Connection public bool CredentialId { get; set; } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 3), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUsername"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUsername"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUsername"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUsername"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] [Browsable(false)] [Obsolete("Use the ConnectionRecord property")] public bool Username { get; set; } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 3), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePassword"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPassword"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePassword"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPassword"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] [Browsable(false)] [Obsolete("Use the ConnectionRecord property")] public bool Password { get; set; } [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 3), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDomain"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDomain"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDomain"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDomain"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] [Browsable(false)] [Obsolete("Use the ConnectionRecord property")] public bool Domain { get; set; } + #endregion + #region Protocol - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameProtocol"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionProtocol"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Protocol {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameExternalTool"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionExternalTool"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool ExtApp {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePort"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPort"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Port {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePuttySession"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPuttySession"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool PuttySession {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEncryptionStrength"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEncryptionStrength"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool ICAEncryptionStrength {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAuthenticationLevel"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAuthenticationLevel"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RDPAuthenticationLevel {get; set; } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDPMinutesToIdleTimeout"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDPMinutesToIdleTimeout"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RDPMinutesToIdleTimeout { get; set; } + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameProtocol"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionProtocol"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Protocol { get; set; } [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDPAlertIdleTimeout"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDPAlertIdleTimeout"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool RDPAlertIdleTimeout { get; set; } + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameExternalTool"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionExternalTool"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool ExtApp { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePort"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPort"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Port { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNamePuttySession"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionPuttySession"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool PuttySession { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEncryptionStrength"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEncryptionStrength"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool ICAEncryptionStrength { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAuthenticationLevel"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAuthenticationLevel"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDPAuthenticationLevel { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDPMinutesToIdleTimeout"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDPMinutesToIdleTimeout"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDPMinutesToIdleTimeout { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDPAlertIdleTimeout"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDPAlertIdleTimeout"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDPAlertIdleTimeout { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameLoadBalanceInfo"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionLoadBalanceInfo"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool LoadBalanceInfo { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRenderingEngine"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRenderingEngine"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RenderingEngine { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUseConsoleSession"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUseConsoleSession"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool UseConsoleSession { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUseCredSsp"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUseCredSsp"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool UseCredSsp { get; set; } - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameLoadBalanceInfo"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionLoadBalanceInfo"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool LoadBalanceInfo {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRenderingEngine"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRenderingEngine"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RenderingEngine {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUseConsoleSession"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUseConsoleSession"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool UseConsoleSession {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryProtocol", 4), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUseCredSsp"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUseCredSsp"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool UseCredSsp {get; set;} #endregion + #region RD Gateway - [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayUsageMethod"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayUsageMethod"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] - public bool RDGatewayUsageMethod {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayHostname"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayHostname"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] - public bool RDGatewayHostname {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayUseConnectionCredentials"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayUseConnectionCredentials"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] - public bool RDGatewayUseConnectionCredentials {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayUsername"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayUsername"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] - public bool RDGatewayUsername {get; set;} - [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayPassword"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayPassword"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] - public bool RDGatewayPassword {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayDomain"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayDomain"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] - public bool RDGatewayDomain {get; set;} + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayUsageMethod"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayUsageMethod"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDGatewayUsageMethod { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayHostname"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayHostname"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDGatewayHostname { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayUseConnectionCredentials"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute( + "strPropertyDescriptionRDGatewayUseConnectionCredentials"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDGatewayUseConnectionCredentials { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayUsername"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayUsername"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDGatewayUsername { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayPassword"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayPassword"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDGatewayPassword { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryGateway", 5), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRDGatewayDomain"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRDGatewayDomain"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RDGatewayDomain { get; set; } + #endregion + #region Appearance - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameResolution"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionResolution"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Resolution {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAutomaticResize"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAutomaticResize"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool AutomaticResize {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameColors"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionColors"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool Colors {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameCacheBitmaps"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionCacheBitmaps"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool CacheBitmaps {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDisplayWallpaper"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDisplayWallpaper"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool DisplayWallpaper {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDisplayThemes"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDisplayThemes"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool DisplayThemes {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEnableFontSmoothing"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEnableFontSmoothing"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool EnableFontSmoothing {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEnableDesktopComposition"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEnableEnableDesktopComposition"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool EnableDesktopComposition {get; set;} + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameResolution"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionResolution"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Resolution { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAutomaticResize"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAutomaticResize"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool AutomaticResize { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameColors"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionColors"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool Colors { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameCacheBitmaps"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionCacheBitmaps"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool CacheBitmaps { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDisplayWallpaper"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDisplayWallpaper"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool DisplayWallpaper { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameDisplayThemes"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionDisplayThemes"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool DisplayThemes { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEnableFontSmoothing"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEnableFontSmoothing"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool EnableFontSmoothing { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 6), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEnableDesktopComposition"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute( + "strPropertyDescriptionEnableEnableDesktopComposition"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool EnableDesktopComposition { get; set; } #endregion + #region Redirect - [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectKeys"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectKeys"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectKeys {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectDrives"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectDrives"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectDiskDrives {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectPrinters"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectPrinters"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectPrinters {get; set;} [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectClipboard"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectClipboard"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectClipboard { get; set; } - - [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectPorts"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectPorts"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectPorts {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectSmartCards"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectSmartCards"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectSmartCards {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectSounds"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectSounds"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool RedirectSound {get; set;} + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectKeys"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectKeys"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectKeys { get; set; } [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameSoundQuality"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionSoundQuality"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectDrives"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectDrives"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectDiskDrives { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectPrinters"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectPrinters"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectPrinters { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectClipboard"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectClipboard"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectClipboard { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectPorts"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectPorts"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectPorts { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectSmartCards"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectSmartCards"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectSmartCards { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameRedirectSounds"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionRedirectSounds"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool RedirectSound { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryRedirect", 7), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameSoundQuality"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionSoundQuality"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public bool SoundQuality { get; set; } + #endregion + #region Misc - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameExternalToolBefore"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionExternalToolBefore"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool PreExtApp {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameExternalToolAfter"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionExternalToolAfter"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool PostExtApp {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameMACAddress"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionMACAddress"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool MacAddress {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUser1"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUser1"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool UserField {get; set;} + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameExternalToolBefore"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionExternalToolBefore"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool PreExtApp { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameExternalToolAfter"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionExternalToolAfter"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool PostExtApp { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameMACAddress"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionMACAddress"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool MacAddress { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 8), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameUser1"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionUser1"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool UserField { get; set; } + #endregion + #region VNC - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameCompression"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionCompression"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCCompression {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEncoding"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEncoding"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCEncoding {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAuthenticationMode"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAuthenticationMode"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCAuthMode {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyType"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyType"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCProxyType {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyAddress"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyAddress"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCProxyIP {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyPort"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyPort"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCProxyPort {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyUsername"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyUsername"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCProxyUsername {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyPassword"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyPassword"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCProxyPassword {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameColors"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionColors"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCColors {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameSmartSizeMode"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionSmartSizeMode"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCSmartSizeMode {get; set;} - - [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), - LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameViewOnly"), - LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionViewOnly"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))]public bool VNCViewOnly {get; set;} - #endregion - - [Browsable(false)] - public object Parent {get; set;} - #endregion - - public ConnectionInfoInheritance(object parent, bool ignoreDefaultInheritance = false) - { + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameCompression"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionCompression"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCCompression { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameEncoding"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionEncoding"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCEncoding { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryConnection", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameAuthenticationMode"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionAuthenticationMode"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCAuthMode { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyType"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyType"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCProxyType { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyAddress"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyAddress"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCProxyIP { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyPort"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyPort"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCProxyPort { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyUsername"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyUsername"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCProxyUsername { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryMiscellaneous", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameVNCProxyPassword"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionVNCProxyPassword"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCProxyPassword { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameColors"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionColors"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCColors { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameSmartSizeMode"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionSmartSizeMode"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCSmartSizeMode { get; set; } + + [LocalizedAttributes.LocalizedCategory("strCategoryAppearance", 9), + LocalizedAttributes.LocalizedDisplayNameInheritAttribute("strPropertyNameViewOnly"), + LocalizedAttributes.LocalizedDescriptionInheritAttribute("strPropertyDescriptionViewOnly"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + public bool VNCViewOnly { get; set; } + + #endregion + + [Browsable(false)] public object Parent { get; set; } + + #endregion + + + public ConnectionInfoInheritance(object parent, bool ignoreDefaultInheritance = false) + { Parent = parent; - if (!ignoreDefaultInheritance) - SetAllValues(DefaultConnectionInheritance.Instance); - } + if (!ignoreDefaultInheritance) + SetAllValues(DefaultConnectionInheritance.Instance); + } - public ConnectionInfoInheritance Clone() - { - var newInheritance = (ConnectionInfoInheritance) MemberwiseClone(); - newInheritance._tempInheritanceStorage = null; + public ConnectionInfoInheritance Clone() + { + var newInheritance = (ConnectionInfoInheritance)MemberwiseClone(); + newInheritance._tempInheritanceStorage = null; return newInheritance; - } + } public void EnableInheritance() { @@ -374,14 +446,14 @@ namespace mRemoteNG.Connection } public void TurnOnInheritanceCompletely() - { - SetAllValues(true); - } - - public void TurnOffInheritanceCompletely() - { - SetAllValues(false); - } + { + SetAllValues(true); + } + + public void TurnOffInheritanceCompletely() + { + SetAllValues(false); + } private bool EverythingIsInherited() { @@ -408,8 +480,8 @@ namespace mRemoteNG.Connection return valueShouldNotBeFiltered; } - private void SetAllValues(bool value) - { + private void SetAllValues(bool value) + { var properties = GetProperties(); foreach (var property in properties) { @@ -418,7 +490,7 @@ namespace mRemoteNG.Connection } } - private void SetAllValues(ConnectionInfoInheritance otherInheritanceObject) + private void SetAllValues(ConnectionInfoInheritance otherInheritanceObject) { var properties = GetProperties(); foreach (var property in properties) diff --git a/mRemoteV1/Connection/ConnectionInitiator.cs b/mRemoteV1/Connection/ConnectionInitiator.cs index 1ef4bf20..ae982fe2 100644 --- a/mRemoteV1/Connection/ConnectionInitiator.cs +++ b/mRemoteV1/Connection/ConnectionInitiator.cs @@ -9,7 +9,8 @@ using System; using System.Collections.Generic; using System.Windows.Forms; using mRemoteNG.Credential; -using TabPage = Crownwood.Magic.Controls.TabPage; +using mRemoteNG.UI.Tabs; +using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.Connection @@ -25,45 +26,71 @@ namespace mRemoteNG.Connection _credentialService = credentialService; } - /// - /// List of unique IDs of the currently active connections - /// public IEnumerable ActiveConnections => _activeConnections; + public void OpenConnection(ContainerInfo containerInfo, ConnectionInfo.Force force = ConnectionInfo.Force.None) + { + OpenConnection(containerInfo, force, null); + } + + public void OpenConnection(ConnectionInfo connectionInfo) + { + try + { + OpenConnection(connectionInfo, ConnectionInfo.Force.None); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strConnectionOpenFailed, ex); + } + } + + public void OpenConnection(ConnectionInfo connectionInfo, ConnectionInfo.Force force) + { + try + { + OpenConnection(connectionInfo, force, null); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strConnectionOpenFailed, ex); + } + } + public bool SwitchToOpenConnection(ConnectionInfo connectionInfo) { var interfaceControl = FindConnectionContainer(connectionInfo); if (interfaceControl == null) return false; - var connectionWindow = (ConnectionWindow)interfaceControl.FindForm(); - connectionWindow?.Focus(); - var findForm = (ConnectionWindow)interfaceControl.FindForm(); - findForm?.Show(FrmMain.Default.pnlDock); - var tabPage = (TabPage)interfaceControl.Parent; - tabPage.Selected = true; + var connT = (ConnectionTab)interfaceControl.FindForm(); + connT?.Focus(); + var findForm = (ConnectionTab)interfaceControl.FindForm(); + findForm?.Show(findForm.DockPanel); return true; } - public void OpenConnection(ContainerInfo containerInfo, ConnectionInfo.Force force) + #region Private + + private void OpenConnection(ContainerInfo containerInfo, ConnectionInfo.Force force, Form conForm) { var children = containerInfo.Children; if (children.Count == 0) return; foreach (var child in children) { - var childAsContainer = child as ContainerInfo; - if (childAsContainer != null) - OpenConnection(childAsContainer, force); + if (child is ContainerInfo childAsContainer) + OpenConnection(childAsContainer, force, conForm); else - OpenConnection(child, force); + OpenConnection(child, force, conForm); } } - public void OpenConnection(ConnectionInfo connectionInfo, ConnectionInfo.Force force = ConnectionInfo.Force.None) + private void OpenConnection(ConnectionInfo connectionInfo, ConnectionInfo.Force force, Form conForm) { try { if (connectionInfo.Hostname == "" && connectionInfo.Protocol != ProtocolType.IntApp) { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, Language.strConnectionOpenFailedNoHostname); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + Language.strConnectionOpenFailedNoHostname); return; } @@ -80,7 +107,7 @@ namespace mRemoteNG.Connection var connectionPanel = SetConnectionPanel(connectionInfo, force); if (string.IsNullOrEmpty(connectionPanel)) return; - var connectionForm = SetConnectionForm(connectionPanel); + var connectionForm = SetConnectionForm(conForm, connectionPanel); var connectionContainer = SetConnectionContainer(connectionInfo, connectionForm); SetConnectionFormEventHandlers(newProtocol, connectionForm); SetConnectionEventHandlers(newProtocol); @@ -110,7 +137,6 @@ namespace mRemoteNG.Connection } } - #region Private private static void StartPreConnectionExternalApp(ConnectionInfo connectionInfo) { if (connectionInfo.PreExtApp == "") return; @@ -123,26 +149,29 @@ namespace mRemoteNG.Connection if (connectionInfo.OpenConnections.Count <= 0) return null; for (var i = 0; i <= Runtime.WindowList.Count - 1; i++) { - var window = Runtime.WindowList[i] as ConnectionWindow; - var connectionWindow = window; - if (connectionWindow?.TabController == null) continue; - foreach (TabPage t in connectionWindow.TabController.TabPages) + // 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) { - var ic = t.Controls[0] as InterfaceControl; + var tab = (ConnectionTab)dockContent; + var ic = InterfaceControl.FindInterfaceControl(tab); if (ic == null) continue; if (ic.Info == connectionInfo) - { return ic; - } } } + return null; } private static string SetConnectionPanel(ConnectionInfo connectionInfo, ConnectionInfo.Force force) { string connectionPanel; - if (connectionInfo.Panel == "" || force.HasFlag(ConnectionInfo.Force.OverridePanel) || Settings.Default.AlwaysShowPanelSelectionDlg) + if (connectionInfo.Panel == "" || force.HasFlag(ConnectionInfo.Force.OverridePanel) || + Settings.Default.AlwaysShowPanelSelectionDlg) { var frmPnl = new FrmChoosePanel(); if (frmPnl.ShowDialog() == DialogResult.OK) @@ -156,43 +185,52 @@ namespace mRemoteNG.Connection } else { - connectionPanel = connectionInfo.Panel; + //Return the current panel if exist, if not return default panel + if (TabHelper.Instance.CurrentPanel != null) + { + connectionPanel = TabHelper.Instance.CurrentPanel.TabText; + } + else + { + connectionPanel = connectionInfo.Panel; + } } + return connectionPanel; } - private ConnectionWindow SetConnectionForm(string connectionPanelName) + private Form SetConnectionForm(Form conForm, string connectionPanel) { - var connectionForm = Runtime.WindowList.FromString(connectionPanelName) as ConnectionWindow; + var connectionForm = conForm ?? Runtime.WindowList.FromString(connectionPanel); if (connectionForm == null) - connectionForm = _panelAdder.AddPanel(connectionPanelName); + connectionForm = _panelAdder.AddPanel(connectionPanel); else - connectionForm.Show(FrmMain.Default.pnlDock); + ((ConnectionWindow)connectionForm).Show(FrmMain.Default.pnlDock); connectionForm.Focus(); return connectionForm; } - private static Control SetConnectionContainer(ConnectionInfo connectionInfo, ConnectionWindow connectionForm) + private static Control SetConnectionContainer(ConnectionInfo connectionInfo, Form connectionForm) { - Control connectionContainer = connectionForm.AddConnectionTab(connectionInfo); + Control connectionContainer = ((ConnectionWindow)connectionForm).AddConnectionTab(connectionInfo); if (connectionInfo.Protocol != ProtocolType.IntApp) return connectionContainer; var extT = Runtime.ExternalToolsService.GetExtAppByName(connectionInfo.ExtApp); - if(extT == null) return connectionContainer; + if (extT == null) return connectionContainer; if (extT.Icon != null) - ((TabPage)connectionContainer).Icon = extT.Icon; + ((ConnectionTab)connectionContainer).Icon = extT.Icon; return connectionContainer; } - private static void SetConnectionFormEventHandlers(ProtocolBase newProtocol, ConnectionWindow connectionForm) + private static void SetConnectionFormEventHandlers(ProtocolBase newProtocol, Form connectionForm) { - newProtocol.Closed += connectionForm.Prot_Event_Closed; + newProtocol.Closed += ((ConnectionWindow)connectionForm).Prot_Event_Closed; } private void SetConnectionEventHandlers(ProtocolBase newProtocol) @@ -203,13 +241,17 @@ namespace mRemoteNG.Connection newProtocol.ErrorOccured += Prot_Event_ErrorOccured; } - private static void BuildConnectionInterfaceController(ConnectionInfo connectionInfo, ProtocolBase newProtocol, Control connectionContainer) + private static void BuildConnectionInterfaceController(ConnectionInfo connectionInfo, + ProtocolBase newProtocol, + Control connectionContainer) { newProtocol.InterfaceControl = new InterfaceControl(connectionContainer, newProtocol, connectionInfo); } + #endregion #region Event handlers + private static void Prot_Event_Disconnected(object sender, string disconnectedMessage, int? reasonCode) { try @@ -225,12 +267,12 @@ namespace mRemoteNG.Connection } } - Runtime.MessageCollector.AddMessage(msgClass, - string.Format( - Language.strProtocolEventDisconnected, - disconnectedMessage, - prot.InterfaceControl.Info.Hostname, - prot.InterfaceControl.Info.Protocol.ToString())); + Runtime.MessageCollector.AddMessage(msgClass, + string.Format( + Language.strProtocolEventDisconnected, + disconnectedMessage, + prot.InterfaceControl.Info.Hostname, + prot.InterfaceControl.Info.Protocol.ToString())); } catch (Exception ex) { @@ -243,16 +285,21 @@ namespace mRemoteNG.Connection try { var prot = (ProtocolBase)sender; - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strConnenctionCloseEvent, true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strConnenctionCloseEvent, + true); string connDetail; - if (prot.InterfaceControl.Info.Hostname == "" && prot.InterfaceControl.Info.Protocol == ProtocolType.IntApp) + if (prot.InterfaceControl.Info.Hostname == "" && + prot.InterfaceControl.Info.Protocol == ProtocolType.IntApp) connDetail = prot.InterfaceControl.Info.ExtApp; else if (prot.InterfaceControl.Info.Hostname != "") connDetail = prot.InterfaceControl.Info.Hostname; else connDetail = "UNKNOWN"; - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strConnenctionClosedByUser, connDetail, prot.InterfaceControl.Info.Protocol, Environment.UserName)); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strConnenctionClosedByUser, connDetail, + prot.InterfaceControl.Info.Protocol, + Environment.UserName)); prot.InterfaceControl.Info.OpenConnections.Remove(prot); if (_activeConnections.Contains(prot.InterfaceControl.Info.ConstantID)) _activeConnections.Remove(prot.InterfaceControl.Info.ConstantID); @@ -270,21 +317,27 @@ namespace mRemoteNG.Connection private static void Prot_Event_Connected(object sender) { var prot = (ProtocolBase)sender; - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strConnectionEventConnected, true); - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strConnectionEventConnectedDetail, prot.InterfaceControl.Info.Hostname, prot.InterfaceControl.Info.Protocol, Environment.UserName, prot.InterfaceControl.Info.Description, prot.InterfaceControl.Info.UserField)); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strConnectionEventConnected, + true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strConnectionEventConnectedDetail, + prot.InterfaceControl.Info.Hostname, + prot.InterfaceControl.Info.Protocol, Environment.UserName, + prot.InterfaceControl.Info.Description, + prot.InterfaceControl.Info.UserField)); } private static void Prot_Event_ErrorOccured(object sender, string errorMessage, int? errorCode) { try { - var prot = (ProtocolBase) sender; + var prot = (ProtocolBase)sender; var msg = string.Format( - Language.strConnectionEventErrorOccured, - errorMessage, - prot.InterfaceControl.Info.Hostname, - errorCode?.ToString() ?? "-"); + Language.strConnectionEventErrorOccured, + errorMessage, + prot.InterfaceControl.Info.Hostname, + errorCode?.ToString() ?? "-"); Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, msg); } catch (Exception ex) @@ -292,6 +345,7 @@ namespace mRemoteNG.Connection Runtime.MessageCollector.AddExceptionStackTrace(Language.strConnectionEventConnectionFailed, ex); } } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/Connection/ConnectionsService.cs b/mRemoteV1/Connection/ConnectionsService.cs index 6a0cbc79..6357042b 100644 --- a/mRemoteV1/Connection/ConnectionsService.cs +++ b/mRemoteV1/Connection/ConnectionsService.cs @@ -47,7 +47,8 @@ namespace mRemoteNG.Connection _puttySessionsManager = puttySessionsManager.ThrowIfNull(nameof(puttySessionsManager)); _credentialService = credentialService.ThrowIfNull(nameof(credentialService)); var path = SettingsFileInfo.SettingsPath; - _localConnectionPropertiesDataProvider = new FileDataProvider(Path.Combine(path, "LocalConnectionProperties.xml")); + _localConnectionPropertiesDataProvider = + new FileDataProvider(Path.Combine(path, "LocalConnectionProperties.xml")); _localConnectionPropertiesSerializer = new LocalConnectionPropertiesXmlSerializer(); _puttySessionsManager.RootPuttySessionsNodes.ForEach(node => ConnectionTreeModel.AddRootNode(node)); @@ -79,7 +80,9 @@ namespace mRemoteNG.Connection var newConnectionInfo = new ConnectionInfo(); newConnectionInfo.CopyFrom(DefaultConnectionInfo.Instance); - newConnectionInfo.Name = Settings.Default.IdentifyQuickConnectTabs ? string.Format(Language.strQuick, uriBuilder.Host) : uriBuilder.Host; + newConnectionInfo.Name = Settings.Default.IdentifyQuickConnectTabs + ? string.Format(Language.strQuick, uriBuilder.Host) + : uriBuilder.Host; newConnectionInfo.Protocol = protocol; newConnectionInfo.Hostname = uriBuilder.Host; @@ -118,7 +121,8 @@ namespace mRemoteNG.Connection var oldIsUsingDatabaseValue = UsingDatabase; var connectionLoader = useDatabase - ? (IConnectionsLoader)new SqlConnectionsLoader(_localConnectionPropertiesSerializer, _localConnectionPropertiesDataProvider) + ? (IConnectionsLoader)new SqlConnectionsLoader(_localConnectionPropertiesSerializer, + _localConnectionPropertiesDataProvider) : new XmlConnectionsLoader(connectionFileName, _credentialService, this); var serializationResult = connectionLoader.Load(); @@ -128,7 +132,8 @@ namespace mRemoteNG.Connection if (serializationResult == null) { - DialogFactory.ShowLoadConnectionsFailedDialog(connectionFileName, "Decrypting connection file failed", IsConnectionsFileLoaded); + DialogFactory.ShowLoadConnectionsFailedDialog(connectionFileName, "Decrypting connection file failed", + IsConnectionsFileLoaded); return; } @@ -144,8 +149,11 @@ namespace mRemoteNG.Connection ConnectionTreeModel.AddRootNode(rootNode); UpdateCustomConsPathSetting(connectionFileName); - RaiseConnectionsLoadedEvent(new List(), new List(), oldIsUsingDatabaseValue, useDatabase, connectionFileName); - Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, $"Connections loaded using {connectionLoader.GetType().Name}"); + // TODO: fix this call + RaiseConnectionsLoadedEvent(new List(), new List(), + oldIsUsingDatabaseValue, useDatabase, connectionFileName); + Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, + $"Connections loaded using {connectionLoader.GetType().Name}"); } /// @@ -170,7 +178,7 @@ namespace mRemoteNG.Connection if (_saveAsyncRequested) SaveConnectionsAsync(); - else if(_saveRequested) + else if (_saveRequested) SaveConnections(); } @@ -235,12 +243,15 @@ namespace mRemoteNG.Connection UsingDatabase = useDatabase; ConnectionFileName = connectionFileName; - RaiseConnectionsSavedEvent(connectionTreeModel, previouslyUsingDatabase, UsingDatabase, connectionFileName); + RaiseConnectionsSavedEvent(connectionTreeModel, previouslyUsingDatabase, UsingDatabase, + connectionFileName); Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Successfully saved connections"); } catch (Exception ex) { - Runtime.MessageCollector?.AddExceptionMessage(string.Format(Language.strConnectionsFileCouldNotSaveAs, connectionFileName), ex, logOnly:false); + Runtime.MessageCollector?.AddExceptionMessage( + string.Format(Language.strConnectionsFileCouldNotSaveAs, + connectionFileName), ex, logOnly: false); } finally { @@ -268,11 +279,11 @@ namespace mRemoteNG.Connection lock (SaveLock) { SaveConnections( - ConnectionTreeModel, - UsingDatabase, - new SaveFilter(), - ConnectionFileName, - propertyNameTrigger: propertyNameTrigger); + ConnectionTreeModel, + UsingDatabase, + new SaveFilter(), + ConnectionFileName, + propertyNameTrigger: propertyNameTrigger); } }); t.SetApartmentState(ApartmentState.STA); @@ -281,15 +292,15 @@ namespace mRemoteNG.Connection public string GetStartupConnectionFileName() { - return Settings.Default.LoadConsFromCustomLocation == false - ? GetDefaultStartupConnectionFileName() + return Settings.Default.LoadConsFromCustomLocation == false + ? GetDefaultStartupConnectionFileName() : Settings.Default.CustomConsPath; } public string GetDefaultStartupConnectionFileName() { - return Runtime.IsPortableEdition - ? GetDefaultStartupConnectionFileNamePortableEdition() + return Runtime.IsPortableEdition + ? GetDefaultStartupConnectionFileNamePortableEdition() : GetDefaultStartupConnectionFileNameNormalEdition(); } @@ -309,9 +320,9 @@ namespace mRemoteNG.Connection private string GetDefaultStartupConnectionFileNameNormalEdition() { var appDataPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - Application.ProductName, - ConnectionsFileInfo.DefaultConnectionsFile); + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + Application.ProductName, + ConnectionsFileInfo.DefaultConnectionsFile); return File.Exists(appDataPath) ? appDataPath : GetDefaultStartupConnectionFileNamePortableEdition(); } @@ -321,6 +332,7 @@ namespace mRemoteNG.Connection } #region Events + public event EventHandler ConnectionsLoaded; public event EventHandler ConnectionsSaved; @@ -331,9 +343,9 @@ namespace mRemoteNG.Connection ConnectionsLoaded?.Invoke(this, new ConnectionsLoadedEventArgs( removedConnections, addedConnections, - previousSourceWasDatabase, - newSourceIsDatabase, - newSourcePath)); + previousSourceWasDatabase, + newSourceIsDatabase, + newSourcePath)); } private void RaiseConnectionsSavedEvent(IConnectionTreeModel modelThatWasSaved, bool previouslyUsingDatabase, bool usingDatabase, string connectionFileName) diff --git a/mRemoteV1/Connection/DefaultConnectionInfo.cs b/mRemoteV1/Connection/DefaultConnectionInfo.cs index 5c391c63..a58c6d5f 100644 --- a/mRemoteV1/Connection/DefaultConnectionInfo.cs +++ b/mRemoteV1/Connection/DefaultConnectionInfo.cs @@ -12,29 +12,31 @@ namespace mRemoteNG.Connection private DefaultConnectionInfo() { IsDefault = true; - Inheritance = DefaultConnectionInheritance.Instance; + Inheritance = DefaultConnectionInheritance.Instance; } public void LoadFrom(TSource sourceInstance, Func propertyNameMutator = null) { if (propertyNameMutator == null) - propertyNameMutator = a => a; + propertyNameMutator = a => a; var connectionProperties = GetSerializableProperties(); foreach (var property in connectionProperties) { try { - var expectedPropertyName = propertyNameMutator(property.Name); - var propertyFromSource = typeof(TSource).GetProperty(expectedPropertyName); + var expectedPropertyName = propertyNameMutator(property.Name); + var propertyFromSource = typeof(TSource).GetProperty(expectedPropertyName); if (propertyFromSource == null) - throw new SettingsPropertyNotFoundException($"No property with name '{expectedPropertyName}' found."); + throw new SettingsPropertyNotFoundException( + $"No property with name '{expectedPropertyName}' found."); + + var valueFromSource = propertyFromSource.GetValue(sourceInstance, null); - var valueFromSource = propertyFromSource.GetValue(sourceInstance, null); - if (property.PropertyType.IsEnum) { - property.SetValue(Instance, Enum.Parse(property.PropertyType, valueFromSource.ToString()), null); + property.SetValue(Instance, Enum.Parse(property.PropertyType, valueFromSource.ToString()), + null); continue; } @@ -42,15 +44,18 @@ namespace mRemoteNG.Connection } catch (Exception ex) { - Runtime.MessageCollector?.AddExceptionStackTrace($"Error loading default connectioninfo property {property.Name}", ex); + Runtime.MessageCollector?.AddExceptionStackTrace( + $"Error loading default connectioninfo property {property.Name}", + ex); } } } - public void SaveTo(TDestination destinationInstance, Func propertyNameMutator = null) + public void SaveTo(TDestination destinationInstance, + Func propertyNameMutator = null) { if (propertyNameMutator == null) - propertyNameMutator = (a) => a; + propertyNameMutator = (a) => a; var connectionProperties = GetSerializableProperties(); @@ -58,24 +63,27 @@ namespace mRemoteNG.Connection { try { - var expectedPropertyName = propertyNameMutator(property.Name); - var propertyFromDestination = typeof(TDestination).GetProperty(expectedPropertyName); + var expectedPropertyName = propertyNameMutator(property.Name); + var propertyFromDestination = typeof(TDestination).GetProperty(expectedPropertyName); - if (propertyFromDestination == null) - throw new SettingsPropertyNotFoundException($"No property with name '{expectedPropertyName}' found."); + if (propertyFromDestination == null) + throw new SettingsPropertyNotFoundException( + $"No property with name '{expectedPropertyName}' found."); - // ensure value is of correct type + // ensure value is of correct type var value = property.PropertyType == propertyFromDestination.PropertyType ? property.GetValue(Instance, null) : propertyFromDestination.PropertyType == typeof(string) ? property.GetValue(Instance, null).ToString() - : Convert.ChangeType(property.GetValue(Instance, null), propertyFromDestination.PropertyType); + : Convert.ChangeType(property.GetValue(Instance, null), propertyFromDestination.PropertyType); propertyFromDestination.SetValue(destinationInstance, value, null); } catch (Exception ex) { - Runtime.MessageCollector?.AddExceptionStackTrace($"Error saving default connectioninfo property {property.Name}", ex); + Runtime.MessageCollector?.AddExceptionStackTrace( + $"Error saving default connectioninfo property {property.Name}", + ex); } } } diff --git a/mRemoteV1/Connection/DefaultConnectionInheritance.cs b/mRemoteV1/Connection/DefaultConnectionInheritance.cs index b55ca863..8e2d8e82 100644 --- a/mRemoteV1/Connection/DefaultConnectionInheritance.cs +++ b/mRemoteV1/Connection/DefaultConnectionInheritance.cs @@ -13,10 +13,11 @@ namespace mRemoteNG.Connection } static DefaultConnectionInheritance() - { } + { + } - public void LoadFrom(TSource sourceInstance, Func propertyNameMutator = null) + public void LoadFrom(TSource sourceInstance, Func propertyNameMutator = null) { if (propertyNameMutator == null) propertyNameMutator = a => a; var inheritanceProperties = GetProperties(); @@ -26,15 +27,18 @@ namespace mRemoteNG.Connection if (propertyFromSettings == null) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, - $"DefaultConInherit-LoadFrom: Could not load {property.Name}", true); + $"DefaultConInherit-LoadFrom: Could not load {property.Name}", + true); continue; } + var valueFromSettings = propertyFromSettings.GetValue(sourceInstance, null); property.SetValue(Instance, valueFromSettings, null); } } - public void SaveTo(TDestination destinationInstance, Func propertyNameMutator = null) + public void SaveTo(TDestination destinationInstance, + Func propertyNameMutator = null) { if (propertyNameMutator == null) propertyNameMutator = a => a; var inheritanceProperties = GetProperties(); @@ -45,9 +49,11 @@ namespace mRemoteNG.Connection if (propertyFromSettings == null) { Runtime.MessageCollector?.AddMessage(Messages.MessageClass.ErrorMsg, - $"DefaultConInherit-SaveTo: Could not load {property.Name}", true); + $"DefaultConInherit-SaveTo: Could not load {property.Name}", + true); continue; } + propertyFromSettings.SetValue(destinationInstance, localValue, null); } } diff --git a/mRemoteV1/Connection/IConnectionInitiator.cs b/mRemoteV1/Connection/IConnectionInitiator.cs index 0023d27a..c29a15d4 100644 --- a/mRemoteV1/Connection/IConnectionInitiator.cs +++ b/mRemoteV1/Connection/IConnectionInitiator.cs @@ -1,5 +1,5 @@ -using mRemoteNG.Container; using System.Collections.Generic; +using mRemoteNG.Container; namespace mRemoteNG.Connection { @@ -7,9 +7,11 @@ namespace mRemoteNG.Connection { IEnumerable ActiveConnections { get; } + void OpenConnection(ConnectionInfo connectionInfo); + void OpenConnection(ContainerInfo containerInfo, ConnectionInfo.Force force = ConnectionInfo.Force.None); - void OpenConnection(ConnectionInfo connectionInfo, ConnectionInfo.Force force = ConnectionInfo.Force.None); + void OpenConnection(ConnectionInfo connectionInfo, ConnectionInfo.Force force); bool SwitchToOpenConnection(ConnectionInfo connectionInfo); } diff --git a/mRemoteV1/Connection/InterfaceControl.cs b/mRemoteV1/Connection/InterfaceControl.cs index 185d5023..b21c31b8 100644 --- a/mRemoteV1/Connection/InterfaceControl.cs +++ b/mRemoteV1/Connection/InterfaceControl.cs @@ -3,32 +3,55 @@ using mRemoteNG.Connection.Protocol; using System; using System.Drawing; using System.Windows.Forms; +using mRemoteNG.UI.Tabs; +using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.Connection { - public sealed partial class InterfaceControl + public sealed partial class InterfaceControl { public ProtocolBase Protocol { get; set; } - public ConnectionInfo Info { get; set; } + public ConnectionInfo Info { get; set; } - public InterfaceControl(Control parent, ProtocolBase protocol, ConnectionInfo info) - { - try - { - Protocol = protocol; - Info = info; + public InterfaceControl(Control parent, ProtocolBase protocol, ConnectionInfo info) + { + try + { + Protocol = protocol; + Info = info; Parent = parent; Location = new Point(0, 0); Size = Parent.Size; Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; - InitializeComponent(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "Couldn\'t create new InterfaceControl" + Environment.NewLine + ex.Message); - } - } - } + InitializeComponent(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "Couldn\'t create new InterfaceControl" + Environment.NewLine + + ex.Message); + } + } + + public static InterfaceControl FindInterfaceControl(DockPanel DockPnl) + { + if (!(DockPnl.ActiveDocument is ConnectionTab ct)) return null; + if (ct.Controls.Count < 1) return null; + if (ct.Controls[0] is InterfaceControl ic) + return ic; + + return null; + } + + public static InterfaceControl FindInterfaceControl(ConnectionTab tab) + { + if (tab.Controls.Count < 1) return null; + if (tab.Controls[0] is InterfaceControl ic) + return ic; + + return null; + } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTP.cs b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTP.cs index cbdaca2f..3ebf3007 100644 --- a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTP.cs +++ b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTP.cs @@ -1,17 +1,16 @@ namespace mRemoteNG.Connection.Protocol.Http { - public class ProtocolHTTP : HTTPBase - { - - public ProtocolHTTP(RenderingEngine RenderingEngine) : base(RenderingEngine) - { + public class ProtocolHTTP : HTTPBase + { + public ProtocolHTTP(RenderingEngine RenderingEngine) : base(RenderingEngine) + { httpOrS = "http"; defaultPort = (int)Defaults.Port; } - - public enum Defaults - { - Port = 80 - } - } -} + + public enum Defaults + { + Port = 80 + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs index 5c426553..9c1fcc02 100644 --- a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs +++ b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPBase.cs @@ -4,64 +4,66 @@ using Gecko; using mRemoteNG.Tools; using mRemoteNG.App; using mRemoteNG.Credential; -using TabPage = Crownwood.Magic.Controls.TabPage; + namespace mRemoteNG.Connection.Protocol.Http { - public class HTTPBase : ProtocolBase - { + public class HTTPBase : ProtocolBase + { #region Private Properties - private Control wBrowser; - protected string httpOrS; - protected int defaultPort; - private string tabTitle; + + private Control wBrowser; + protected string httpOrS; + protected int defaultPort; + private string tabTitle; + #endregion - + #region Public Methods - protected HTTPBase(RenderingEngine RenderingEngine) - { - try - { - if (RenderingEngine == RenderingEngine.Gecko) - { - if(!Xpcom.IsInitialized) + protected HTTPBase(RenderingEngine RenderingEngine) + { + try + { + if (RenderingEngine == RenderingEngine.Gecko) + { + if (!Xpcom.IsInitialized) Xpcom.Initialize("Firefox"); Control = new GeckoWebBrowser(); - } - else - { + } + else + { Control = new WebBrowser(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpConnectionFailed, ex); - } - } - - public override bool Initialize() - { - base.Initialize(); - - try - { - var objTabPage = InterfaceControl.Parent as TabPage; - if (objTabPage != null) tabTitle = objTabPage.Title; - } - catch (Exception) - { + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpConnectionFailed, ex); + } + } + + public override bool Initialize() + { + base.Initialize(); + + try + { + var objTabPage = InterfaceControl.Parent as TabPage; + // if (objTabPage != null) tabTitle = objTabPage.Title; + } + catch (Exception) + { tabTitle = ""; - } - - try - { + } + + try + { wBrowser = Control; - - if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) - { - var GeckoBrowser = (GeckoWebBrowser) wBrowser; + + if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) + { + var GeckoBrowser = (GeckoWebBrowser)wBrowser; if (GeckoBrowser != null) { GeckoBrowser.DocumentTitleChanged += geckoBrowser_DocumentTitleChanged; @@ -73,31 +75,31 @@ namespace mRemoteNG.Connection.Protocol.Http } } else - { + { var objWebBrowser = (WebBrowser)wBrowser; - objWebBrowser.ScrollBarsEnabled = true; + objWebBrowser.ScrollBarsEnabled = true; // http://stackoverflow.com/questions/4655662/how-to-ignore-script-errors-in-webbrowser objWebBrowser.ScriptErrorsSuppressed = true; objWebBrowser.Navigated += wBrowser_Navigated; - objWebBrowser.DocumentTitleChanged += wBrowser_DocumentTitleChanged; - } - - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpSetPropsFailed, ex); - return false; - } - } - - public override bool Connect() - { - try - { - var strHost = InterfaceControl.Info.Hostname; + objWebBrowser.DocumentTitleChanged += wBrowser_DocumentTitleChanged; + } + + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpSetPropsFailed, ex); + return false; + } + } + + public override bool Connect() + { + try + { + var strHost = InterfaceControl.Info.Hostname; /* * Commenting out since this codes doesn't actually do anything at this time... * Possibly related to MR-221 and/or MR-533 ???? @@ -108,117 +110,120 @@ namespace mRemoteNG.Connection.Protocol.Http { strAuth = "Authorization: Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(InterfaceControl.Info.Username + ":" + InterfaceControl.Info.Password)) + Environment.NewLine; } - */ - if (InterfaceControl.Info.Port != defaultPort) - { - if (strHost.EndsWith("/")) - { - strHost = strHost.Substring(0, strHost.Length - 1); - } - - if (strHost.Contains(httpOrS + "://") == false) - { - strHost = httpOrS + "://" + strHost; - } - - if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) - { + */ + if (InterfaceControl.Info.Port != defaultPort) + { + if (strHost.EndsWith("/")) + { + strHost = strHost.Substring(0, strHost.Length - 1); + } + + if (strHost.Contains(httpOrS + "://") == false) + { + strHost = httpOrS + "://" + strHost; + } + + if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) + { ((GeckoWebBrowser)wBrowser).Navigate(strHost + ":" + InterfaceControl.Info.Port); - } - else - { + } + else + { ((WebBrowser)wBrowser).Navigate(strHost + ":" + InterfaceControl.Info.Port); - } - } - else - { - if (strHost.Contains(httpOrS + "://") == false) - { - strHost = httpOrS + "://" + strHost; - } - - if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) - { - ((GeckoWebBrowser)wBrowser).Navigate(strHost); - } - else - { + } + } + else + { + if (strHost.Contains(httpOrS + "://") == false) + { + strHost = httpOrS + "://" + strHost; + } + + if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) + { + ((GeckoWebBrowser)wBrowser).Navigate(strHost); + } + else + { ((WebBrowser)wBrowser).Navigate(strHost); - } - } - - base.Connect(); - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpConnectFailed, ex); - return false; - } - } + } + } + + base.Connect(); + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpConnectFailed, ex); + return false; + } + } + #endregion - + #region Private Methods + #endregion - + #region Events - private void wBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e) - { - var objWebBrowser = wBrowser as WebBrowser; - if (objWebBrowser == null) return; - - // This can only be set once the WebBrowser control is shown, it will throw a COM exception otherwise. - objWebBrowser.AllowWebBrowserDrop = false; - - objWebBrowser.Navigated -= wBrowser_Navigated; - } + + private void wBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e) + { + var objWebBrowser = wBrowser as WebBrowser; + if (objWebBrowser == null) return; + + // This can only be set once the WebBrowser control is shown, it will throw a COM exception otherwise. + objWebBrowser.AllowWebBrowserDrop = false; + + objWebBrowser.Navigated -= wBrowser_Navigated; + } private void wBrowser_DocumentTitleChanged(object sender, EventArgs e) - { - try - { - var tabP = InterfaceControl.Parent as TabPage; + { + try + { + var tabP = InterfaceControl.Parent as TabPage; - if (tabP == null) return; - string shortTitle; - - if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) - { - if (((GeckoWebBrowser) wBrowser).DocumentTitle.Length >= 15) - { - shortTitle = ((GeckoWebBrowser) wBrowser).DocumentTitle.Substring(0, 10) + "..."; - } - else - { - shortTitle = ((GeckoWebBrowser) wBrowser).DocumentTitle; - } - } - else - { - if (((WebBrowser) wBrowser).DocumentTitle.Length >= 15) - { - shortTitle = ((WebBrowser) wBrowser).DocumentTitle.Substring(0, 10) + "..."; - } - else - { - shortTitle = ((WebBrowser) wBrowser).DocumentTitle; - } - } - - if (!string.IsNullOrEmpty(tabTitle)) - { - tabP.Title = tabTitle + @" - " + shortTitle; - } - else - { - tabP.Title = shortTitle; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpDocumentTileChangeFailed, ex); - } - } + if (tabP == null) return; + string shortTitle; + + if (InterfaceControl.Info.RenderingEngine == RenderingEngine.Gecko) + { + if (((GeckoWebBrowser)wBrowser).DocumentTitle.Length >= 15) + { + shortTitle = ((GeckoWebBrowser)wBrowser).DocumentTitle.Substring(0, 10) + "..."; + } + else + { + shortTitle = ((GeckoWebBrowser)wBrowser).DocumentTitle; + } + } + else + { + if (((WebBrowser)wBrowser).DocumentTitle.Length >= 15) + { + shortTitle = ((WebBrowser)wBrowser).DocumentTitle.Substring(0, 10) + "..."; + } + else + { + shortTitle = ((WebBrowser)wBrowser).DocumentTitle; + } + } + + /* if (!string.IsNullOrEmpty(tabTitle)) + { + tabP.Title = tabTitle + @" - " + shortTitle; + } + else + { + tabP.Title = shortTitle; + }*/ + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpDocumentTileChangeFailed, ex); + } + } private void geckoBrowser_DocumentTitleChanged(object sender, EventArgs e) @@ -234,50 +239,53 @@ namespace mRemoteNG.Connection.Protocol.Http { if (((GeckoWebBrowser)wBrowser).DocumentTitle.Length >= 15) { - shortTitle = ((GeckoWebBrowser) wBrowser).DocumentTitle.Substring(0, 10) + "..."; + shortTitle = ((GeckoWebBrowser)wBrowser).DocumentTitle.Substring(0, 10) + "..."; } else { - shortTitle = ((GeckoWebBrowser) wBrowser).DocumentTitle; + shortTitle = ((GeckoWebBrowser)wBrowser).DocumentTitle; } } else { - if (((WebBrowser) wBrowser).DocumentTitle.Length >= 15) + if (((WebBrowser)wBrowser).DocumentTitle.Length >= 15) { - shortTitle = ((WebBrowser) wBrowser).DocumentTitle.Substring(0, 10) + "..."; + shortTitle = ((WebBrowser)wBrowser).DocumentTitle.Substring(0, 10) + "..."; } else { - shortTitle = ((WebBrowser) wBrowser).DocumentTitle; + shortTitle = ((WebBrowser)wBrowser).DocumentTitle; } } - if (!string.IsNullOrEmpty(tabTitle)) - { - tabP.Title = tabTitle + @" - " + shortTitle; - } - else - { - tabP.Title = shortTitle; - } + /* if (!string.IsNullOrEmpty(tabTitle)) + { + tabP.Title = tabTitle + @" - " + shortTitle; + } + else + { + tabP.Title = shortTitle; + }*/ } catch (Exception ex) { Runtime.MessageCollector.AddExceptionStackTrace(Language.strHttpDocumentTileChangeFailed, ex); } } -#endregion - -#region Enums - public enum RenderingEngine - { + + #endregion + + #region Enums + + public enum RenderingEngine + { [LocalizedAttributes.LocalizedDescription("strHttpInternetExplorer")] IE = 1, + [LocalizedAttributes.LocalizedDescription("strHttpGecko")] Gecko = 2 - } + } -#endregion - } + #endregion + } } diff --git a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.CertEvent.cs b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.CertEvent.cs index 086d8b49..5e9f1322 100644 --- a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.CertEvent.cs +++ b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.CertEvent.cs @@ -4,6 +4,7 @@ using mRemoteNG.App; using mRemoteNG.App.Info; using mRemoteNG.Messages; using mRemoteNG.UI.TaskDialog; + // ReSharper disable RedundantAssignment namespace mRemoteNG.Connection.Protocol.Http @@ -26,15 +27,17 @@ namespace mRemoteNG.Connection.Protocol.Http string[] commandButtons = { - Language.strHttpsInsecureAllowOnce, // 0 - Language.strHttpsInsecureAllowAlways, // 1 - Language.strHttpsInsecureDontAllow // 2 + Language.strHttpsInsecureAllowOnce, // 0 + Language.strHttpsInsecureAllowAlways, // 1 + Language.strHttpsInsecureDontAllow // 2 }; CTaskDialog.ShowTaskDialogBox(null, GeneralAppInfo.ProductName, Language.strHttpsInsecurePromptTitle, - string.Format(Language.strHttpsInsecurePrompt, e.Uri.AbsoluteUri), "", "", "", "", - string.Join(" | ", commandButtons), ETaskDialogButtons.None, ESysIcons.Question, ESysIcons.Question); - + string.Format(Language.strHttpsInsecurePrompt, e.Uri.AbsoluteUri), "", "", "", + "", + string.Join(" | ", commandButtons), ETaskDialogButtons.None, + ESysIcons.Question, ESysIcons.Question); + var allow = false; var temporary = true; // ReSharper disable once SwitchStatementMissingSomeCases @@ -53,10 +56,11 @@ namespace mRemoteNG.Connection.Protocol.Http temporary = true; // just to be safe break; } - + if (!allow) { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, $"User did not allow navigation to {e.Uri.AbsoluteUri} with an insecure certificate: {e.Message}"); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + $"User did not allow navigation to {e.Uri.AbsoluteUri} with an insecure certificate: {e.Message}"); return; } @@ -65,10 +69,11 @@ namespace mRemoteNG.Connection.Protocol.Http * However, my testing was successful in Gecko 45.0.22 */ CertOverrideService.GetService().RememberValidityOverride(e.Uri, e.Certificate, - CertOverride.Mismatch | CertOverride.Time | CertOverride.Untrusted, temporary); + CertOverride.Mismatch | CertOverride.Time | + CertOverride.Untrusted, temporary); e.Handled = true; ((GeckoWebBrowser)sender).Navigate(e.Uri.AbsoluteUri); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.cs b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.cs index 08f28a92..90f35f5a 100644 --- a/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.cs +++ b/mRemoteV1/Connection/Protocol/Http/Connection.Protocol.HTTPS.cs @@ -1,17 +1,16 @@ namespace mRemoteNG.Connection.Protocol.Http { - public class ProtocolHTTPS : HTTPBase - { - - public ProtocolHTTPS(RenderingEngine RenderingEngine) : base(RenderingEngine) - { + public class ProtocolHTTPS : HTTPBase + { + public ProtocolHTTPS(RenderingEngine RenderingEngine) : base(RenderingEngine) + { httpOrS = "https"; defaultPort = (int)Defaults.Port; } - - public enum Defaults - { - Port = 443 - } - } -} + + public enum Defaults + { + Port = 443 + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/ICA/IcaProtocol.cs b/mRemoteV1/Connection/Protocol/ICA/IcaProtocol.cs index 5096fbac..0522cc85 100644 --- a/mRemoteV1/Connection/Protocol/ICA/IcaProtocol.cs +++ b/mRemoteV1/Connection/Protocol/ICA/IcaProtocol.cs @@ -17,108 +17,116 @@ using mRemoteNG.Security; namespace mRemoteNG.Connection.Protocol.ICA { public class IcaProtocol : ProtocolBase - { - private AxICAClient _icaClient; - private ConnectionInfo _info; + { + private AxICAClient _icaClient; + private ConnectionInfo _info; private readonly FrmMain _frmMain = FrmMain.Default; - - #region Public Methods - public IcaProtocol() - { - try - { - Control = new AxICAClient(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strIcaControlFailed + Environment.NewLine + ex.Message, true); - } - } - - public override bool Initialize() - { - base.Initialize(); - - try - { - _icaClient = (AxICAClient)Control; - _info = InterfaceControl.Info; - _icaClient.CreateControl(); - - while (!_icaClient.Created) - { - Thread.Sleep(10); - Application.DoEvents(); - } - _icaClient.Address = _info.Hostname; - SetCredentials(); - SetResolution(); - SetColors(); - SetSecurity(); - - //Disable hotkeys for international users - _icaClient.Hotkey1Shift = null; - _icaClient.Hotkey1Char = null; - _icaClient.Hotkey2Shift = null; - _icaClient.Hotkey2Char = null; - _icaClient.Hotkey3Shift = null; - _icaClient.Hotkey3Char = null; - _icaClient.Hotkey4Shift = null; - _icaClient.Hotkey4Char = null; - _icaClient.Hotkey5Shift = null; - _icaClient.Hotkey5Char = null; - _icaClient.Hotkey6Shift = null; - _icaClient.Hotkey6Char = null; - _icaClient.Hotkey7Shift = null; - _icaClient.Hotkey7Char = null; - _icaClient.Hotkey8Shift = null; - _icaClient.Hotkey8Char = null; - _icaClient.Hotkey9Shift = null; - _icaClient.Hotkey9Char = null; - _icaClient.Hotkey10Shift = null; - _icaClient.Hotkey10Char = null; - _icaClient.Hotkey11Shift = null; - _icaClient.Hotkey11Char = null; - - _icaClient.PersistentCacheEnabled = _info.CacheBitmaps; - _icaClient.Title = _info.Name; - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strIcaSetPropsFailed + Environment.NewLine + ex.Message, true); - return false; - } - } - - public override bool Connect() - { - SetEventHandlers(); - - try - { - _icaClient.Connect(); - base.Connect(); - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strIcaConnectionFailed + Environment.NewLine + ex.Message); - return false; - } - } + #region Public Methods + + public IcaProtocol() + { + try + { + Control = new AxICAClient(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strIcaControlFailed + Environment.NewLine + ex.Message, + true); + } + } + + public override bool Initialize() + { + base.Initialize(); + + try + { + _icaClient = (AxICAClient)Control; + _info = InterfaceControl.Info; + _icaClient.CreateControl(); + + while (!_icaClient.Created) + { + Thread.Sleep(10); + Application.DoEvents(); + } + + _icaClient.Address = _info.Hostname; + SetCredentials(); + SetResolution(); + SetColors(); + SetSecurity(); + + //Disable hotkeys for international users + _icaClient.Hotkey1Shift = null; + _icaClient.Hotkey1Char = null; + _icaClient.Hotkey2Shift = null; + _icaClient.Hotkey2Char = null; + _icaClient.Hotkey3Shift = null; + _icaClient.Hotkey3Char = null; + _icaClient.Hotkey4Shift = null; + _icaClient.Hotkey4Char = null; + _icaClient.Hotkey5Shift = null; + _icaClient.Hotkey5Char = null; + _icaClient.Hotkey6Shift = null; + _icaClient.Hotkey6Char = null; + _icaClient.Hotkey7Shift = null; + _icaClient.Hotkey7Char = null; + _icaClient.Hotkey8Shift = null; + _icaClient.Hotkey8Char = null; + _icaClient.Hotkey9Shift = null; + _icaClient.Hotkey9Char = null; + _icaClient.Hotkey10Shift = null; + _icaClient.Hotkey10Char = null; + _icaClient.Hotkey11Shift = null; + _icaClient.Hotkey11Char = null; + + _icaClient.PersistentCacheEnabled = _info.CacheBitmaps; + _icaClient.Title = _info.Name; + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strIcaSetPropsFailed + Environment.NewLine + ex.Message, + true); + return false; + } + } + + public override bool Connect() + { + SetEventHandlers(); + + try + { + _icaClient.Connect(); + base.Connect(); + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strIcaConnectionFailed + Environment.NewLine + ex.Message); + return false; + } + } + #endregion - + #region Private Methods - private void SetCredentials() - { - try - { + + private void SetCredentials() + { + try + { if (Force.HasFlag(ConnectionInfo.Force.NoCredentials)) - { - return; - } + { + return; + } var cred = Runtime.CredentialService.GetEffectiveCredentialRecord(_info.CredentialRecordId .FirstOrDefault()).FirstOrDefault(); @@ -127,229 +135,253 @@ namespace mRemoteNG.Connection.Protocol.ICA var pass = cred.Password?.ConvertToUnsecureString() ?? ""; var dom = cred.Domain ?? ""; - if (string.IsNullOrEmpty(user)) - { - if (Settings.Default.EmptyCredentials == "windows") - { - _icaClient.Username = Environment.UserName; - } - else if (Settings.Default.EmptyCredentials == "custom") - { + if (string.IsNullOrEmpty(user)) + { + if (Settings.Default.EmptyCredentials == "windows") + { + _icaClient.Username = Environment.UserName; + } + else if (Settings.Default.EmptyCredentials == "custom") + { _icaClient.Username = Runtime.CredentialService.GetCredentialRecord(Settings.Default.DefaultCredentialRecord).Username; - } - } - else - { - _icaClient.Username = user; - } - - if (string.IsNullOrEmpty(pass)) - { - if (Settings.Default.EmptyCredentials == "custom") - { + } + } + else + { + _icaClient.Username = user; + } + + if (string.IsNullOrEmpty(pass)) + { + if (Settings.Default.EmptyCredentials == "custom") + { var p = Runtime.CredentialService.GetCredentialRecord(Settings.Default.DefaultCredentialRecord).Password; if (p.Length > 0) - { + { _icaClient.SetProp("ClearPassword", p.ConvertToUnsecureString()); - } - } - } - else - { - _icaClient.SetProp("ClearPassword", pass); - } - - if (string.IsNullOrEmpty(dom)) - { - if (Settings.Default.EmptyCredentials == "windows") - { - _icaClient.Domain = Environment.UserDomainName; - } - else if (Settings.Default.EmptyCredentials == "custom") - { - _icaClient.Domain = Runtime.CredentialService.GetCredentialRecord(Settings.Default.DefaultCredentialRecord).Domain; - } - } - else - { - _icaClient.Domain = dom; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strIcaSetCredentialsFailed + Environment.NewLine + ex.Message, true); - } - } - - private void SetResolution() - { - try - { - if (Force.HasFlag(ConnectionInfo.Force.Fullscreen)) - { - _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, Screen.FromControl(_frmMain).Bounds.Width, Screen.FromControl(_frmMain).Bounds.Height, 0); - _icaClient.FullScreenWindow(); - - return; - } - - if (InterfaceControl.Info.Resolution == RdpProtocol.RDPResolutions.FitToWindow) - { - _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, InterfaceControl.Size.Width, InterfaceControl.Size.Height, 0); - } - else if (InterfaceControl.Info.Resolution == RdpProtocol.RDPResolutions.SmartSize) - { - _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, InterfaceControl.Size.Width, InterfaceControl.Size.Height, 0); - } - else if (InterfaceControl.Info.Resolution == RdpProtocol.RDPResolutions.Fullscreen) - { - _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, Screen.FromControl(_frmMain).Bounds.Width, Screen.FromControl(_frmMain).Bounds.Height, 0); - _icaClient.FullScreenWindow(); - } - else - { - var resolution = RdpProtocol.GetResolutionRectangle(_info.Resolution); - _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, resolution.Width, resolution.Height, 0); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strIcaSetResolutionFailed + Environment.NewLine + ex.Message, true); - } - } - - private void SetColors() - { - // ReSharper disable once SwitchStatementMissingSomeCases - switch (_info.Colors) - { - case RdpProtocol.RDPColors.Colors256: - _icaClient.SetProp("DesiredColor", "2"); - break; - case RdpProtocol.RDPColors.Colors15Bit: - _icaClient.SetProp("DesiredColor", "4"); - break; - case RdpProtocol.RDPColors.Colors16Bit: - _icaClient.SetProp("DesiredColor", "4"); - break; - default: - _icaClient.SetProp("DesiredColor", "8"); - break; - } - } - - private void SetSecurity() - { - // ReSharper disable once SwitchStatementMissingSomeCases - switch (_info.ICAEncryptionStrength) - { - case EncryptionStrength.Encr128BitLogonOnly: - _icaClient.Encrypt = true; - _icaClient.EncryptionLevelSession = "EncRC5-0"; - break; - case EncryptionStrength.Encr40Bit: - _icaClient.Encrypt = true; - _icaClient.EncryptionLevelSession = "EncRC5-40"; - break; - case EncryptionStrength.Encr56Bit: - _icaClient.Encrypt = true; - _icaClient.EncryptionLevelSession = "EncRC5-56"; - break; - case EncryptionStrength.Encr128Bit: - _icaClient.Encrypt = true; - _icaClient.EncryptionLevelSession = "EncRC5-128"; - break; - } - } - - private void SetEventHandlers() - { - try - { - _icaClient.OnConnecting += ICAEvent_OnConnecting; - _icaClient.OnConnect += ICAEvent_OnConnected; - _icaClient.OnConnectFailed += ICAEvent_OnConnectFailed; - _icaClient.OnDisconnect += ICAEvent_OnDisconnect; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strIcaSetEventHandlersFailed + Environment.NewLine + ex.Message, true); - } - } - #endregion - - #region Private Events & Handlers - private void ICAEvent_OnConnecting(object sender, EventArgs e) - { - Event_Connecting(this); - } - - private void ICAEvent_OnConnected(object sender, EventArgs e) - { - Event_Connected(this); - } - - private void ICAEvent_OnConnectFailed(object sender, EventArgs e) - { - Event_ErrorOccured(this, e.ToString(), null); - } - - private void ICAEvent_OnDisconnect(object sender, EventArgs e) - { - Event_Disconnected(this, e.ToString(), null); - - if (Settings.Default.ReconnectOnDisconnect) - { - ReconnectGroup = new ReconnectGroup(); - //this.Load += ReconnectGroup_Load; - ReconnectGroup.Left = (int) (((double) Control.Width / 2) - ((double) ReconnectGroup.Width / 2)); - ReconnectGroup.Top = (int) (((double) Control.Height / 2) - ((double) ReconnectGroup.Height / 2)); - ReconnectGroup.Parent = Control; - ReconnectGroup.Show(); - tmrReconnect.Enabled = true; - } - else - { - Close(); - } - } - #endregion - - #region Reconnect Stuff - public void tmrReconnect_Elapsed(object sender, ElapsedEventArgs e) - { - var srvReady = PortScanner.IsPortOpen(_info.Hostname, Convert.ToString(_info.Port)); - - ReconnectGroup.ServerReady = srvReady; + } + } + } + else + { + _icaClient.SetProp("ClearPassword", pass); + } + + if (string.IsNullOrEmpty(dom)) + { + if (Settings.Default.EmptyCredentials == "windows") + { + _icaClient.Domain = Environment.UserDomainName; + } + else if (Settings.Default.EmptyCredentials == "custom") + { + _icaClient.Domain = Runtime.CredentialService.GetCredentialRecord(Settings.Default.DefaultCredentialRecord).Domain; + } + } + else + { + _icaClient.Domain = dom; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strIcaSetCredentialsFailed + Environment.NewLine + + ex.Message, true); + } + } + + private void SetResolution() + { + try + { + if (Force.HasFlag(ConnectionInfo.Force.Fullscreen)) + { + _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, + Screen.FromControl(_frmMain).Bounds.Width, + Screen.FromControl(_frmMain).Bounds.Height, 0); + _icaClient.FullScreenWindow(); + + return; + } + + if (InterfaceControl.Info.Resolution == RdpProtocol.RDPResolutions.FitToWindow) + { + _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, InterfaceControl.Size.Width, + InterfaceControl.Size.Height, 0); + } + else if (InterfaceControl.Info.Resolution == RdpProtocol.RDPResolutions.SmartSize) + { + _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, InterfaceControl.Size.Width, + InterfaceControl.Size.Height, 0); + } + else if (InterfaceControl.Info.Resolution == RdpProtocol.RDPResolutions.Fullscreen) + { + _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, + Screen.FromControl(_frmMain).Bounds.Width, + Screen.FromControl(_frmMain).Bounds.Height, 0); + _icaClient.FullScreenWindow(); + } + else + { + var resolution = RdpProtocol.GetResolutionRectangle(_info.Resolution); + _icaClient.SetWindowSize(WFICALib.ICAWindowType.WindowTypeClient, resolution.Width, + resolution.Height, 0); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strIcaSetResolutionFailed + Environment.NewLine + + ex.Message, true); + } + } + + private void SetColors() + { + // ReSharper disable once SwitchStatementMissingSomeCases + switch (_info.Colors) + { + case RdpProtocol.RDPColors.Colors256: + _icaClient.SetProp("DesiredColor", "2"); + break; + case RdpProtocol.RDPColors.Colors15Bit: + _icaClient.SetProp("DesiredColor", "4"); + break; + case RdpProtocol.RDPColors.Colors16Bit: + _icaClient.SetProp("DesiredColor", "4"); + break; + default: + _icaClient.SetProp("DesiredColor", "8"); + break; + } + } + + private void SetSecurity() + { + // ReSharper disable once SwitchStatementMissingSomeCases + switch (_info.ICAEncryptionStrength) + { + case EncryptionStrength.Encr128BitLogonOnly: + _icaClient.Encrypt = true; + _icaClient.EncryptionLevelSession = "EncRC5-0"; + break; + case EncryptionStrength.Encr40Bit: + _icaClient.Encrypt = true; + _icaClient.EncryptionLevelSession = "EncRC5-40"; + break; + case EncryptionStrength.Encr56Bit: + _icaClient.Encrypt = true; + _icaClient.EncryptionLevelSession = "EncRC5-56"; + break; + case EncryptionStrength.Encr128Bit: + _icaClient.Encrypt = true; + _icaClient.EncryptionLevelSession = "EncRC5-128"; + break; + } + } + + private void SetEventHandlers() + { + try + { + _icaClient.OnConnecting += ICAEvent_OnConnecting; + _icaClient.OnConnect += ICAEvent_OnConnected; + _icaClient.OnConnectFailed += ICAEvent_OnConnectFailed; + _icaClient.OnDisconnect += ICAEvent_OnDisconnect; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strIcaSetEventHandlersFailed + Environment.NewLine + + ex.Message, true); + } + } - if (!ReconnectGroup.ReconnectWhenReady || !srvReady) return; - tmrReconnect.Enabled = false; - ReconnectGroup.DisposeReconnectGroup(); - _icaClient.Connect(); - } #endregion - + + #region Private Events & Handlers + + private void ICAEvent_OnConnecting(object sender, EventArgs e) + { + Event_Connecting(this); + } + + private void ICAEvent_OnConnected(object sender, EventArgs e) + { + Event_Connected(this); + } + + private void ICAEvent_OnConnectFailed(object sender, EventArgs e) + { + Event_ErrorOccured(this, e.ToString(), null); + } + + private void ICAEvent_OnDisconnect(object sender, EventArgs e) + { + Event_Disconnected(this, e.ToString(), null); + + if (Settings.Default.ReconnectOnDisconnect) + { + ReconnectGroup = new ReconnectGroup(); + //this.Load += ReconnectGroup_Load; + ReconnectGroup.Left = (int)(((double)Control.Width / 2) - ((double)ReconnectGroup.Width / 2)); + ReconnectGroup.Top = (int)(((double)Control.Height / 2) - ((double)ReconnectGroup.Height / 2)); + ReconnectGroup.Parent = Control; + ReconnectGroup.Show(); + tmrReconnect.Enabled = true; + } + else + { + Close(); + } + } + + #endregion + + #region Reconnect Stuff + + public void tmrReconnect_Elapsed(object sender, ElapsedEventArgs e) + { + var srvReady = PortScanner.IsPortOpen(_info.Hostname, Convert.ToString(_info.Port)); + + ReconnectGroup.ServerReady = srvReady; + + if (!ReconnectGroup.ReconnectWhenReady || !srvReady) return; + tmrReconnect.Enabled = false; + ReconnectGroup.DisposeReconnectGroup(); + _icaClient.Connect(); + } + + #endregion + #region Enums - public enum Defaults - { - Port = 1494, - EncryptionStrength = 0 - } - - public enum EncryptionStrength - { + + public enum Defaults + { + Port = 1494, + EncryptionStrength = 0 + } + + public enum EncryptionStrength + { [LocalizedAttributes.LocalizedDescription("strEncBasic")] EncrBasic = 1, + [LocalizedAttributes.LocalizedDescription("strEnc128BitLogonOnly")] Encr128BitLogonOnly = 127, + [LocalizedAttributes.LocalizedDescription("strEnc40Bit")] Encr40Bit = 40, + [LocalizedAttributes.LocalizedDescription("strEnc56Bit")] Encr56Bit = 56, + [LocalizedAttributes.LocalizedDescription("strEnc128Bit")] Encr128Bit = 128 - } + } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/IntegratedProgram.cs b/mRemoteV1/Connection/Protocol/IntegratedProgram.cs index 2954ee32..afe463da 100644 --- a/mRemoteV1/Connection/Protocol/IntegratedProgram.cs +++ b/mRemoteV1/Connection/Protocol/IntegratedProgram.cs @@ -10,175 +10,198 @@ using mRemoteNG.Tools; namespace mRemoteNG.Connection.Protocol { - public class IntegratedProgram : ProtocolBase - { + public class IntegratedProgram : ProtocolBase + { #region Private Fields + private ExternalTool _externalTool; private IntPtr _handle; private Process _process; + #endregion #region Public Methods - public override bool Initialize() - { - if (InterfaceControl.Info == null) - return base.Initialize(); - _externalTool = Runtime.ExternalToolsService.GetExtAppByName(InterfaceControl.Info.ExtApp); + public override bool Initialize() + { + if (InterfaceControl.Info == null) + return base.Initialize(); - if (_externalTool == null) - { - Runtime.MessageCollector?.AddMessage(MessageClass.ErrorMsg, string.Format(Language.CouldNotFindExternalTool, InterfaceControl.Info.ExtApp)); - return false; - } + _externalTool = Runtime.ExternalToolsService.GetExtAppByName(InterfaceControl.Info.ExtApp); - _externalTool.ConnectionInfo = InterfaceControl.Info; + if (_externalTool == null) + { + Runtime.MessageCollector?.AddMessage(MessageClass.ErrorMsg, + string.Format(Language.CouldNotFindExternalTool, + InterfaceControl.Info.ExtApp)); + return false; + } - return base.Initialize(); - } - - public override bool Connect() - { - try - { - Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, $"Attempting to start: {_externalTool.DisplayName}", true); + _externalTool.ConnectionInfo = InterfaceControl.Info; + + return base.Initialize(); + } + + public override bool Connect() + { + try + { + Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, + $"Attempting to start: {_externalTool.DisplayName}", true); if (_externalTool.TryIntegrate == false) - { - _externalTool.Start(InterfaceControl.Info); + { + _externalTool.Start(InterfaceControl.Info); /* Don't call close here... There's nothing for the override to do in this case since * _process is not created in this scenario. When returning false, ProtocolBase.Close() * will be called - which is just going to call IntegratedProgram.Close() again anyway... * Close(); */ - Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, $"Assuming no other errors/exceptions occurred immediately before this message regarding {_externalTool.DisplayName}, the next \"closed by user\" message can be ignored", true); + Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, + $"Assuming no other errors/exceptions occurred immediately before this message regarding {_externalTool.DisplayName}, the next \"closed by user\" message can be ignored", + true); return false; - } + } var argParser = new ExternalToolArgumentParser(_externalTool.ConnectionInfo, Runtime.CredentialService); - _process = new Process - { - StartInfo = - { - UseShellExecute = true, - FileName = argParser.ParseArguments(_externalTool.FileName), - Arguments = argParser.ParseArguments(_externalTool.Arguments) - }, - EnableRaisingEvents = true - }; + _process = new Process + { + StartInfo = + { + UseShellExecute = true, + FileName = argParser.ParseArguments(_externalTool.FileName), + Arguments = argParser.ParseArguments(_externalTool.Arguments) + }, + EnableRaisingEvents = true + }; - _process.Exited += ProcessExited; - - _process.Start(); + _process.Exited += ProcessExited; + + _process.Start(); _process.WaitForInputIdle(Settings.Default.MaxPuttyWaitTime * 1000); var startTicks = Environment.TickCount; - while (_handle.ToInt32() == 0 & Environment.TickCount < startTicks + Settings.Default.MaxPuttyWaitTime * 1000) - { - _process.Refresh(); - if (_process.MainWindowTitle != "Default IME") - { - _handle = _process.MainWindowHandle; - } - if (_handle.ToInt32() == 0) - { - Thread.Sleep(0); - } - } - - NativeMethods.SetParent(_handle, InterfaceControl.Handle); - Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, Language.strIntAppStuff, true); - Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, string.Format(Language.strIntAppHandle, _handle), true); - Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, string.Format(Language.strIntAppTitle, _process.MainWindowTitle), true); - Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, string.Format(Language.strIntAppParentHandle, InterfaceControl.Parent.Handle), true); - - Resize(this, new EventArgs()); - base.Connect(); - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector?.AddExceptionMessage(Language.strIntAppConnectionFailed, ex); - return false; - } - } - - public override void Focus() - { - try - { - if (ConnectionWindow.InTabDrag) return; - NativeMethods.SetForegroundWindow(_handle); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppFocusFailed, ex); - } - } + while (_handle.ToInt32() == 0 & + Environment.TickCount < startTicks + Settings.Default.MaxPuttyWaitTime * 1000) + { + _process.Refresh(); + if (_process.MainWindowTitle != "Default IME") + { + _handle = _process.MainWindowHandle; + } - protected override void Resize(object sender, EventArgs e) - { - try - { - if (InterfaceControl.Size == Size.Empty) return; - NativeMethods.MoveWindow(_handle, -SystemInformation.FrameBorderSize.Width, -(SystemInformation.CaptionHeight + SystemInformation.FrameBorderSize.Height), InterfaceControl.Width + SystemInformation.FrameBorderSize.Width * 2, InterfaceControl.Height + SystemInformation.CaptionHeight + SystemInformation.FrameBorderSize.Height * 2, true); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppResizeFailed, ex); - } - } - - public override void Close() - { + if (_handle.ToInt32() == 0) + { + Thread.Sleep(0); + } + } + + NativeMethods.SetParent(_handle, InterfaceControl.Handle); + Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, Language.strIntAppStuff, true); + Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strIntAppHandle, _handle), true); + Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strIntAppTitle, _process.MainWindowTitle), + true); + Runtime.MessageCollector?.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strIntAppParentHandle, + InterfaceControl.Parent.Handle), true); + + Resize(this, new EventArgs()); + base.Connect(); + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector?.AddExceptionMessage(Language.strIntAppConnectionFailed, ex); + return false; + } + } + + public override void Focus() + { + try + { + NativeMethods.SetForegroundWindow(_handle); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppFocusFailed, ex); + } + } + + public override void Resize(object sender, EventArgs e) + { + try + { + if (InterfaceControl.Size == Size.Empty) return; + NativeMethods.MoveWindow(_handle, -SystemInformation.FrameBorderSize.Width, + -(SystemInformation.CaptionHeight + SystemInformation.FrameBorderSize.Height), + InterfaceControl.Width + SystemInformation.FrameBorderSize.Width * 2, + InterfaceControl.Height + SystemInformation.CaptionHeight + + SystemInformation.FrameBorderSize.Height * 2, true); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppResizeFailed, ex); + } + } + + public override void Close() + { /* only attempt this if we have a valid process object - * Non-integated tools will still call base.Close() and don't have a valid process object. + * Non-integrated tools will still call base.Close() and don't have a valid process object. * See Connect() above... This just muddies up the log. */ if (_process != null) - { - try - { - if (!_process.HasExited) - { - _process.Kill(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppKillFailed, ex); - } + { + try + { + if (!_process.HasExited) + { + _process.Kill(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppKillFailed, ex); + } - try - { - if (!_process.HasExited) - { - _process.Dispose(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppDisposeFailed, ex); - } - } + try + { + if (!_process.HasExited) + { + _process.Dispose(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppDisposeFailed, ex); + } + } + + base.Close(); + } - base.Close(); - } #endregion - + #region Private Methods - private void ProcessExited(object sender, EventArgs e) - { - Event_Closed(this); - } + + private void ProcessExited(object sender, EventArgs e) + { + Event_Closed(this); + } + #endregion - + #region Enumerations - public enum Defaults - { - Port = 0 - } + + public enum Defaults + { + Port = 0 + } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/ProtocolBase.cs b/mRemoteV1/Connection/Protocol/ProtocolBase.cs index 3cb14011..a9c9023d 100644 --- a/mRemoteV1/Connection/Protocol/ProtocolBase.cs +++ b/mRemoteV1/Connection/Protocol/ProtocolBase.cs @@ -3,58 +3,64 @@ using mRemoteNG.Tools; using System; using System.Threading; using System.Windows.Forms; -using mRemoteNG.Credential; +using mRemoteNG.UI.Tabs; +// ReSharper disable UnusedMember.Local namespace mRemoteNG.Connection.Protocol { - public abstract class ProtocolBase: IDisposable + public abstract class ProtocolBase { #region Private Variables - private UI.Window.ConnectionWindow _connectionWindow; + private ConnectionTab _connectionTab; private InterfaceControl _interfaceControl; - private ConnectingEventHandler ConnectingEvent; + private ConnectingEventHandler ConnectingEvent; private ConnectedEventHandler ConnectedEvent; private DisconnectedEventHandler DisconnectedEvent; private ErrorOccuredEventHandler ErrorOccuredEvent; private ClosingEventHandler ClosingEvent; private ClosedEventHandler ClosedEvent; + #endregion #region Public Properties + #region Control + private string Name { get; } - protected UI.Window.ConnectionWindow ConnectionWindow - { - get => _connectionWindow; - private set - { - _connectionWindow = value; - _connectionWindow.ResizeBegin += ResizeBegin; - _connectionWindow.Resize += Resize; - _connectionWindow.ResizeEnd += ResizeEnd; - } - } + private ConnectionTab ConnectionTab + { + get => _connectionTab; + set + { + _connectionTab = value; + _connectionTab.ResizeBegin += ResizeBegin; + _connectionTab.Resize += Resize; + _connectionTab.ResizeEnd += ResizeEnd; + } + } public InterfaceControl InterfaceControl - { - get => _interfaceControl; + { + get => _interfaceControl; set - { - _interfaceControl = value; - ConnectionWindow = _interfaceControl.GetContainerControl() as UI.Window.ConnectionWindow; - } - } + { + _interfaceControl = value; + + if (_interfaceControl.Parent is ConnectionTab ct) + ConnectionTab = ct; + } + } protected Control Control { get; set; } - #endregion + #endregion public ConnectionInfo.Force Force { get; set; } - public readonly System.Timers.Timer tmrReconnect = new System.Timers.Timer(2000); + public readonly System.Timers.Timer tmrReconnect = new System.Timers.Timer(2000); protected ReconnectGroup ReconnectGroup; protected ProtocolBase(string name) @@ -69,254 +75,260 @@ namespace mRemoteNG.Connection.Protocol #endregion #region Methods + //public abstract int GetDefaultPort(); public virtual void Focus() - { - try - { - Control.Focus(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("Couldn't focus Control (Connection.Protocol.Base)", ex); - } - } - - protected virtual void ResizeBegin(object sender, EventArgs e) - { - } - - protected virtual void Resize(object sender, EventArgs e) - { - } - - protected virtual void ResizeEnd(object sender, EventArgs e) - { - } - - public virtual bool Initialize() - { - try - { - _interfaceControl.Parent.Tag = _interfaceControl; - _interfaceControl.Show(); - - if (Control == null) return true; - Control.Name = Name; - Control.Parent = _interfaceControl; - Control.Location = _interfaceControl.Location; - Control.Size = InterfaceControl.Size; - Control.Anchor = _interfaceControl.Anchor; - - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("Couldn't SetProps (Connection.Protocol.Base)", ex); - return false; - } - } - - public virtual bool Connect() - { - if (InterfaceControl.Info.Protocol == ProtocolType.RDP) return false; - if (ConnectedEvent == null) return false; - ConnectedEvent(this); - return true; - } - - public virtual void Disconnect() - { - Close(); - } - - public virtual void Close() - { - var t = new Thread(CloseBG); - t.SetApartmentState(ApartmentState.STA); - t.IsBackground = true; - t.Start(); - } - - private void CloseBG() - { - ClosedEvent?.Invoke(this); - try - { - tmrReconnect.Enabled = false; - - if (Control != null) - { - try - { - DisposeControl(); - } - catch (Exception ex) - { - Runtime.MessageCollector?.AddExceptionStackTrace("Couldn't dispose control, probably form is already closed (Connection.Protocol.Base)", ex); - } - } - - if (_interfaceControl == null) return; - - try - { - if (_interfaceControl.Parent == null) return; - - if (_interfaceControl.Parent.Tag != null) - { - SetTagToNothing(); - } - - DisposeInterface(); - } - catch (Exception ex) - { - Runtime.MessageCollector?.AddExceptionStackTrace("Couldn't set InterfaceControl.Parent.Tag or Dispose Interface, probably form is already closed (Connection.Protocol.Base)", ex); - } - } - catch (Exception ex) - { - Runtime.MessageCollector?.AddExceptionStackTrace("Couldn't Close InterfaceControl BG (Connection.Protocol.Base)", ex); - } - } - - private delegate void DisposeInterfaceCB(); - private void DisposeInterface() - { - if (_interfaceControl.InvokeRequired) - { - var s = new DisposeInterfaceCB(DisposeInterface); - _interfaceControl.Invoke(s); - } - else - { - _interfaceControl.Dispose(); - } - } - - private delegate void SetTagToNothingCB(); - private void SetTagToNothing() - { - if (_interfaceControl.Parent.InvokeRequired) - { - var s = new SetTagToNothingCB(SetTagToNothing); - _interfaceControl.Parent.Invoke(s); - } - else - { - _interfaceControl.Parent.Tag = null; - } - } - - private delegate void DisposeControlCB(); - private void DisposeControl() - { - if (Control.InvokeRequired) - { - var s = new DisposeControlCB(DisposeControl); - Control.Invoke(s); - } - else - { - Control.Dispose(); - } - } - - protected virtual void Dispose(bool disposing) { - if (disposing) + try { - tmrReconnect.Dispose(); + Control.Focus(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace("Couldn't focus Control (Connection.Protocol.Base)", + ex); } } - public void Dispose() + public virtual void ResizeBegin(object sender, EventArgs e) { - Dispose(true); - GC.SuppressFinalize(this); } + + public virtual void Resize(object sender, EventArgs e) + { + } + + public virtual void ResizeEnd(object sender, EventArgs e) + { + } + + public virtual bool Initialize() + { + try + { + _interfaceControl.Parent.Tag = _interfaceControl; + _interfaceControl.Show(); + + if (Control == null) return true; + Control.Name = Name; + Control.Parent = _interfaceControl; + Control.Location = _interfaceControl.Location; + Control.Size = InterfaceControl.Size; + Control.Anchor = _interfaceControl.Anchor; + + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace("Couldn't SetProps (Connection.Protocol.Base)", ex); + return false; + } + } + + public virtual bool Connect() + { + if (InterfaceControl.Info.Protocol == ProtocolType.RDP) return false; + if (ConnectedEvent == null) return false; + ConnectedEvent(this); + return true; + } + + public virtual void Disconnect() + { + Close(); + } + + public virtual void Close() + { + var t = new Thread(CloseBG); + t.SetApartmentState(ApartmentState.STA); + t.IsBackground = true; + t.Start(); + } + + private void CloseBG() + { + ClosedEvent?.Invoke(this); + try + { + tmrReconnect.Enabled = false; + + if (Control != null) + { + try + { + DisposeControl(); + } + catch (Exception ex) + { + Runtime.MessageCollector?.AddExceptionStackTrace( + "Couldn't dispose control, probably form is already closed (Connection.Protocol.Base)", + ex); + } + } + + if (_interfaceControl == null) return; + + try + { + if (_interfaceControl.Parent == null) return; + + if (_interfaceControl.Parent.Tag != null) + { + SetTagToNothing(); + } + + DisposeInterface(); + } + catch (Exception ex) + { + Runtime.MessageCollector?.AddExceptionStackTrace( + "Couldn't set InterfaceControl.Parent.Tag or Dispose Interface, probably form is already closed (Connection.Protocol.Base)", + ex); + } + } + catch (Exception ex) + { + Runtime.MessageCollector?.AddExceptionStackTrace( + "Couldn't Close InterfaceControl BG (Connection.Protocol.Base)", + ex); + } + } + + private delegate void DisposeInterfaceCB(); + + private void DisposeInterface() + { + if (_interfaceControl.InvokeRequired) + { + var s = new DisposeInterfaceCB(DisposeInterface); + _interfaceControl.Invoke(s); + } + else + { + _interfaceControl.Dispose(); + } + } + + private delegate void SetTagToNothingCB(); + + private void SetTagToNothing() + { + if (_interfaceControl.Parent.InvokeRequired) + { + var s = new SetTagToNothingCB(SetTagToNothing); + _interfaceControl.Parent.Invoke(s); + } + else + { + _interfaceControl.Parent.Tag = null; + } + } + + private delegate void DisposeControlCB(); + + private void DisposeControl() + { + if (Control.InvokeRequired) + { + var s = new DisposeControlCB(DisposeControl); + Control.Invoke(s); + } + else + { + Control.Dispose(); + } + } + #endregion #region Events + public delegate void ConnectingEventHandler(object sender); - public event ConnectingEventHandler Connecting - { - add => ConnectingEvent = (ConnectingEventHandler) Delegate.Combine(ConnectingEvent, value); - remove => ConnectingEvent = (ConnectingEventHandler) Delegate.Remove(ConnectingEvent, value); - } - - public delegate void ConnectedEventHandler(object sender); - public event ConnectedEventHandler Connected - { - add => ConnectedEvent = (ConnectedEventHandler) Delegate.Combine(ConnectedEvent, value); - remove => ConnectedEvent = (ConnectedEventHandler) Delegate.Remove(ConnectedEvent, value); - } - - public delegate void DisconnectedEventHandler(object sender, string disconnectedMessage, int? reasonCode); - public event DisconnectedEventHandler Disconnected - { - add => DisconnectedEvent = (DisconnectedEventHandler) Delegate.Combine(DisconnectedEvent, value); - remove => DisconnectedEvent = (DisconnectedEventHandler) Delegate.Remove(DisconnectedEvent, value); - } - - public delegate void ErrorOccuredEventHandler(object sender, string errorMessage, int? errorCode); - public event ErrorOccuredEventHandler ErrorOccured - { - add => ErrorOccuredEvent = (ErrorOccuredEventHandler) Delegate.Combine(ErrorOccuredEvent, value); - remove => ErrorOccuredEvent = (ErrorOccuredEventHandler) Delegate.Remove(ErrorOccuredEvent, value); - } - - public delegate void ClosingEventHandler(object sender); - public event ClosingEventHandler Closing - { - add => ClosingEvent = (ClosingEventHandler) Delegate.Combine(ClosingEvent, value); - remove => ClosingEvent = (ClosingEventHandler) Delegate.Remove(ClosingEvent, value); - } - - public delegate void ClosedEventHandler(object sender); - public event ClosedEventHandler Closed - { - add => ClosedEvent = (ClosedEventHandler) Delegate.Combine(ClosedEvent, value); - remove => ClosedEvent = (ClosedEventHandler) Delegate.Remove(ClosedEvent, value); - } - - - public void Event_Closing(object sender) - { - ClosingEvent?.Invoke(sender); - } - protected void Event_Closed(object sender) - { - ClosedEvent?.Invoke(sender); - } + public event ConnectingEventHandler Connecting + { + add => ConnectingEvent = (ConnectingEventHandler)Delegate.Combine(ConnectingEvent, value); + remove => ConnectingEvent = (ConnectingEventHandler)Delegate.Remove(ConnectingEvent, value); + } - protected void Event_Connecting(object sender) - { - ConnectingEvent?.Invoke(sender); - } + public delegate void ConnectedEventHandler(object sender); - protected void Event_Connected(object sender) - { - ConnectedEvent?.Invoke(sender); - } + public event ConnectedEventHandler Connected + { + add => ConnectedEvent = (ConnectedEventHandler)Delegate.Combine(ConnectedEvent, value); + remove => ConnectedEvent = (ConnectedEventHandler)Delegate.Remove(ConnectedEvent, value); + } - protected void Event_Disconnected(object sender, string disconnectedMessage, int? reasonCode) - { - DisconnectedEvent?.Invoke(sender, disconnectedMessage, reasonCode); - } + public delegate void DisconnectedEventHandler(object sender, string disconnectedMessage, int? reasonCode); - protected void Event_ErrorOccured(object sender, string errorMsg, int? errorCode) - { - ErrorOccuredEvent?.Invoke(sender, errorMsg, errorCode); - } + public event DisconnectedEventHandler Disconnected + { + add => DisconnectedEvent = (DisconnectedEventHandler)Delegate.Combine(DisconnectedEvent, value); + remove => DisconnectedEvent = (DisconnectedEventHandler)Delegate.Remove(DisconnectedEvent, value); + } + + public delegate void ErrorOccuredEventHandler(object sender, string errorMessage, int? errorCode); + + public event ErrorOccuredEventHandler ErrorOccured + { + add => ErrorOccuredEvent = (ErrorOccuredEventHandler)Delegate.Combine(ErrorOccuredEvent, value); + remove => ErrorOccuredEvent = (ErrorOccuredEventHandler)Delegate.Remove(ErrorOccuredEvent, value); + } + + public delegate void ClosingEventHandler(object sender); + + public event ClosingEventHandler Closing + { + add => ClosingEvent = (ClosingEventHandler)Delegate.Combine(ClosingEvent, value); + remove => ClosingEvent = (ClosingEventHandler)Delegate.Remove(ClosingEvent, value); + } + + public delegate void ClosedEventHandler(object sender); + + public event ClosedEventHandler Closed + { + add => ClosedEvent = (ClosedEventHandler)Delegate.Combine(ClosedEvent, value); + remove => ClosedEvent = (ClosedEventHandler)Delegate.Remove(ClosedEvent, value); + } + + + public void Event_Closing(object sender) + { + ClosingEvent?.Invoke(sender); + } + + protected void Event_Closed(object sender) + { + ClosedEvent?.Invoke(sender); + } + + protected void Event_Connecting(object sender) + { + ConnectingEvent?.Invoke(sender); + } + + protected void Event_Connected(object sender) + { + ConnectedEvent?.Invoke(sender); + } + + protected void Event_Disconnected(object sender, string disconnectedMessage, int? reasonCode) + { + DisconnectedEvent?.Invoke(sender, disconnectedMessage, reasonCode); + } + + protected void Event_ErrorOccured(object sender, string errorMsg, int? errorCode) + { + ErrorOccuredEvent?.Invoke(sender, errorMsg, errorCode); + } + + protected void Event_ReconnectGroupCloseClicked() + { + Close(); + } - protected void Event_ReconnectGroupCloseClicked() - { - Close(); - } #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/ProtocolFactory.cs b/mRemoteV1/Connection/Protocol/ProtocolFactory.cs index c4f6ca99..6c7611f1 100644 --- a/mRemoteV1/Connection/Protocol/ProtocolFactory.cs +++ b/mRemoteV1/Connection/Protocol/ProtocolFactory.cs @@ -16,51 +16,53 @@ namespace mRemoteNG.Connection.Protocol { var newProtocol = default(ProtocolBase); // ReSharper disable once SwitchStatementMissingSomeCases - switch (connectionInfo.Protocol) - { - case ProtocolType.RDP: - newProtocol = new RdpProtocol - { - LoadBalanceInfoUseUtf8 = Settings.Default.RdpLoadBalanceInfoUseUtf8 + switch (connectionInfo.Protocol) + { + case ProtocolType.RDP: + newProtocol = new RdpProtocol + { + LoadBalanceInfoUseUtf8 = Settings.Default.RdpLoadBalanceInfoUseUtf8 }; - ((RdpProtocol) newProtocol).tmrReconnect.Elapsed += ((RdpProtocol) newProtocol).tmrReconnect_Elapsed; - break; - case ProtocolType.VNC: - newProtocol = new ProtocolVNC(); - break; - case ProtocolType.SSH1: - newProtocol = new ProtocolSSH1(); - break; - case ProtocolType.SSH2: - newProtocol = new ProtocolSSH2(); - break; - case ProtocolType.Telnet: - newProtocol = new ProtocolTelnet(); - break; - case ProtocolType.Rlogin: - newProtocol = new ProtocolRlogin(); - break; - case ProtocolType.RAW: - newProtocol = new RawProtocol(); - break; - case ProtocolType.HTTP: - newProtocol = new ProtocolHTTP(connectionInfo.RenderingEngine); - break; - case ProtocolType.HTTPS: - newProtocol = new ProtocolHTTPS(connectionInfo.RenderingEngine); - break; - case ProtocolType.ICA: - newProtocol = new IcaProtocol(); - ((IcaProtocol) newProtocol).tmrReconnect.Elapsed += ((IcaProtocol) newProtocol).tmrReconnect_Elapsed; - break; - case ProtocolType.IntApp: - newProtocol = new IntegratedProgram(); - if (connectionInfo.ExtApp == "") - { - throw (new Exception(Language.strNoExtAppDefined)); - } - break; - } + ((RdpProtocol)newProtocol).tmrReconnect.Elapsed += ((RdpProtocol)newProtocol).tmrReconnect_Elapsed; + break; + case ProtocolType.VNC: + newProtocol = new ProtocolVNC(); + break; + case ProtocolType.SSH1: + newProtocol = new ProtocolSSH1(); + break; + case ProtocolType.SSH2: + newProtocol = new ProtocolSSH2(); + break; + case ProtocolType.Telnet: + newProtocol = new ProtocolTelnet(); + break; + case ProtocolType.Rlogin: + newProtocol = new ProtocolRlogin(); + break; + case ProtocolType.RAW: + newProtocol = new RawProtocol(); + break; + case ProtocolType.HTTP: + newProtocol = new ProtocolHTTP(connectionInfo.RenderingEngine); + break; + case ProtocolType.HTTPS: + newProtocol = new ProtocolHTTPS(connectionInfo.RenderingEngine); + break; + case ProtocolType.ICA: + newProtocol = new IcaProtocol(); + ((IcaProtocol)newProtocol).tmrReconnect.Elapsed += ((IcaProtocol)newProtocol).tmrReconnect_Elapsed; + break; + case ProtocolType.IntApp: + newProtocol = new IntegratedProgram(); + if (connectionInfo.ExtApp == "") + { + throw (new Exception(Language.strNoExtAppDefined)); + } + + break; + } + return newProtocol; } } diff --git a/mRemoteV1/Connection/Protocol/ProtocolList.cs b/mRemoteV1/Connection/Protocol/ProtocolList.cs index 9eee86eb..0edbe325 100644 --- a/mRemoteV1/Connection/Protocol/ProtocolList.cs +++ b/mRemoteV1/Connection/Protocol/ProtocolList.cs @@ -1,69 +1,82 @@ using System; using System.Collections; using System.Collections.Specialized; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Connection.Protocol { - public class ProtocolList : CollectionBase, INotifyCollectionChanged - { + public class ProtocolList : CollectionBase, INotifyCollectionChanged + { public ProtocolBase this[object index] - { - get - { - var @base = index as ProtocolBase; - if (@base != null) + { + get + { + var @base = index as ProtocolBase; + if (@base != null) return @base; - if (index is int) - return (ProtocolBase) List[Convert.ToInt32(index)]; - return null; - } - } - + if (index is int) + return (ProtocolBase)List[Convert.ToInt32(index)]; + return null; + } + } + public new int Count { get { return List.Count; } } - public void Add(ProtocolBase cProt) - { - List.Add(cProt); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, cProt)); + public void Add(ProtocolBase cProt) + { + List.Add(cProt); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, cProt)); } - - public void AddRange(ProtocolBase[] cProt) - { - foreach (var cP in cProt) - { - List.Add(cP); - } - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, cProt)); - } - - public void Remove(ProtocolBase cProt) - { - try - { - List.Remove(cProt); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cProt)); - } - catch (Exception) - { - } - } - - public new void Clear() - { - if (Count == 0) return; - List.Clear(); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } - public event NotifyCollectionChangedEventHandler CollectionChanged; - private void RaiseCollectionChangedEvent(object sender, NotifyCollectionChangedEventArgs args) - { - CollectionChanged?.Invoke(sender, args); - } + public void AddRange(ProtocolBase[] cProt) + { + foreach (var cP in cProt) + { + List.Add(cP); + } + + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, cProt)); + } + + public void Remove(ProtocolBase cProt) + { + try + { + if (!List.Contains(cProt)) + return; + + List.Remove(cProt); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, + cProt)); + } + catch (Exception) + { + } + } + + public new void Clear() + { + if (Count == 0) + return; + + List.Clear(); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + } + + public event NotifyCollectionChangedEventHandler CollectionChanged; + + private void RaiseCollectionChangedEvent(object sender, NotifyCollectionChangedEventArgs args) + { + CollectionChanged?.Invoke(sender, args); + } } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/ProtocolType.cs b/mRemoteV1/Connection/Protocol/ProtocolType.cs index 69d4fa6f..44aca2f9 100644 --- a/mRemoteV1/Connection/Protocol/ProtocolType.cs +++ b/mRemoteV1/Connection/Protocol/ProtocolType.cs @@ -2,29 +2,39 @@ using mRemoteNG.Tools; namespace mRemoteNG.Connection.Protocol { - public enum ProtocolType - { + public enum ProtocolType + { [LocalizedAttributes.LocalizedDescription("strRDP")] RDP = 0, + [LocalizedAttributes.LocalizedDescription("strVnc")] VNC = 1, + [LocalizedAttributes.LocalizedDescription("strSsh1")] SSH1 = 2, + [LocalizedAttributes.LocalizedDescription("strSsh2")] SSH2 = 3, + [LocalizedAttributes.LocalizedDescription("strTelnet")] Telnet = 4, + [LocalizedAttributes.LocalizedDescription("strRlogin")] Rlogin = 5, + [LocalizedAttributes.LocalizedDescription("strRAW")] RAW = 6, + [LocalizedAttributes.LocalizedDescription("strHttp")] HTTP = 7, + [LocalizedAttributes.LocalizedDescription("strHttps")] HTTPS = 8, + [LocalizedAttributes.LocalizedDescription("strICA")] ICA = 9, + [LocalizedAttributes.LocalizedDescription("strExtApp")] IntApp = 20 - } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/PuttyBase.cs b/mRemoteV1/Connection/Protocol/PuttyBase.cs index 515bba51..ced700e9 100644 --- a/mRemoteV1/Connection/Protocol/PuttyBase.cs +++ b/mRemoteV1/Connection/Protocol/PuttyBase.cs @@ -18,9 +18,9 @@ using mRemoteNG.Security; namespace mRemoteNG.Connection.Protocol { public class PuttyBase : ProtocolBase - { - private const int IDM_RECONF = 0x50; // PuTTY Settings Menu ID - private bool _isPuttyNg; + { + private const int IDM_RECONF = 0x50; // PuTTY Settings Menu ID + private bool _isPuttyNg; private readonly DisplayProperties _display = new DisplayProperties(); #region Public Properties @@ -29,228 +29,258 @@ namespace mRemoteNG.Connection.Protocol protected Putty_SSHVersion PuttySSHVersion { private get; set; } - public IntPtr PuttyHandle { get; set; } + public IntPtr PuttyHandle { get; set; } - private Process PuttyProcess { get; set; } + private Process PuttyProcess { get; set; } - public static string PuttyPath { get; set; } + public static string PuttyPath { get; set; } - public bool Focused - { - get { return NativeMethods.GetForegroundWindow() == PuttyHandle; } - } + public bool Focused + { + get { return NativeMethods.GetForegroundWindow() == PuttyHandle; } + } - #endregion - - #region Private Events & Handlers - private void ProcessExited(object sender, EventArgs e) - { - Event_Closed(this); - } #endregion - + + #region Private Events & Handlers + + private void ProcessExited(object sender, EventArgs e) + { + Event_Closed(this); + } + + #endregion + #region Public Methods - public override bool Connect() - { - try - { - _isPuttyNg = PuttyTypeDetector.GetPuttyType() == PuttyTypeDetector.PuttyType.PuttyNg; - PuttyProcess = new Process - { - StartInfo = - { - UseShellExecute = false, - FileName = PuttyPath - } - }; + public override bool Connect() + { + try + { + _isPuttyNg = PuttyTypeDetector.GetPuttyType() == PuttyTypeDetector.PuttyType.PuttyNg; - var arguments = new CommandLineArguments {EscapeForShell = false}; + PuttyProcess = new Process + { + StartInfo = + { + UseShellExecute = false, + FileName = PuttyPath + } + }; + + var arguments = new CommandLineArguments {EscapeForShell = false}; + + arguments.Add("-load", InterfaceControl.Info.PuttySession); + + if (!(InterfaceControl.Info is PuttySessionInfo)) + { + arguments.Add("-" + PuttyProtocol); + + if (PuttyProtocol == Putty_Protocol.ssh) + { - arguments.Add("-load", InterfaceControl.Info.PuttySession); - if (!(InterfaceControl.Info is PuttySessionInfo)) - { - arguments.Add("-" + PuttyProtocol); - - if (PuttyProtocol == Putty_Protocol.ssh) - { - arguments.Add("-" + (int)PuttySSHVersion); + - if (!Force.HasFlag(ConnectionInfo.Force.NoCredentials)) - { + arguments.Add("-" + (int)PuttySSHVersion); + + if (!Force.HasFlag(ConnectionInfo.Force.NoCredentials)) + { var cred = Runtime.CredentialService.GetEffectiveCredentialRecord(InterfaceControl?.Info.CredentialRecordId .FirstOrDefault()).FirstOrDefault(); var username = cred.Username; var password = cred.Password.ConvertToUnsecureString(); - if (!string.IsNullOrEmpty(username)) - { - arguments.Add("-l", username); - } - if (!string.IsNullOrEmpty(password)) - { - arguments.Add("-pw", password); - } - } - } - - arguments.Add("-P", InterfaceControl.Info.Port.ToString()); - arguments.Add(InterfaceControl.Info.Hostname); - } - - if (_isPuttyNg) - { - arguments.Add("-hwndparent", InterfaceControl.Handle.ToString()); - } - - PuttyProcess.StartInfo.Arguments = arguments.ToString(); - - PuttyProcess.EnableRaisingEvents = true; - PuttyProcess.Exited += ProcessExited; - - PuttyProcess.Start(); - PuttyProcess.WaitForInputIdle(Settings.Default.MaxPuttyWaitTime * 1000); - - var startTicks = Environment.TickCount; - while (PuttyHandle.ToInt32() == 0 & Environment.TickCount < startTicks + Settings.Default.MaxPuttyWaitTime * 1000) - { - if (_isPuttyNg) - { - PuttyHandle = NativeMethods.FindWindowEx( - InterfaceControl.Handle, new IntPtr(0), null, null); - } - else - { - PuttyProcess.Refresh(); - PuttyHandle = PuttyProcess.MainWindowHandle; - } - if (PuttyHandle.ToInt32() == 0) - { - Thread.Sleep(0); - } - } - - if (!_isPuttyNg) - { - NativeMethods.SetParent(PuttyHandle, InterfaceControl.Handle); - } - - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strPuttyStuff, true); - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strPuttyHandle, PuttyHandle), true); - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strPuttyTitle, PuttyProcess.MainWindowTitle), true); - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strPuttyParentHandle, InterfaceControl.Parent.Handle), true); - - Resize(this, new EventArgs()); - base.Connect(); - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strPuttyConnectionFailed + Environment.NewLine + ex.Message); - return false; - } - } - - public override void Focus() - { - try - { - if (ConnectionWindow.InTabDrag) - { - return; - } - NativeMethods.SetForegroundWindow(PuttyHandle); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strPuttyFocusFailed + Environment.NewLine + ex.Message, true); - } - } + if (!string.IsNullOrEmpty(username)) + { + arguments.Add("-l", username); + } - protected override void Resize(object sender, EventArgs e) - { - try - { - if (InterfaceControl.Size == Size.Empty) - { - return; - } + if (!string.IsNullOrEmpty(password)) + { + arguments.Add("-pw", password); + } + } + } - var scaledFrameBorderHeight = _display.ScaleHeight(SystemInformation.FrameBorderSize.Height); - var scaledFrameBorderWidth = _display.ScaleWidth(SystemInformation.FrameBorderSize.Width); + arguments.Add("-P", InterfaceControl.Info.Port.ToString()); + arguments.Add(InterfaceControl.Info.Hostname); + } - NativeMethods.MoveWindow( - PuttyHandle, - -scaledFrameBorderWidth, - -(SystemInformation.CaptionHeight + scaledFrameBorderHeight), - InterfaceControl.Width + scaledFrameBorderWidth * 2, - InterfaceControl.Height + SystemInformation.CaptionHeight + scaledFrameBorderHeight * 2, - true); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strPuttyResizeFailed + Environment.NewLine + ex.Message, true); - } - } - - public override void Close() - { - try - { - if (PuttyProcess.HasExited == false) - { - PuttyProcess.Kill(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strPuttyKillFailed + Environment.NewLine + ex.Message, true); - } - - try - { - PuttyProcess.Dispose(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strPuttyDisposeFailed + Environment.NewLine + ex.Message, true); - } - - base.Close(); - } - - public void ShowSettingsDialog() - { - try - { + if (_isPuttyNg) + { + arguments.Add("-hwndparent", InterfaceControl.Handle.ToString()); + } + + PuttyProcess.StartInfo.Arguments = arguments.ToString(); + + PuttyProcess.EnableRaisingEvents = true; + PuttyProcess.Exited += ProcessExited; + + PuttyProcess.Start(); + PuttyProcess.WaitForInputIdle(Settings.Default.MaxPuttyWaitTime * 1000); + + var startTicks = Environment.TickCount; + while (PuttyHandle.ToInt32() == 0 & + Environment.TickCount < startTicks + Settings.Default.MaxPuttyWaitTime * 1000) + { + if (_isPuttyNg) + { + PuttyHandle = NativeMethods.FindWindowEx( + InterfaceControl.Handle, new IntPtr(0), null, null); + } + else + { + PuttyProcess.Refresh(); + PuttyHandle = PuttyProcess.MainWindowHandle; + } + + if (PuttyHandle.ToInt32() == 0) + { + Thread.Sleep(0); + } + } + + if (!_isPuttyNg) + { + NativeMethods.SetParent(PuttyHandle, InterfaceControl.Handle); + } + + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strPuttyStuff, true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strPuttyHandle, PuttyHandle), true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strPuttyTitle, PuttyProcess.MainWindowTitle), + true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strPuttyParentHandle, + InterfaceControl.Parent.Handle), true); + + Resize(this, new EventArgs()); + base.Connect(); + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strPuttyConnectionFailed + Environment.NewLine + + ex.Message); + return false; + } + } + + public override void Focus() + { + try + { + NativeMethods.SetForegroundWindow(PuttyHandle); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strPuttyFocusFailed + Environment.NewLine + ex.Message, + true); + } + } + + public override void Resize(object sender, EventArgs e) + { + try + { + if (InterfaceControl.Size == Size.Empty) + return; + + if (_isPuttyNg) + { + // PuTTYNG 0.70.0.1 and later doesn't have any window borders + NativeMethods.MoveWindow(PuttyHandle, 0, 0, InterfaceControl.Width, InterfaceControl.Height, true); + } + else + { + var scaledFrameBorderHeight = _display.ScaleHeight(SystemInformation.FrameBorderSize.Height); + var scaledFrameBorderWidth = _display.ScaleWidth(SystemInformation.FrameBorderSize.Width); + + NativeMethods.MoveWindow(PuttyHandle, -scaledFrameBorderWidth, + -(SystemInformation.CaptionHeight + scaledFrameBorderHeight), + InterfaceControl.Width + scaledFrameBorderWidth * 2, + InterfaceControl.Height + SystemInformation.CaptionHeight + + scaledFrameBorderHeight * 2, + true); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strPuttyResizeFailed + Environment.NewLine + ex.Message, + true); + } + } + + public override void Close() + { + try + { + if (PuttyProcess.HasExited == false) + { + PuttyProcess.Kill(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strPuttyKillFailed + Environment.NewLine + ex.Message, + true); + } + + try + { + PuttyProcess.Dispose(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strPuttyDisposeFailed + Environment.NewLine + ex.Message, + true); + } + + base.Close(); + } + + public void ShowSettingsDialog() + { + try + { NativeMethods.PostMessage(PuttyHandle, NativeMethods.WM_SYSCOMMAND, (IntPtr)IDM_RECONF, (IntPtr)0); NativeMethods.SetForegroundWindow(PuttyHandle); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strPuttyShowSettingsDialogFailed + Environment.NewLine + ex.Message, true); - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strPuttyShowSettingsDialogFailed + Environment.NewLine + + ex.Message, true); + } + } + #endregion - + #region Enums - protected enum Putty_Protocol - { - ssh = 0, - telnet = 1, - rlogin = 2, - raw = 3, - serial = 4 - } + protected enum Putty_Protocol + { + ssh = 0, + telnet = 1, + rlogin = 2, + raw = 3, + serial = 4 + } + + protected enum Putty_SSHVersion + { + ssh1 = 1, + ssh2 = 2 + } - protected enum Putty_SSHVersion - { - ssh1 = 1, - ssh2 = 2 - } #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/RAW/RawProtocol.cs b/mRemoteV1/Connection/Protocol/RAW/RawProtocol.cs index 4e9643e3..cb7f0a51 100644 --- a/mRemoteV1/Connection/Protocol/RAW/RawProtocol.cs +++ b/mRemoteV1/Connection/Protocol/RAW/RawProtocol.cs @@ -1,15 +1,15 @@ namespace mRemoteNG.Connection.Protocol.RAW { - public class RawProtocol : PuttyBase - { - public RawProtocol() - { - PuttyProtocol = Putty_Protocol.raw; - } - - public enum Defaults - { - Port = 23 - } - } + public class RawProtocol : PuttyBase + { + public RawProtocol() + { + PuttyProtocol = Putty_Protocol.raw; + } + + public enum Defaults + { + Port = 23 + } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs b/mRemoteV1/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs index e0836053..1f7a2e38 100644 --- a/mRemoteV1/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs +++ b/mRemoteV1/Connection/Protocol/RDP/AzureLoadBalanceInfoEncoder.cs @@ -37,4 +37,4 @@ namespace mRemoteNG.Connection.Protocol.RDP return Encoding.Unicode.GetString(bytes); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/RDP/RdpClientWrap.cs b/mRemoteV1/Connection/Protocol/RDP/RdpClientWrap.cs new file mode 100644 index 00000000..08ed2f85 --- /dev/null +++ b/mRemoteV1/Connection/Protocol/RDP/RdpClientWrap.cs @@ -0,0 +1,24 @@ +using mRemoteNG.App; +using mRemoteNG.UI.Tabs; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mRemoteNG.Connection.Protocol.RDP +{ + class RdpClientWrap : AxMSTSCLib.AxMsRdpClient8NotSafeForScripting + { + public RdpClientWrap() + : base() + { + GotFocus += RdpClientWrap_GotFocus; + } + + private void RdpClientWrap_GotFocus(object sender, EventArgs e) + { + ((ConnectionTab)Parent.Parent).Focus(); + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/RDP/RdpErrorCodes.cs b/mRemoteV1/Connection/Protocol/RDP/RdpErrorCodes.cs index aa963ffd..b20980c1 100644 --- a/mRemoteV1/Connection/Protocol/RDP/RdpErrorCodes.cs +++ b/mRemoteV1/Connection/Protocol/RDP/RdpErrorCodes.cs @@ -12,18 +12,18 @@ namespace mRemoteNG.Connection.Protocol.RDP { _description = new Hashtable { - { 0, "Language.strRdpErrorUnknown"}, - { 1, "Language.strRdpErrorCode1"}, - { 2, "Language.strRdpErrorOutOfMemory"}, - { 3, "Language.strRdpErrorWindowCreation"}, - { 4, "Language.strRdpErrorCode2"}, - { 5, "Language.strRdpErrorCode3"}, - { 6, "Language.strRdpErrorCode4"}, - { 7, "Language.strRdpErrorConnection"}, - { 100, "Language.strRdpErrorWinsock"} + {0, "Language.strRdpErrorUnknown"}, + {1, "Language.strRdpErrorCode1"}, + {2, "Language.strRdpErrorOutOfMemory"}, + {3, "Language.strRdpErrorWindowCreation"}, + {4, "Language.strRdpErrorCode2"}, + {5, "Language.strRdpErrorCode3"}, + {6, "Language.strRdpErrorCode4"}, + {7, "Language.strRdpErrorConnection"}, + {100, "Language.strRdpErrorWinsock"} }; } - + public static string GetError(int id) { try diff --git a/mRemoteV1/Connection/Protocol/RDP/RdpProtocol.cs b/mRemoteV1/Connection/Protocol/RDP/RdpProtocol.cs index 07019df7..7f0102ce 100644 --- a/mRemoteV1/Connection/Protocol/RDP/RdpProtocol.cs +++ b/mRemoteV1/Connection/Protocol/RDP/RdpProtocol.cs @@ -18,7 +18,7 @@ using mRemoteNG.Security; namespace mRemoteNG.Connection.Protocol.RDP { public class RdpProtocol : ProtocolBase - { + { /* RDP v8 requires Windows 7 with: * https://support.microsoft.com/en-us/kb/2592687 * OR @@ -32,99 +32,104 @@ namespace mRemoteNG.Connection.Protocol.RDP private bool _loginComplete; private bool _redirectKeys; private bool _alertOnIdleDisconnect; - private readonly DisplayProperties _displayProperties; + private readonly DisplayProperties _displayProperties; private readonly FrmMain _frmMain = FrmMain.Default; #region Properties - public bool SmartSize - { - get => _rdpClient.AdvancedSettings2.SmartSizing; - private set - { - _rdpClient.AdvancedSettings2.SmartSizing = value; - ReconnectForResize(); - } - } - - public bool Fullscreen - { - get => _rdpClient.FullScreen; - private set - { - _rdpClient.FullScreen = value; - ReconnectForResize(); - } - } - private bool RedirectKeys - { + public bool SmartSize + { + get => _rdpClient.AdvancedSettings2.SmartSizing; + private set + { + _rdpClient.AdvancedSettings2.SmartSizing = value; + ReconnectForResize(); + } + } + + public bool Fullscreen + { + get => _rdpClient.FullScreen; + private set + { + _rdpClient.FullScreen = value; + ReconnectForResize(); + } + } + + private bool RedirectKeys + { /* get { return _redirectKeys; } */ - set - { - _redirectKeys = value; - try - { - if (!_redirectKeys) - { - return; - } - - Debug.Assert(Convert.ToBoolean(_rdpClient.SecuredSettingsEnabled)); + set + { + _redirectKeys = value; + try + { + if (!_redirectKeys) + { + return; + } + + Debug.Assert(Convert.ToBoolean(_rdpClient.SecuredSettingsEnabled)); var msRdpClientSecuredSettings = _rdpClient.SecuredSettings2; - msRdpClientSecuredSettings.KeyboardHookMode = 1; // Apply key combinations at the remote server. - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetRedirectKeysFailed, ex); - } - } - } + msRdpClientSecuredSettings.KeyboardHookMode = 1; // Apply key combinations at the remote server. + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetRedirectKeysFailed, ex); + } + } + } public bool LoadBalanceInfoUseUtf8 { get; set; } + #endregion #region Constructors + public RdpProtocol() { - Control = new AxMsRdpClient8NotSafeForScripting(); + Control = new RdpClientWrap(); _displayProperties = new DisplayProperties(); } + #endregion #region Public Methods - public override bool Initialize() - { - base.Initialize(); - try - { - Control.CreateControl(); - _connectionInfo = InterfaceControl.Info; - - try - { - while (!Control.Created) - { - Thread.Sleep(0); - Application.DoEvents(); - } - _rdpClient = (MsRdpClient8NotSafeForScripting)((AxMsRdpClient8NotSafeForScripting)Control).GetOcx(); - } - catch (System.Runtime.InteropServices.COMException ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strRdpControlCreationFailed, ex); - Control.Dispose(); - return false; - } - - _rdpVersion = new Version(_rdpClient.Version); - - _rdpClient.Server = _connectionInfo.Hostname; + public override bool Initialize() + { + base.Initialize(); + try + { + Control.CreateControl(); + _connectionInfo = InterfaceControl.Info; + + try + { + while (!Control.Created) + { + Thread.Sleep(0); + Application.DoEvents(); + } + + _rdpClient = (MsRdpClient8NotSafeForScripting)((AxMsRdpClient8NotSafeForScripting)Control).GetOcx(); + } + catch (System.Runtime.InteropServices.COMException ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strRdpControlCreationFailed, ex); + Control.Dispose(); + return false; + } + + _rdpVersion = new Version(_rdpClient.Version); + + _rdpClient.Server = _connectionInfo.Hostname; SetCredentials(); SetResolution(); @@ -135,505 +140,534 @@ namespace mRemoteNG.Connection.Protocol.RDP //not user changeable _rdpClient.AdvancedSettings2.GrabFocusOnConnect = true; - _rdpClient.AdvancedSettings3.EnableAutoReconnect = true; - _rdpClient.AdvancedSettings3.MaxReconnectAttempts = Settings.Default.RdpReconnectionCount; - _rdpClient.AdvancedSettings2.keepAliveInterval = 60000; //in milliseconds (10,000 = 10 seconds) - _rdpClient.AdvancedSettings5.AuthenticationLevel = 0; - _rdpClient.AdvancedSettings2.EncryptionEnabled = 1; - - _rdpClient.AdvancedSettings2.overallConnectionTimeout = Settings.Default.ConRDPOverallConnectionTimeout; - - _rdpClient.AdvancedSettings2.BitmapPeristence = Convert.ToInt32(_connectionInfo.CacheBitmaps); - if (_rdpVersion >= Versions.RDC61) - { - _rdpClient.AdvancedSettings7.EnableCredSspSupport = _connectionInfo.UseCredSsp; - _rdpClient.AdvancedSettings8.AudioQualityMode = (uint)_connectionInfo.SoundQuality; - } + _rdpClient.AdvancedSettings3.EnableAutoReconnect = true; + _rdpClient.AdvancedSettings3.MaxReconnectAttempts = Settings.Default.RdpReconnectionCount; + _rdpClient.AdvancedSettings2.keepAliveInterval = 60000; //in milliseconds (10,000 = 10 seconds) + _rdpClient.AdvancedSettings5.AuthenticationLevel = 0; + _rdpClient.AdvancedSettings2.EncryptionEnabled = 1; + + _rdpClient.AdvancedSettings2.overallConnectionTimeout = Settings.Default.ConRDPOverallConnectionTimeout; + + _rdpClient.AdvancedSettings2.BitmapPeristence = Convert.ToInt32(_connectionInfo.CacheBitmaps); + if (_rdpVersion >= Versions.RDC61) + { + _rdpClient.AdvancedSettings7.EnableCredSspSupport = _connectionInfo.UseCredSsp; + _rdpClient.AdvancedSettings8.AudioQualityMode = (uint)_connectionInfo.SoundQuality; + } SetUseConsoleSession(); SetPort(); - RedirectKeys = _connectionInfo.RedirectKeys; + RedirectKeys = _connectionInfo.RedirectKeys; SetRedirection(); SetAuthenticationLevel(); - SetLoadBalanceInfo(); + SetLoadBalanceInfo(); SetRdGateway(); _rdpClient.ColorDepth = (int)_connectionInfo.Colors; SetPerformanceFlags(); - - _rdpClient.ConnectingText = Language.strConnecting; - - Control.Anchor = AnchorStyles.None; - - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetPropsFailed, ex); - return false; - } - } - public override bool Connect() - { - _loginComplete = false; - SetEventHandlers(); + _rdpClient.ConnectingText = Language.strConnecting; + + Control.Anchor = AnchorStyles.None; + + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetPropsFailed, ex); + return false; + } + } + + public override bool Connect() + { + _loginComplete = false; + SetEventHandlers(); try - { - _rdpClient.Connect(); - base.Connect(); - return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strConnectionOpenFailed, ex); - } - - return false; - } - - public override void Disconnect() - { - try - { - _rdpClient.Disconnect(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpDisconnectFailed, ex); - Close(); - } - } - - public void ToggleFullscreen() - { - try - { + { + _rdpClient.Connect(); + base.Connect(); + return true; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strConnectionOpenFailed, ex); + } + + return false; + } + + public override void Disconnect() + { + try + { + _rdpClient.Disconnect(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpDisconnectFailed, ex); + Close(); + } + } + + public void ToggleFullscreen() + { + try + { Fullscreen = !Fullscreen; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpToggleFullscreenFailed, ex); - } - } - - public void ToggleSmartSize() - { - try - { + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpToggleFullscreenFailed, ex); + } + } + + public void ToggleSmartSize() + { + try + { SmartSize = !SmartSize; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpToggleSmartSizeFailed, ex); - } - } - - public override void Focus() - { - try - { - if (Control.ContainsFocus == false) - { - Control.Focus(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpFocusFailed, ex); - } - } - - private Size _controlBeginningSize; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpToggleSmartSizeFailed, ex); + } + } - protected override void ResizeBegin(object sender, EventArgs e) - { - _controlBeginningSize = Control.Size; - } + public override void Focus() + { + try + { + if (Control.ContainsFocus == false) + { + Control.Focus(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpFocusFailed, ex); + } + } - protected override void Resize(object sender, EventArgs e) - { - if (DoResize() && _controlBeginningSize.IsEmpty) - { - ReconnectForResize(); - } - base.Resize(sender, e); - } + private Size _controlBeginningSize; + + public override void ResizeBegin(object sender, EventArgs e) + { + _controlBeginningSize = Control.Size; + } + + public override void Resize(object sender, EventArgs e) + { + if (DoResize() && _controlBeginningSize.IsEmpty) + { + ReconnectForResize(); + } + + base.Resize(sender, e); + } + + public override void ResizeEnd(object sender, EventArgs e) + { + DoResize(); + if (!(Control.Size == _controlBeginningSize)) + { + ReconnectForResize(); + } + + _controlBeginningSize = Size.Empty; + } - protected override void ResizeEnd(object sender, EventArgs e) - { - DoResize(); - if (!(Control.Size == _controlBeginningSize)) - { - ReconnectForResize(); - } - _controlBeginningSize = Size.Empty; - } #endregion - - #region Private Methods - private bool DoResize() - { - Control.Location = InterfaceControl.Location; - if (!(Control.Size == InterfaceControl.Size) && !(InterfaceControl.Size == Size.Empty)) // kmscode - this doesn't look right to me. But I'm not aware of any functionality issues with this currently... - { - Control.Size = InterfaceControl.Size; - return true; - } - else - { - return false; - } - } - - private void ReconnectForResize() - { - if (_rdpVersion < Versions.RDC80) - { - return; - } - - if (!_loginComplete) - { - return; - } - - if (!InterfaceControl.Info.AutomaticResize) - { - return; - } - - if (!(InterfaceControl.Info.Resolution == RDPResolutions.FitToWindow | InterfaceControl.Info.Resolution == RDPResolutions.Fullscreen)) - { - return; - } - - if (SmartSize) - { - return; - } - try - { - Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, $"Resizing RDP connection to host '{_connectionInfo.Hostname}'"); - var size = !Fullscreen ? Control.Size : Screen.FromControl(Control).Bounds.Size; + #region Private Methods + + private bool DoResize() + { + Control.Location = InterfaceControl.Location; + if (!(Control.Size == InterfaceControl.Size) && !(InterfaceControl.Size == Size.Empty) + ) // kmscode - this doesn't look right to me. But I'm not aware of any functionality issues with this currently... + { + Control.Size = InterfaceControl.Size; + return true; + } + else + { + return false; + } + } + + private void ReconnectForResize() + { + if (_rdpVersion < Versions.RDC80) + { + return; + } + + if (!_loginComplete) + { + return; + } + + if (!InterfaceControl.Info.AutomaticResize) + { + return; + } + + if (!(InterfaceControl.Info.Resolution == RDPResolutions.FitToWindow | + InterfaceControl.Info.Resolution == RDPResolutions.Fullscreen)) + { + return; + } + + if (SmartSize) + { + return; + } + + try + { + Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, + $"Resizing RDP connection to host '{_connectionInfo.Hostname}'"); + var size = !Fullscreen ? Control.Size : Screen.FromControl(Control).Bounds.Size; IMsRdpClient8 msRdpClient8 = _rdpClient; - msRdpClient8.Reconnect((uint)size.Width, (uint)size.Height); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(string.Format(Language.ChangeConnectionResolutionError, _connectionInfo.Hostname), - ex, MessageClass.WarningMsg, false); - } - } - - private void SetRdGateway() - { - try - { - if (_rdpClient.TransportSettings.GatewayIsSupported == 0) - { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strRdpGatewayNotSupported, true); - return; - } - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strRdpGatewayIsSupported, true); + msRdpClient8.Reconnect((uint)size.Width, (uint)size.Height); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + string.Format(Language.ChangeConnectionResolutionError, + _connectionInfo.Hostname), + ex, MessageClass.WarningMsg, false); + } + } - if (_connectionInfo.RDGatewayUsageMethod != RDGatewayUsageMethod.Never) - { - _rdpClient.TransportSettings.GatewayUsageMethod = (uint)_connectionInfo.RDGatewayUsageMethod; - _rdpClient.TransportSettings.GatewayHostname = _connectionInfo.RDGatewayHostname; - _rdpClient.TransportSettings.GatewayProfileUsageMethod = 1; // TSC_PROXY_PROFILE_MODE_EXPLICIT - if (_connectionInfo.RDGatewayUseConnectionCredentials == RDGatewayUseConnectionCredentials.SmartCard) - { - _rdpClient.TransportSettings.GatewayCredsSource = 1; // TSC_PROXY_CREDS_MODE_SMARTCARD - } - if (_rdpVersion >= Versions.RDC61 && !Force.HasFlag(ConnectionInfo.Force.NoCredentials)) - { - if (_connectionInfo.RDGatewayUseConnectionCredentials == RDGatewayUseConnectionCredentials.Yes) - { + private void SetRdGateway() + { + try + { + if (_rdpClient.TransportSettings.GatewayIsSupported == 0) + { + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strRdpGatewayNotSupported, + true); + return; + } + + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strRdpGatewayIsSupported, + true); + + if (_connectionInfo.RDGatewayUsageMethod != RDGatewayUsageMethod.Never) + { + _rdpClient.TransportSettings.GatewayUsageMethod = (uint)_connectionInfo.RDGatewayUsageMethod; + _rdpClient.TransportSettings.GatewayHostname = _connectionInfo.RDGatewayHostname; + _rdpClient.TransportSettings.GatewayProfileUsageMethod = 1; // TSC_PROXY_PROFILE_MODE_EXPLICIT + if (_connectionInfo.RDGatewayUseConnectionCredentials == + RDGatewayUseConnectionCredentials.SmartCard) + { + _rdpClient.TransportSettings.GatewayCredsSource = 1; // TSC_PROXY_CREDS_MODE_SMARTCARD + } + + if (_rdpVersion >= Versions.RDC61 && !Force.HasFlag(ConnectionInfo.Force.NoCredentials)) + { + if (_connectionInfo.RDGatewayUseConnectionCredentials == RDGatewayUseConnectionCredentials.Yes) + { _rdpClient.TransportSettings2.GatewayUsername = _connectionInfo.CredentialRecord.Username; _rdpClient.TransportSettings2.GatewayPassword = _connectionInfo.CredentialRecord.Password.ConvertToUnsecureString(); _rdpClient.TransportSettings2.GatewayDomain = _connectionInfo.CredentialRecord.Domain; - } - else if (_connectionInfo.RDGatewayUseConnectionCredentials == RDGatewayUseConnectionCredentials.SmartCard) - { - _rdpClient.TransportSettings2.GatewayCredSharing = 0; - } - else - { + } + else if (_connectionInfo.RDGatewayUseConnectionCredentials == + RDGatewayUseConnectionCredentials.SmartCard) + { + _rdpClient.TransportSettings2.GatewayCredSharing = 0; + } + else + { _rdpClient.TransportSettings2.GatewayUsername = _connectionInfo.RDGatewayUsername; _rdpClient.TransportSettings2.GatewayPassword = _connectionInfo.RDGatewayPassword; _rdpClient.TransportSettings2.GatewayDomain = _connectionInfo.RDGatewayDomain; _rdpClient.TransportSettings2.GatewayCredSharing = 0; } - } - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetGatewayFailed, ex); - } - } - - private void SetUseConsoleSession() - { - try - { - bool value; - - if (Force.HasFlag(ConnectionInfo.Force.UseConsoleSession)) - { - value = true; - } - else if (Force.HasFlag(ConnectionInfo.Force.DontUseConsoleSession)) - { - value = false; - } - else - { - value = _connectionInfo.UseConsoleSession; - } - - if (_rdpVersion >= Versions.RDC61) - { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strRdpSetConsoleSwitch, _rdpVersion), true); - _rdpClient.AdvancedSettings7.ConnectToAdministerServer = value; - } - else - { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, string.Format(Language.strRdpSetConsoleSwitch, _rdpVersion) + Environment.NewLine + "No longer supported in this RDP version. Reference: https://msdn.microsoft.com/en-us/library/aa380863(v=vs.85).aspx", true); + } + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetGatewayFailed, ex); + } + } + + private void SetUseConsoleSession() + { + try + { + bool value; + + if (Force.HasFlag(ConnectionInfo.Force.UseConsoleSession)) + { + value = true; + } + else if (Force.HasFlag(ConnectionInfo.Force.DontUseConsoleSession)) + { + value = false; + } + else + { + value = _connectionInfo.UseConsoleSession; + } + + if (_rdpVersion >= Versions.RDC61) + { + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strRdpSetConsoleSwitch, _rdpVersion), + true); + _rdpClient.AdvancedSettings7.ConnectToAdministerServer = value; + } + else + { + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + string.Format(Language.strRdpSetConsoleSwitch, _rdpVersion) + + Environment.NewLine + + "No longer supported in this RDP version. Reference: https://msdn.microsoft.com/en-us/library/aa380863(v=vs.85).aspx", + true); // ConnectToServerConsole is deprecated //https://msdn.microsoft.com/en-us/library/aa380863(v=vs.85).aspx //_rdpClient.AdvancedSettings2.ConnectToServerConsole = value; } } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetConsoleSessionFailed, ex); - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetConsoleSessionFailed, ex); + } + } - private object GetExtendedProperty(string property) - { - try - { - // ReSharper disable once UseIndexedProperty - return ((IMsRdpExtendedSettings)_rdpClient).get_Property(property); - } - catch (Exception e) - { - Runtime.MessageCollector.AddExceptionMessage($"Error getting extended RDP property '{property}'", - e, MessageClass.WarningMsg, false); - return null; - } - } + private object GetExtendedProperty(string property) + { + try + { + // ReSharper disable once UseIndexedProperty + return ((IMsRdpExtendedSettings)_rdpClient).get_Property(property); + } + catch (Exception e) + { + Runtime.MessageCollector.AddExceptionMessage($"Error getting extended RDP property '{property}'", + e, MessageClass.WarningMsg, false); + return null; + } + } private void SetExtendedProperty(string property, object value) - { - try - { - // ReSharper disable once UseIndexedProperty - ((IMsRdpExtendedSettings)_rdpClient).set_Property(property, ref value); - } - catch (Exception e) - { - Runtime.MessageCollector.AddExceptionMessage($"Error setting extended RDP property '{property}'", - e, MessageClass.WarningMsg, false); - } - } + { + try + { + // ReSharper disable once UseIndexedProperty + ((IMsRdpExtendedSettings)_rdpClient).set_Property(property, ref value); + } + catch (Exception e) + { + Runtime.MessageCollector.AddExceptionMessage($"Error setting extended RDP property '{property}'", + e, MessageClass.WarningMsg, false); + } + } - private void SetCredentials() - { - try - { - if (Force.HasFlag(ConnectionInfo.Force.NoCredentials)) - { - return; - } + private void SetCredentials() + { + try + { + if (Force.HasFlag(ConnectionInfo.Force.NoCredentials)) + { + return; + } var cred = Runtime.CredentialService.GetEffectiveCredentialRecord(_connectionInfo.CredentialRecordId + .FirstOrDefault()).FirstOrDefault(); _rdpClient.UserName = cred.Username ?? ""; - _rdpClient.AdvancedSettings2.ClearTextPassword = cred.Password?.ConvertToUnsecureString() ?? ""; + + _rdpClient.AdvancedSettings2.ClearTextPassword = cred.Password?.ConvertToUnsecureString() ?? ""; + _rdpClient.Domain = cred.Domain ?? ""; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetCredentialsFailed, ex); - } - } - - private void SetResolution() - { - try - { - var scaleFactor = (uint)_displayProperties.ResolutionScalingFactor.Width * 100; - SetExtendedProperty("DesktopScaleFactor", scaleFactor); - SetExtendedProperty("DeviceScaleFactor", (uint)100); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetCredentialsFailed, ex); + } + } + + private void SetResolution() + { + try + { + var scaleFactor = (uint)_displayProperties.ResolutionScalingFactor.Width * 100; + SetExtendedProperty("DesktopScaleFactor", scaleFactor); + SetExtendedProperty("DeviceScaleFactor", (uint)100); if (Force.HasFlag(ConnectionInfo.Force.Fullscreen)) - { - _rdpClient.FullScreen = true; + { + _rdpClient.FullScreen = true; _rdpClient.DesktopWidth = Screen.FromControl(_frmMain).Bounds.Width; _rdpClient.DesktopHeight = Screen.FromControl(_frmMain).Bounds.Height; - - return; - } - - if ((InterfaceControl.Info.Resolution == RDPResolutions.FitToWindow) || (InterfaceControl.Info.Resolution == RDPResolutions.SmartSize)) - { - _rdpClient.DesktopWidth = InterfaceControl.Size.Width; - _rdpClient.DesktopHeight = InterfaceControl.Size.Height; - if (InterfaceControl.Info.Resolution == RDPResolutions.SmartSize) - { + return; + } + + if ((InterfaceControl.Info.Resolution == RDPResolutions.FitToWindow) || + (InterfaceControl.Info.Resolution == RDPResolutions.SmartSize)) + { + _rdpClient.DesktopWidth = InterfaceControl.Size.Width; + _rdpClient.DesktopHeight = InterfaceControl.Size.Height; + + if (InterfaceControl.Info.Resolution == RDPResolutions.SmartSize) + { _rdpClient.AdvancedSettings2.SmartSizing = true; } - } - else if (InterfaceControl.Info.Resolution == RDPResolutions.Fullscreen) - { - _rdpClient.FullScreen = true; + } + else if (InterfaceControl.Info.Resolution == RDPResolutions.Fullscreen) + { + _rdpClient.FullScreen = true; _rdpClient.DesktopWidth = Screen.FromControl(_frmMain).Bounds.Width; _rdpClient.DesktopHeight = Screen.FromControl(_frmMain).Bounds.Height; - } - else - { - var resolution = GetResolutionRectangle(_connectionInfo.Resolution); - _rdpClient.DesktopWidth = resolution.Width; - _rdpClient.DesktopHeight = resolution.Height; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetResolutionFailed, ex); - } - } - - private void SetPort() - { - try - { - if (_connectionInfo.Port != (int)Defaults.Port) - { - _rdpClient.AdvancedSettings2.RDPPort = _connectionInfo.Port; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetPortFailed, ex); - } - } - - private void SetRedirection() - { - try - { - _rdpClient.AdvancedSettings2.RedirectDrives = _connectionInfo.RedirectDiskDrives; - _rdpClient.AdvancedSettings2.RedirectPorts = _connectionInfo.RedirectPorts; - _rdpClient.AdvancedSettings2.RedirectPrinters = _connectionInfo.RedirectPrinters; - _rdpClient.AdvancedSettings2.RedirectSmartCards = _connectionInfo.RedirectSmartCards; - _rdpClient.SecuredSettings2.AudioRedirectionMode = (int)_connectionInfo.RedirectSound; + } + else + { + var resolution = GetResolutionRectangle(_connectionInfo.Resolution); + _rdpClient.DesktopWidth = resolution.Width; + _rdpClient.DesktopHeight = resolution.Height; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetResolutionFailed, ex); + } + } + + private void SetPort() + { + try + { + if (_connectionInfo.Port != (int)Defaults.Port) + { + _rdpClient.AdvancedSettings2.RDPPort = _connectionInfo.Port; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetPortFailed, ex); + } + } + + private void SetRedirection() + { + try + { + _rdpClient.AdvancedSettings2.RedirectDrives = _connectionInfo.RedirectDiskDrives; + _rdpClient.AdvancedSettings2.RedirectPorts = _connectionInfo.RedirectPorts; + _rdpClient.AdvancedSettings2.RedirectPrinters = _connectionInfo.RedirectPrinters; + _rdpClient.AdvancedSettings2.RedirectSmartCards = _connectionInfo.RedirectSmartCards; + _rdpClient.SecuredSettings2.AudioRedirectionMode = (int)_connectionInfo.RedirectSound; _rdpClient.AdvancedSettings.DisableRdpdr = _connectionInfo.RedirectClipboard ? 0 : 1; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetRedirectionFailed, ex); - } - } - - private void SetPerformanceFlags() - { - try - { - var pFlags = 0; - if (_connectionInfo.DisplayThemes == false) - { - pFlags += Convert.ToInt32(RDPPerformanceFlags.DisableThemes); - } - - if (_connectionInfo.DisplayWallpaper == false) - { - pFlags += Convert.ToInt32(RDPPerformanceFlags.DisableWallpaper); - } - - if (_connectionInfo.EnableFontSmoothing) - { - pFlags += Convert.ToInt32(RDPPerformanceFlags.EnableFontSmoothing); - } - - if (_connectionInfo.EnableDesktopComposition) - { - pFlags += Convert.ToInt32(RDPPerformanceFlags.EnableDesktopComposition); - } - - _rdpClient.AdvancedSettings2.PerformanceFlags = pFlags; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetPerformanceFlagsFailed, ex); - } - } - - private void SetAuthenticationLevel() - { - try - { - _rdpClient.AdvancedSettings5.AuthenticationLevel = (uint)_connectionInfo.RDPAuthenticationLevel; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetAuthenticationLevelFailed, ex); - } - } - - private void SetLoadBalanceInfo() - { - if (string.IsNullOrEmpty(_connectionInfo.LoadBalanceInfo)) - { - return; - } - try - { - _rdpClient.AdvancedSettings2.LoadBalanceInfo = LoadBalanceInfoUseUtf8 - ? new AzureLoadBalanceInfoEncoder().Encode(_connectionInfo.LoadBalanceInfo) + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetRedirectionFailed, ex); + } + } + + private void SetPerformanceFlags() + { + try + { + var pFlags = 0; + if (_connectionInfo.DisplayThemes == false) + { + pFlags += Convert.ToInt32(RDPPerformanceFlags.DisableThemes); + } + + if (_connectionInfo.DisplayWallpaper == false) + { + pFlags += Convert.ToInt32(RDPPerformanceFlags.DisableWallpaper); + } + + if (_connectionInfo.EnableFontSmoothing) + { + pFlags += Convert.ToInt32(RDPPerformanceFlags.EnableFontSmoothing); + } + + if (_connectionInfo.EnableDesktopComposition) + { + pFlags += Convert.ToInt32(RDPPerformanceFlags.EnableDesktopComposition); + } + + _rdpClient.AdvancedSettings2.PerformanceFlags = pFlags; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetPerformanceFlagsFailed, ex); + } + } + + private void SetAuthenticationLevel() + { + try + { + _rdpClient.AdvancedSettings5.AuthenticationLevel = (uint)_connectionInfo.RDPAuthenticationLevel; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetAuthenticationLevelFailed, ex); + } + } + + private void SetLoadBalanceInfo() + { + if (string.IsNullOrEmpty(_connectionInfo.LoadBalanceInfo)) + { + return; + } + + try + { + _rdpClient.AdvancedSettings2.LoadBalanceInfo = LoadBalanceInfoUseUtf8 + ? new AzureLoadBalanceInfoEncoder().Encode(_connectionInfo.LoadBalanceInfo) : _connectionInfo.LoadBalanceInfo; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("Unable to set load balance info.", ex); - } - } - - private void SetEventHandlers() - { - try - { - _rdpClient.OnConnecting += RDPEvent_OnConnecting; - _rdpClient.OnConnected += RDPEvent_OnConnected; - _rdpClient.OnLoginComplete += RDPEvent_OnLoginComplete; - _rdpClient.OnFatalError += RDPEvent_OnFatalError; - _rdpClient.OnDisconnected += RDPEvent_OnDisconnected; - _rdpClient.OnLeaveFullScreenMode += RDPEvent_OnLeaveFullscreenMode; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace("Unable to set load balance info.", ex); + } + } + + private void SetEventHandlers() + { + try + { + _rdpClient.OnConnecting += RDPEvent_OnConnecting; + _rdpClient.OnConnected += RDPEvent_OnConnected; + _rdpClient.OnLoginComplete += RDPEvent_OnLoginComplete; + _rdpClient.OnFatalError += RDPEvent_OnFatalError; + _rdpClient.OnDisconnected += RDPEvent_OnDisconnected; + _rdpClient.OnLeaveFullScreenMode += RDPEvent_OnLeaveFullscreenMode; _rdpClient.OnIdleTimeoutNotification += RDPEvent_OnIdleTimeoutNotification; } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetEventHandlersFailed, ex); - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace(Language.strRdpSetEventHandlersFailed, ex); + } + } + #endregion - + #region Private Events & Handlers + private void RDPEvent_OnIdleTimeoutNotification() { Close(); //Simply close the RDP Session if the idle timeout has been triggered. if (!_alertOnIdleDisconnect) return; - MessageBox.Show($"The {_connectionInfo.Name} session was disconnected due to inactivity", "Session Disconnected", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show($"The {_connectionInfo.Name} session was disconnected due to inactivity", + "Session Disconnected", MessageBoxButtons.OK, MessageBoxIcon.Information); } @@ -641,233 +675,251 @@ namespace mRemoteNG.Connection.Protocol.RDP { var errorMsg = RdpErrorCodes.GetError(errorCode); Event_ErrorOccured(this, errorMsg, errorCode); - } - - private void RDPEvent_OnDisconnected(int discReason) - { - const int UI_ERR_NORMAL_DISCONNECT = 0xB08; - if (discReason != UI_ERR_NORMAL_DISCONNECT) - { - var reason = _rdpClient.GetErrorDescription((uint)discReason, (uint) _rdpClient.ExtendedDisconnectReason); - Event_Disconnected(this, reason, discReason); - } - - if (Settings.Default.ReconnectOnDisconnect) - { - ReconnectGroup = new ReconnectGroup(); - ReconnectGroup.CloseClicked += Event_ReconnectGroupCloseClicked; - ReconnectGroup.Left = (int) ((double) Control.Width / 2 - (double) ReconnectGroup.Width / 2); - ReconnectGroup.Top = (int) ((double) Control.Height / 2 - (double) ReconnectGroup.Height / 2); - ReconnectGroup.Parent = Control; - ReconnectGroup.Show(); - tmrReconnect.Enabled = true; - } - else - { - Close(); - } - } - - private void RDPEvent_OnConnecting() - { - Event_Connecting(this); - } - - private void RDPEvent_OnConnected() - { - Event_Connected(this); - } - - private void RDPEvent_OnLoginComplete() - { - _loginComplete = true; - } - - private void RDPEvent_OnLeaveFullscreenMode() - { - Fullscreen = false; + } + + private void RDPEvent_OnDisconnected(int discReason) + { + const int UI_ERR_NORMAL_DISCONNECT = 0xB08; + if (discReason != UI_ERR_NORMAL_DISCONNECT) + { + var reason = + _rdpClient.GetErrorDescription((uint)discReason, (uint)_rdpClient.ExtendedDisconnectReason); + Event_Disconnected(this, reason, discReason); + } + + if (Settings.Default.ReconnectOnDisconnect) + { + ReconnectGroup = new ReconnectGroup(); + ReconnectGroup.CloseClicked += Event_ReconnectGroupCloseClicked; + ReconnectGroup.Left = (int)((double)Control.Width / 2 - (double)ReconnectGroup.Width / 2); + ReconnectGroup.Top = (int)((double)Control.Height / 2 - (double)ReconnectGroup.Height / 2); + ReconnectGroup.Parent = Control; + ReconnectGroup.Show(); + tmrReconnect.Enabled = true; + } + else + { + Close(); + } + } + + private void RDPEvent_OnConnecting() + { + Event_Connecting(this); + } + + private void RDPEvent_OnConnected() + { + Event_Connected(this); + } + + private void RDPEvent_OnLoginComplete() + { + _loginComplete = true; + } + + private void RDPEvent_OnLeaveFullscreenMode() + { + Fullscreen = false; _leaveFullscreenEvent?.Invoke(this, new EventArgs()); } + #endregion - + #region Public Events & Handlers - public delegate void LeaveFullscreenEventHandler(object sender, EventArgs e); - private LeaveFullscreenEventHandler _leaveFullscreenEvent; - - public event LeaveFullscreenEventHandler LeaveFullscreen - { - add => _leaveFullscreenEvent = (LeaveFullscreenEventHandler)Delegate.Combine(_leaveFullscreenEvent, value); - remove => _leaveFullscreenEvent = (LeaveFullscreenEventHandler)Delegate.Remove(_leaveFullscreenEvent, value); + + public delegate void LeaveFullscreenEventHandler(object sender, EventArgs e); + + private LeaveFullscreenEventHandler _leaveFullscreenEvent; + + public event LeaveFullscreenEventHandler LeaveFullscreen + { + add => _leaveFullscreenEvent = (LeaveFullscreenEventHandler)Delegate.Combine(_leaveFullscreenEvent, value); + remove => + _leaveFullscreenEvent = (LeaveFullscreenEventHandler)Delegate.Remove(_leaveFullscreenEvent, value); } + #endregion - + #region Enums - public enum Defaults - { - Colors = RDPColors.Colors16Bit, - Sounds = RDPSounds.DoNotPlay, - Resolution = RDPResolutions.FitToWindow, - Port = 3389 - } - - public enum RDPColors - { + + public enum Defaults + { + Colors = RDPColors.Colors16Bit, + Sounds = RDPSounds.DoNotPlay, + Resolution = RDPResolutions.FitToWindow, + Port = 3389 + } + + public enum RDPColors + { [LocalizedAttributes.LocalizedDescription("strRDP256Colors")] Colors256 = 8, + [LocalizedAttributes.LocalizedDescription("strRDP32768Colors")] Colors15Bit = 15, + [LocalizedAttributes.LocalizedDescription("strRDP65536Colors")] Colors16Bit = 16, + [LocalizedAttributes.LocalizedDescription("strRDP16777216Colors")] Colors24Bit = 24, + [LocalizedAttributes.LocalizedDescription("strRDP4294967296Colors")] Colors32Bit = 32 - } - - public enum RDPSounds - { + } + + public enum RDPSounds + { [LocalizedAttributes.LocalizedDescription("strRDPSoundBringToThisComputer")] BringToThisComputer = 0, + [LocalizedAttributes.LocalizedDescription("strRDPSoundLeaveAtRemoteComputer")] LeaveAtRemoteComputer = 1, + [LocalizedAttributes.LocalizedDescription("strRDPSoundDoNotPlay")] DoNotPlay = 2 - } + } - public enum RDPSoundQuality - { + public enum RDPSoundQuality + { [LocalizedAttributes.LocalizedDescription("strRDPSoundQualityDynamic")] Dynamic = 0, + [LocalizedAttributes.LocalizedDescription("strRDPSoundQualityMedium")] Medium = 1, + [LocalizedAttributes.LocalizedDescription("strRDPSoundQualityHigh")] High = 2 } private enum RDPPerformanceFlags - { - [Description("strRDPDisableWallpaper")]DisableWallpaper = 0x1, + { + [Description("strRDPDisableWallpaper")] + DisableWallpaper = 0x1, + // [Description("strRDPDisableFullWindowdrag")]DisableFullWindowDrag = 0x2, // [Description("strRDPDisableMenuAnimations")]DisableMenuAnimations = 0x4, - [Description("strRDPDisableThemes")]DisableThemes = 0x8, + [Description("strRDPDisableThemes")] DisableThemes = 0x8, + // [Description("strRDPDisableCursorShadow")]DisableCursorShadow = 0x20, // [Description("strRDPDisableCursorblinking")]DisableCursorBlinking = 0x40, - [Description("strRDPEnableFontSmoothing")]EnableFontSmoothing = 0x80, - [Description("strRDPEnableDesktopComposition")]EnableDesktopComposition = 0x100 - } + [Description("strRDPEnableFontSmoothing")] + EnableFontSmoothing = 0x80, + + [Description("strRDPEnableDesktopComposition")] + EnableDesktopComposition = 0x100 + } public enum RDPResolutions { [LocalizedAttributes.LocalizedDescription("strRDPFitToPanel")] FitToWindow, + [LocalizedAttributes.LocalizedDescription("strFullscreen")] Fullscreen, + [LocalizedAttributes.LocalizedDescription("strRDPSmartSize")] SmartSize, - [Description("800x600")] - Res800x600, - [Description("1024x768")] - Res1024x768, - [Description("1152x864")] - Res1152x864, - [Description("1280x800")] - Res1280x800, - [Description("1280x1024")] - Res1280x1024, - [Description("1366x768")] - Res1366x768, - [Description("1440x900")] - Res1440x900, - [Description("1600x900")] - Res1600x900, - [Description("1600x1200")] - Res1600x1200, - [Description("1680x1050")] - Res1680x1050, - [Description("1920x1080")] - Res1920x1080, - [Description("1920x1200")] - Res1920x1200, - [Description("2048x1536")] - Res2048x1536, - [Description("2560x1440")] - Res2560x1440, - [Description("2560x1600")] - Res2560x1600, - [Description("2560x2048")] - Res2560x2048, - [Description("3840x2160")] - Res3840x2160 + [Description("800x600")] Res800x600, + [Description("1024x768")] Res1024x768, + [Description("1152x864")] Res1152x864, + [Description("1280x800")] Res1280x800, + [Description("1280x1024")] Res1280x1024, + [Description("1366x768")] Res1366x768, + [Description("1440x900")] Res1440x900, + [Description("1600x900")] Res1600x900, + [Description("1600x1200")] Res1600x1200, + [Description("1680x1050")] Res1680x1050, + [Description("1920x1080")] Res1920x1080, + [Description("1920x1200")] Res1920x1200, + [Description("2048x1536")] Res2048x1536, + [Description("2560x1440")] Res2560x1440, + [Description("2560x1600")] Res2560x1600, + [Description("2560x2048")] Res2560x2048, + [Description("3840x2160")] Res3840x2160 } public enum AuthenticationLevel - { + { [LocalizedAttributes.LocalizedDescription("strAlwaysConnectEvenIfAuthFails")] NoAuth = 0, + [LocalizedAttributes.LocalizedDescription("strDontConnectWhenAuthFails")] AuthRequired = 1, + [LocalizedAttributes.LocalizedDescription("strWarnIfAuthFails")] WarnOnFailedAuth = 2 - } - - public enum RDGatewayUsageMethod - { + } + + public enum RDGatewayUsageMethod + { [LocalizedAttributes.LocalizedDescription("strNever")] Never = 0, // TSC_PROXY_MODE_NONE_DIRECT + [LocalizedAttributes.LocalizedDescription("strAlways")] Always = 1, // TSC_PROXY_MODE_DIRECT + [LocalizedAttributes.LocalizedDescription("strDetect")] Detect = 2 // TSC_PROXY_MODE_DETECT - } - - public enum RDGatewayUseConnectionCredentials - { + } + + public enum RDGatewayUseConnectionCredentials + { [LocalizedAttributes.LocalizedDescription("strUseDifferentUsernameAndPassword")] No = 0, + [LocalizedAttributes.LocalizedDescription("strUseSameUsernameAndPassword")] Yes = 1, + [LocalizedAttributes.LocalizedDescription("strUseSmartCard")] SmartCard = 2 - } + } + #endregion - + #region Resolution - public static Rectangle GetResolutionRectangle(RDPResolutions resolution) - { - string[] resolutionParts = null; - if (resolution != RDPResolutions.FitToWindow & resolution != RDPResolutions.Fullscreen & resolution != RDPResolutions.SmartSize) - { - resolutionParts = resolution.ToString().Replace("Res", "").Split('x'); - } - if (resolutionParts == null || resolutionParts.Length != 2) - { - return new Rectangle(0, 0, 0, 0); - } - else - { + + public static Rectangle GetResolutionRectangle(RDPResolutions resolution) + { + string[] resolutionParts = null; + if (resolution != RDPResolutions.FitToWindow & resolution != RDPResolutions.Fullscreen & + resolution != RDPResolutions.SmartSize) + { + resolutionParts = resolution.ToString().Replace("Res", "").Split('x'); + } + + if (resolutionParts == null || resolutionParts.Length != 2) + { + return new Rectangle(0, 0, 0, 0); + } + else + { return new Rectangle(0, 0, Convert.ToInt32(resolutionParts[0]), Convert.ToInt32(resolutionParts[1])); - } - } + } + } + #endregion public static class Versions - { - 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 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); - } - + } + #region Reconnect Stuff - public void tmrReconnect_Elapsed(object sender, System.Timers.ElapsedEventArgs e) - { - try - { - var srvReady = PortScanner.IsPortOpen(_connectionInfo.Hostname, Convert.ToString(_connectionInfo.Port)); - - ReconnectGroup.ServerReady = srvReady; + + public void tmrReconnect_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + try + { + var srvReady = PortScanner.IsPortOpen(_connectionInfo.Hostname, Convert.ToString(_connectionInfo.Port)); + + ReconnectGroup.ServerReady = srvReady; if (!ReconnectGroup.ReconnectWhenReady || !srvReady) return; tmrReconnect.Enabled = false; @@ -875,12 +927,15 @@ namespace mRemoteNG.Connection.Protocol.RDP //SetProps() _rdpClient.Connect(); } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(string.Format(Language.AutomaticReconnectError, _connectionInfo.Hostname), - ex, MessageClass.WarningMsg, false); - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + string.Format(Language.AutomaticReconnectError, + _connectionInfo.Hostname), + ex, MessageClass.WarningMsg, false); + } + } + #endregion - } + } } diff --git a/mRemoteV1/Connection/Protocol/Rlogin/Connection.Protocol.Rlogin.cs b/mRemoteV1/Connection/Protocol/Rlogin/Connection.Protocol.Rlogin.cs index 6a8b187b..e3fcba19 100644 --- a/mRemoteV1/Connection/Protocol/Rlogin/Connection.Protocol.Rlogin.cs +++ b/mRemoteV1/Connection/Protocol/Rlogin/Connection.Protocol.Rlogin.cs @@ -1,16 +1,15 @@ namespace mRemoteNG.Connection.Protocol.Rlogin { - public class ProtocolRlogin : PuttyBase - { - - public ProtocolRlogin() - { - this.PuttyProtocol = Putty_Protocol.rlogin; - } - - public enum Defaults - { - Port = 513 - } - } + public class ProtocolRlogin : PuttyBase + { + public ProtocolRlogin() + { + this.PuttyProtocol = Putty_Protocol.rlogin; + } + + public enum Defaults + { + Port = 513 + } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH1.cs b/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH1.cs index 53d59a28..8472308d 100644 --- a/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH1.cs +++ b/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH1.cs @@ -1,19 +1,16 @@ - - namespace mRemoteNG.Connection.Protocol.SSH { - public class ProtocolSSH1 : PuttyBase - { - - public ProtocolSSH1() - { - this.PuttyProtocol = Putty_Protocol.ssh; - this.PuttySSHVersion = Putty_SSHVersion.ssh1; - } - - public enum Defaults - { - Port = 22 - } - } -} + public class ProtocolSSH1 : PuttyBase + { + public ProtocolSSH1() + { + PuttyProtocol = Putty_Protocol.ssh; + PuttySSHVersion = Putty_SSHVersion.ssh1; + } + + public enum Defaults + { + Port = 22 + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH2.cs b/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH2.cs index 2fa12b4f..d05c40fe 100644 --- a/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH2.cs +++ b/mRemoteV1/Connection/Protocol/SSH/Connection.Protocol.SSH2.cs @@ -1,17 +1,16 @@ namespace mRemoteNG.Connection.Protocol.SSH { - public class ProtocolSSH2 : PuttyBase - { - - public ProtocolSSH2() - { - this.PuttyProtocol = Putty_Protocol.ssh; - this.PuttySSHVersion = Putty_SSHVersion.ssh2; - } - - public enum Defaults - { - Port = 22 - } - } -} + public class ProtocolSSH2 : PuttyBase + { + public ProtocolSSH2() + { + PuttyProtocol = Putty_Protocol.ssh; + PuttySSHVersion = Putty_SSHVersion.ssh2; + } + + public enum Defaults + { + Port = 22 + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/Serial/Connection.Protocol.Serial.cs b/mRemoteV1/Connection/Protocol/Serial/Connection.Protocol.Serial.cs index 9e8d2ffd..0f4ca94d 100644 --- a/mRemoteV1/Connection/Protocol/Serial/Connection.Protocol.Serial.cs +++ b/mRemoteV1/Connection/Protocol/Serial/Connection.Protocol.Serial.cs @@ -1,16 +1,15 @@ namespace mRemoteNG.Connection.Protocol.Serial { - public class ProtocolSerial : PuttyBase - { - - public ProtocolSerial() - { - this.PuttyProtocol = Putty_Protocol.serial; - } - - public enum Defaults - { - Port = 9600 - } - } + public class ProtocolSerial : PuttyBase + { + public ProtocolSerial() + { + this.PuttyProtocol = Putty_Protocol.serial; + } + + public enum Defaults + { + Port = 9600 + } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/Telnet/Connection.Protocol.Telnet.cs b/mRemoteV1/Connection/Protocol/Telnet/Connection.Protocol.Telnet.cs index 7fc93cbf..6f891c07 100644 --- a/mRemoteV1/Connection/Protocol/Telnet/Connection.Protocol.Telnet.cs +++ b/mRemoteV1/Connection/Protocol/Telnet/Connection.Protocol.Telnet.cs @@ -1,16 +1,15 @@ namespace mRemoteNG.Connection.Protocol.Telnet { - public class ProtocolTelnet : PuttyBase - { - - public ProtocolTelnet() - { - this.PuttyProtocol = Putty_Protocol.telnet; - } - - public enum Defaults - { - Port = 23 - } - } + public class ProtocolTelnet : PuttyBase + { + public ProtocolTelnet() + { + this.PuttyProtocol = Putty_Protocol.telnet; + } + + public enum Defaults + { + Port = 23 + } + } } \ No newline at end of file diff --git a/mRemoteV1/Connection/Protocol/VNC/Connection.Protocol.VNC.cs b/mRemoteV1/Connection/Protocol/VNC/Connection.Protocol.VNC.cs index d5eed46a..fc5ad63f 100644 --- a/mRemoteV1/Connection/Protocol/VNC/Connection.Protocol.VNC.cs +++ b/mRemoteV1/Connection/Protocol/VNC/Connection.Protocol.VNC.cs @@ -11,274 +11,307 @@ using System.ComponentModel; namespace mRemoteNG.Connection.Protocol.VNC { public class ProtocolVNC : ProtocolBase - { + { #region Properties + public bool SmartSize { get { return _VNC.Scaled; } set { _VNC.Scaled = value; } } - public bool ViewOnly - { - get { return _VNC.ViewOnly; } - set { _VNC.ViewOnly = value; } - } + public bool ViewOnly + { + get { return _VNC.ViewOnly; } + set { _VNC.ViewOnly = value; } + } - #endregion - - #region Private Declarations - private VncSharp.RemoteDesktop _VNC; - private ConnectionInfo Info; #endregion - + + #region Private Declarations + + private VncSharp.RemoteDesktop _VNC; + private ConnectionInfo Info; + + #endregion + #region Public Methods - public ProtocolVNC() - { - Control = new VncSharp.RemoteDesktop(); - } - - public override bool Initialize() - { - base.Initialize(); - - try - { + + public ProtocolVNC() + { + Control = new VncSharp.RemoteDesktop(); + } + + public override bool Initialize() + { + base.Initialize(); + + try + { _VNC = (VncSharp.RemoteDesktop)Control; - - Info = InterfaceControl.Info; - - _VNC.VncPort = Info.Port; + + Info = InterfaceControl.Info; + + _VNC.VncPort = Info.Port; return true; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncSetPropsFailed + Environment.NewLine + ex.Message, true); - return false; - } - } - - public override bool Connect() - { - SetEventHandlers(); - - try - { - _VNC.Connect(Info.Hostname, Info.VNCViewOnly, Info.VNCSmartSizeMode != SmartSizeMode.SmartSNo); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strConnectionOpenFailed + Environment.NewLine + ex.Message); - return false; - } - - return true; - } - - public override void Disconnect() - { - try - { - _VNC.Disconnect(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncConnectionDisconnectFailed + Environment.NewLine + ex.Message, true); - } - } - - public void SendSpecialKeys(SpecialKeys Keys) - { - try - { - // ReSharper disable once SwitchStatementMissingSomeCases - switch (Keys) - { - case SpecialKeys.CtrlAltDel: - _VNC.SendSpecialKeys(VncSharp.SpecialKeys.CtrlAltDel); - break; - case SpecialKeys.CtrlEsc: - _VNC.SendSpecialKeys(VncSharp.SpecialKeys.CtrlEsc); - break; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncSendSpecialKeysFailed + Environment.NewLine + ex.Message, true); - } - } - - public void ToggleSmartSize() - { - try - { - SmartSize = !SmartSize; - RefreshScreen(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncToggleSmartSizeFailed + Environment.NewLine + ex.Message, true); - } - } - - public void ToggleViewOnly() - { - try - { - ViewOnly = !ViewOnly; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncToggleViewOnlyFailed + Environment.NewLine + ex.Message, true); - } - } - - - public void StartChat() - { - throw new NotImplementedException(); - } - - public void StartFileTransfer() - { + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncSetPropsFailed + Environment.NewLine + ex.Message, + true); + return false; + } + } + + public override bool Connect() + { + SetEventHandlers(); + + try + { + _VNC.Connect(Info.Hostname, Info.VNCViewOnly, Info.VNCSmartSizeMode != SmartSizeMode.SmartSNo); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strConnectionOpenFailed + Environment.NewLine + + ex.Message); + return false; + } + + return true; + } + + public override void Disconnect() + { + try + { + _VNC.Disconnect(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncConnectionDisconnectFailed + Environment.NewLine + + ex.Message, true); + } + } + + public void SendSpecialKeys(SpecialKeys Keys) + { + try + { + // ReSharper disable once SwitchStatementMissingSomeCases + switch (Keys) + { + case SpecialKeys.CtrlAltDel: + _VNC.SendSpecialKeys(VncSharp.SpecialKeys.CtrlAltDel); + break; + case SpecialKeys.CtrlEsc: + _VNC.SendSpecialKeys(VncSharp.SpecialKeys.CtrlEsc); + break; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncSendSpecialKeysFailed + Environment.NewLine + + ex.Message, true); + } + } + + public void ToggleSmartSize() + { + try + { + SmartSize = !SmartSize; + RefreshScreen(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncToggleSmartSizeFailed + Environment.NewLine + + ex.Message, true); + } + } + + public void ToggleViewOnly() + { + try + { + ViewOnly = !ViewOnly; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncToggleViewOnlyFailed + Environment.NewLine + + ex.Message, true); + } + } + + + public void StartChat() + { throw new NotImplementedException(); } - - public void RefreshScreen() - { - try - { - _VNC.FullScreenUpdate(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncRefreshFailed + Environment.NewLine + ex.Message, true); - } - } - #endregion - - #region Private Methods - private void SetEventHandlers() - { - try - { - _VNC.ConnectComplete += VNCEvent_Connected; - _VNC.ConnectionLost += VNCEvent_Disconnected; - FrmMain.ClipboardChanged += VNCEvent_ClipboardChanged; - if (!Force.HasFlag(ConnectionInfo.Force.NoCredentials) && Info?.CredentialRecord?.Password?.Length > 0) - { - _VNC.GetPassword = VNCEvent_Authenticate; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strVncSetEventHandlersFailed + Environment.NewLine + ex.Message, true); - } - } - #endregion - - #region Private Events & Handlers - private void VNCEvent_Connected(object sender, EventArgs e) - { - Event_Connected(this); - _VNC.AutoScroll = Info.VNCSmartSizeMode == SmartSizeMode.SmartSNo; - } - - private void VNCEvent_Disconnected(object sender, EventArgs e) - { - FrmMain.ClipboardChanged -= VNCEvent_ClipboardChanged; - Event_Disconnected(sender, @"VncSharp Disconnected.", null); - Close(); - } - - private void VNCEvent_ClipboardChanged() - { - _VNC.FillServerClipboard(); - } - - private string VNCEvent_Authenticate() - { - return Info.CredentialRecord.Password.ConvertToUnsecureString(); - } - #endregion - + public void StartFileTransfer() + { + throw new NotImplementedException(); + } + + public void RefreshScreen() + { + try + { + _VNC.FullScreenUpdate(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncRefreshFailed + Environment.NewLine + ex.Message, + true); + } + } + + #endregion + + #region Private Methods + + private void SetEventHandlers() + { + try + { + _VNC.ConnectComplete += VNCEvent_Connected; + _VNC.ConnectionLost += VNCEvent_Disconnected; + FrmMain.ClipboardChanged += VNCEvent_ClipboardChanged; + if (!Force.HasFlag(ConnectionInfo.Force.NoCredentials) && Info?.CredentialRecord?.Password?.Length > 0) + { + _VNC.GetPassword = VNCEvent_Authenticate; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strVncSetEventHandlersFailed + Environment.NewLine + + ex.Message, true); + } + } + + #endregion + + #region Private Events & Handlers + + private void VNCEvent_Connected(object sender, EventArgs e) + { + Event_Connected(this); + _VNC.AutoScroll = Info.VNCSmartSizeMode == SmartSizeMode.SmartSNo; + } + + private void VNCEvent_Disconnected(object sender, EventArgs e) + { + FrmMain.ClipboardChanged -= VNCEvent_ClipboardChanged; + Event_Disconnected(sender, @"VncSharp Disconnected.", null); + Close(); + } + + private void VNCEvent_ClipboardChanged() + { + _VNC.FillServerClipboard(); + } + + private string VNCEvent_Authenticate() + { + return Info.CredentialRecord.Password.ConvertToUnsecureString(); + } + + #endregion + #region Enums - public enum Defaults - { - Port = 5900 - } - - public enum SpecialKeys - { - CtrlAltDel, - CtrlEsc - } - - public enum Compression - { - [LocalizedAttributes.LocalizedDescription("strNoCompression")]CompNone = 99, - [Description("0")]Comp0 = 0, - [Description("1")]Comp1 = 1, - [Description("2")]Comp2 = 2, - [Description("3")]Comp3 = 3, - [Description("4")]Comp4 = 4, - [Description("5")]Comp5 = 5, - [Description("6")]Comp6 = 6, - [Description("7")]Comp7 = 7, - [Description("8")]Comp8 = 8, - [Description("9")]Comp9 = 9 - } - - public enum Encoding - { - [Description("Raw")]EncRaw, - [Description("RRE")]EncRRE, - [Description("CoRRE")]EncCorre, - [Description("Hextile")]EncHextile, - [Description("Zlib")]EncZlib, - [Description("Tight")]EncTight, - [Description("ZlibHex")]EncZLibHex, - [Description("ZRLE")]EncZRLE - } - - public enum AuthMode - { + + public enum Defaults + { + Port = 5900 + } + + public enum SpecialKeys + { + CtrlAltDel, + CtrlEsc + } + + public enum Compression + { + [LocalizedAttributes.LocalizedDescription("strNoCompression")] + CompNone = 99, + [Description("0")] Comp0 = 0, + [Description("1")] Comp1 = 1, + [Description("2")] Comp2 = 2, + [Description("3")] Comp3 = 3, + [Description("4")] Comp4 = 4, + [Description("5")] Comp5 = 5, + [Description("6")] Comp6 = 6, + [Description("7")] Comp7 = 7, + [Description("8")] Comp8 = 8, + [Description("9")] Comp9 = 9 + } + + public enum Encoding + { + [Description("Raw")] EncRaw, + [Description("RRE")] EncRRE, + [Description("CoRRE")] EncCorre, + [Description("Hextile")] EncHextile, + [Description("Zlib")] EncZlib, + [Description("Tight")] EncTight, + [Description("ZlibHex")] EncZLibHex, + [Description("ZRLE")] EncZRLE + } + + public enum AuthMode + { [LocalizedAttributes.LocalizedDescription("VNC")] AuthVNC, + [LocalizedAttributes.LocalizedDescription("Windows")] AuthWin - } - - public enum ProxyType - { + } + + public enum ProxyType + { [LocalizedAttributes.LocalizedDescription("strNone")] ProxyNone, + [LocalizedAttributes.LocalizedDescription("strHttp")] ProxyHTTP, + [LocalizedAttributes.LocalizedDescription("strSocks5")] ProxySocks5, + [LocalizedAttributes.LocalizedDescription("strUltraVncRepeater")] ProxyUltra - } - - public enum Colors - { + } + + public enum Colors + { [LocalizedAttributes.LocalizedDescription("strNormal")] ColNormal, - [Description("8-bit")]Col8Bit - } - - public enum SmartSizeMode - { + [Description("8-bit")] Col8Bit + } + + public enum SmartSizeMode + { [LocalizedAttributes.LocalizedDescription("strNoSmartSize")] SmartSNo, + [LocalizedAttributes.LocalizedDescription("strFree")] SmartSFree, + [LocalizedAttributes.LocalizedDescription("strAspect")] SmartSAspect - } + } + #endregion - } + } } diff --git a/mRemoteV1/Connection/Protocol/VNC/VNCEnum.cs b/mRemoteV1/Connection/Protocol/VNC/VNCEnum.cs index c7267613..0ff96f11 100644 --- a/mRemoteV1/Connection/Protocol/VNC/VNCEnum.cs +++ b/mRemoteV1/Connection/Protocol/VNC/VNCEnum.cs @@ -4,77 +4,84 @@ using mRemoteNG.Tools; namespace mRemoteNG.Connection.Protocol.VNC { public enum Defaults - { - Port = 5900 - } - - public enum SpecialKeys - { - CtrlAltDel, - CtrlEsc - } - - public enum Compression - { - [LocalizedAttributes.LocalizedDescription("strNoCompression")]CompNone = 99, - [Description("0")]Comp0 = 0, - [Description("1")]Comp1 = 1, - [Description("2")]Comp2 = 2, - [Description("3")]Comp3 = 3, - [Description("4")]Comp4 = 4, - [Description("5")]Comp5 = 5, - [Description("6")]Comp6 = 6, - [Description("7")]Comp7 = 7, - [Description("8")]Comp8 = 8, - [Description("9")]Comp9 = 9 - } - - public enum Encoding - { - [Description("Raw")]EncRaw, - [Description("RRE")]EncRRE, - [Description("CoRRE")]EncCorre, - [Description("Hextile")]EncHextile, - [Description("Zlib")]EncZlib, - [Description("Tight")]EncTight, - [Description("ZlibHex")]EncZLibHex, - [Description("ZRLE")]EncZRLE - } - - public enum AuthMode - { - [LocalizedAttributes.LocalizedDescription("VNC")] - AuthVNC, - [LocalizedAttributes.LocalizedDescription("Windows")] - AuthWin - } - - public enum ProxyType - { - [LocalizedAttributes.LocalizedDescription("strNone")] - ProxyNone, - [LocalizedAttributes.LocalizedDescription("strHttp")] - ProxyHTTP, - [LocalizedAttributes.LocalizedDescription("strSocks5")] - ProxySocks5, - [LocalizedAttributes.LocalizedDescription("strUltraVncRepeater")] - ProxyUltra - } - - public enum Colors - { - [LocalizedAttributes.LocalizedDescription("strNormal")] - ColNormal, - [Description("8-bit")]Col8Bit - } - - public enum SmartSizeMode - { - [LocalizedAttributes.LocalizedDescription("strNoSmartSize")] - SmartSNo, - [LocalizedAttributes.LocalizedDescription("strFree")] - SmartSFree, - [LocalizedAttributes.LocalizedDescription("strAspect")] - SmartSAspect - } -} + { + Port = 5900 + } + + public enum SpecialKeys + { + CtrlAltDel, + CtrlEsc + } + + public enum Compression + { + [LocalizedAttributes.LocalizedDescription("strNoCompression")] + CompNone = 99, + [Description("0")] Comp0 = 0, + [Description("1")] Comp1 = 1, + [Description("2")] Comp2 = 2, + [Description("3")] Comp3 = 3, + [Description("4")] Comp4 = 4, + [Description("5")] Comp5 = 5, + [Description("6")] Comp6 = 6, + [Description("7")] Comp7 = 7, + [Description("8")] Comp8 = 8, + [Description("9")] Comp9 = 9 + } + + public enum Encoding + { + [Description("Raw")] EncRaw, + [Description("RRE")] EncRRE, + [Description("CoRRE")] EncCorre, + [Description("Hextile")] EncHextile, + [Description("Zlib")] EncZlib, + [Description("Tight")] EncTight, + [Description("ZlibHex")] EncZLibHex, + [Description("ZRLE")] EncZRLE + } + + public enum AuthMode + { + [LocalizedAttributes.LocalizedDescription("VNC")] + AuthVNC, + + [LocalizedAttributes.LocalizedDescription("Windows")] + AuthWin + } + + public enum ProxyType + { + [LocalizedAttributes.LocalizedDescription("strNone")] + ProxyNone, + + [LocalizedAttributes.LocalizedDescription("strHttp")] + ProxyHTTP, + + [LocalizedAttributes.LocalizedDescription("strSocks5")] + ProxySocks5, + + [LocalizedAttributes.LocalizedDescription("strUltraVncRepeater")] + ProxyUltra + } + + public enum Colors + { + [LocalizedAttributes.LocalizedDescription("strNormal")] + ColNormal, + [Description("8-bit")] Col8Bit + } + + public enum SmartSizeMode + { + [LocalizedAttributes.LocalizedDescription("strNoSmartSize")] + SmartSNo, + + [LocalizedAttributes.LocalizedDescription("strFree")] + SmartSFree, + + [LocalizedAttributes.LocalizedDescription("strAspect")] + SmartSAspect + } +} \ No newline at end of file diff --git a/mRemoteV1/Connection/PuttySessionInfo.cs b/mRemoteV1/Connection/PuttySessionInfo.cs index 4578f0ba..03ca7d88 100644 --- a/mRemoteV1/Connection/PuttySessionInfo.cs +++ b/mRemoteV1/Connection/PuttySessionInfo.cs @@ -11,19 +11,16 @@ using System.ComponentModel; namespace mRemoteNG.Connection { public sealed class PuttySessionInfo : ConnectionInfo, IComponent - { + { #region Properties - [Browsable(false)] - public RootPuttySessionsNodeInfo RootRootPuttySessionsInfo { get; set; } - [ReadOnly(true)] - public override string PuttySession { get; set; } + [Browsable(false)] public RootPuttySessionsNodeInfo RootRootPuttySessionsInfo { get; set; } - [ReadOnly(true)] - public override string Name { get; set; } + [ReadOnly(true)] public override string PuttySession { get; set; } - [ReadOnly(true), Browsable(false)] - public override string Description { get; set; } + [ReadOnly(true)] public override string Name { get; set; } + + [ReadOnly(true), Browsable(false)] public override string Description { get; set; } [ReadOnly(true), Browsable(false)] public override string Icon @@ -39,56 +36,52 @@ namespace mRemoteNG.Connection set { } } - [ReadOnly(true)] - public override string Hostname { get; set; } + [ReadOnly(true)] public override string Hostname { get; set; } - [ReadOnly(true)] - public override string Username { get; set; } + [ReadOnly(true)] public override string Username { get; set; } - [ReadOnly(true), Browsable(false)] - public override string Password { get; set; } + [ReadOnly(true), Browsable(false)] public override string Password { get; set; } - [ReadOnly(true)] - public override ProtocolType Protocol { get; set; } + [ReadOnly(true)] public override ProtocolType Protocol { get; set; } - [ReadOnly(true)] - public override int Port { get; set; } + [ReadOnly(true)] public override int Port { get; set; } - [ReadOnly(true), Browsable(false)] - public override string PreExtApp { get; set; } + [ReadOnly(true), Browsable(false)] public override string PreExtApp { get; set; } - [ReadOnly(true), Browsable(false)] - public override string PostExtApp { get; set; } + [ReadOnly(true), Browsable(false)] public override string PostExtApp { get; set; } - [ReadOnly(true), Browsable(false)] - public override string MacAddress { get; set; } + [ReadOnly(true), Browsable(false)] public override string MacAddress { get; set; } + + [ReadOnly(true), Browsable(false)] public override string UserField { get; set; } - [ReadOnly(true), Browsable(false)] - public override string UserField { get; set; } #endregion - [Command(),LocalizedAttributes.LocalizedDisplayName("strPuttySessionSettings")] + [Command(), LocalizedAttributes.LocalizedDisplayName("strPuttySessionSettings")] public void SessionSettings() - { - try - { - var puttyProcess = new PuttyProcessController(); - if (!puttyProcess.Start()) - { - return; - } - if (puttyProcess.SelectListBoxItem(PuttySession)) - { - puttyProcess.ClickButton("&Load"); - } - puttyProcess.SetControlText("Button", "&Cancel", "&Close"); - puttyProcess.SetControlVisible("Button", "&Open", false); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strErrorCouldNotLaunchPutty + Environment.NewLine + ex.Message); - } - } + { + try + { + var puttyProcess = new PuttyProcessController(); + if (!puttyProcess.Start()) + { + return; + } + + if (puttyProcess.SelectListBoxItem(PuttySession)) + { + puttyProcess.ClickButton("&Load"); + } + + puttyProcess.SetControlText("Button", "&Cancel", "&Close"); + puttyProcess.SetControlVisible("Button", "&Open", false); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strErrorCouldNotLaunchPutty + Environment.NewLine + + ex.Message); + } + } public override TreeNodeType GetTreeNodeType() { @@ -96,19 +89,21 @@ namespace mRemoteNG.Connection } #region IComponent + [Browsable(false)] public ISite Site - { - get => new PropertyGridCommandSite(this); + { + get => new PropertyGridCommandSite(this); set => throw (new NotImplementedException()); } public void Dispose() - { + { Disposed?.Invoke(this, EventArgs.Empty); } public event EventHandler Disposed; + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Container/ContainerInfo.cs b/mRemoteV1/Container/ContainerInfo.cs index 989fc911..69c9c1dd 100644 --- a/mRemoteV1/Container/ContainerInfo.cs +++ b/mRemoteV1/Container/ContainerInfo.cs @@ -9,34 +9,37 @@ using mRemoteNG.Tree; namespace mRemoteNG.Container { - [DefaultProperty("Name")] + [DefaultProperty("Name")] public class ContainerInfo : ConnectionInfo, INotifyCollectionChanged - { - private bool _isExpanded; + { + private bool _isExpanded; - [Browsable(false)] - public List Children { get; } = new List(); + [Browsable(false)] public List Children { get; } = new List(); - [Category(""), Browsable(false), ReadOnly(false), Bindable(false), DefaultValue(""), DesignOnly(false)] - public bool IsExpanded - { - get => _isExpanded; - set => SetField(ref _isExpanded, value, "IsExpanded"); - } + [Category(""), Browsable(false), ReadOnly(false), Bindable(false), DefaultValue(""), DesignOnly(false)] + public bool IsExpanded + { + get => _isExpanded; + set => SetField(ref _isExpanded, value, "IsExpanded"); + } - [Browsable(false)] - public override bool IsContainer { get { return true; } set {} } + [Browsable(false)] + public override bool IsContainer + { + get { return true; } + set { } + } - public ContainerInfo(string uniqueId) - : base(uniqueId) + public ContainerInfo(string uniqueId) + : base(uniqueId) { SetDefaults(); } - public ContainerInfo() - : this(Guid.NewGuid().ToString()) - { - } + public ContainerInfo() + : this(Guid.NewGuid().ToString()) + { + } public override TreeNodeType GetTreeNodeType() { @@ -76,7 +79,9 @@ namespace mRemoteNG.Container newChildItem.Parent = this; Children.Insert(index, newChildItem); SubscribeToChildEvents(newChildItem); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newChildItem)); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, + newChildItem)); } public void AddChildRange(IEnumerable newChildren) @@ -93,7 +98,9 @@ namespace mRemoteNG.Container removalTarget.Parent = null; Children.Remove(removalTarget); UnsubscribeToChildEvents(removalTarget); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removalTarget)); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, + removalTarget)); } public void RemoveChildRange(IEnumerable removalTargets) @@ -111,7 +118,10 @@ namespace mRemoteNG.Container Children.Remove(child); if (newIndex > Children.Count) newIndex = Children.Count; Children.Insert(newIndex, child); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, child, newIndex, originalIndex)); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, child, + newIndex, + originalIndex)); } public void SetChildAbove(ConnectionInfo childToPromote, ConnectionInfo reference) @@ -161,7 +171,8 @@ namespace mRemoteNG.Container SortOn(connectionInfo => connectionInfo.Name, sortDirection); } - public void SortOn(Func propertyToCompare, ListSortDirection sortDirection = ListSortDirection.Ascending) + public void SortOn(Func propertyToCompare, + ListSortDirection sortDirection = ListSortDirection.Ascending) where TProperty : IComparable { var connectionComparer = new ConnectionInfoComparer(propertyToCompare) @@ -169,7 +180,8 @@ namespace mRemoteNG.Container SortDirection = sortDirection }; Children.Sort(connectionComparer); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public void SortRecursive(ListSortDirection sortDirection = ListSortDirection.Ascending) @@ -177,7 +189,8 @@ namespace mRemoteNG.Container SortOnRecursive(connectionInfo => connectionInfo.Name, sortDirection); } - public void SortOnRecursive(Func propertyToCompare, ListSortDirection sortDirection = ListSortDirection.Ascending) + public void SortOnRecursive(Func propertyToCompare, + ListSortDirection sortDirection = ListSortDirection.Ascending) where TProperty : IComparable { foreach (var child in Children.OfType()) @@ -187,7 +200,7 @@ namespace mRemoteNG.Container // Deep clone, recursive public override ConnectionInfo Clone() - { + { var newContainer = new ContainerInfo(); newContainer.CopyFrom(this); newContainer.OpenConnections = new ProtocolList(); @@ -198,14 +211,15 @@ namespace mRemoteNG.Container newChild.RemoveParent(); newContainer.AddChild(newChild); } + return newContainer; - } - - private void SetDefaults() - { - Name = "New Folder"; + } + + private void SetDefaults() + { + Name = "New Folder"; IsExpanded = true; - } + } public IEnumerable GetRecursiveChildList() { @@ -217,6 +231,7 @@ namespace mRemoteNG.Container if (childContainer != null) childList.AddRange(GetRecursiveChildList(childContainer)); } + return childList; } @@ -230,6 +245,7 @@ namespace mRemoteNG.Container if (childContainer != null) childList.AddRange(GetRecursiveChildList(childContainer)); } + return childList; } @@ -250,9 +266,10 @@ namespace mRemoteNG.Container } public event NotifyCollectionChangedEventHandler CollectionChanged; + private void RaiseCollectionChangedEvent(object sender, NotifyCollectionChangedEventArgs args) { CollectionChanged?.Invoke(sender, args); } - } + } } \ No newline at end of file diff --git a/mRemoteV1/Credential/CredentialDeletionMsgBoxConfirmer.cs b/mRemoteV1/Credential/CredentialDeletionMsgBoxConfirmer.cs index 7fe3dcd2..f433371d 100644 --- a/mRemoteV1/Credential/CredentialDeletionMsgBoxConfirmer.cs +++ b/mRemoteV1/Credential/CredentialDeletionMsgBoxConfirmer.cs @@ -11,7 +11,8 @@ namespace mRemoteNG.Credential { private readonly Func _confirmationFunc; - public CredentialDeletionMsgBoxConfirmer(Func confirmationFunc) + public CredentialDeletionMsgBoxConfirmer( + Func confirmationFunc) { if (confirmationFunc == null) throw new ArgumentNullException(nameof(confirmationFunc)); @@ -25,18 +26,19 @@ namespace mRemoteNG.Credential 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)); + string.Format( + "Are you sure you want to delete these {0} selected credentials?", + targetsArray.Length)); return PromptUser( - string.Format( - Language.strConfirmDeleteCredentialRecord, - targetsArray.First().Title)); + string.Format( + Language.strConfirmDeleteCredentialRecord, + targetsArray.First().Title)); } private bool PromptUser(string promptMessage) { - var msgBoxResponse = _confirmationFunc.Invoke(promptMessage, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question); + var msgBoxResponse = _confirmationFunc.Invoke(promptMessage, Application.ProductName, + MessageBoxButtons.YesNo, MessageBoxIcon.Question); return msgBoxResponse == DialogResult.Yes; } } diff --git a/mRemoteV1/Credential/CredentialRecordTypeConverter.cs b/mRemoteV1/Credential/CredentialRecordTypeConverter.cs index e19a6d99..df5c1672 100644 --- a/mRemoteV1/Credential/CredentialRecordTypeConverter.cs +++ b/mRemoteV1/Credential/CredentialRecordTypeConverter.cs @@ -11,21 +11,24 @@ namespace mRemoteNG.Credential { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - return sourceType == typeof(Guid) || - base.CanConvertFrom(context, sourceType); + return sourceType == typeof(Guid) || + base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(Guid) || - destinationType == typeof(ICredentialRecord) || - base.CanConvertTo(context, destinationType); + destinationType == typeof(ICredentialRecord) || + base.CanConvertTo(context, destinationType); } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object ConvertTo(ITypeDescriptorContext context, + CultureInfo culture, + object value, + Type destinationType) { if (value is ICredentialRecord && destinationType == typeof(Guid)) - return ((ICredentialRecord) value).Id; + return ((ICredentialRecord)value).Id; if (value is ICredentialRecord && destinationType == typeof(ICredentialRecord)) return value; return base.ConvertTo(context, culture, value, destinationType); @@ -34,7 +37,8 @@ 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.CredentialService.RepositoryList.GetCredentialRecords().Where(record => record.Id.Equals(value)).ToArray(); + var matchedCredentials = Runtime.CredentialService.RepositoryList.GetCredentialRecords() + .Where(record => record.Id.Equals(value)).ToArray(); return matchedCredentials.Any() ? matchedCredentials.First() : null; } } diff --git a/mRemoteV1/Credential/Repositories/CredentialRepositoryConfig.cs b/mRemoteV1/Credential/Repositories/CredentialRepositoryConfig.cs index 7a7575bd..1b3575e8 100644 --- a/mRemoteV1/Credential/Repositories/CredentialRepositoryConfig.cs +++ b/mRemoteV1/Credential/Repositories/CredentialRepositoryConfig.cs @@ -39,7 +39,7 @@ namespace mRemoteNG.Credential.Repositories get { return _source; } set { - _source = value; + _source = value; RaisePropertyChangedEvent(nameof(Source)); } } @@ -49,7 +49,7 @@ namespace mRemoteNG.Credential.Repositories get { return _key; } set { - _key = value; + _key = value; RaisePropertyChangedEvent(nameof(Key)); } } @@ -74,6 +74,7 @@ namespace mRemoteNG.Credential.Repositories } public event PropertyChangedEventHandler PropertyChanged; + protected virtual void RaisePropertyChangedEvent(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); diff --git a/mRemoteV1/Credential/Repositories/CredentialRepositoryList.cs b/mRemoteV1/Credential/Repositories/CredentialRepositoryList.cs index 87552e0d..521ffaf6 100644 --- a/mRemoteV1/Credential/Repositories/CredentialRepositoryList.cs +++ b/mRemoteV1/Credential/Repositories/CredentialRepositoryList.cs @@ -22,7 +22,7 @@ namespace mRemoteNG.Credential.Repositories _credentialProviders.Add(credentialProvider); credentialProvider.CredentialsUpdated += RaiseCredentialsUpdatedEvent; credentialProvider.RepositoryConfigUpdated += OnRepoConfigChanged; - RaiseRepositoriesUpdatedEvent(ActionType.Added, new[] { credentialProvider }); + RaiseRepositoriesUpdatedEvent(ActionType.Added, new[] {credentialProvider}); } public void RemoveProvider(ICredentialRepository credentialProvider) @@ -33,7 +33,7 @@ namespace mRemoteNG.Credential.Repositories credentialProvider.CredentialsUpdated -= RaiseCredentialsUpdatedEvent; credentialProvider.RepositoryConfigUpdated -= OnRepoConfigChanged; _credentialProviders.Remove(credentialProvider); - RaiseRepositoriesUpdatedEvent(ActionType.Removed, new[] { credentialProvider }); + RaiseRepositoriesUpdatedEvent(ActionType.Removed, new[] {credentialProvider}); } public Optional GetProvider(Guid id) @@ -57,12 +57,14 @@ namespace mRemoteNG.Credential.Repositories { list.AddRange(repository.CredentialRecords); } + return list; } public ICredentialRecord GetCredentialRecord(Guid id) { - return CredentialProviders.SelectMany(repo => repo.CredentialRecords).FirstOrDefault(record => record.Id.Equals(id)); + return CredentialProviders.SelectMany(repo => repo.CredentialRecords) + .FirstOrDefault(record => record.Id.Equals(id)); } public IEnumerator GetEnumerator() @@ -80,7 +82,8 @@ namespace mRemoteNG.Credential.Repositories private void RaiseRepositoriesUpdatedEvent(ActionType action, IEnumerable changedItems) { - RepositoriesUpdated?.Invoke(this, new CollectionUpdatedEventArgs(action, changedItems)); + RepositoriesUpdated?.Invoke(this, + new CollectionUpdatedEventArgs(action, changedItems)); } private void RaiseCredentialsUpdatedEvent(object sender, CollectionUpdatedEventArgs args) @@ -92,7 +95,7 @@ namespace mRemoteNG.Credential.Repositories { var repo = sender as ICredentialRepository; if (repo == null) return; - RaiseRepositoriesUpdatedEvent(ActionType.Updated, new[] { repo }); + RaiseRepositoriesUpdatedEvent(ActionType.Updated, new[] {repo}); } } } \ No newline at end of file diff --git a/mRemoteV1/Credential/Repositories/XmlCredentialRepository.cs b/mRemoteV1/Credential/Repositories/XmlCredentialRepository.cs index 864c15d2..a32d2cf1 100644 --- a/mRemoteV1/Credential/Repositories/XmlCredentialRepository.cs +++ b/mRemoteV1/Credential/Repositories/XmlCredentialRepository.cs @@ -90,7 +90,8 @@ namespace mRemoteNG.Credential.Repositories RepositoryConfigUpdated?.Invoke(this, args); } - protected virtual void RaiseCredentialsUpdatedEvent(object sender, CollectionUpdatedEventArgs args) + protected virtual void RaiseCredentialsUpdatedEvent(object sender, + CollectionUpdatedEventArgs args) { CredentialsUpdated?.Invoke(this, args); } diff --git a/mRemoteV1/Messages/Message.cs b/mRemoteV1/Messages/Message.cs index 45dc0699..5888e579 100644 --- a/mRemoteV1/Messages/Message.cs +++ b/mRemoteV1/Messages/Message.cs @@ -2,12 +2,12 @@ using System; namespace mRemoteNG.Messages { - public class Message : IMessage - { - public MessageClass Class { get; set; } - public string Text { get; set; } - public DateTime Date { get; set; } - public bool OnlyLog { get; set; } + public class Message : IMessage + { + public MessageClass Class { get; set; } + public string Text { get; set; } + public DateTime Date { get; set; } + public bool OnlyLog { get; set; } public Message(MessageClass messageClass, string messageText, bool onlyLog = false) { @@ -16,5 +16,5 @@ namespace mRemoteNG.Messages Date = DateTime.Now; OnlyLog = onlyLog; } - } + } } \ No newline at end of file diff --git a/mRemoteV1/Messages/MessageCollector.cs b/mRemoteV1/Messages/MessageCollector.cs index b156cc12..9a89be74 100644 --- a/mRemoteV1/Messages/MessageCollector.cs +++ b/mRemoteV1/Messages/MessageCollector.cs @@ -3,6 +3,7 @@ using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Messages @@ -26,7 +27,7 @@ namespace mRemoteNG.Messages public void AddMessage(IMessage message) { - AddMessages(new [] {message}); + AddMessages(new[] {message}); } public void AddMessages(IEnumerable messages) @@ -38,18 +39,27 @@ namespace mRemoteNG.Messages _messageList.Add(message); newMessages.Add(message); } + if (newMessages.Any()) RaiseCollectionChangedEvent(NotifyCollectionChangedAction.Add, newMessages); } - public void AddExceptionMessage(string message, Exception ex, MessageClass msgClass = MessageClass.ErrorMsg, bool logOnly = true) + public void AddExceptionMessage(string message, + Exception ex, + MessageClass msgClass = MessageClass.ErrorMsg, + bool logOnly = true) { - AddMessage(msgClass, message + Environment.NewLine + Tools.MiscTools.GetExceptionMessageRecursive(ex), logOnly); + AddMessage(msgClass, message + Environment.NewLine + Tools.MiscTools.GetExceptionMessageRecursive(ex), + logOnly); } - public void AddExceptionStackTrace(string message, Exception ex, MessageClass msgClass = MessageClass.ErrorMsg, bool logOnly = true) + public void AddExceptionStackTrace(string message, + Exception ex, + MessageClass msgClass = MessageClass.ErrorMsg, + bool logOnly = true) { - AddMessage(msgClass, message + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, logOnly); + AddMessage(msgClass, message + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, + logOnly); } public void ClearMessages() diff --git a/mRemoteV1/Messages/MessageWriters/NotificationPanelMessageWriter.cs b/mRemoteV1/Messages/MessageWriters/NotificationPanelMessageWriter.cs index 7ec99de3..29cb3d44 100644 --- a/mRemoteV1/Messages/MessageWriters/NotificationPanelMessageWriter.cs +++ b/mRemoteV1/Messages/MessageWriters/NotificationPanelMessageWriter.cs @@ -26,7 +26,7 @@ namespace mRemoteNG.Messages.MessageWriters private void AddToList(ListViewItem lvItem) { if (_messageWindow.lvErrorCollector.InvokeRequired) - _messageWindow.lvErrorCollector.Invoke((MethodInvoker) (() => AddToList(lvItem))); + _messageWindow.lvErrorCollector.Invoke((MethodInvoker)(() => AddToList(lvItem))); else _messageWindow.lvErrorCollector.Items.Insert(0, lvItem); } diff --git a/mRemoteV1/Messages/MessageWriters/PopupMessageWriter.cs b/mRemoteV1/Messages/MessageWriters/PopupMessageWriter.cs index 93602d50..2e6a0495 100644 --- a/mRemoteV1/Messages/MessageWriters/PopupMessageWriter.cs +++ b/mRemoteV1/Messages/MessageWriters/PopupMessageWriter.cs @@ -10,16 +10,20 @@ namespace mRemoteNG.Messages.MessageWriters switch (message.Class) { case MessageClass.DebugMsg: - MessageBox.Show(message.Text, string.Format(Language.strTitleInformation, message.Date), MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show(message.Text, string.Format(Language.strTitleInformation, message.Date), + MessageBoxButtons.OK, MessageBoxIcon.Information); break; case MessageClass.InformationMsg: - MessageBox.Show(message.Text, string.Format(Language.strTitleInformation, message.Date), MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show(message.Text, string.Format(Language.strTitleInformation, message.Date), + MessageBoxButtons.OK, MessageBoxIcon.Information); break; case MessageClass.WarningMsg: - MessageBox.Show(message.Text, string.Format(Language.strTitleWarning, message.Date), MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(message.Text, string.Format(Language.strTitleWarning, message.Date), + MessageBoxButtons.OK, MessageBoxIcon.Warning); break; case MessageClass.ErrorMsg: - MessageBox.Show(message.Text, string.Format(Language.strTitleError, message.Date), MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(message.Text, string.Format(Language.strTitleError, message.Date), + MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: throw new ArgumentOutOfRangeException(); diff --git a/mRemoteV1/Messages/WriterDecorators/MessageFocusDecorator.cs b/mRemoteV1/Messages/WriterDecorators/MessageFocusDecorator.cs index c9d7d9dc..a3e30c68 100644 --- a/mRemoteV1/Messages/WriterDecorators/MessageFocusDecorator.cs +++ b/mRemoteV1/Messages/WriterDecorators/MessageFocusDecorator.cs @@ -15,7 +15,9 @@ namespace mRemoteNG.Messages.WriterDecorators private readonly ErrorAndInfoWindow _messageWindow; private readonly FrmMain _frmMain = FrmMain.Default; - public MessageFocusDecorator(ErrorAndInfoWindow messageWindow, IMessageTypeFilteringOptions filter, IMessageWriter decoratedWriter) + public MessageFocusDecorator(ErrorAndInfoWindow messageWindow, + IMessageTypeFilteringOptions filter, + IMessageWriter decoratedWriter) { _filter = filter ?? throw new ArgumentNullException(nameof(filter)); _messageWindow = messageWindow ?? throw new ArgumentNullException(nameof(messageWindow)); @@ -46,14 +48,15 @@ namespace mRemoteNG.Messages.WriterDecorators if (_filter.AllowErrorMessages) return true; break; } + return false; } private async Task SwitchToMessageAsync() { await Task - .Delay(TimeSpan.FromMilliseconds(300)) - .ContinueWith(task => SwitchToMessage()); + .Delay(TimeSpan.FromMilliseconds(300)) + .ContinueWith(task => SwitchToMessage()); } private void SwitchToMessage() diff --git a/mRemoteV1/Messages/WriterDecorators/MessageTypeFilterDecorator.cs b/mRemoteV1/Messages/WriterDecorators/MessageTypeFilterDecorator.cs index cf92b577..ed8a4be2 100644 --- a/mRemoteV1/Messages/WriterDecorators/MessageTypeFilterDecorator.cs +++ b/mRemoteV1/Messages/WriterDecorators/MessageTypeFilterDecorator.cs @@ -43,6 +43,7 @@ namespace mRemoteNG.Messages.WriterDecorators if (_filter.AllowDebugMessages) return true; break; } + return false; } } diff --git a/mRemoteV1/Properties/AssemblyInfo.cs b/mRemoteV1/Properties/AssemblyInfo.cs index 78e360d6..2f15b6a7 100644 --- a/mRemoteV1/Properties/AssemblyInfo.cs +++ b/mRemoteV1/Properties/AssemblyInfo.cs @@ -3,7 +3,6 @@ using System.Resources; using System.Runtime.InteropServices; - // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. @@ -14,7 +13,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyDescription("Multi-protocol remote connections manager")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("mRemoteNG")] -[assembly: AssemblyCopyright("Copyright © 2018 mRemoteNG Dev Team; 2010-2013 Riley McArdle; 2007-2009 Felix Deimel")] +[assembly: AssemblyCopyright("Copyright © 2019 mRemoteNG Dev Team; 2010-2013 Riley McArdle; 2007-2009 Felix Deimel")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] diff --git a/mRemoteV1/Properties/Resources.Designer.cs b/mRemoteV1/Properties/Resources.Designer.cs index 1b038fe6..edab3f50 100644 --- a/mRemoteV1/Properties/Resources.Designer.cs +++ b/mRemoteV1/Properties/Resources.Designer.cs @@ -1347,6 +1347,36 @@ namespace mRemoteNG { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap tab_add { + get { + object obj = ResourceManager.GetObject("tab_add", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap tab_delete { + get { + object obj = ResourceManager.GetObject("tab_delete", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap tab_edit { + get { + object obj = ResourceManager.GetObject("tab_edit", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// @@ -1357,6 +1387,36 @@ namespace mRemoteNG { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap TabExit { + get { + object obj = ResourceManager.GetObject("TabExit", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap TabOption { + get { + object obj = ResourceManager.GetObject("TabOption", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap TabOverflow { + get { + object obj = ResourceManager.GetObject("TabOverflow", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// diff --git a/mRemoteV1/Properties/Resources.resx b/mRemoteV1/Properties/Resources.resx index 3289c14e..3797bb98 100644 --- a/mRemoteV1/Properties/Resources.resx +++ b/mRemoteV1/Properties/Resources.resx @@ -538,6 +538,15 @@ ..\Resources\Icons\Tab_Icon.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\Images\TabOption.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Images\TabOverflow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Images\TabExit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Resources\Icons\Update_Icon.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a @@ -547,4 +556,13 @@ ..\Resources\Images\mRemoteNG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\Images\tab_add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Images\tab_delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Images\tab_edit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + \ No newline at end of file diff --git a/mRemoteV1/Properties/Settings.Designer.cs b/mRemoteV1/Properties/Settings.Designer.cs index dd602bde..c4dc26bc 100644 --- a/mRemoteV1/Properties/Settings.Designer.cs +++ b/mRemoteV1/Properties/Settings.Designer.cs @@ -12,7 +12,7 @@ namespace mRemoteNG { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); @@ -2533,7 +2533,7 @@ namespace mRemoteNG { [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] + [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool ThemingActive { get { return ((bool)(this["ThemingActive"])); @@ -2770,5 +2770,17 @@ namespace mRemoteNG { this["AlwaysShowConnectionTabs"] = value; } } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool OverrideFIPSCheck { + get { + return ((bool)(this["OverrideFIPSCheck"])); + } + set { + this["OverrideFIPSCheck"] = value; + } + } } } diff --git a/mRemoteV1/Properties/Settings.settings b/mRemoteV1/Properties/Settings.settings index 82244aac..78279bf4 100644 --- a/mRemoteV1/Properties/Settings.settings +++ b/mRemoteV1/Properties/Settings.settings @@ -1,693 +1,698 @@  - - - - - 0, 0 - - - 0, 0 - - - Normal - - - False - - - True - - - - - - True - - - True - - - True - - - False - - - False - - - - - - True - - - True - - - False - - - False - - - True - - - False - - - False - - - noinfo - - - False - - - True - - - False - - - False - - - False - - - - - - 80 - - - False - - - - - - - - - - - - RDP - - - Default Settings - - - False - - - FitToWindow - - - Colors16Bit - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - DoNotPlay - - - 2 - - - False - - - False - - - False - - - 0 - - - False - - - True - - - 0, 0 - - - Bottom - - - True - - - 3, 24 - - - Top - - - False - - - False - - - - - - - - - - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - EncrBasic - - - False - - - - - - - - - False - - - False - - - False - - - True - - - False - - - False - - - AuthVNC - - - ColNormal - - - SmartSAspect - - - False - - - CompNone - - - EncHextile - - - - - - - - - 0 - - - ProxyNone - - - - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - NoAuth - - - False - - - 5500 - - - False - - - - - - IE - - - False - - - - - - False - - - False - - - - - - False - - - - - - False - - - False - - - 14 - - - 1980-01-01 - - - False - - - Never - - - Yes - - - mRemoteNG - - - False - - - False - - - False - - - False - - - False - - - False - - - 5 - - - - - - - - - - - - - - - - - - False - - - False - - - False - - - False - - - 4 - - - - - - - - - mRemoteNG - - - 10 - - - {0}.{1:yyyyMMdd-HHmmssffff}.backup - - - False - - - True - - - False - - - False - - - release - - - - - - True - - - - - - - - - True - - - https://mremoteng.org/ - - - - - - True - - - False - - - False - - - RDP - - - 9/9, 33/8 - - - 9/8, 34/8 - - - False - - - 20 - - - AES - - - GCM - - - 1000 - - - Dynamic - - - False - - - 0 - - - False - - - False - - - False - - - False - - - 00000000-0000-0000-0000-000000000000 - - - - - - False - - - True - - - True - - - True - - - False - - - False - - - True - - - True - - - False - - - False - - - False - - - False - - - True - - - True - - - cs-CZ,de,el,en,en-US,es-AR,es,fr,hu,it,ja-JP,ko-KR,nb-NO,nl,pt,pt-BR,pl,ru,uk,tr-TR,zh-CN,zh-TW - - - False - - - - - - - - - - - - General - - - True - - - False - - - False - - - False - - - False - - - 0, 0 - - - - - - False - - - False - - - General - + + + + + + 0, 0 + + + 0, 0 + + + Normal + + + False + + + True + + + + + + True + + + True + + + True + + + False + + + False + + + + + + True + + + True + + + False + + + False + + + True + + + False + + + False + + + noinfo + + + False + + + True + + + False + + + False + + + False + + + + + + 80 + + + False + + + + + + + + + + + + RDP + + + Default Settings + + + False + + + FitToWindow + + + Colors16Bit + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + DoNotPlay + + + 2 + + + False + + + False + + + False + + + 0 + + + False + + + True + + + 0, 0 + + + Bottom + + + True + + + 3, 24 + + + Top + + + False + + + False + + + + + + + + + + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + EncrBasic + + + False + + + + + + + + + False + + + False + + + False + + + True + + + False + + + False + + + AuthVNC + + + ColNormal + + + SmartSAspect + + + False + + + CompNone + + + EncHextile + + + + + + + + + 0 + + + ProxyNone + + + + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + NoAuth + + + False + + + 5500 + + + False + + + + + + IE + + + False + + + + + + False + + + False + + + + + + False + + + + + + False + + + False + + + 14 + + + 1980-01-01 + + + False + + + Never + + + Yes + + + mRemoteNG + + + False + + + False + + + False + + + False + + + False + + + False + + + 5 + + + + + + + + + + + + + + + + + + False + + + False + + + False + + + False + + + 4 + + + + + + + + + mRemoteNG + + + 10 + + + {0}.{1:yyyyMMdd-HHmmssffff}.backup + + + False + + + True + + + False + + + False + + + release + + + + + + True + + + + + + + + + True + + + https://mremoteng.org/ + + + + + + True + + + False + + + False + + + RDP + + + 9/9, 33/8 + + + 9/8, 34/8 + + + False + + + 20 + + + AES + + + GCM + + + 1000 + + + Dynamic + + + False + + + 0 + + + False + + + False + + + False + + + False + + + 00000000-0000-0000-0000-000000000000 + + + + + + False + + + True + + + True + + + True + + + False + + + False + + + True + + + True + + + False + + + False + + + False + + + False + + + True + + + True + + + cs-CZ,de,el,en,en-US,es-AR,es,fr,hu,it,ja-JP,ko-KR,nb-NO,nl,pt,pt-BR,pl,ru,uk,tr-TR,zh-CN,zh-TW + + + True + + + + + + + + + + + + General + + + True + + + False + + + False + + + False + + + False + + + 0, 0 + + + + + + False + + + False + + + General + True - - False - - - False - + + False + + + False + 00000000-0000-0000-0000-000000000000 - - True - - + + True + + + False + + \ No newline at end of file diff --git a/mRemoteV1/References/MagicLibrary.dll b/mRemoteV1/References/MagicLibrary.dll deleted file mode 100644 index 24cfa5d0..00000000 Binary files a/mRemoteV1/References/MagicLibrary.dll and /dev/null differ diff --git a/mRemoteV1/Resources/Help/Index.htm b/mRemoteV1/Resources/Help/Index.htm index cfa50ca0..cc9cad1d 100644 --- a/mRemoteV1/Resources/Help/Index.htm +++ b/mRemoteV1/Resources/Help/Index.htm @@ -1,48 +1,86 @@ - - mRemoteNG Help - + + mRemoteNG Help + -
+
Done from nmat, please remove this div after review. -
-

Welcome to mRemoteNG

-
-

+

+

Welcome to mRemoteNG

+
+

This documentation is written and based on version 1.76 of mRemoteNG. If you find anything to improve or wrong with the documentation then please report it to github. Also note that documentation can be found on github pages that are updated more frequently then information provided here. -

-

Getting Started

- -

User Interface

- -

Special Topics

-

Connections

- +

+

Getting Started

+ +

User Interface

+ +

Special Topics

+

Connections

+ - + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/Introduction.htm b/mRemoteV1/Resources/Help/Introduction.htm index 114ff60b..c92c6511 100644 --- a/mRemoteV1/Resources/Help/Introduction.htm +++ b/mRemoteV1/Resources/Help/Introduction.htm @@ -1,26 +1,26 @@ - - Introduction - + + Introduction + -
+
Done from nmat, please remove this div after review. -
-

Introduction

-
-

+

+

Introduction

+
+

mRemoteNG is a multi-protocol remote connections manager.
As of Version 1.00 it supports the RDP, VNC, ICA, SSH, Telnet, RAW, Rlogin and HTTP/S protocols.
The main goal is to minimize window clutter and to provide a easy gui for managing all your remote connections. -

-

Features

-
-
    +

    +

    Features

    +
    +
    • Free and Open Source, released under the GPL
    • Panels and tabs allow to group certain connections together, dock them to any side of the window or completely undock them and move them to another screen for example
    • Multiple supported protocols (RDP, VNC, ICA, SSH, Telnet, RAW, Rlogin and HTTP/S)
    • @@ -41,13 +41,13 @@
    • Fullscreen (Kiosk) mode
    • Assign global credentials to use when no information is provided on connection basis
    • Host Up/Down (Ping) feature shows if the selected host answers to a ping
    • -
    -

    License

    -
    -

    +

+

License

+
+

The application is released under the GPL (V2)
Binary and source code packages are available for download. -

+

- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/Main.css b/mRemoteV1/Resources/Help/Main.css index 48c211da..a00e6a96 100644 --- a/mRemoteV1/Resources/Help/Main.css +++ b/mRemoteV1/Resources/Help/Main.css @@ -1,19 +1,16 @@ /* COMMON STUFF */ -body -{ - background-color: #FFFFFF; - margin-left: 10px; - margin-top: 10px; - margin-right: 10px; - margin-bottom: 10px; - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; - font-size: 0.75em; - color: #333333; +body { + background-color: #FFFFFF; + margin-left: 10px; + margin-top: 10px; + margin-right: 10px; + margin-bottom: 10px; + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + font-size: 0.75em; + color: #333333; } -img { - border: none; -} +img { border: none; } hr { display: block; @@ -25,75 +22,73 @@ hr { } /* HEADINGS */ + h1 { - font-size: 2.0em; - color: #000000; + font-size: 2.0em; + color: #000000; } h2 { - font-size: 1.5em; - color: #000000; + font-size: 1.5em; + color: #000000; } h3 { - font-size: 1.17em; - color: #000000; + font-size: 1.17em; + color: #000000; } h4 { - font-size: 1em; - color: #000000; + font-size: 1em; + color: #000000; } h5 { - font-size: .83em; - color: #000000; + font-size: .83em; + color: #000000; } /* LINKS */ -a:link -{ - color: #5d6b70; - text-decoration: none; + +a:link { + color: #5d6b70; + text-decoration: none; } -a:visited -{ - color: #5d6b70; - text-decoration: none; +a:visited { + color: #5d6b70; + text-decoration: none; } -a:hover -{ - color: Black; - text-decoration: underline; +a:hover { + color: Black; + text-decoration: underline; } /* TABLES */ + table { - font-family: arial, sans-serif; - border-collapse: collapse; + font-family: arial, sans-serif; + border-collapse: collapse; } td, th { - border: 1px solid #dddddd; - text-align: left; - padding: 8px; + border: 1px solid #dddddd; + text-align: left; + padding: 8px; } -tr:nth-child(even) { - background-color: #f2f2f2; -} +tr:nth-child(even) { background-color: #f2f2f2; } /* MISC STYLES */ -.Code -{ - padding-right: 5px; - padding-left: 5px; - color: #000000; - font-family: 'Courier New' , Monospace; - background-color: #C1C1C1; + +.Code { + padding-right: 5px; + padding-left: 5px; + color: #000000; + font-family: 'Courier New', Monospace; + background-color: #C1C1C1; } .monospace { @@ -101,28 +96,29 @@ tr:nth-child(even) { font-family: 'Courier New', monospace; } -.nowrap { - white-space: nowrap -} +.nowrap { white-space: nowrap } .isa_info, .isa_success, .isa_warning, .isa_error { margin: 10px 0px; - padding:12px; - + padding: 12px; } + .isa_info { color: #00529B; background-color: #BDE5F8; } + .isa_success { color: #4F8A10; background-color: #DFF2BF; } + .isa_warning { color: #9F6000; background-color: #FEEFB3; } + .isa_error { color: #D8000C; background-color: #FFD2D2; -} +} \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/gs_command_line_switches.htm b/mRemoteV1/Resources/Help/gs_command_line_switches.htm index 23c5fa11..c120b56d 100644 --- a/mRemoteV1/Resources/Help/gs_command_line_switches.htm +++ b/mRemoteV1/Resources/Help/gs_command_line_switches.htm @@ -1,78 +1,80 @@ - - Command-Line Switches - + + Command-Line Switches + -
+
Complete from nmat updates, please remove this div after review. -
-

+

+

The following is a list of command line switches supported by mRemoteNG. -

-
+

+
- - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CommandDescription
- /cons:PathToConnectionsFile -

- /c:PathToConnectionsFile -
- Loads the connections file from the given path. -

- This path can be a: -
    -
  • full file path
  • -
  • path relative to the current directory
  • -
  • path relative to the mRemoteNG application directory
  • -
  • path relative to the mRemoteNG default connection file directory
  • -
-
/resetResets window position, panels and toolbars
- /resetpos -

- /rp -
Reset the windows position
- /resetpanels -

- /rpnl -
Resets all panel's positions. Use this if you have troubles with panel layouts
- /resettoolbar -

- /rtbr -
Resets the positions of all toolbars
- /noreconnect -

- /norc -
Temporary disables reconnect to previously opened sessions. Use this if you have problems opening mRemoteNG after you enabled the setting and restarted mRemoteNG
CommandDescription
+ /cons:PathToConnectionsFile +

+ /c:PathToConnectionsFile +
+ Loads the connections file from the given path. +

+ This path can be a: +
    +
  • full file path
  • +
  • path relative to the current directory
  • +
  • path relative to the mRemoteNG application directory
  • +
  • path relative to the mRemoteNG default connection file directory
  • +
+
+ /reset + Resets window position, panels and toolbars
+ /resetpos +

+ /rp +
Reset the windows position
+ /resetpanels +

+ /rpnl +
Resets all panel's positions. Use this if you have troubles with panel layouts
+ /resettoolbar +

+ /rtbr +
Resets the positions of all toolbars
+ /noreconnect +

+ /norc +
Temporary disables reconnect to previously opened sessions. Use this if you have problems opening mRemoteNG after you enabled the setting and restarted mRemoteNG
-
+
- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/gs_installation.htm b/mRemoteV1/Resources/Help/gs_installation.htm index 8526efb9..9b419bc3 100644 --- a/mRemoteV1/Resources/Help/gs_installation.htm +++ b/mRemoteV1/Resources/Help/gs_installation.htm @@ -1,43 +1,43 @@ - - Installation - + + Installation + -
+
Done from nmat, remove this div after review. -
-

Information

-

+

+

Information

+

Downloads are provided in four different packages, the setup package, binary package, portable package and the source package. They are described below. -

-

Setup Package

-

+

+

Setup Package

+

The setup package is the compiled version of mRemoteNG which comes in an MSI installer.
The common way to get mRemoteNG up and running -

-

Portable Package

-

+

+

Portable Package

+

The portable package consists of the same files as the bin package but contains an modified version of the executable which stores and loads all your settings - from files in the application's directory.
+ from files in the application's directory.
This package can be used to run mRemoteNG from an USB stick an preserve your configuration wherever you go. -

-

Source Package

-

+

+

Source Package

+

The source package is a zip package and contains the source code in form of a Visual Studio solution. -

-

Updating and Uninstalling

-

+

+

Updating and Uninstalling

+

mRemoteNG can be updated without uninstalling it before.
For portable version of mRemoteNG stores all user data in same folder as mRemoteNG.exe file. -

+

- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/gs_prerequisites.htm b/mRemoteV1/Resources/Help/gs_prerequisites.htm index 41438410..ce1a87d2 100644 --- a/mRemoteV1/Resources/Help/gs_prerequisites.htm +++ b/mRemoteV1/Resources/Help/gs_prerequisites.htm @@ -1,115 +1,143 @@ - - Prerequisites - + + Prerequisites + -
+
Done from nmat, remove this div after review -
+
-

Supported Operating Systems:

-
- +

Prerequisites:

+
+
    +
  • + Microsoft .NET Framework 4.0 +
  • +
  • + Microsoft Terminal Services Client 8.0 or later. +
      +
    • Needed if you use RDP. mstscax.dll and/or msrdp.ocx must be registered.
    • +
    • + Included with newer Windows versions. + KB2574819 AND either + KB2592687 or + KB2923545 + is required for Windows 7/Windows Server 2008 R2 +
    • +
    +
  • +
  • + PuTTY +
      +
    • Needed if you use Telnet, SSH, Rlogin or RAW. Included in all packages.
    • +
    • An appropriate and integrated version is included with mRemoteNG.
    • +
    +
  • +
  • + Citrix ICA Client +
      +
    • Needed if you use ICA. wfica.ocx must be registered.
    • +
    +
  • +
- -

Windows™ 7/Windows Server 2008 R2 clients (requirements)

-
+ +

Windows™ 7/Windows Server 2008 R2 clients (requirements)

+
TIP! You can use powershell to fetch if the hotfixes are installed. Try using example:

Get-HotFix | where {$_.HotFixID -eq "KB2574819" -and $_.HotFixID -eq "KB2592687"} -
-

+

+

The following updates must be present on any Windows 7 or Server 2008 client that will be running mRemoteNG. (They must have been installed in the order provided below): -

- + - + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/gs_running_mremoteng.htm b/mRemoteV1/Resources/Help/gs_running_mremoteng.htm index abf39373..b82e102d 100644 --- a/mRemoteV1/Resources/Help/gs_running_mremoteng.htm +++ b/mRemoteV1/Resources/Help/gs_running_mremoteng.htm @@ -1,177 +1,179 @@ - + Running mRemoteNG - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
-

First Run

-
-

- Here is a quick reference of the interface: -

- -

- The screenshot above explains the most basic of the interface. To understand it all - we are creating a small tutorial here. -

+

First Run

+
+

+ Here is a quick reference of the interface: +

+ +

+ The screenshot above explains the most basic of the interface. To understand it all + we are creating a small tutorial here. +

-

Creating a connection

-

- Right click on the root item (the little blue globe named "Connections") in - the Connections panel and select "New Connection". Or use the keybinding - Ctrl+N if the Connections are selected. -

- -

- A new item shows up under the root item. You can give it a name now - (or rename it later). Here we just name it "Test". -

- -

- Now lets look at the Config panel in the bottom left, just under the - Connections panel. -

- -

- As you may notice this is where you configure all the properties of connections - and folders.
- There are a lot of values that can be set but for our first connection we will - keep things simple. -

-

- The most important things right now are that we tell the application which host - we want to connect to and which protocol we want to use.
- In this example we will use a Windows 2012 R2 server that has RDP (Remote Desktop - Protocol) enabled.
- As RDP is the default protocol whenever you create a new connection we don't have - to change anything there. -

-

- The next thing we will do is to fill in the Hostname/IP field with the hostname - we want to connect to. Lets also fill in a username and password so that we login - automatically to the server. -

- -

- Lets now try to connect to the server. -

-
- TIP! You can see an indicator in the properties window that is glowing green. - -

- This icon does a ICMP ping on to check response from the server. If it glows green - it indicates a connection response can be made using ping to the host. - However this is turned off on windows by default. You have to enable ICMP and allow - the firewall access for it. -
-

Opening and Closing Connections

-

- There are multiple ways to open a connection in mRemoteNG, but the easiest - way is to double click the connection in the Connections panel. -

-

- If you double click the connection you will notice that the connection is going - to try and open in a new panel called  General  and under a tab - called  Test . -

- -
- NOTE! If the connection fails you will find out what the problem was - in the dialog notifications panel. -
-

- If all goes well you should see the remote desktop without any problems. -

-

- To close the connection you can do any of the following: -

    +

    Creating a connection

    +

    + Right click on the root item (the little blue globe named "Connections") in + the Connections panel and select "New Connection". Or use the keybinding + Ctrl+N if the Connections are selected. +

    + +

    + A new item shows up under the root item. You can give it a name now + (or rename it later). Here we just name it "Test". +

    + +

    + Now lets look at the Config panel in the bottom left, just under the + Connections panel. +

    + +

    + As you may notice this is where you configure all the properties of connections + and folders.
    + There are a lot of values that can be set but for our first connection we will + keep things simple. +

    +

    + The most important things right now are that we tell the application which host + we want to connect to and which protocol we want to use.
    + In this example we will use a Windows 2012 R2 server that has RDP (Remote Desktop + Protocol) enabled.
    + As RDP is the default protocol whenever you create a new connection we don't have + to change anything there. +

    +

    + The next thing we will do is to fill in the Hostname/IP field with the hostname + we want to connect to. Lets also fill in a username and password so that we login + automatically to the server. +

    + +

    + Lets now try to connect to the server. +

    +
    + TIP! You can see an indicator in the properties window that is glowing green. + +

    + This icon does a ICMP ping on to check response from the server. If it glows green + it indicates a connection response can be made using ping to the host. + However this is turned off on windows by default. You have to enable ICMP and allow + the firewall access for it. +
    +

    Opening and Closing Connections

    +

    + There are multiple ways to open a connection in mRemoteNG, but the easiest + way is to double click the connection in the Connections panel. +

    +

    + If you double click the connection you will notice that the connection is going + to try and open in a new panel called  General  and under a tab + called  Test . +

    + +
    + NOTE! If the connection fails you will find out what the problem was + in the dialog notifications panel. +
    +

    + If all goes well you should see the remote desktop without any problems. +

    +

    + To close the connection you can do any of the following: +

    • Log off in the start menu - Closes the connection and logs you out completely from RDP
    • Close the panel with the - Which leaves your session active on server but closes connection in mRemoteNG
    • Close the connection tab with - Also keeps your login active on server but closes RDP connection in mRemoteNG
    • Double click the connection tab - Same as above where the connection is active on server but closes RDP connection in mRemoteNG
    • -
    -

    -

    Folders and Inheritance

    -

    - Folders on mRemoteNG cannot only be used to categorize connections but also to - apply properties to the underlying connections. -

    -

    Example

    -

    - You have 10 Remote Desktop enabled servers in one domain and 15 in another domain. -

    -

    - Normally you would spend a lot of time creating all those connections and setting - the individual properties like username, password, etc. In mRemoteNG there is an - easier way. You just create two folders, one for domain A and one for domain B - and set all properties there. -

    -

    - Then create the Connections and let them inherit every property. The only - properties left to fill on Connection basis are the Connections name and hostname. - Everything else will be inherited from the parent folder. -

    -

    - Here is how you do this: -

    -

    1. Add the folder

    -

    - This can be done with: -

      +
    +

    +

    Folders and Inheritance

    +

    + Folders on mRemoteNG cannot only be used to categorize connections but also to + apply properties to the underlying connections. +

    +

    Example

    +

    + You have 10 Remote Desktop enabled servers in one domain and 15 in another domain. +

    +

    + Normally you would spend a lot of time creating all those connections and setting + the individual properties like username, password, etc. In mRemoteNG there is an + easier way. You just create two folders, one for domain A and one for domain B + and set all properties there. +

    +

    + Then create the Connections and let them inherit every property. The only + properties left to fill on Connection basis are the Connections name and hostname. + Everything else will be inherited from the parent folder. +

    +

    + Here is how you do this: +

    +

    1. Add the folder

    +

    + This can be done with: +

    • Right click on connections and click on New Folder
    • -
    • File > New Folder
    • +
    • + File > New Folder +
    • Or with keybinding: Ctrl+Shift+N
    • -
    -

    - -

    - Then give it a name and fill all the properties you need (like you did with - the test connection) -

    -
    - -

    - When you have filled in the settings and values you can either just drag the test - Connection inside the folder or create a new one. -

    - -

    - Right now nothing has changed and nothing will be inherited.
    - To enable inheritance switch to the inheritance view by clicking the - dedicated button. (Marked with a red arrow below) -

    - -

    - The properties that show up now are almost the same as before, but you - only select yes or no to enable or disable a inheritance. -

    - -

    - When no is selected the property will not be inherited, yes indicates - an inherited property. -

    -

    - For this test set Inherit Everything to Yes. -

    -

    - Now if you switch back to the properties view (the button left - of the inheritance button) you should see that not much is left of all - those properties. -

    - -

    - Only the Name and Hostname/IP properties are left over, everything else will be - inherited from the parent folder. -

    -

    - Of course you can also only let some of the properties be inherited. Just play - around with this a bit and you'll get the hang of it. -

    - - +
+

+ +

+ Then give it a name and fill all the properties you need (like you did with + the test connection) +

+
+ +

+ When you have filled in the settings and values you can either just drag the test + Connection inside the folder or create a new one. +

+ +

+ Right now nothing has changed and nothing will be inherited.
+ To enable inheritance switch to the inheritance view by clicking the + dedicated button. (Marked with a red arrow below) +

+ +

+ The properties that show up now are almost the same as before, but you + only select yes or no to enable or disable a inheritance. +

+ +

+ When no is selected the property will not be inherited, yes indicates + an inherited property. +

+

+ For this test set Inherit Everything to Yes. +

+

+ Now if you switch back to the properties view (the button left + of the inheritance button) you should see that not much is left of all + those properties. +

+ +

+ Only the Name and Hostname/IP properties are left over, everything else will be + inherited from the parent folder. +

+

+ Of course you can also only let some of the properties be inherited. Just play + around with this a bit and you'll get the hang of it. +

+ + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/st_common_problems_rdp.htm b/mRemoteV1/Resources/Help/st_common_problems_rdp.htm index 6a418d77..ef0a32b2 100644 --- a/mRemoteV1/Resources/Help/st_common_problems_rdp.htm +++ b/mRemoteV1/Resources/Help/st_common_problems_rdp.htm @@ -1,66 +1,73 @@ - + Common Problems (RDP) - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
-

Introduction

-

- Its hard to make a document on all problems that can occur with connections - but here at least we are trying to list some of the most common problems for RDP - that has been noticed. -

+

Introduction

+

+ Its hard to make a document on all problems that can occur with connections + but here at least we are trying to list some of the most common problems for RDP + that has been noticed. +

- -

Quick Reference

- - + +

Quick Reference

+ + - -

CredSSP - CVE-2018-0886 - Authentication error

-

- mRemoteNG uses the Microsoft Terminal Services Client (MSTSC) libraries in order - to make Remote Desktop connections. mRemoteNG has no control over the functionality - changes implemented by Microsoft. -

-

- Relevant line of code that shows our - "RDP Client" connection "object": - - private MsRdpClient8NotSafeForScripting _rdpClient; -

-

- Relevant MS documentation for this .NET class: - MsRdpClient8NotSafeForScripting class -

-

- Please refer to - Microsoft's documentation - for full details regarding this problem. -

-

- Patched clients attempting to connect to Unpatched servers will fail with the following error: -

- -

- The same error will occur with MSTSC directly on a - patched client attempting to connect to an unpatched server. -

-

Per the MS documentation, the only ways around this are to:

-
    -
  • Patch the servers
  • -
  • set the "Encryption Oracle Remediation" policy to "Vulnerable" - refer to the MS documentation above for details:
    -
  • -
  • Uninstall KB4103727
  • -
- - - + +

CredSSP - CVE-2018-0886 - Authentication error

+

+ mRemoteNG uses the Microsoft Terminal Services Client (MSTSC) libraries in order + to make Remote Desktop connections. mRemoteNG has no control over the functionality + changes implemented by Microsoft. +

+

+ Relevant line of code that shows our + "RDP Client" connection "object": + + private MsRdpClient8NotSafeForScripting _rdpClient; + +

+

+ Relevant MS documentation for this .NET class: + MsRdpClient8NotSafeForScripting class +

+

+ Please refer to + Microsoft's documentation + for full details regarding this problem. +

+

+ Patched clients attempting to connect to Unpatched servers will fail with the following error: +

+ +

+ The same error will occur with MSTSC directly on a + patched client attempting to connect to an unpatched server. +

+

Per the MS documentation, the only ways around this are to:

+
    +
  • Patch the servers
  • +
  • + set the "Encryption Oracle Remediation" policy to "Vulnerable" - refer to the MS documentation above for details:
    + +
  • +
  • Uninstall KB4103727
  • +
+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_config.htm b/mRemoteV1/Resources/Help/ui_config.htm index aed8bc99..3be5e0b0 100644 --- a/mRemoteV1/Resources/Help/ui_config.htm +++ b/mRemoteV1/Resources/Help/ui_config.htm @@ -1,67 +1,71 @@ - + Config - - -
- Complete from nmat updates, please remove this div after review. Need information in properties and inheritance. -
+ + +
+ Complete from nmat updates, please remove this div after review. Need information in properties and inheritance. +
- -

Introduction

-
- -

- Config dialog to setup the connection specific properties. - This includes inheritance from other items before the item and more. Details below is about - how to work with this dialog to get the most out of connections and configuration. -

-

Quick Reference

-
    -
  • Top Bar - Main top bar information.
  • -
- + +

Introduction

+
+ +

+ Config dialog to setup the connection specific properties. + This includes inheritance from other items before the item and more. Details below is about + how to work with this dialog to get the most out of connections and configuration. +

+

Quick Reference

+ + - -

Top Bar

-
-

- -

+ +

Top Bar

+
+

+ +

Red - Sort values Categories or Alphabetical.
Green - Show Properties, Inheritance values
Blue - Connection icon
Yellow - Host status (based on ICMP ping) -

-

Sort Values

-

- Sorts the values in properties either by Categories or Alphabetically. -

+

+

Sort Values

+

+ Sorts the values in properties either by Categories or Alphabetically. +

Categories sort - Shows values in categories with expanding options.
Alphabetical sort - Expands everything and shows values in alphabetical order instead -

-

Properties and Inheritance

-

- -

-

Icon

-

- The icon indicates the visual identifier for the connection. Clicking the icon will let you set a different icon - for the connection. -

-
- NOTE! Don't forget that mRemoteNG will save the change on exit auto unless you have unchecked this setting in options. -
-

Status

-

Is a indicator that will glow red or green depending on the status of the host. The status is based on ICMP ping to the host.

-
- IMPORTANT! In order for this to work you have to open up ICMP. On windows servers this is also disabled in windows firewall. -
- - - +

+

Properties and Inheritance

+

+ +

+

Icon

+

+ The icon indicates the visual identifier for the connection. Clicking the icon will let you set a different icon + for the connection. +

+
+ NOTE! Don't forget that mRemoteNG will save the change on exit auto unless you have unchecked this setting in options. +
+

Status

+

Is a indicator that will glow red or green depending on the status of the host. The status is based on ICMP ping to the host.

+
+ IMPORTANT! In order for this to work you have to open up ICMP. On windows servers this is also disabled in windows firewall. +
+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_connections.htm b/mRemoteV1/Resources/Help/ui_connections.htm index c67afec6..b5d5e4c2 100644 --- a/mRemoteV1/Resources/Help/ui_connections.htm +++ b/mRemoteV1/Resources/Help/ui_connections.htm @@ -1,86 +1,98 @@ - + Connections - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
-

Introduction

-
-

- The connections dialog is the main collection of all connections that is added to mRemoteNG. This document will - explain the details of the connections dialog. -

+

Introduction

+
+

+ The connections dialog is the main collection of all connections that is added to mRemoteNG. This document will + explain the details of the connections dialog. +

- -

Top Menu Bar

-
-

- -

+ +

Top Menu Bar

+
+

+ +

Red - New Connection
Green - New Folder
Blue - View (Expand/Collapse all folders)
Yellow - Ascending sort -

-

Quick Reference

- - +

+

Quick Reference

+ + - -

New Connection

-
-

- Creates a new connection item in the connections dialog after where cursor is present. -

-
- TIP! You can also duplicate an already created connection if you want to follow - some sort of template of a connection. Just right click on folder or connection to - duplicate the item. The information is then carried over for editing. This can save a lot - of time when the connection list is large. -
- + +

New Connection

+
+

+ Creates a new connection item in the connections dialog after where cursor is present. +

+
+ TIP! You can also duplicate an already created connection if you want to follow + some sort of template of a connection. Just right click on folder or connection to + duplicate the item. The information is then carried over for editing. This can save a lot + of time when the connection list is large. +
+ - -

New Folder

-
-

- Creates a new folder in connections dialog after where cursor is present. -

-
- TIP! Folders can help to make adding connections easier. By setting a folder with - some values that can be inheritaded down to the connections. Read more about this in - Configuration -
- + +

New Folder

+
+

+ Creates a new folder in connections dialog after where cursor is present. +

+
+ TIP! Folders can help to make adding connections easier. By setting a folder with + some values that can be inheritaded down to the connections. Read more about this in + Configuration +
+ - -

View

-
-

- Collapses or expands all directories in the connection dialog. Useful when working with - a lot of connections sorted in different directories. -

- + +

View

+
+

+ Collapses or expands all directories in the connection dialog. Useful when working with + a lot of connections sorted in different directories. +

+ - -

Ascending

-
-

- Works like a sort or a refresh to get connection in ascending order. (Descending order is - note supported yet) When you have been moving around in the tree of connections, just click - this item to refresh the list and get everything in ascending ordering. -

- - - + +

Ascending

+
+

+ Works like a sort or a refresh to get connection in ascending order. (Descending order is + note supported yet) When you have been moving around in the tree of connections, just click + this item to refresh the list and get everything in ascending ordering. +

+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_external_tools.htm b/mRemoteV1/Resources/Help/ui_external_tools.htm index eafa63ba..d554bcfa 100644 --- a/mRemoteV1/Resources/Help/ui_external_tools.htm +++ b/mRemoteV1/Resources/Help/ui_external_tools.htm @@ -1,44 +1,44 @@ - - External Tools - + + External Tools + -
+
Complete from nmat updates, please remove this div after review. -
- -

Introduction to External Tools

-

+

+ +

Introduction to External Tools

+

External Tools can help you get things done that can't be done in mRemoteNG.
You can for example start a command prompt or launch your favorite FTP tool from within mRemoteNG.
This wouldn't make much sense by itself because you can already launch your applications by using the Windows Start Menu, Quick Launch or whatever you prefer to use to start your apps. -

-

+

+

But there's more! -

-

+

+

In mRemoteNG, you can launch applications and tell them what to do with the use of arguments (parameters) and variables of the currently selected Connection. You can, for example, select your home router's SSH Connection entry and do a traceroute (tracert) on that host. This is much quicker and more powerful than opening the console and typing "tracert yourhost". -

-

+

+

The external tools configuration is stored in %APPDATA%\mRemoteNG\extApps.xml -

-

Variables

-

+

+

Variables

+

Variables and arguments can be used to tell the external tool what to do. -

-

+

+

This is the list of variables supported by mRemoteNG: -

-
    +

    +
    • %NAME%
    • %HOSTNAME%
    • %PORT%
    • @@ -48,183 +48,185 @@
    • %DESCRIPTION%
    • %MACADDRESS%
    • %USERFIELD%
    • -
    -

    +

+

Variables always refer to the currently selected connection. Variable names are case-insensitive. Variables can be used in both the Filename and Arguments fields. -

-

+

+

mRemoteNG will also expand environment variables such as %PATH% and %USERPROFILE%. If you need to use an environment variable with the same name as an mRemoteNG variable, use \% instead of %. The most common use of this is for the USERNAME environment variable. %USERNAME% will be expanded to the username set in the currently selected connection. \%USERNAME\% will be expanded to the value set in the USERNAME environment variable. -

-

+

+

If you need to send a variable name to a program without mRemoteNG expanding it, use ^% instead of %. mRemoteNG will remove the caret (^) and leave the rest unchanged. For example, ^%USERNAME^% will be sent to the program as %USERNAME% and will not be expanded. -

-

Special Character Escaping

-

+

+

Special Character Escaping

+

Expanded variables will be escaped using the rules below. There are two levels of escaping that are done. The first is escaping for standard argument splitting (C/C++ argv, CommandLineToArgvW, etc). The second is escaping shell metacharacters for ShellExecute. -

-

Argument splitting escaping:

-
    +

    +

    Argument splitting escaping:

    +
    • Each quotation mark will be escaped by a backslash.
    • -
    • One or more backslashes (\) followed by a quotation mark ("): -
        -
      • Each backslash will be escaped by another backslash.
      • -
      • The quotation mark will be escaped by a backslash.
      • -      If the connection's user field contains - "This" is a \"test\".
        -      Then %USERFIELD% is replaced with - \"This\" is a \\\"test\\\". -
      +
    • + One or more backslashes (\) followed by a quotation mark ("): +
        +
      • Each backslash will be escaped by another backslash.
      • +
      • The quotation mark will be escaped by a backslash.
      • +      If the connection's user field contains + "This" is a \"test\".
        +      Then %USERFIELD% is replaced with + \"This\" is a \\\"test\\\". +
    • -
    • A variable name followed by a quotation mark (for example, %USERFIELD%") with - a value ending in one or more backslashes: -
        -
      • Each backslash will be escaped by another backslash.
      • -
      • Example:
      • -      If the connection's user field contains c:\Example\
        -      Then "%USERFIELD%" is replaced with "c:\Example\\" -
      +
    • + A variable name followed by a quotation mark (for example, %USERFIELD%") with + a value ending in one or more backslashes: +
        +
      • Each backslash will be escaped by another backslash.
      • +
      • Example:
      • +      If the connection's user field contains c:\Example\
        +      Then "%USERFIELD%" is replaced with "c:\Example\\" +
    • -
    -

    +

+

To disable argument splitting escaping for a variable, precede its name with a minus (-) sign. For example, %-USERFIELD%. -

-

Shell metacharacter escaping:

-
    +

    +

    Shell metacharacter escaping:

    +
    • The shell metacharacters are ( ) % ! ^ " < > & |
    • Each shell metacharacter will be escaped by a caret (^).
    • -
    -

    +

+

To disable both argument splitting and shell metacharacter escaping for a variable, precede its name with an exclamation point (!). For example, %!USERFIELD%. This is not recommended and may cause unexpected results. -

-

+

+

Only variables that have been expanded will be escaped. It is up to you to escape the rest of the arguments. -

+

-

Variable Examples

- +

Variable Examples

+
- - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - + - + - + - + -
ArgumentsUser FieldResultArgumentsUser FieldResult
%USERFIELD%"Example" Text\^"Example\^" Text%USERFIELD%"Example" Text\^"Example\^" Text
%-USERFIELD%"Example" Text^"Example^" Text%-USERFIELD%"Example" Text^"Example^" Text
%!USERFIELD%"Example" Text"Example" Text%!USERFIELD%"Example" Text"Example" Text
^%USERFIELD^%"Example" Text%USERFIELD%^%USERFIELD^%"Example" Text%USERFIELD%
^^%USERFIELD^^%"Example" Text^%USERFIELD^%^^%USERFIELD^^%"Example" Text^%USERFIELD^%
-d "%USERFIELD%"c:\Example\-d "c:\Example\\"-d "%USERFIELD%"c:\Example\-d "c:\Example\\"
-d "%-USERFIELD%"c:\Example\-d "c:\Example\"-d "%-USERFIELD%"c:\Example\-d "c:\Example\"
-d "%USERFIELD%"Left & Right-d "Left ^& Right"-d "%USERFIELD%"Left & Right-d "Left ^& Right"
-d "%!USERFIELD%"Left & Right-d "Left & Right"-d "%!USERFIELD%"Left & Right-d "Left & Right"
%WINDIR%N/Ac:\Windows\%WINDIR%N/Ac:\Windows\
\%WINDIR\%N/Ac:\Windows\\%WINDIR\%N/Ac:\Windows\
\^%WINDIR\^%N/A\%WINDIR\%\^%WINDIR\^%N/A\%WINDIR\%
\\%WINDIR\\%N/A\\%WINDIR\\%\\%WINDIR\\%N/A\\%WINDIR\\%
-

Example

-

+ +

Example

+

First of all, start the external tools editor. To do this, click Tools in the main menu and select External Tools.
You will see a screen like on the following screenshot. -

-

- -

-

+

+

+ +

+

The fields below the list are greyed out because you haven't created an external tool entry yet.
To create one, right click the blank area in the list and select Add, as in the screenshot below. -

-

- -

-

+

+

+ +

+

This is what you'll get: -

-

- -

-

+

+

+ +

+

So the three fields are now available and need to be filled.
The Display Name is simply the name you will see when you want to launch that tool, so give it a descriptive name.
I named mine Traceroute as I will create a external tool that will start the tracert command in the console. -

-

- -

-

+

+

+ +

+

Ok, the next thing we'll need is a filename. This is the program that we want to be executed.
I simply type in cmd for a Windows cmd console. -

-

- -

-

+

+

+ +

+

Now the fun part comes in—the arguments.
The Windows cmd has a command line argument that tells the console to launch the command followed by that argument and stay open.
@@ -234,23 +236,23 @@ completes.
After that, I just type tracert %HostName%. This tells the console to do a traceroute on the hostname of the currently selected Connection. -

-

- -

-

+

+

+ +

+

Alright! That's all we'll need.
Now right click one of you connections, click Tools, External Tools and select Traceroute. -

-

- -

-

+

+

+ +

+

Voilà! A console window will popup and execute your tracert command. -

-

- -

+

+

+ +

- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_file_transfer.htm b/mRemoteV1/Resources/Help/ui_file_transfer.htm index 33adffbe..e37703de 100644 --- a/mRemoteV1/Resources/Help/ui_file_transfer.htm +++ b/mRemoteV1/Resources/Help/ui_file_transfer.htm @@ -1,79 +1,80 @@ - - SSH File Transfer - + + SSH File Transfer + -
+
Complete from nmat updates, please remove this div after review. -
+
- -

Introduction

-
-

+ +

Introduction

+
+

SSH File Transfer functionality allows you to securely transfer files to a remote host over an encrypted tunnel using either SFTP or SCP. -

- +

+ - -

Use Cases

-
-

The primary use case is to upload individual files, such as configuration files, to a remote host.

- + +

Use Cases

+
+

The primary use case is to upload individual files, such as configuration files, to a remote host.

+ - -

Prerequisites

-
-
    + +

    Prerequisites

    +
    +
    • SSH File Transfer requires an SSH service to listen on an available network port (default 22) on a remote host.
    • A username and password must be supplied to connect with the remote host.
    • The remote host must have a writeable folder on its filesystem to place the transferred files.
    • -
    - +
+ - -

Configuration Options

-
-
    + +

    Configuration Options

    +
    +
    • Host - The remote host you connect to. Can be DNS name or IP address.
    • Port - Remote network port listening for SSH/SFTP/SCP traffic.
    • User - Username for account to log on to remote host.
    • Password - Password for account to log on to remote host.
    • Protocol - Choice of SCP or SFTP protocol used for communication.
    • Local File - Path of file to transfer from local host.
    • -
    • Remote File - Path where file will be transferred on remote host. -
        -
      • Example: /home/John/Documents
      • -
      +
    • + Remote File - Path where file will be transferred on remote host. +
        +
      • Example: /home/John/Documents
      • +
    • -
    - +
+ -

Using SSH File Transfer

-
-

+

Using SSH File Transfer

+
+

To begin, select Tools and then SSH File Transfer. The tool will fill the window and allow you to input the configuration options. Each piece of information is needed for a successful transfer. -

+

-

+

To populate the Local File option, select the Browse button and navigate to the desired file on the local filesystem. To populate the Remote File option, manually type desired filesystem path, including the desired file name. -

+

-

+

Once all options are populated, select Transfer and the progress bar at the bottom of the window will show the progress. -

+

-

Troubleshooting SSH File Transfer

-
-

+

Troubleshooting SSH File Transfer

+
+

To troubleshoot issues with SSH File Transfer, consult the log under %AppData%\mRemoteNG\mRemoteNG.log. This log provides verbose information about successful and failed connections.

Common Issues

@@ -91,6 +92,6 @@ [14] ERROR- SSH background transfer failed!
This issue was likely encountered due to a permissions issue. Ensure you have appropriate access to write to the specified Remote File. -

+

- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_import_and_export.htm b/mRemoteV1/Resources/Help/ui_import_and_export.htm index 659c2b33..e42d287a 100644 --- a/mRemoteV1/Resources/Help/ui_import_and_export.htm +++ b/mRemoteV1/Resources/Help/ui_import_and_export.htm @@ -1,48 +1,48 @@ - + Import/Export - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
- -

Introduction

-
-

- Import/Export is for importing or exporting your configuration of connections. -

- + +

Introduction

+
+

+ Import/Export is for importing or exporting your configuration of connections. +

+ - -

Import

-
-

Import from File...

-

- Opens a normal file load dialog to open a exported xml or csv file for mRemoteNG. - See Export to file... further down this page for information on - exporting your connections. -

-

Import from Active Directory

-

- If you have servers that is located in a domain. Then this option can be used to fetch - those servers to easily import them to mRemoteNG. -

-

Import from Port Scan

- + +

Import

+
+

Import from File...

+

+ Opens a normal file load dialog to open a exported xml or csv file for mRemoteNG. + See Export to file... further down this page for information on + exporting your connections. +

+

Import from Active Directory

+

+ If you have servers that is located in a domain. Then this option can be used to fetch + those servers to easily import them to mRemoteNG. +

+

Import from Port Scan

+ - -

Export to file...

-
-

- Here you can export your settings to a file to share or backup. The dialog shown below - is the dialog of which you chose the options to export. -

- - - - + +

Export to file...

+
+

+ Here you can export your settings to a file to share or backup. The dialog shown below + is the dialog of which you chose the options to export. +

+ + + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_keyboardshortcuts.htm b/mRemoteV1/Resources/Help/ui_keyboardshortcuts.htm index bbe18af2..4de806ad 100644 --- a/mRemoteV1/Resources/Help/ui_keyboardshortcuts.htm +++ b/mRemoteV1/Resources/Help/ui_keyboardshortcuts.htm @@ -1,106 +1,136 @@  - + Keyboardshortcuts - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
-

Keybindings

-

File

- - +

Keybindings

+

File

+
+ - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - -
Keybinding Action
Ctrl+N
+ Ctrl+N + New Connection
Ctrl+Shift+N
+ Ctrl+Shift+N + New Folder
Ctrl+O
+ Ctrl+O + Open Connection File...
Ctrl+S
+ Ctrl+S + Save Connection File
Ctrl+Shift+S
+ Ctrl+Shift+S + Save Connection File As...
+ + -

View

- - +

View

+
+ - - - + + + - - - + + + - - - + + + - -
Keybinding Action
Ctrl+Alt+C
+ Ctrl+Alt+C + Jump to (Connections and Config)
Ctrl+Alt+E
+ Ctrl+Alt+E + Jump to (Notifications)
F11
+ F11 + Fullscreen
+ + -

Connections

- - +

Connections

+
+ - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - -
Keybinding Action
Ctrl+Shift+C
+ Ctrl+Shift+C + Connect
Ctrl+D
+ Ctrl+D + Duplicate
F2
+ F2 + Rename
Del
+ Del + Delete...
Ctrl+Up
+ Ctrl+Up + Move Up
Ctrl+Down
+ Ctrl+Down + Move Down
+ + -

Help

- - +

Help

+
+ - - - + + + - -
Keybinding Action
F1
+ F1 + mRemoteNG Help
- - + + + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_menus.htm b/mRemoteV1/Resources/Help/ui_menus.htm index df4d7c8f..85334e94 100644 --- a/mRemoteV1/Resources/Help/ui_menus.htm +++ b/mRemoteV1/Resources/Help/ui_menus.htm @@ -1,224 +1,240 @@ - - Menus - + + Menus + -
+
Complete from nmat updates, please remove this div after review. -
+
- -

Introduction

-
- -

+ +

Introduction

+
+ +

In this section we are going to explain the menus located in mRemoteNG. The above screenshot shows the main menu with colors. Short color explanation:

- Red - Anchor to move menu around the interface
- Green - The menu items + Red - Anchor to move menu around the interface
+ Green - The menu items

-

-

Quick Reference

-
    -
  • File Menu - Contains standard commands for the application
  • -
  • View Menu - Menu for additional dialogs for mRemoteNG
  • -
  • Tools Menu - Additional tools that can be used and triggered in mRemoteNG
  • -
  • Help Menu - Get more information for the application
  • -
- +

+

Quick Reference

+ + - -

File Menu

-
- + +

File Menu

+
+
- - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + -
ItemDescriptionItemDescription
New ConnectionWill add a new connection to the Connections dialog after where the cursor is positioned.New ConnectionWill add a new connection to the Connections dialog after where the cursor is positioned.
New FolderAdd a new folder in the Connections dialog tree where the cursor is positioned.New FolderAdd a new folder in the Connections dialog tree where the cursor is positioned.
New Connection FileCreate a new connection file. Dialog will come up asking about: filename and where to place the new connection file.New Connection FileCreate a new connection file. Dialog will come up asking about: filename and where to place the new connection file.
Open Connection File - Open a connection file. Dialog comes up asking about which file to open. For security reasons, this also shows a dialog - to ask if you want to save the current file before continuing. - Open Connection File + Open a connection file. Dialog comes up asking about which file to open. For security reasons, this also shows a dialog + to ask if you want to save the current file before continuing. +
Save Connection FileSaves the currently opened connection file. If you are using a SQL server connection instead it will send a save to the SQL server.Save Connection FileSaves the currently opened connection file. If you are using a SQL server connection instead it will send a save to the SQL server.
Save Connection File As...Saves the current connection file to a specific location on disk.Save Connection File As...Saves the current connection file to a specific location on disk.
Delete...Delete currently selected item in connections dialog.Delete...Delete currently selected item in connections dialog.
RenameRename current selected item in connections dialog.RenameRename current selected item in connections dialog.
DuplicateDuplicate current selected item in connections dialog.DuplicateDuplicate current selected item in connections dialog.
Reconnect All Open ConnectionsSends a reconnect to all the open connections in mRemoteNG.Reconnect All Open ConnectionsSends a reconnect to all the open connections in mRemoteNG.
ExitExit mRemoteNG applicationExitExit mRemoteNG application
- + + - -

View Menu

-
- + +

View Menu

+
+
- - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + -
ItemDescriptionItemDescription
Add Connection PanelCreate a new and empty panel.Add Connection PanelCreate a new and empty panel.
Connection PanelsJump to panel.Connection PanelsJump to panel.
ConnectionsShow connections dialogConnectionsShow connections dialog
ConfigShow config dialogConfigShow config dialog
NotificationsShow notifications dialogNotificationsShow notifications dialog
ScreenshotsOpen Screenshots panel (See: ScreenshotManager for more information)ScreenshotsOpen Screenshots panel (See: ScreenshotManager for more information)
Jump ToPlace focus on "Connections and Config" or "Notifications" panel based on selection.Jump ToPlace focus on "Connections and Config" or "Notifications" panel based on selection.
Reset layoutResets the layout of panels and dialogs. Warning will come up about the action before continuing.Reset layoutResets the layout of panels and dialogs. Warning will come up about the action before continuing.
Lock toolbar positionsLocks the toolbars at the top of the application so you do not move around items by mistake.Lock toolbar positionsLocks the toolbars at the top of the application so you do not move around items by mistake.
Quick Connect ToolbarShow quick connect toolbarQuick Connect ToolbarShow quick connect toolbar
External Tools ToolbarShow external tools toolbarExternal Tools ToolbarShow external tools toolbar
Multi SSH ToolbarShow multi ssh toolbarMulti SSH ToolbarShow multi ssh toolbar
FullscreenFullscreen mRemoteNG (will not fullscreen connection window but only the mRemoteNG application)FullscreenFullscreen mRemoteNG (will not fullscreen connection window but only the mRemoteNG application)
- + + - -

Tools Menu

-
- + +

Tools Menu

+
+
- - + + - - + + - - + + - - + + - - + + - - + + -
ItemDescriptionItemDescription
SSH File TransferShow SSH file transer panel (See: SSH File Transfer for more details)SSH File TransferShow SSH file transer panel (See: SSH File Transfer for more details)
External ToolsShow external tools dialog (See: External Tools for more details)External ToolsShow external tools dialog (See: External Tools for more details)
Port ScanShow port scan dialog (See: Port Scan for more details)Port ScanShow port scan dialog (See: Port Scan for more details)
Components CheckShow installed components requirements testComponents CheckShow installed components requirements test
OptionsOpens mRemoteNG global settings and options dialogOptionsOpens mRemoteNG global settings and options dialog
- + + - -

Help Menu

-
- + +

Help Menu

+
+
- - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + -
ItemDescriptionItemDescription
mRemoteNG HelpShow help panel (this panel)mRemoteNG HelpShow help panel (this panel)
WebsiteGo to mRemoteNG websiteWebsiteGo to mRemoteNG website
DonateGo to mRemoteNG donation page. (Please help keep mRemoteNG awesome!)DonateGo to mRemoteNG donation page. (Please help keep mRemoteNG awesome!)
Support ForumGo to mRemoteNG suport forum (Best place is still chat for fast answers)Support ForumGo to mRemoteNG suport forum (Best place is still chat for fast answers)
Report a BugGo to github page to report a bug foundReport a BugGo to github page to report a bug found
Check for UpdatesOpens dialog to check for any updates of mRemoteNGCheck for UpdatesOpens dialog to check for any updates of mRemoteNG
AboutOpen about dialog for mRemoteNG (Shows contributors, changelog and more)AboutOpen about dialog for mRemoteNG (Shows contributors, changelog and more)
- + + - + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_navigation.htm b/mRemoteV1/Resources/Help/ui_navigation.htm index 141adffb..ddeb3876 100644 --- a/mRemoteV1/Resources/Help/ui_navigation.htm +++ b/mRemoteV1/Resources/Help/ui_navigation.htm @@ -1,134 +1,140 @@ - + Navigation - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
-

Introduction

-

-

-

Quick Reference

- +

Introduction

+

+

+

Quick Reference

+ - -

-

- mRemoteNG is using panels and tabs to stay organized but also to create a better - view of all multitasking that is being done inside the application. Because - of that it can be good to know some more information on how to work with panels - and tabs to get the most out of those features. -

-

Panels

-

- Panels are used to organize tabbed connections. This might seem - a bit confusing but its a great way to stay organized. Below is a few examples - of how to use panels to give you a hands on better view of them. -

-
    -
  • + +

    +

    + mRemoteNG is using panels and tabs to stay organized but also to create a better + view of all multitasking that is being done inside the application. Because + of that it can be good to know some more information on how to work with panels + and tabs to get the most out of those features. +

    +

    Panels

    +

    + Panels are used to organize tabbed connections. This might seem + a bit confusing but its a great way to stay organized. Below is a few examples + of how to use panels to give you a hands on better view of them. +

    +
      +
    • Test and Production - You can add 2 panels where you have the test servers are located and the other where production servers are running. -
    • -
    • +
    • +
    • Datacenters - Maybe you divide them into datacenters. -
    • -
    • +
    • +
    • Temp project - To see all servers you work on for a temporary project. -
    • -
    • +
    • +
    • Home vs Work - Maybe you are sneaky at work and want to login at home to check you machine at home for something while keeping work in its own panel. -
    • -
    • +
    • +
    • ...and many more -
    • -
    -

    - For this tutorial we will keep it simple with Domain A and Domain B. Where both - have their own panels. -

    - -

    Creating panels

    -

    - Usually panels are created using connections and folders to stay organized - automatic when making connections. However you can also create panels manually. - See below: -

    - -

    - Creating manual panels will make you able to organize tabs manually in mRemoteNG. - To then open a connection to the new panel then Right click on connection and use - "Connect (with options)" > Choose panel before connecting -

    -

    - The other option in the menu named "Connection Panels" will list all panels - in open in the current running mRemoteNG window. -

    -

    More options

    -

    - Right click menu for panels will give you a few more options for the panels: -

    - -
      -
    • Rename - Rename the panel
    • -
    • +
    • +
    +

    + For this tutorial we will keep it simple with Domain A and Domain B. Where both + have their own panels. +

    + +

    Creating panels

    +

    + Usually panels are created using connections and folders to stay organized + automatic when making connections. However you can also create panels manually. + See below: +

    + +

    + Creating manual panels will make you able to organize tabs manually in mRemoteNG. + To then open a connection to the new panel then Right click on connection and use + "Connect (with options)" > Choose panel before connecting +

    +

    + The other option in the menu named "Connection Panels" will list all panels + in open in the current running mRemoteNG window. +

    +

    More options

    +

    + Right click menu for panels will give you a few more options for the panels: +

    + +
      +
    • Rename - Rename the panel
    • +
    • Send To... - Send the whole panel to monitor/screen [number]. Note this is not a real window but a detachable panel. So if you double click the title the panel will go back to mRemoteNG and not fullscreen the window. -
    • -
    -

    Tabs

    -

    - Speaking plain the tabs are also the connections that is open in mRemoteNG. - There are few tips and tricks regarding tabs and we will try to list them here. - In the below examples we will give you examples of RDP and SSH connections. -

    -

    Right click conext menu

    -

    - The right click context menu allows you to trigger som additional actions on - tabs for example: Rename Tab, Duplicate Tab, Reconnect, Disconnect etc. Below - are the two context menus from RDP and SSH. -

    -
    -

    RDP context menu

    - -
    -
    -

    SSH context menu

    - -
    -

    - If you check the difference between the menus you can see that there are some - actions that differ depending on the connection. This is intentional since its - specific for the type of connection. -

    -

    - The default and always available menu items are: -

      + +
    +

    Tabs

    +

    + Speaking plain the tabs are also the connections that is open in mRemoteNG. + There are few tips and tricks regarding tabs and we will try to list them here. + In the below examples we will give you examples of RDP and SSH connections. +

    +

    Right click conext menu

    +

    + The right click context menu allows you to trigger som additional actions on + tabs for example: Rename Tab, Duplicate Tab, Reconnect, Disconnect etc. Below + are the two context menus from RDP and SSH. +

    +
    +

    RDP context menu

    + +
    +
    +

    SSH context menu

    + +
    +

    + If you check the difference between the menus you can see that there are some + actions that differ depending on the connection. This is intentional since its + specific for the type of connection. +

    +

    + The default and always available menu items are: +

    • Screenshot - Create a screenshot to Screenshot Manager
    • External Tools - Run external tool script/action
    • Rename Tab - Rename current tab
    • Duplicate Tab - Duplicate tab connection
    • Reconnect - Reconnect the current tab
    • - Disconnect - Disconnect the current tab (Double clicking the tab - will also disconnect the current tab. If you want to change this action then - go to Tools > Options > Tabs & Panels and uncheck - "Double click on tab closes it") + Disconnect - Disconnect the current tab (Double clicking the tab + will also disconnect the current tab. If you want to change this action then + go to Tools > Options > Tabs & Panels and uncheck + "Double click on tab closes it")
    • -
    - Click around and try it out. You will get the hang of it. -

    - - - +
+ Click around and try it out. You will get the hang of it. +

+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_notifications.htm b/mRemoteV1/Resources/Help/ui_notifications.htm index 34aa1619..13a24511 100644 --- a/mRemoteV1/Resources/Help/ui_notifications.htm +++ b/mRemoteV1/Resources/Help/ui_notifications.htm @@ -1,82 +1,82 @@ - + Notifications - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
- -

Introduction

-
-

- Notifications panel contains information for any errors or informational messages that - mRemoteNG triggers. Some example errors can be if there is a problem to connect, information - on lost connection and so much more. -

-

Settings for notifications

-
-

- Notification settings can be found in (Tools > Options > Notifications) below we will explain what - can be set and how they do affect for various troubleshooting. -

- + +

Introduction

+
+

+ Notifications panel contains information for any errors or informational messages that + mRemoteNG triggers. Some example errors can be if there is a problem to connect, information + on lost connection and so much more. +

+

Settings for notifications

+
+

+ Notification settings can be found in (Tools > Options > Notifications) below we will explain what + can be set and how they do affect for various troubleshooting. +

+ - -

Notifications general settings

- notification warning -

- This will tell mRemoteNG what type of messages and the level of messages to send to the panel. - It does not the level for the log that mRemoteNG has but only for panel output. -

-

There is also 2 different options mentioned below:

-
    -
  • + +

    Notifications general settings

    +notification warning +

    + This will tell mRemoteNG what type of messages and the level of messages to send to the panel. + It does not the level for the log that mRemoteNG has but only for panel output. +

    +

    There is also 2 different options mentioned below:

    +
      +
    • Show these message types - Level of messages to show in panel. (default: Warnings and Errors) -
    • -
    • +
    • +
    • Switch to Notifications panel on - If interface should switch to the panel when a level of message occurs (default: all enabled)
      - TIP! If you dont want the panel to show at all. Then unmark all options in - Switch to Notification panel on. Then the panel will not come up automatic. + TIP! If you dont want the panel to show at all. Then unmark all options in + Switch to Notification panel on. Then the panel will not come up automatic.
      -
    • -
    - +
  • +
+ - -

Logging settings

-

- Here you define the logging of messages. That is a continues log which can be used to backtrack - any error that has occurred. Good when for example reporting issues about mRemoteNG or to check - more details about problems. -

-
    -
  • + +

    Logging settings

    +

    + Here you define the logging of messages. That is a continues log which can be used to backtrack + any error that has occurred. Good when for example reporting issues about mRemoteNG or to check + more details about problems. +

    +
      +
    • Log path - Choose where the log should recide (default: Log to application directory) -
    • -
    • +
    • +
    • Log these message types - Level of logging to logfile (default: Informations, Warnings, Errors) -
    • -
    - +
  • +
+ - -

Popups settings

- popup warning -

- When items are selected here you will recieve a popup on the error that occurrs based on level - chosen in settings here. This can be useful if you do not want to use the notification area and only - get a popup if error occurs. (default: all off) -

- - - + +

Popups settings

+popup warning +

+ When items are selected here you will recieve a popup on the error that occurrs based on level + chosen in settings here. This can be useful if you do not want to use the notification area and only + get a popup if error occurs. (default: all off) +

+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_options.htm b/mRemoteV1/Resources/Help/ui_options.htm index c4e6b78e..7fe7be77 100644 --- a/mRemoteV1/Resources/Help/ui_options.htm +++ b/mRemoteV1/Resources/Help/ui_options.htm @@ -1,456 +1,512 @@ - + Options - - -
- Complete from nmat updates, please remove this div after review. Need help with missing information here. -
+ + +
+ Complete from nmat updates, please remove this div after review. Need help with missing information here. +
- -

Introduction

-
-

- Options window which can also be named settings is the window where you can personalize - your options for all of mRemoteNG. This includes how to set logging, credentials and so on. - Continue reading for the details of the different options here. -

-

Quick Reference

- - + +

Introduction

+
+

+ Options window which can also be named settings is the window where you can personalize + your options for all of mRemoteNG. This includes how to set logging, credentials and so on. + Continue reading for the details of the different options here. +

+

Quick Reference

+ + - -

Startup/Exit

-

- Options below are for the various settings for Startup/Exit of mRemoteNG. -

- - - - - - - + +

Startup/Exit

+

+ Options below are for the various settings for Startup/Exit of mRemoteNG. +

+
OptionDefaultDescription
+ + + + + + - - + + - - + This option will allow you to open the connection from which + you where connected to after last exit of application. + + + - - + + - -
+ Option + + Default + + Description +
Save connection on exit On Save to connection file/database on exit of mRemoteNG.
Reconnect to previously opened sessions on startup Off - This option will allow you to open the connection from which - you where connected to after last exit of application. -
Allow only a single instance of the application (mRemoteNG restart required) Off - Enforces and makes sure only a single instance of mRemoteNG is running on the - computer. + Enforces and makes sure only a single instance of mRemoteNG is running on the + computer.
Check proper installation of components at startup Off Opens the panel for Components Check on every startup.
- + + + - -

Appearance

-

- Various options for mRemoteNG appearance. -

- - - - - - - + +

Appearance

+

+ Various options for mRemoteNG appearance. +

+
OptionDefaultDescription
+ + + + + + - - + + - - + + - - + + - - + + - -
+ Option + + Default + + Description +
Language (Automatically Detect) Which language to use for the interface of mRemoteNG.
Show description tooltips in connection tree Off - Holding mouse over a item in connection tree will show a popout from mouse - with information. + Holding mouse over a item in connection tree will show a popout from mouse + with information.
Show full connections file path in window title Off - Adds the complete path to the title of mRemoteNG to where the connection file is - located. + Adds the complete path to the title of mRemoteNG to where the connection file is + located.
Always show notification area icon Off - Adds mRemoteNG to the taskbar in the OS. + Adds mRemoteNG to the taskbar in the OS.
Minimize to notification area Off - Will place mRemoteNG in taskbar on minimize. + Will place mRemoteNG in taskbar on minimize.
- + + + - -

Tabs & Panels

-

- Various settings for how tabs & panels should work in mRemoteNG. -

- - - - - - - + +

Tabs & Panels

+

+ Various settings for how tabs & panels should work in mRemoteNG. +

+
OptionDefaultDescription
+ + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - -
+ Option + + Default + + Description +
Always show panel tabs Off Will always show the tabs & panels in mRemoteNG
Open new tab to the right of the currently selected tab On - When active then open next tab on the right of the active selection in mRemoteNG. Turn - this off and next tab will open the next connection at the end of all tabs. + When active then open next tab on the right of the active selection in mRemoteNG. Turn + this off and next tab will open the next connection at the end of all tabs.
Show logon information on tab names Off Show your login in the connection tab.
Show protocols on tab names Off When active then in the tab show what protocol is used for the connection.
Identify quick connect tabs by adding the prefix "Quick:" Off - When active shows Quick: before the connection name in the tab connection to easier - identify what is a quick connection and what is a non quick connection. + When active shows Quick: before the connection name in the tab connection to easier + identify what is a quick connection and what is a non quick connection.
Double click on tab closes it On - When double clicking a tab it will close the connection but does not log you - out from the server. The connection in this case is active on the destination - server. + When double clicking a tab it will close the connection but does not log you + out from the server. The connection in this case is active on the destination + server.
Always show panel selection dialog when opening connections Off - Option to allow you to always select what panel to place the connection on. - If this is off it will create a General panel where the connection is placed - or use the connections set panel from the connection options. + Option to allow you to always select what panel to place the connection on. + If this is off it will create a General panel where the connection is placed + or use the connections set panel from the connection options.
Create a empty panel when mRemoteNG starts Off - On startup if this is active mRemoteNG will create a panel mentioned under - Panel Name: + On startup if this is active mRemoteNG will create a panel mentioned under + Panel Name:
- + + + - -

Notifications

- - + +

Notifications

+ + - -

Connections

-

-

- - - - - - - + +

Connections

+

+

+
OptionDefaultDescription
+ + + + + + - - + + - - + + - - + + - - + + - - + + - - - + + - - - + + - - - + + - -
+ Option + + Default + + Description +
Single click on connections opens it Off - In connection tree when this is active will try to connect on single click. By default - this is turned off to use double click to open connection. + In connection tree when this is active will try to connect on single click. By default + this is turned off to use double click to open connection.
Single click on opened connection in Connection Tree switches to the opened Connection Tab Off - Allows you to single click on a active connection in the connection tree to go to that - open connection in the tabs faster. + Allows you to single click on a active connection in the connection tree to go to that + open connection in the tabs faster.
Set hostname like display name when creating or renaming connections Off - Will make mRemoteNG try to use the remote host hostname to set the title of the tab - in mRemoteNG. + Will make mRemoteNG try to use the remote host hostname to set the title of the tab + in mRemoteNG.
Save connections after every exit On - When active mRemoteNG will save the connection tree to the active config - after every exit. If inactive then you have to save using - File > Save Connection File or keyboard shortcut - Ctrl+S + When active mRemoteNG will save the connection tree to the active config + after every exit. If inactive then you have to save using + File > Save Connection File or keyboard shortcut + Ctrl+S
Filter search matches in connection tree Off - Allows you to filter out the connections to which does not match - your filter search in the connection tree. If not active the search - will only select the filter to which you do search. + Allows you to filter out the connections to which does not match + your filter search in the connection tree. If not active the search + will only select the filter to which you do search.
RDP Reconnect count 5Value in seconds
+
+ Value in seconds
RDP Connection Timeout 20Value in seconds
+
+ Value in seconds
Auto save time in minutes (0 means disabled) 0Value in minutes
+
+ Value in minutes
When closing connections Warn me when closing connections - Various options of how mRemoteNG should act when you close connections. - The different options are listed below: -
    -
  • Warn me when closing connections
  • -
  • Warn me only when closing multiple connections
  • -
  • Warn me only when exiting mRemoteNG
  • -
  • Do not warn me when closing connections
  • -
- By default a warning will come up on closing a connection. Change this value - based on your prefered settings. + Various options of how mRemoteNG should act when you close connections. + The different options are listed below: +
    +
  • Warn me when closing connections
  • +
  • Warn me only when closing multiple connections
  • +
  • Warn me only when exiting mRemoteNG
  • +
  • Do not warn me when closing connections
  • +
+ By default a warning will come up on closing a connection. Change this value + based on your prefered settings.
- + + + - -

Credentials

-

- Options for credentials in mRemoteNG. The main purpose here - is that when you have empty username, password or domain field - then use below information. -

- - - - - - - + +

Credentials

+

+ Options for credentials in mRemoteNG. The main purpose here + is that when you have empty username, password or domain field + then use below information. +

+
OptionDefaultDescription
+ + + + + + - - + + - - + + - -
+ Option + + Default + + Description +
None On Use no specific settings on login
My Current credentials (Windows logon information) Off - This option will use the logon information for the OS. This is useful if you - are in a domain that uses specific credentials and want to login to servers - with those credentials. + This option will use the logon information for the OS. This is useful if you + are in a domain that uses specific credentials and want to login to servers + with those credentials.
The following: Off - Use one or two of the options below for the empty login or all of them. - For example if you have a different domain that you login to the servers with. + Use one or two of the options below for the empty login or all of them. + For example if you have a different domain that you login to the servers with.
- + + + - - -

SQL Server

-
- NOTE! To understand more about SQL Server connection please - See here -
- - - - - - - + + +

SQL Server

+
+ NOTE! To understand more about SQL Server connection please + + See here + +
+
OptionDefaultDescription
+ + + + + + - -
+ Option + + Default + + Description +
Use SQL Server to load & save connections Off Enable to fetch connections from a database.
- + + + - -

Updates

-

- Options for how mRemoteNG should check for updates from the website. -

- - - - - - - + +

Updates

+

+ Options for how mRemoteNG should check for updates from the website. +

+
OptionDefaultDescription
+ + + + + + - - + + - - + + - -
+ Option + + Default + + Description +
Check for updates at startup On (Every 14 days) - Here you can choose how often mRemoteNG checks for updates. - Standard is every 14 days + Here you can choose how often mRemoteNG checks for updates. + Standard is every 14 days
Release Channel: Stable - The main channel to use for mRemoteNG. Note that the channels are described under - the selection. Stable is suggested for normal usage but its always good to get - feedback on upcoming releases. + The main channel to use for mRemoteNG. Note that the channels are described under + the selection. Stable is suggested for normal usage but its always good to get + feedback on upcoming releases.
Use a proxy server to connect Off - Proxy to connect through to check for updates. This is not a proxy connection - for when you connect to a server but more to check for updates. + Proxy to connect through to check for updates. This is not a proxy connection + for when you connect to a server but more to check for updates.
- + + + - - -

Theme

-

- UI themes. This is not enabled by default but can be used - inside mRemoteNG. To enable themes you have to first - enable it in the checkbox at the bottom of the options. - Then restart mRemoteNG in order for it to work. -

-

- Default theme is: vs2015light -

-
- NOTE! To know more about themes and how to - create your own See Here -
- + + +

Theme

+

+ UI themes. This is not enabled by default but can be used + inside mRemoteNG. To enable themes you have to first + enable it in the checkbox at the bottom of the options. + Then restart mRemoteNG in order for it to work. +

+

+ Default theme is: vs2015light +

+
+ NOTE! To know more about themes and how to + create your own + + See Here + +
+ - - -

Security

- + + +

Security

+ - - -

Advanced

- - - - - - - + + +

Advanced

+
OptionDefaultDescription
+ + + + + + - - + + - - + + - - + + - - + + - - + + - -
+ Option + + Default + + Description +
Automatically get session information Off
Automatically try to reconnect when disconnected from server (RDP & ICA only) Off
Use UTF8 encoding for RDP "Load Balance info" property Off
Use custom PuTTY path: Off
To configure PuTTY sessions click this button: Launch PuTTY Will launch the putty agent so you can edit the sessions.
Maximum PuTTY and integrated external tools wait time: 2 seconds
- - - + + + + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_port_scan.htm b/mRemoteV1/Resources/Help/ui_port_scan.htm index a1120370..bd77b6d5 100644 --- a/mRemoteV1/Resources/Help/ui_port_scan.htm +++ b/mRemoteV1/Resources/Help/ui_port_scan.htm @@ -1,57 +1,58 @@ - + Port Scan - - -
- Complete from nmat updates, please remove this div after review. -
+ + +
+ Complete from nmat updates, please remove this div after review. +
- -

Introduction

-
-

- The Port Scan feature (under Tools > Port Scan) is similar to a nmap port scan. - It will scan a range of IP addresses and to determine if specific mRemoteNG supported - protocols are active. Hosts can then be bulk imported into mRemoteNG. -

- + +

Introduction

+
+

+ The Port Scan feature (under Tools > Port Scan) is similar to a nmap port scan. + It will scan a range of IP addresses and to determine if specific mRemoteNG supported + protocols are active. Hosts can then be bulk imported into mRemoteNG. +

+ - -

Use Case

-
-

- You've just inherited a new network with little to no documentation. - Inputting a range of IP addresses and scanning your entire network - should give you a good idea of what is currently online. - Importing those devices will then give you a quick - (relatively, scanning a large subnet will take a while) way to get into those devices. -

- + +

Use Case

+
+

+ You've just inherited a new network with little to no documentation. + Inputting a range of IP addresses and scanning your entire network + should give you a good idea of what is currently online. + Importing those devices will then give you a quick + (relatively, scanning a large subnet will take a while) way to get into those devices. +

+ - -

How to use

-
-
    -
  1. Start the Port Scan feature by clicking Tools > Port Scan in the menu bar.
  2. -
  3. Input your Start IP and End IP of the range you'd like to scan.
  4. -
  5. Enter the Start Port and End Port that mRemoteNG should test for. + +

    How to use

    +
    +
      +
    1. Start the Port Scan feature by clicking Tools > Port Scan in the menu bar.
    2. +
    3. Input your Start IP and End IP of the range you'd like to scan.
    4. +
    5. + Enter the Start Port and End Port that mRemoteNG should test for.
      - TIP! If you leave this at the default of 0 & 0, - the test will be for the default protocol ports that mRemoteNG supports. + TIP! If you leave this at the default of 0 & 0, + the test will be for the default protocol ports that mRemoteNG supports.
      -
    6. -
    7. Click Scan
    8. -
    9. Wait. Possibly a long time.
    10. -
    11. +
    12. +
    13. Click Scan
    14. +
    15. Wait. Possibly a long time.
    16. +
    17. The table will populate, and eventually you'll get a notification that the scan has completed. Alternatively, you can press Stop to end the scan at any time. -
    18. -
    19. Change the dropdown to the protocol you'd like to import and click Import.
    20. -
    - - - +
  6. +
  7. Change the dropdown to the protocol you'd like to import and click Import.
  8. +
+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_quick_connect.htm b/mRemoteV1/Resources/Help/ui_quick_connect.htm index 1123f605..a60e75c4 100644 --- a/mRemoteV1/Resources/Help/ui_quick_connect.htm +++ b/mRemoteV1/Resources/Help/ui_quick_connect.htm @@ -1,54 +1,54 @@ - - Quick Connect - + + Quick Connect + -
+
Complete from nmat updates, please remove this div after review. -
- -

+

+ +

The Quick Connect functionality of mRemoteNG allows you to quickly connect to a remote host using a variety of network protocols. -

-

Use Cases

-

+

+

Use Cases

+

The primary use case for Quick Connect is to connect to remote hosts when you already remember the DNS hostname/IP address and the appropriate protocol for the connection.

An additional use case is to connect to remote hosts saved as a connection quickly. -

+

-

Prerequisites

-
    +

    Prerequisites

    +
    • Knowledge of a DNS host name or IP address
    • Knowledge of an appropriate protocol to communicate with remote host
    • -
    -

    OR

    -
      +
    +

    OR

    +
    • A predefined mRemoteNG connection
    • -
    +
-

Using QuickConnect

+

Using QuickConnect

-

+

To use Quick Connect, ensure the Quick Connect toolbar is enabled by selecting View and then Quick Connect Toolbar.
Next, input a DNS host name or IP address into the box labeled "Connect". This box will also save previous entries during your session.
- Quick Connect Toolbar + Quick Connect Toolbar

- Quick Connect Toolbar + Quick Connect Toolbar

Select the appropriate network protocol by clicking the arrow next to the Connect box.
- Quick Connect Toolbar + Quick Connect Toolbar

If you wish to use an existing connection, select the globe icon next to the protocol button and select the appropriate connection. -

+

- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_screenshot_manager.htm b/mRemoteV1/Resources/Help/ui_screenshot_manager.htm index 7d1db7cd..783c3e01 100644 --- a/mRemoteV1/Resources/Help/ui_screenshot_manager.htm +++ b/mRemoteV1/Resources/Help/ui_screenshot_manager.htm @@ -1,62 +1,62 @@ - + Screenshot Manager - - - -
- Complete from nmat updates, please remove this div after review. -
+ + + +
+ Complete from nmat updates, please remove this div after review. +
-

Introduction

-

- The screenshot manager is a panel and tool that can be used to organize - and take screenshots inside mRemoteNG. -

+

Introduction

+

+ The screenshot manager is a panel and tool that can be used to organize + and take screenshots inside mRemoteNG. +

- -

Take a screenshot

-

- To take a screenshot of a instance its as easy as to right click on the - connection tab and press Screenshot and it will open the screenshot - manager. -

- - -

- On the left image you will see the right click menu for the connection tab. Clicking the - screenshot there will allow mRemoteNG to create a screenshot. -

-

- The right image is where the screenshots are stored in mRemoteNG. Here you can store - and then decide what to do with the images after you are done taking screenshots. -

- + +

Take a screenshot

+

+ To take a screenshot of a instance its as easy as to right click on the + connection tab and press Screenshot and it will open the screenshot + manager. +

+ + +

+ On the left image you will see the right click menu for the connection tab. Clicking the + screenshot there will allow mRemoteNG to create a screenshot. +

+

+ The right image is where the screenshots are stored in mRemoteNG. Here you can store + and then decide what to do with the images after you are done taking screenshots. +

+ - -

Editing

-

- The manager is a simple tool for saving and deleting screenshots. If you need to do - more with the screenshots then the suggestion is to open them in a third party app. - Here is what the manager allows you to do: -

    + +

    Editing

    +

    + The manager is a simple tool for saving and deleting screenshots. If you need to do + more with the screenshots then the suggestion is to open them in a third party app. + Here is what the manager allows you to do: +

    • Save
    • Save All
    • Delete
    • Delete All
    • -
    -

    -

    - Once you press save, a window to save the files will come up where you want to save - the screenshots. -

    -

    - Short summary of screenshot manager is that you can sit and create screenshots without - having to open a different manager all the time and instead let mRemoteNG create the - main screenshot which can be edited later on. -

    - - - +
+

+

+ Once you press save, a window to save the files will come up where you want to save + the screenshots. +

+

+ Short summary of screenshot manager is that you can sit and create screenshots without + having to open a different manager all the time and instead let mRemoteNG create the + main screenshot which can be edited later on. +

+ + + \ No newline at end of file diff --git a/mRemoteV1/Resources/Help/ui_sql_configuration.htm b/mRemoteV1/Resources/Help/ui_sql_configuration.htm index 1c652c95..1d0803e3 100644 --- a/mRemoteV1/Resources/Help/ui_sql_configuration.htm +++ b/mRemoteV1/Resources/Help/ui_sql_configuration.htm @@ -1,39 +1,39 @@ - - SQL Configuration - + + SQL Configuration + -
+
Complete from nmat updates, please remove this div after review. -
+
-

Warning!

-
+

Warning!

+
The SQL feature is in an early beta stage and not intended for use in an productive environment! I recommend you to do a full backup of your connections and settings before switching to SQL Server. -
-

Databases Supported

-
-

+

+

Databases Supported

+
+

The list below are databases which have been tested on for support. Note that other databases may be supported in the future. -

-
    +

    +
    • Microsoft™ SQL Server
    • -
    -

    Steps to configure your SQL Server

    -
    -
      +
+

Steps to configure your SQL Server

+
+
  1. Create a new Database called "mRemoteNG" on your SQL Server.
  2. Run the SQL Script for your DB type listed below in topic (SQL Table creation Scripts) on the newly created Database.
  3. Give the users that you want to grant access to the mRemoteNG Connections Database Read/Write permissions on the Database.
  4. -
-

Steps to configure mRemoteNG for SQL

-
-
    +
+

Steps to configure mRemoteNG for SQL

+
+
  1. Start mRemoteNG if it's not already running.
  2. Go to Tools - Options - SQL Server
  3. Check the box that says "Use SQL Server to load & save connections".
  4. @@ -42,24 +42,26 @@
  5. Click OK to apply the changes. The main window title should now change to "mRemoteNG | SQL Server".
  6. Now click on File - Save to update the tables on your SQL Server with the data from the loaded connections xml file. (Do not click File - New, this doesn't work yet)
  7. You should now be able to do everything you were able to do with the XML storage plus see the changes live on another mRemoteNG instance that is connected to the same Database.
  8. -
-

SQL Table creation Scripts

-
-
+ +

SQL Table creation Scripts

+
+
- - - - - - - - - + + + + + + + + +
Script (click on script below for your db type)Description
Microsoft™ SQL scriptMicrosoft™ SQL Server
Script (click on script below for your db type)Description
+ Microsoft™ SQL script + Microsoft™ SQL Server
-
+
- + \ No newline at end of file diff --git a/mRemoteV1/Resources/Images/TabExit.png b/mRemoteV1/Resources/Images/TabExit.png new file mode 100644 index 00000000..a70a2aba Binary files /dev/null and b/mRemoteV1/Resources/Images/TabExit.png differ diff --git a/mRemoteV1/Resources/Images/TabOption.png b/mRemoteV1/Resources/Images/TabOption.png new file mode 100644 index 00000000..455c453a Binary files /dev/null and b/mRemoteV1/Resources/Images/TabOption.png differ diff --git a/mRemoteV1/Resources/Images/TabOverflow.png b/mRemoteV1/Resources/Images/TabOverflow.png new file mode 100644 index 00000000..84619ba1 Binary files /dev/null and b/mRemoteV1/Resources/Images/TabOverflow.png differ diff --git a/mRemoteV1/Resources/Images/tab_add.png b/mRemoteV1/Resources/Images/tab_add.png new file mode 100644 index 00000000..d3b99364 Binary files /dev/null and b/mRemoteV1/Resources/Images/tab_add.png differ diff --git a/mRemoteV1/Resources/Images/tab_delete.png b/mRemoteV1/Resources/Images/tab_delete.png new file mode 100644 index 00000000..100da2f1 Binary files /dev/null and b/mRemoteV1/Resources/Images/tab_delete.png differ diff --git a/mRemoteV1/Resources/Images/tab_edit.png b/mRemoteV1/Resources/Images/tab_edit.png new file mode 100644 index 00000000..4c09c0fd Binary files /dev/null and b/mRemoteV1/Resources/Images/tab_edit.png differ diff --git a/mRemoteV1/Resources/Language/Language.Designer.cs b/mRemoteV1/Resources/Language/Language.Designer.cs index 14045330..ffef8a37 100644 --- a/mRemoteV1/Resources/Language/Language.Designer.cs +++ b/mRemoteV1/Resources/Language/Language.Designer.cs @@ -19,7 +19,7 @@ namespace mRemoteNG { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Language { @@ -2072,11 +2072,11 @@ namespace mRemoteNG { } /// - /// Looks up a localized string similar to The Windows security setting, "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing", is enabled. This setting is not compatible with {0}. + /// Looks up a localized string similar to The Windows security setting, "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing", is enabled. /// ///See the Microsoft Support article at http://support.microsoft.com/kb/811833 for more information. /// - ///{0} will now close.. + ///{0} is not fully FIPS compliant. Click OK to proceed at your own discretion, or Cancel to Exit.. /// internal static string strErrorFipsPolicyIncompatible { get { @@ -4435,7 +4435,7 @@ namespace mRemoteNG { } /// - /// Looks up a localized string similar to Warning: Restart is required to disable the themes or to completely apply a new one. + /// Looks up a localized string similar to Warning: Restart is required to commit any theme configuration change.. /// internal static string strOptionsThemeThemeChaangeWarning { get { diff --git a/mRemoteV1/Resources/Language/Language.cs-CZ.resx b/mRemoteV1/Resources/Language/Language.cs-CZ.resx index 3d98f7a8..e06a1ed3 100644 --- a/mRemoteV1/Resources/Language/Language.cs-CZ.resx +++ b/mRemoteV1/Resources/Language/Language.cs-CZ.resx @@ -654,13 +654,6 @@ Otevírám nový prázdný soubor seznamu spojení. Začifrování se nezdařilo. {0} - - V nastavení politik zabezepčení systému Windows je aktivována možnost "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing" (Systémová kryptografie: Pro šifrování, hashe a podpisy využívat algoritmy odpovídají FIPS") Toto nastavení není kompatibilní s {0}. - -Pro další informace navštivte článek podpory fy. Microsoft na http://support.microsoft.com/kb/811833 - -{0} se nyní ukončí. - Chyby diff --git a/mRemoteV1/Resources/Language/Language.de.resx b/mRemoteV1/Resources/Language/Language.de.resx index 45fb1bf6..4907e90f 100644 --- a/mRemoteV1/Resources/Language/Language.de.resx +++ b/mRemoteV1/Resources/Language/Language.de.resx @@ -630,9 +630,6 @@ Starte mit neuer Datei. Verschlüsselung fehlgeschlagen. {0} - - Die Sicherheitseinstellung von Windows "Systemkryptografie: Verwenden sie FIPS-konformen Algorithmus für Verschlüsselung, Hashing und Signatur" ist aktiviert. Diese Einstellung ist nicht kompatibel mit {0}. Weitere Informationen finden sie im Microsoft Support-Artikel unter http://support.microsoft.com/kb/811833. {0} wird jetzt beendet. - Fehler diff --git a/mRemoteV1/Resources/Language/Language.es-AR.resx b/mRemoteV1/Resources/Language/Language.es-AR.resx index 1a129f57..137b29f5 100644 --- a/mRemoteV1/Resources/Language/Language.es-AR.resx +++ b/mRemoteV1/Resources/Language/Language.es-AR.resx @@ -376,9 +376,6 @@ Descripción del Error: {1} La encriptación falló. {0} - - La configuración de seguridad de Windows, "criptografía de sistema: usar FIPS algoritmos compatibles para codificación, algoritmos hash y firma", está habilitada. Esta configuración no es compatible con {0}. Consulte el artículo de soporte técnico de Microsoft en http://support.microsoft.com/kb/811833 para obtener más información. {0} se cerrará. - Errores diff --git a/mRemoteV1/Resources/Language/Language.es.resx b/mRemoteV1/Resources/Language/Language.es.resx index a41667ef..9f854f17 100644 --- a/mRemoteV1/Resources/Language/Language.es.resx +++ b/mRemoteV1/Resources/Language/Language.es.resx @@ -618,13 +618,6 @@ Arrancando con un nuevo archivo de conexiones. Cifrado fallido. {0} - - La configuración de Seguridad de Windows, "Criptografia del sistema: Usar Algoritmos compatibles FIPS para Encripción, Hashing y Firma", esta habilitada. Esta configuración es incompatible con {0}. - -Ver el articulo de soporte de Microsoft en http://support.microsoft.com/kb/811833 Para más información. - -{0} Se Cerrará. - Errores diff --git a/mRemoteV1/Resources/Language/Language.fr.resx b/mRemoteV1/Resources/Language/Language.fr.resx index 93a15347..84fe5c4b 100644 --- a/mRemoteV1/Resources/Language/Language.fr.resx +++ b/mRemoteV1/Resources/Language/Language.fr.resx @@ -608,12 +608,6 @@ Si la vérification des composants ou l'utilisation d'ICA échoue malgré tout, Échec du chiffrement.{0} - - Les paramètres de sécurité Windows, "Système de cryptographie: Utilise FIPS, algorithmes compatible pour le cryptage, hachage et signature", est activé. Ce paramètre n'est pas compatible avec {0}. -Consultez l'article du support de Microsoft pour plus d'informations http://support.microsoft.com/kb/811833 - -{0} va maintenant se fermer. - Erreurs diff --git a/mRemoteV1/Resources/Language/Language.it.resx b/mRemoteV1/Resources/Language/Language.it.resx index f4e50cd4..27fdf604 100644 --- a/mRemoteV1/Resources/Language/Language.it.resx +++ b/mRemoteV1/Resources/Language/Language.it.resx @@ -613,13 +613,6 @@ Creazione di un nuovo file delle connessioni. Criptaggio fallito. {0} - - L'impostazione Windows di sicurezza "Crittografia di sistema: utilizza algoritmi FIPS compatibili per crittografia, hash e firma" è abilitata. Tale impostazione non è compatibile con {0}. - -Visualizza il supporto Microsoft http://support.microsoft.com/kb/811833/it per ottenere maggiori informazioni. - -{0} sarà chiuso. - Errori diff --git a/mRemoteV1/Resources/Language/Language.ja-JP.resx b/mRemoteV1/Resources/Language/Language.ja-JP.resx index ef9d4ff5..650d4e8d 100644 --- a/mRemoteV1/Resources/Language/Language.ja-JP.resx +++ b/mRemoteV1/Resources/Language/Language.ja-JP.resx @@ -664,13 +664,6 @@ Starting with new connections file. 暗号化に失敗しました:{0} - - The Windows security setting, "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing", is enabled. This setting is not compatible with {0}. - -See the Microsoft Support article at http://support.microsoft.com/kb/811833 for more information. - -{0} will now close. - エラー diff --git a/mRemoteV1/Resources/Language/Language.ko-KR.resx b/mRemoteV1/Resources/Language/Language.ko-KR.resx index d7173f34..ba44d2f4 100644 --- a/mRemoteV1/Resources/Language/Language.ko-KR.resx +++ b/mRemoteV1/Resources/Language/Language.ko-KR.resx @@ -791,11 +791,6 @@ VncSharp 제어 버전 {0} 암호화에 실패. {0} - - Windows 보안 설정 인 "시스템 암호화 : 암호화, 해시 및 서명에 FIPS 호환 알고리즘 사용"이 사용됩니다. 이 설정은 {0}과 호환되지 않습니다. - -자세한 내용은 http://support.microsoft.com/kb/811833에서 Microsoft 지원 문서를 참조하십시오. - 오류 diff --git a/mRemoteV1/Resources/Language/Language.nb-NO.resx b/mRemoteV1/Resources/Language/Language.nb-NO.resx index 877450fd..22e51b82 100644 --- a/mRemoteV1/Resources/Language/Language.nb-NO.resx +++ b/mRemoteV1/Resources/Language/Language.nb-NO.resx @@ -625,13 +625,6 @@ Starter med ny tilkoblingsfil. Kryptering mislyktes. {0} - - Innstillingen for Windows-sikkerhet, "Systemkryptografi: Bruk FIPS-kompatible algoritmer til kryptering, nummerering og signering", er aktivert. Denne innstillingen er ikke kompatibel med {0}. - -Se Microsoft Support-artikkelen på http://support.microsoft.com/kb/811833 for mer informasjon. - -{0} vil bli avsluttet. - Feil diff --git a/mRemoteV1/Resources/Language/Language.nl.resx b/mRemoteV1/Resources/Language/Language.nl.resx index 86b083a0..ce32286f 100644 --- a/mRemoteV1/Resources/Language/Language.nl.resx +++ b/mRemoteV1/Resources/Language/Language.nl.resx @@ -625,13 +625,6 @@ Beginnen met nieuwe Connectie bestand. Encryptie is mislukt. {0} - - De beveiligingsinstelling voor Windows, "Systeemcryptografie: gebruik FIPS-compatibele algoritmes voor codering, hashing en ondertekening", is ingeschakeld. Deze instelling is niet compatibel met {0}. - -Zie het Microsoft Support artikel op http://support.microsoft.com/kb/811833 voor meer informatie. - -{0} wordt nu gesloten. - Foutmeldingen diff --git a/mRemoteV1/Resources/Language/Language.pt.resx b/mRemoteV1/Resources/Language/Language.pt.resx index a29b6cf9..17a388a6 100644 --- a/mRemoteV1/Resources/Language/Language.pt.resx +++ b/mRemoteV1/Resources/Language/Language.pt.resx @@ -600,9 +600,6 @@ Descrição do erro: {1} Falha de descriptografia. {0} - - A configuração de segurança do Windows, "criptografia de sistema: usar FIPS compatível com algoritmos para criptografia, hash e assinatura", está habilitado. Essa configuração não é compatível com {0}. Consulte o artigo do Microsoft Support em http://support.microsoft.com/kb/811833 para obter mais informações. {0} agora vai ser fechado. - Erros diff --git a/mRemoteV1/Resources/Language/Language.resx b/mRemoteV1/Resources/Language/Language.resx index 889a9031..e8b94216 100644 --- a/mRemoteV1/Resources/Language/Language.resx +++ b/mRemoteV1/Resources/Language/Language.resx @@ -655,11 +655,11 @@ Starting with new connections file. Encryption failed. {0} - The Windows security setting, "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing", is enabled. This setting is not compatible with {0}. + The Windows security setting, "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing", is enabled. See the Microsoft Support article at http://support.microsoft.com/kb/811833 for more information. -{0} will now close. +{0} is not fully FIPS compliant. Click OK to proceed at your own discretion, or Cancel to Exit. Errors @@ -2585,7 +2585,7 @@ This page will walk you through the process of upgrading your connections file o Type the new theme name - Warning: Restart is required to disable the themes or to completely apply a new one + Warning: Restart is required to commit any theme configuration change. No themes are loaded, check that the default mRemoteNG themes exist in the 'themes' folder diff --git a/mRemoteV1/Resources/Language/Language.ru.resx b/mRemoteV1/Resources/Language/Language.ru.resx index 39758344..c7ee50b7 100644 --- a/mRemoteV1/Resources/Language/Language.ru.resx +++ b/mRemoteV1/Resources/Language/Language.ru.resx @@ -630,13 +630,6 @@ VncSharp Control Version {0} Не удалось зашифровать. {0} - - - Настройки системы безопасности Windows: "Использование системной криптографии FIPS-совместимых алгоритмов шифрования, хеширования и подписывания», включено. Эта установка не совместима с {0}. - -См. статью Microsoft Support на http://support.microsoft.com/kb/811833 для получения дополнительной информации. - -{0} будет закрыто. Ошибки diff --git a/mRemoteV1/Resources/Language/Language.tr-TR.resx b/mRemoteV1/Resources/Language/Language.tr-TR.resx index c64c5721..8b69ebc8 100644 --- a/mRemoteV1/Resources/Language/Language.tr-TR.resx +++ b/mRemoteV1/Resources/Language/Language.tr-TR.resx @@ -675,13 +675,6 @@ Normal bağlantı dosyaları için lütfen Dosya - Bağlantıları Yükle'yi kul Şifreleme başarısız. {0} - - Windows güvenlik ayarlarında "Sistem şifrelemesi: FIPS uyumlu algoritmaları, karıştırma ve imzalama" açıldı. Bu ayarlar {0} ile uyumlu değil. - -Daha fazla bilgi için http://support.microsoft.com/kb/811833 adresindeki Microsoft Destk makalesine bakın. - -{0} şimdi kapanacak. - Hatalar diff --git a/mRemoteV1/Resources/Language/Language.uk.resx b/mRemoteV1/Resources/Language/Language.uk.resx index 0f808cf5..27f46871 100644 --- a/mRemoteV1/Resources/Language/Language.uk.resx +++ b/mRemoteV1/Resources/Language/Language.uk.resx @@ -616,13 +616,6 @@ VncSharp Control Version {0} Не вдалося зашифрувати. {0} - - Налаштування системи безпеки Windows: "Використання системної криптографії FIPS-сумісних алгоритмів шифрування, хешування та підписування», включено. Це налаштування не сумісне з {0}. - -Див. статтю Microsoft Support на http://support.microsoft.com/kb/811833 для отримання додаткової інформації. - -{0} буде закрито. - Помилки diff --git a/mRemoteV1/Resources/Language/Language.zh-CN.resx b/mRemoteV1/Resources/Language/Language.zh-CN.resx index 8c1f8a6c..eee16342 100644 --- a/mRemoteV1/Resources/Language/Language.zh-CN.resx +++ b/mRemoteV1/Resources/Language/Language.zh-CN.resx @@ -646,11 +646,6 @@ VncSharp 版本 {0} 加密失败。{0} - - Windows 安全设置中已启用"系统加密:使用 FIPS 兼容算法进行加密、散列和签名操作"。此设置与 {0} 不兼容。 -请参阅 Microsoft 支持文章中的详细信息:http://support.microsoft.com/kb/811833 -{0} 即将关闭。 - 错误 diff --git a/mRemoteV1/Resources/Language/Language.zh-TW.resx b/mRemoteV1/Resources/Language/Language.zh-TW.resx index 3b16b76e..45d1a777 100644 --- a/mRemoteV1/Resources/Language/Language.zh-TW.resx +++ b/mRemoteV1/Resources/Language/Language.zh-TW.resx @@ -592,13 +592,6 @@ VncSharp Control 版本 {0} 加密失敗。 {0} - - Windows 安全性設定,「系統加密編譯: 使用 FIPS 相容演算法於加密,雜湊,以及簽章」已啟用。 此設定與 {0} 不相容。 - -更多資訊請查看 Microsoft Support 文章於 http://support.microsoft.com/kb/811833? - -{0} 將關閉。 - 錯誤 diff --git a/mRemoteV1/Resources/PuTTYNG.exe b/mRemoteV1/Resources/PuTTYNG.exe index ca9cea48..5cb31dee 100644 Binary files a/mRemoteV1/Resources/PuTTYNG.exe and b/mRemoteV1/Resources/PuTTYNG.exe differ diff --git a/mRemoteV1/Resources/Themes/darcula.vstheme b/mRemoteV1/Resources/Themes/darcula.vstheme index 9958fff5..cd40e78b 100644 --- a/mRemoteV1/Resources/Themes/darcula.vstheme +++ b/mRemoteV1/Resources/Themes/darcula.vstheme @@ -106,8 +106,8 @@ - - + + diff --git a/mRemoteV1/Resources/Tiles/mRemoteNG.VisualElementsManifest.xml b/mRemoteV1/Resources/Tiles/mRemoteNG.VisualElementsManifest.xml index 1976da8a..21d61de8 100644 --- a/mRemoteV1/Resources/Tiles/mRemoteNG.VisualElementsManifest.xml +++ b/mRemoteV1/Resources/Tiles/mRemoteNG.VisualElementsManifest.xml @@ -1,8 +1,8 @@ - - + + \ No newline at end of file diff --git a/mRemoteV1/Schemas/mremoteng_confcons_v2_5.xsd b/mRemoteV1/Schemas/mremoteng_confcons_v2_5.xsd index eea55c96..2364b621 100644 --- a/mRemoteV1/Schemas/mremoteng_confcons_v2_5.xsd +++ b/mRemoteV1/Schemas/mremoteng_confcons_v2_5.xsd @@ -1,135 +1,135 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mRemoteV1/Schemas/mremoteng_confcons_v2_6.xsd b/mRemoteV1/Schemas/mremoteng_confcons_v2_6.xsd index e9df6b67..f472fec3 100644 --- a/mRemoteV1/Schemas/mremoteng_confcons_v2_6.xsd +++ b/mRemoteV1/Schemas/mremoteng_confcons_v2_6.xsd @@ -1,147 +1,147 @@  + + targetNamespace="http://mremoteng.org" + xmlns="http://mremoteng.org" + xmlns:mrng="http://mremoteng.org" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + elementFormDefault="unqualified"> - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/mRemoteV1/Schemas/mremoteng_confcons_v2_7.xsd b/mRemoteV1/Schemas/mremoteng_confcons_v2_7.xsd index ad155709..32a3c499 100644 --- a/mRemoteV1/Schemas/mremoteng_confcons_v2_7.xsd +++ b/mRemoteV1/Schemas/mremoteng_confcons_v2_7.xsd @@ -1,148 +1,148 @@  + - - - - - - - - - - - - - - - - - + targetNamespace="http://mremoteng.org" + elementFormDefault="unqualified" + xmlns="http://mremoteng.org" + xmlns:mrng="http://mremoteng.org" + xmlns:xs="http://www.w3.org/2001/XMLSchema"> - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mRemoteV1/Schemas/mremoteng_credrepo_list_v1_0.xsd b/mRemoteV1/Schemas/mremoteng_credrepo_list_v1_0.xsd index 4f498b76..76a4750a 100644 --- a/mRemoteV1/Schemas/mremoteng_credrepo_list_v1_0.xsd +++ b/mRemoteV1/Schemas/mremoteng_credrepo_list_v1_0.xsd @@ -1,26 +1,26 @@  + + targetNamespace="http://mremoteng.org" + elementFormDefault="qualified" + xmlns="http://mremoteng.org" + xmlns:mrng="http://mremoteng.org" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + version="1.0"> - - - - - - + + + + + + + + + + + + + + - - - - - - - - \ No newline at end of file diff --git a/mRemoteV1/Schemas/mremoteng_creds_v1_0.xsd b/mRemoteV1/Schemas/mremoteng_creds_v1_0.xsd index 8ad81340..13e176f2 100644 --- a/mRemoteV1/Schemas/mremoteng_creds_v1_0.xsd +++ b/mRemoteV1/Schemas/mremoteng_creds_v1_0.xsd @@ -1,32 +1,32 @@  + + targetNamespace="http://mremoteng.org" + elementFormDefault="qualified" + xmlns="http://mremoteng.org" + xmlns:mrng="http://mremoteng.org" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + version="1.0"> - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - \ No newline at end of file diff --git a/mRemoteV1/Security/Authentication/PasswordAuthenticator.cs b/mRemoteV1/Security/Authentication/PasswordAuthenticator.cs index 83bf82a6..8c105cd7 100644 --- a/mRemoteV1/Security/Authentication/PasswordAuthenticator.cs +++ b/mRemoteV1/Security/Authentication/PasswordAuthenticator.cs @@ -14,7 +14,9 @@ namespace mRemoteNG.Security.Authentication public int MaxAttempts { get; set; } = 3; public SecureString LastAuthenticatedPassword { get; private set; } - public PasswordAuthenticator(ICryptographyProvider cryptographyProvider, string cipherText, Func> authenticationRequestor) + public PasswordAuthenticator(ICryptographyProvider cryptographyProvider, + string cipherText, + Func> authenticationRequestor) { _cryptographyProvider = cryptographyProvider.ThrowIfNull(nameof(cryptographyProvider)); _cipherText = cipherText.ThrowIfNullOrEmpty(nameof(cipherText)); @@ -42,8 +44,10 @@ namespace mRemoteNG.Security.Authentication password = providedPassword.First(); if (password == null || password.Length == 0) break; } + attempts++; } + return authenticated; } } diff --git a/mRemoteV1/Security/BlockCipherEngines.cs b/mRemoteV1/Security/BlockCipherEngines.cs index 88932b87..45f89d01 100644 --- a/mRemoteV1/Security/BlockCipherEngines.cs +++ b/mRemoteV1/Security/BlockCipherEngines.cs @@ -1,5 +1,5 @@ - -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming + namespace mRemoteNG.Security { public enum BlockCipherEngines diff --git a/mRemoteV1/Security/BlockCipherModes.cs b/mRemoteV1/Security/BlockCipherModes.cs index 11d2e932..cb1cfd27 100644 --- a/mRemoteV1/Security/BlockCipherModes.cs +++ b/mRemoteV1/Security/BlockCipherModes.cs @@ -1,5 +1,5 @@ - -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming + namespace mRemoteNG.Security { public enum BlockCipherModes diff --git a/mRemoteV1/Security/EncryptedSecureString.cs b/mRemoteV1/Security/EncryptedSecureString.cs index 9b66713d..848de5d4 100644 --- a/mRemoteV1/Security/EncryptedSecureString.cs +++ b/mRemoteV1/Security/EncryptedSecureString.cs @@ -1,6 +1,7 @@ using System.Security; using mRemoteNG.Security.SymmetricEncryption; using Org.BouncyCastle.Security; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Security @@ -51,7 +52,7 @@ namespace mRemoteNG.Security { machineKeyString += (char)random.Next(33, 126); } - + return machineKeyString.ConvertToSecureString(); } } diff --git a/mRemoteV1/Security/Factories/CryptoProviderFactoryFromSettings.cs b/mRemoteV1/Security/Factories/CryptoProviderFactoryFromSettings.cs index 16052ed8..7873e992 100644 --- a/mRemoteV1/Security/Factories/CryptoProviderFactoryFromSettings.cs +++ b/mRemoteV1/Security/Factories/CryptoProviderFactoryFromSettings.cs @@ -4,7 +4,9 @@ { public ICryptographyProvider Build() { - var provider = new CryptoProviderFactory(Settings.Default.EncryptionEngine, Settings.Default.EncryptionBlockCipherMode).Build(); + var provider = + new CryptoProviderFactory(Settings.Default.EncryptionEngine, Settings.Default.EncryptionBlockCipherMode) + .Build(); provider.KeyDerivationIterations = Settings.Default.EncryptionKeyDerivationIterations; return provider; } diff --git a/mRemoteV1/Security/Factories/CryptoProviderFactoryFromXml.cs b/mRemoteV1/Security/Factories/CryptoProviderFactoryFromXml.cs index 69da8ff4..6d4d5d55 100644 --- a/mRemoteV1/Security/Factories/CryptoProviderFactoryFromXml.cs +++ b/mRemoteV1/Security/Factories/CryptoProviderFactoryFromXml.cs @@ -21,8 +21,10 @@ namespace mRemoteNG.Security.Factories ICryptographyProvider cryptoProvider; try { - var engine = (BlockCipherEngines)Enum.Parse(typeof(BlockCipherEngines), _element?.Attribute("EncryptionEngine")?.Value ?? ""); - var mode = (BlockCipherModes)Enum.Parse(typeof(BlockCipherModes), _element?.Attribute("BlockCipherMode")?.Value ?? ""); + var engine = (BlockCipherEngines)Enum.Parse(typeof(BlockCipherEngines), + _element?.Attribute("EncryptionEngine")?.Value ?? ""); + var mode = (BlockCipherModes)Enum.Parse(typeof(BlockCipherModes), + _element?.Attribute("BlockCipherMode")?.Value ?? ""); cryptoProvider = new CryptoProviderFactory(engine, mode).Build(); var keyDerivationIterations = int.Parse(_element?.Attribute("KdfIterations")?.Value ?? ""); diff --git a/mRemoteV1/Security/KeyDerivation/IKeyDerivationFunction.cs b/mRemoteV1/Security/KeyDerivation/IKeyDerivationFunction.cs index 5b081e93..ee3c7770 100644 --- a/mRemoteV1/Security/KeyDerivation/IKeyDerivationFunction.cs +++ b/mRemoteV1/Security/KeyDerivation/IKeyDerivationFunction.cs @@ -1,5 +1,4 @@ - -namespace mRemoteNG.Security.KeyDerivation +namespace mRemoteNG.Security.KeyDerivation { public interface IKeyDerivationFunction { diff --git a/mRemoteV1/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs b/mRemoteV1/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs index 8d01c88b..c34bfc3e 100644 --- a/mRemoteV1/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs +++ b/mRemoteV1/Security/KeyDerivation/Pkcs5S2KeyGenerator.cs @@ -28,7 +28,7 @@ namespace mRemoteNG.Security.KeyDerivation var keyGenerator = new Pkcs5S2ParametersGenerator(); keyGenerator.Init(passwordInBytes, salt, _iterations); - var keyParameter = (KeyParameter) keyGenerator.GenerateDerivedMacParameters(_keyBitSize); + var keyParameter = (KeyParameter)keyGenerator.GenerateDerivedMacParameters(_keyBitSize); var keyBytes = keyParameter.GetKey(); return keyBytes; } diff --git a/mRemoteV1/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs b/mRemoteV1/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs index 46bf1616..86ba562a 100644 --- a/mRemoteV1/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs +++ b/mRemoteV1/Security/PasswordCreation/PasswordIncludesSpecialCharactersConstraint.cs @@ -10,7 +10,7 @@ namespace mRemoteNG.Security.PasswordCreation { private readonly int _minimumCount; - public IEnumerable SpecialCharacters { get; } = new []{'!','@','#','$','%','^','&','*'}; + public IEnumerable SpecialCharacters { get; } = new[] {'!', '@', '#', '$', '%', '^', '&', '*'}; public string ConstraintHint { get; } @@ -22,14 +22,15 @@ namespace mRemoteNG.Security.PasswordCreation _minimumCount = minimumCount; } - public PasswordIncludesSpecialCharactersConstraint(IEnumerable specialCharacters, int minimumCount = 1) + public PasswordIncludesSpecialCharactersConstraint(IEnumerable specialCharacters, int minimumCount = 1) : this(minimumCount) { if (specialCharacters == null) throw new ArgumentNullException(nameof(specialCharacters)); SpecialCharacters = specialCharacters; - ConstraintHint = string.Format(Language.strPasswordConstainsSpecialCharactersConstraintHint, _minimumCount, string.Concat(SpecialCharacters)); + ConstraintHint = string.Format(Language.strPasswordConstainsSpecialCharactersConstraintHint, _minimumCount, + string.Concat(SpecialCharacters)); } public bool Validate(SecureString password) diff --git a/mRemoteV1/Security/PasswordCreation/PasswordLengthConstraint.cs b/mRemoteV1/Security/PasswordCreation/PasswordLengthConstraint.cs index 0c675814..adbdb17b 100644 --- a/mRemoteV1/Security/PasswordCreation/PasswordLengthConstraint.cs +++ b/mRemoteV1/Security/PasswordCreation/PasswordLengthConstraint.cs @@ -18,7 +18,8 @@ namespace mRemoteNG.Security.PasswordCreation if (maxLength <= 0) throw new ArgumentException($"{nameof(maxLength)} must be a positive, non-zero value."); if (maxLength < minimumLength) - throw new ArgumentException($"{nameof(maxLength)} must be greater than or equal to {nameof(minimumLength)}."); + throw new ArgumentException( + $"{nameof(maxLength)} must be greater than or equal to {nameof(minimumLength)}."); _minLength = minimumLength; _maxLength = maxLength; diff --git a/mRemoteV1/Security/RandomGenerator.cs b/mRemoteV1/Security/RandomGenerator.cs index 286caddf..7687080a 100644 --- a/mRemoteV1/Security/RandomGenerator.cs +++ b/mRemoteV1/Security/RandomGenerator.cs @@ -13,12 +13,14 @@ namespace mRemoteNG.Security var randomGen = new SecureRandom(); var stringBuilder = new StringBuilder(); - const string availableChars = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+|[]{};:',./<>?"; + const string availableChars = + @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+|[]{};:',./<>?"; for (var x = 0; x < length; x++) { var randomIndex = randomGen.Next(availableChars.Length - 1); stringBuilder.Append(availableChars[randomIndex]); } + return stringBuilder.ToString(); } } diff --git a/mRemoteV1/Security/SaveFilter.cs b/mRemoteV1/Security/SaveFilter.cs index 7216e82d..db3a086f 100644 --- a/mRemoteV1/Security/SaveFilter.cs +++ b/mRemoteV1/Security/SaveFilter.cs @@ -1,26 +1,25 @@ - namespace mRemoteNG.Security { - public class SaveFilter - { - public SaveFilter(bool disableEverything = false) - { - if (disableEverything) return; - SaveUsername = true; - SavePassword = true; - SaveDomain = true; - SaveCredentialId = true; + public class SaveFilter + { + public SaveFilter(bool disableEverything = false) + { + if (disableEverything) return; + SaveUsername = true; + SavePassword = true; + SaveDomain = true; + SaveCredentialId = true; SaveInheritance = true; - } + } - public bool SaveUsername { get; set; } + public bool SaveUsername { get; set; } - public bool SavePassword { get; set; } + public bool SavePassword { get; set; } - public bool SaveDomain { get; set; } + public bool SaveDomain { get; set; } public bool SaveCredentialId { get; set; } - public bool SaveInheritance { get; set; } - } + public bool SaveInheritance { get; set; } + } } \ No newline at end of file diff --git a/mRemoteV1/Security/SymmetricEncryption/AeadCryptographyProvider.cs b/mRemoteV1/Security/SymmetricEncryption/AeadCryptographyProvider.cs index 850da78d..c8e0635c 100644 --- a/mRemoteV1/Security/SymmetricEncryption/AeadCryptographyProvider.cs +++ b/mRemoteV1/Security/SymmetricEncryption/AeadCryptographyProvider.cs @@ -16,6 +16,7 @@ using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Security.SymmetricEncryption @@ -115,7 +116,8 @@ namespace mRemoteNG.Security.SymmetricEncryption //User Error Checks if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength) - throw new ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", nameof(password)); + throw new ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", + nameof(password)); if (secretMessage == null || secretMessage.Length == 0) throw new ArgumentException(@"Secret Message Required!", nameof(secretMessage)); @@ -170,6 +172,7 @@ namespace mRemoteNG.Security.SymmetricEncryption //Write Cipher Text binaryWriter.Write(cipherText); } + return combinedStream.ToArray(); } @@ -180,21 +183,27 @@ namespace mRemoteNG.Security.SymmetricEncryption return decryptedText; } - private string SimpleDecryptWithPassword(string encryptedMessage, SecureString decryptionKey, int nonSecretPayloadLength = 0) + private string SimpleDecryptWithPassword(string encryptedMessage, + SecureString decryptionKey, + int nonSecretPayloadLength = 0) { 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); + var plainText = SimpleDecryptWithPassword(cipherText, decryptionKey.ConvertToUnsecureString(), + nonSecretPayloadLength); return plainText == null ? null : _encoding.GetString(plainText); } - private byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0) + private byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, + string password, + int nonSecretPayloadLength = 0) { //User Error Checks if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength) - throw new ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", nameof(password)); + throw new ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", + nameof(password)); if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException(@"Encrypted Message Required!", nameof(encryptedMessage)); @@ -227,13 +236,14 @@ namespace mRemoteNG.Security.SymmetricEncryption //Grab Nonce var nonce = cipherReader.ReadBytes(NonceBitSize / 8); - + var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload); _aeadBlockCipher.Init(false, parameters); //Decrypt Cipher Text - var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length); - var plainText = new byte[_aeadBlockCipher.GetOutputSize(cipherText.Length)]; + var cipherText = + cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length); + var plainText = new byte[_aeadBlockCipher.GetOutputSize(cipherText.Length)]; try { diff --git a/mRemoteV1/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs b/mRemoteV1/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs index 5ebd0eb3..5cfa17ef 100644 --- a/mRemoteV1/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs +++ b/mRemoteV1/Security/SymmetricEncryption/LegacyRijndaelCryptographyProvider.cs @@ -9,69 +9,70 @@ using mRemoteNG.Messages; namespace mRemoteNG.Security.SymmetricEncryption { - public class LegacyRijndaelCryptographyProvider : ICryptographyProvider - { + public class LegacyRijndaelCryptographyProvider : ICryptographyProvider + { public int BlockSizeInBytes { get; } public BlockCipherEngines CipherEngine { get; } public BlockCipherModes CipherMode { get; } - public int KeyDerivationIterations { get; set; } + public int KeyDerivationIterations { get; set; } - public LegacyRijndaelCryptographyProvider() - { - BlockSizeInBytes = 16; - } + public LegacyRijndaelCryptographyProvider() + { + BlockSizeInBytes = 16; + } public string Encrypt(string strToEncrypt, SecureString strSecret) - { - if (strToEncrypt == "" || strSecret.Length == 0) - return strToEncrypt; - - try - { - var rd = new RijndaelManaged(); + { + if (strToEncrypt == "" || strSecret.Length == 0) + return strToEncrypt; + + try + { + var rd = new RijndaelManaged(); var md5 = new MD5CryptoServiceProvider(); var key = md5.ComputeHash(Encoding.UTF8.GetBytes(strSecret.ConvertToUnsecureString())); - - md5.Clear(); - rd.Key = key; - rd.GenerateIV(); + + md5.Clear(); + rd.Key = key; + rd.GenerateIV(); var iv = rd.IV; var ms = new MemoryStream(); - - ms.Write(iv, 0, iv.Length); + + ms.Write(iv, 0, iv.Length); var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write); var data = Encoding.UTF8.GetBytes(strToEncrypt); - - cs.Write(data, 0, data.Length); - cs.FlushFinalBlock(); + + cs.Write(data, 0, data.Length); + cs.FlushFinalBlock(); var encdata = ms.ToArray(); - cs.Close(); - rd.Clear(); - - return Convert.ToBase64String(encdata); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strErrorEncryptionFailed, ex.Message)); - } - - return strToEncrypt; - } - - public string Decrypt(string ciphertextBase64, SecureString password) - { - if (string.IsNullOrEmpty(ciphertextBase64) || password.Length == 0) - return ciphertextBase64; - - try - { + cs.Close(); + rd.Clear(); + + return Convert.ToBase64String(encdata); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + string.Format(Language.strErrorEncryptionFailed, ex.Message)); + } + + return strToEncrypt; + } + + public string Decrypt(string ciphertextBase64, SecureString password) + { + if (string.IsNullOrEmpty(ciphertextBase64) || password.Length == 0) + return ciphertextBase64; + + try + { var plaintext = ""; using (var rijndaelManaged = new RijndaelManaged()) @@ -89,7 +90,8 @@ namespace mRemoteNG.Security.SymmetricEncryption memoryStream.Read(iv, 0, iv.Length); rijndaelManaged.IV = iv; - var cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(), CryptoStreamMode.Read); + var cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(), + CryptoStreamMode.Read); using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8, true)) { plaintext = streamReader.ReadToEnd(); @@ -99,11 +101,11 @@ namespace mRemoteNG.Security.SymmetricEncryption return plaintext; } - catch (Exception ex) - { - //Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strErrorDecryptionFailed, ex.Message)); + catch (Exception ex) + { + //Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strErrorDecryptionFailed, ex.Message)); throw new EncryptionException(Language.strErrorDecryptionFailed, ex); - } - } - } + } + } + } } \ No newline at end of file diff --git a/mRemoteV1/Settings.cs b/mRemoteV1/Settings.cs index 53c71396..60a55207 100644 --- a/mRemoteV1/Settings.cs +++ b/mRemoteV1/Settings.cs @@ -2,17 +2,16 @@ namespace mRemoteNG { - - // This class allows you to handle specific events on the settings class: // The SettingChanging event is raised before a setting's value is changed. // The PropertyChanged event is raised after a setting's value is changed. // The SettingsLoaded event is raised after the setting values are loaded. // The SettingsSaving event is raised before the setting values are saved. [global::System.Configuration.SettingsProviderAttribute(typeof(mRemoteNG.Config.Settings.Providers.ChooseProvider))] - internal sealed partial class Settings { - - public Settings() { + internal sealed partial class Settings + { + public Settings() + { // // To add event handlers for saving and changing settings, uncomment the lines below: // // this.SettingChanging += this.SettingChangingEventHandler; @@ -21,12 +20,14 @@ namespace mRemoteNG // } - private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) { + private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) + { // Add code to handle the SettingChangingEvent event here. } - - private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) { + + private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) + { // Add code to handle the SettingsSaving event here. } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Themes/ExtendedColorPalette.cs b/mRemoteV1/Themes/ExtendedColorPalette.cs index 4ecc1c52..f8bbe1d7 100644 --- a/mRemoteV1/Themes/ExtendedColorPalette.cs +++ b/mRemoteV1/Themes/ExtendedColorPalette.cs @@ -3,9 +3,8 @@ using System.Drawing; namespace mRemoteNG.Themes { - /// - /// Class used for the UI to display the color tables,as the Dictionary value keys cannot be directly replaced + /// Class used for the UI to display the color tables,as the Dictionary value keys cannot be directly replaced /// public class PseudoKeyColor { @@ -14,6 +13,7 @@ namespace mRemoteNG.Themes Key = _key; Value = _value; } + public string Key { get; set; } public Color Value { get; set; } @@ -26,49 +26,55 @@ namespace mRemoteNG.Themes public class ExtendedColorPalette { #region Private Variables + //Collection for color values that are not loaded by dock panels (list, buttons,panel content, etc) #endregion #region Constructors + public ExtendedColorPalette() { ExtColorPalette = new Dictionary(); - DefaultColorPalette = new Dictionary(); // If this is the default palette, it will not have a default-default palette - + DefaultColorPalette = + new Dictionary(); // If this is the default palette, it will not have a default-default palette } + #endregion #region Public Methods + // Set the default theme, that theme should contain all color values used by the application public void setDefault(ExtendedColorPalette inPalettte) { DefaultColorPalette = inPalettte.ExtColorPalette; } + #endregion - + /// /// Obtains a color from the extended palette, if not present obtains it from the default palette, in the extreme case it uses Pink as a signal that a color is missing /// /// /// - public Color getColor(string colorKey) + public Color getColor(string colorKey) { - var retColor = ExtColorPalette.ContainsKey(colorKey) ? ExtColorPalette[colorKey]:Color.Empty; + var 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) + if (DefaultColorPalette != null) { - retColor = DefaultColorPalette.ContainsKey(colorKey) ? DefaultColorPalette[colorKey] : Color.Empty; + retColor = DefaultColorPalette.ContainsKey(colorKey) ? DefaultColorPalette[colorKey] : Color.Empty; } + //why are we here?, just avoid a crash - if(retColor == Color.Empty) + if (retColor == Color.Empty) { //Fail to pink , because why not retColor = Color.Pink; } - return retColor; + return retColor; } /// @@ -76,7 +82,7 @@ namespace mRemoteNG.Themes /// /// /// - public void addColor(string colorKey,Color inColor) + public void addColor(string colorKey, Color inColor) { ExtColorPalette.Add(colorKey, inColor); } @@ -89,7 +95,7 @@ namespace mRemoteNG.Themes /// public void replaceColor(string colorKey, Color inColor) { - ExtColorPalette[colorKey]= inColor; + ExtColorPalette[colorKey] = inColor; } public Dictionary DefaultColorPalette { get; set; } @@ -97,7 +103,4 @@ namespace mRemoteNG.Themes public Dictionary ExtColorPalette { get; set; } } -} - - - \ No newline at end of file +} \ No newline at end of file diff --git a/mRemoteV1/Themes/MremoteNGPaletteManipulator.cs b/mRemoteV1/Themes/MremoteNGPaletteManipulator.cs index 2ee357cb..e62b8913 100644 --- a/mRemoteV1/Themes/MremoteNGPaletteManipulator.cs +++ b/mRemoteV1/Themes/MremoteNGPaletteManipulator.cs @@ -4,24 +4,22 @@ using System.Globalization; using System.IO; using System.Xml; -namespace mRemoteNG.Themes +namespace mRemoteNG.Themes { //Class to extract the rest of the required theme colors for MremoteNG from the vstheme file - public class MremoteNGPaletteManipulator + public class MremoteNGPaletteManipulator { private XmlDocument _xml; - private ExtendedColorPalette _defaultPalette; + private ExtendedColorPalette _defaultPalette; - //warning, defaultpalette should always contain all the values, because when is loaded there is no default palette (parameter is null - public MremoteNGPaletteManipulator(byte[] file, ExtendedColorPalette defaultPalette = null ) + public MremoteNGPaletteManipulator(byte[] file, ExtendedColorPalette defaultPalette = null) { _xml = new XmlDocument(); - _xml.LoadXml(new StreamReader(new MemoryStream(file)).ReadToEnd()); + _xml.LoadXml(new StreamReader(new MemoryStream(file)).ReadToEnd()); _defaultPalette = defaultPalette ?? new ExtendedColorPalette(); } - //Load the colors for the mRemoteNG own components as Dockpanel only have a menus and docks palette @@ -33,19 +31,19 @@ namespace mRemoteNG.Themes // foreach (DictionaryEntry entry in resourceSet) { - var colorName = entry.Key.ToString(); + var colorName = entry.Key.ToString(); var 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; - if (color != null ) + if (color != null) { - newPalette.addColor(colorName , ColorTranslator.FromHtml($"#{color}")); + newPalette.addColor(colorName, ColorTranslator.FromHtml($"#{color}")); } - } + } return newPalette; - } + } /// @@ -53,10 +51,10 @@ namespace mRemoteNG.Themes /// /// /// - public byte[] mergePalette(ExtendedColorPalette colorPalette) + public byte[] mergePalette(ExtendedColorPalette colorPalette) { var resourceSet = ColorMapTheme.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); - + foreach (DictionaryEntry entry in resourceSet) { var colorName = entry.Key.ToString(); @@ -66,12 +64,12 @@ namespace mRemoteNG.Themes var paletteColor = colorPalette.getColor(colorName); colorNodeList[0].Value = $"FF{paletteColor.R:X2}{paletteColor.G:X2}{paletteColor.B:X2}"; } + var ms = new MemoryStream(); _xml.Save(ms); var bytes = ms.ToArray(); return bytes; } - } -} +} \ No newline at end of file diff --git a/mRemoteV1/Themes/MremoteNGThemeBase.cs b/mRemoteV1/Themes/MremoteNGThemeBase.cs index 5e76d11c..bebbf325 100644 --- a/mRemoteV1/Themes/MremoteNGThemeBase.cs +++ b/mRemoteV1/Themes/MremoteNGThemeBase.cs @@ -1,6 +1,8 @@ namespace mRemoteNG.Themes { - + using System.Drawing; + using UI.Tabs; + using WeifenLuo.WinFormsUI.Docking; using WeifenLuo.WinFormsUI.ThemeVS2015; @@ -18,4 +20,27 @@ ShowAutoHideContentOnHover = false; } } + + public class MremoteDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory + { + public DockPaneStripBase CreateDockPaneStrip(DockPane pane) + { + return new DockPaneStripNG(pane); + } + } + + public class MremoteFloatWindowFactory : DockPanelExtender.IFloatWindowFactory + { + public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds) + { + var activeDocumentBounds = (dockPanel?.ActiveDocument as ConnectionTab)?.Bounds; + + return new FloatWindowNG(dockPanel, pane, activeDocumentBounds ?? bounds); + } + + public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane) + { + return new FloatWindowNG(dockPanel, pane); + } + } } \ No newline at end of file diff --git a/mRemoteV1/Themes/ThemeInfo.cs b/mRemoteV1/Themes/ThemeInfo.cs index 86db8d84..eb0f2445 100644 --- a/mRemoteV1/Themes/ThemeInfo.cs +++ b/mRemoteV1/Themes/ThemeInfo.cs @@ -6,24 +6,29 @@ using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.Themes { - /// /// /// Container class for all the color and style elements to define a theme /// - public class ThemeInfo : ICloneable + public class ThemeInfo : ICloneable { #region Private Variables + private string _name; private ThemeBase _theme; - private string _URI; + private string _URI; private VisualStudioToolStripExtender.VsVersion _version; private ExtendedColorPalette _extendedPalette; #endregion #region Constructors - public ThemeInfo(string themeName, ThemeBase inTheme, string inURI, VisualStudioToolStripExtender.VsVersion inVersion, ExtendedColorPalette inExtendedPalette) + + public ThemeInfo(string themeName, + ThemeBase inTheme, + string inURI, + VisualStudioToolStripExtender.VsVersion inVersion, + ExtendedColorPalette inExtendedPalette) { _name = themeName; _theme = inTheme; @@ -32,9 +37,17 @@ namespace mRemoteNG.Themes _extendedPalette = inExtendedPalette; IsThemeBase = false; IsExtendable = false; + + if (_extendedPalette != null) + IsExtended = true; + + setCustomExtenders(); } - public ThemeInfo(string themeName, ThemeBase inTheme, string inURI, VisualStudioToolStripExtender.VsVersion inVersion) + public ThemeInfo(string themeName, + ThemeBase inTheme, + string inURI, + VisualStudioToolStripExtender.VsVersion inVersion) { _name = themeName; _theme = inTheme; @@ -42,10 +55,14 @@ namespace mRemoteNG.Themes _version = inVersion; IsThemeBase = false; IsExtendable = false; + IsExtended = false; + setCustomExtenders(); } + #endregion #region Public Methods + public object Clone() { var extPalette = new ExtendedColorPalette @@ -67,19 +84,21 @@ namespace mRemoteNG.Themes #region Properties + [Browsable(false)] public string Name - { - get => _name; + { + get => _name; set - { - if (string.Equals(_name, value, StringComparison.InvariantCulture)) - { - return; - } - _name = value; - } - } + { + if (string.Equals(_name, value, StringComparison.InvariantCulture)) + { + return; + } + + _name = value; + } + } public ThemeBase Theme { @@ -90,11 +109,13 @@ namespace mRemoteNG.Themes { return; } + _theme = value; + setCustomExtenders(); } } - public string URI + public string URI { get => _URI; set @@ -103,6 +124,7 @@ namespace mRemoteNG.Themes { return; } + _URI = value; } } @@ -116,6 +138,7 @@ namespace mRemoteNG.Themes { return; } + _version = value; } } @@ -129,6 +152,7 @@ namespace mRemoteNG.Themes { return; } + _extendedPalette = value; } } @@ -137,6 +161,15 @@ namespace mRemoteNG.Themes public bool IsExtendable { get; set; } + public bool IsExtended { get; private set; } + #endregion + + //Custom extenders for mremote customizations in DPS + private void setCustomExtenders() + { + _theme.Extender.DockPaneStripFactory = new MremoteDockPaneStripFactory(); + _theme.Extender.FloatWindowFactory = new MremoteFloatWindowFactory(); + } } } \ No newline at end of file diff --git a/mRemoteV1/Themes/ThemeManager.cs b/mRemoteV1/Themes/ThemeManager.cs index 0bddccfe..53a6fbb8 100644 --- a/mRemoteV1/Themes/ThemeManager.cs +++ b/mRemoteV1/Themes/ThemeManager.cs @@ -1,12 +1,12 @@ using mRemoteNG.App; -using mRemoteNG.Messages; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; +using System.Diagnostics; using System.IO; using System.Linq; +using mRemoteNG.Messages; using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.Themes @@ -19,31 +19,44 @@ namespace mRemoteNG.Themes { #region Private Variables - private ThemeInfo _activeTheme; - private Hashtable themes; + private ThemeInfo _activeTheme; + private Hashtable themes; private bool _themeActive; private static ThemeManager themeInstance; + private readonly string themePath = App.Info.SettingsFileInfo.ThemeFolder; + #endregion #region Constructors + private ThemeManager() { LoadThemes(); SetActive(); - _themeActive = Settings.Default.ThemingActive; + _themeActive = true; } private void SetActive() { if (themes[Settings.Default.ThemeName] != null) - ActiveTheme = (ThemeInfo) themes[Settings.Default.ThemeName]; + ActiveTheme = (ThemeInfo)themes[Settings.Default.ThemeName]; else + { ActiveTheme = DefaultTheme; + if (string.IsNullOrEmpty(Settings.Default.ThemeName)) return; + + //too early for logging to be enabled... + Debug.WriteLine("Detected invalid Theme in settings file. Resetting to default."); + // if we got here, then there's an invalid theme name in use, so just empty it out... + Settings.Default.ThemeName = ""; + Settings.Default.Save(); + } } #endregion #region Public Methods + public static ThemeManager getInstance() { return themeInstance ?? (themeInstance = new ThemeManager()); @@ -52,83 +65,168 @@ namespace mRemoteNG.Themes public ThemeInfo getTheme(string themeName) { - if(themes[themeName] != null) + if (themes[themeName] != null) return (ThemeInfo)themes[themeName]; return null; } - //THe manager precharges all the themes at once - public List LoadThemes() + private bool ThemeDirExists() { - if (themes != null) return themes.Values.OfType().ToList(); - themes = new Hashtable(); - - //Load the files in theme folder first, to incluide vstheme light as default - var themePath = App.Info.SettingsFileInfo.ThemeFolder; - if (themePath == null) return themes.Values.OfType().ToList(); + //Load the files in theme folder first, to include vstheme light as default + if (themePath == null) return false; try { - //In install mode first time is necesary to copy the themes folder + //In install mode first time is necessary to copy the themes folder if (!Directory.Exists(themePath)) { Directory.CreateDirectory(themePath); - } + var orig = new DirectoryInfo(App.Info.SettingsFileInfo.InstalledThemeFolder); var files = orig.GetFiles(); foreach (var file in files) { - if (!File.Exists(Path.Combine(themePath, file.Name))) file.CopyTo(Path.Combine(themePath, file.Name), true); } + return Directory.Exists(themePath); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace("Error loading theme directory", ex); + } + return false; + } + private ThemeInfo LoadDefaultTheme() + { + try + { + if (ThemeDirExists()) + { + var defaultThemeURL = $"{themePath}\\vs2015light.vstheme"; + + if (!File.Exists($"{themePath}\\vs2015light.vstheme")) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "Could not find default theme file.", + true); + return null; + } + + //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); + defaultTheme.Name = $"{defaultTheme.Name}NG"; + return defaultTheme; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace("Error loading default theme", ex); + } + + return null; + } + + //The manager precharges all the themes at once + public List LoadThemes() + { + if (themes != null) return themes.Values.OfType().ToList(); + themes = new Hashtable(); + + if (themePath == null) return themes.Values.OfType().ToList(); + try + { //Check that theme folder exist before trying to load themes - if (Directory.Exists(themePath)) + if (ThemeDirExists()) { var themeFiles = Directory.GetFiles(themePath, "*.vstheme"); - var defaultThemeURL = Directory.GetFiles(themePath, "vs2015light" + ".vstheme")[0]; - //First we load the default theme, its vs2015light - var defaultTheme = ThemeSerializer.LoadFromXmlFile(defaultThemeURL); + + //First we load the default base theme, its vs2015lightNG + var defaultTheme = LoadDefaultTheme(); themes.Add(defaultTheme.Name, defaultTheme); //Then the rest foreach (var 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); - if (extTheme.Theme != null && !themes.ContainsKey(extTheme.Name)) - { - themes.Add(extTheme.Name, extTheme); - } + if (extTheme.Theme == null || themes.ContainsKey(extTheme.Name)) continue; + + if (extTheme.Name.Equals("darcula") || extTheme.Name.Equals("vs2015blue") || + extTheme.Name.Equals("vs2015dark")) + extTheme.Name = $"{extTheme.Name}NG"; + + themes.Add(extTheme.Name, extTheme); } - //Load the embedded themes, extended palettes are taken from the vs2015 themes, trying to match the color theme - var vs2003 = new ThemeInfo("Vs2003", new VS2003Theme(), "", VisualStudioToolStripExtender.VsVersion.Vs2003, ((ThemeInfo)themes["vs2015light"]).ExtendedPalette); + + // 2003 + var vs2003 = new ThemeInfo("vs2003", new VS2003Theme(), "", + VisualStudioToolStripExtender.VsVersion.Vs2003, + ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette); themes.Add(vs2003.Name, vs2003); - var vs2005 = new ThemeInfo("Vs2005", new VS2005Theme(), "", VisualStudioToolStripExtender.VsVersion.Vs2005, ((ThemeInfo)themes["vs2015light"]).ExtendedPalette); + + // 2005 + var vs2005 = new ThemeInfo("vs2005", new VS2005Theme(), "", + VisualStudioToolStripExtender.VsVersion.Vs2005, + ((ThemeInfo)themes["vs2015lightNG"]).ExtendedPalette); themes.Add(vs2005.Name, vs2005); - var vs2012Light = new ThemeInfo("vs2012Light", new VS2012LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2012, ((ThemeInfo)themes["vs2015light"]).ExtendedPalette); + + // 2012 + var vs2012Light = new ThemeInfo("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["vs2015dark"]).ExtendedPalette); + var vs2012Dark = new ThemeInfo("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["vs2015blue"]).ExtendedPalette); + var vs2012Blue = new ThemeInfo("vs2012Blue", new VS2012BlueTheme(), "", + VisualStudioToolStripExtender.VsVersion.Vs2012, + ((ThemeInfo)themes["vs2015blueNG"]).ExtendedPalette); themes.Add(vs2012Blue.Name, vs2012Blue); - var vs2013Light = new ThemeInfo("vs2013Light", new VS2013LightTheme(), "", VisualStudioToolStripExtender.VsVersion.Vs2013, ((ThemeInfo)themes["vs2015light"]).ExtendedPalette); + + // 2013 + var vs2013Light = new ThemeInfo("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["vs2015dark"]).ExtendedPalette); + var vs2013Dark = new ThemeInfo("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["vs2015blue"]).ExtendedPalette); + var vs2013Blue = new ThemeInfo("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); + themes.Add(vs2015Light.Name, vs2015Light); + var vs2015Dark = new ThemeInfo("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); + themes.Add(vs2015Blue.Name, vs2015Blue); } } - catch(Exception ex) + catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "Error loading themes" + Environment.NewLine + ex.Message, true); + Runtime.MessageCollector.AddExceptionStackTrace("Error loading themes", ex); } - return themes.Values.OfType().ToList(); + + return themes.Values.OfType().ToList(); } /// @@ -144,8 +242,8 @@ namespace mRemoteNG.Themes modifiedTheme.Name = newThemeName; modifiedTheme.IsExtendable = true; modifiedTheme.IsThemeBase = false; - ThemeSerializer.SaveToXmlFile(modifiedTheme,baseTheme); - themes.Add(newThemeName,modifiedTheme); + ThemeSerializer.SaveToXmlFile(modifiedTheme, baseTheme); + themes.Add(newThemeName, modifiedTheme); return modifiedTheme; } @@ -153,16 +251,16 @@ namespace mRemoteNG.Themes public void deleteTheme(ThemeInfo themeToDelete) { if (!themes.Contains(themeToDelete.Name)) return; - if(ActiveTheme == themeToDelete) + if (ActiveTheme == themeToDelete) ActiveTheme = DefaultTheme; themes.Remove(themeToDelete.Name); ThemeSerializer.DeleteFile(themeToDelete); } - //Sincronize the theme XML values from memory to disk + //Synchronize the theme XML values from memory to disk public void updateTheme(ThemeInfo themeToUpdate) { - ThemeSerializer.UpdateThemeXMLValues(themeToUpdate); + ThemeSerializer.UpdateThemeXMLValues(themeToUpdate); } //refresh the ui controls to reflect a theme change @@ -179,33 +277,37 @@ namespace mRemoteNG.Themes var badChars = Path.GetInvalidFileNameChars(); return name.IndexOfAny(badChars) == -1; } - - + #endregion #region Events + public delegate void ThemeChangedEventHandler(); + private ThemeChangedEventHandler ThemeChangedEvent; - public event ThemeChangedEventHandler ThemeChanged + public event ThemeChangedEventHandler ThemeChanged { add => ThemeChangedEvent = (ThemeChangedEventHandler)Delegate.Combine(ThemeChangedEvent, value); remove => ThemeChangedEvent = (ThemeChangedEventHandler)Delegate.Remove(ThemeChangedEvent, value); } // ReSharper disable once UnusedParameter.Local - private void NotifyThemeChanged(object sender, PropertyChangedEventArgs e) + private void NotifyThemeChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Name") { return; } + ThemeChangedEvent?.Invoke(); } + #endregion #region Properties - public bool ThemingActive + + public bool ThemingActive { get => _themeActive; set @@ -217,24 +319,44 @@ namespace mRemoteNG.Themes } } - public ThemeInfo DefaultTheme => (ThemeInfo) themes["vs2015light"]; + public ThemeInfo DefaultTheme => + themes != null && ThemesCount > 0 + ? (ThemeInfo)themes["vs2015Light"] + : new ThemeInfo("vs2015Light", new VS2015LightTheme(), "", + VisualStudioToolStripExtender.VsVersion.Vs2015); public ThemeInfo ActiveTheme - { + { // default if themes are not enabled get => ThemingActive == false ? DefaultTheme : _activeTheme; set - { - //You can only enable theming if there are themes laoded - if (value == null) return; - _activeTheme = value; - Settings.Default.ThemeName = value.Name; - NotifyThemeChanged(this, new PropertyChangedEventArgs("theme")); - } - } + { + // You can only enable theming if there are themes loaded + // Default accordingly... + if (value == null) + { + var changed = !Settings.Default.ThemeName.Equals(DefaultTheme.Name); + + Settings.Default.ThemeName = DefaultTheme.Name; + _activeTheme = DefaultTheme; + + if (changed) + NotifyThemeChanged(this, new PropertyChangedEventArgs("theme")); + + Settings.Default.Save(); + return; + } + + _activeTheme = value; + Settings.Default.ThemeName = value.Name; + NotifyThemeChanged(this, new PropertyChangedEventArgs("theme")); + } + } + + public bool ActiveAndExtended => ThemingActive && ActiveTheme.IsExtended; public int ThemesCount => themes.Count; #endregion } -} \ No newline at end of file +} \ No newline at end of file diff --git a/mRemoteV1/Themes/ThemeSerializer.cs b/mRemoteV1/Themes/ThemeSerializer.cs index 25eacc97..34540708 100644 --- a/mRemoteV1/Themes/ThemeSerializer.cs +++ b/mRemoteV1/Themes/ThemeSerializer.cs @@ -4,30 +4,30 @@ using System.Linq; namespace mRemoteNG.Themes { - public static class ThemeSerializer - { - /// - /// Save the theme to file, name property is used as filename - /// The baseTheme is used as a template, by copy that file and rewrite the extpalette values - /// - /// - /// - 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"; + public static class ThemeSerializer + { + /// + /// Save the theme to file, name property is used as filename + /// The baseTheme is used as a template, by copy that file and rewrite the extpalette values + /// + /// + /// + 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"; File.Copy(baseTheme.URI, toSaveURI); themeToSave.URI = toSaveURI; - } + } public static void DeleteFile(ThemeInfo themeToDelete) { File.Delete(themeToDelete.URI); } - + /// - /// Takes a theme in memory and update the color values that the user might have changed + /// Takes a theme in memory and update the color values that the user might have changed /// /// public static void UpdateThemeXMLValues(ThemeInfo themeToUpdate) @@ -44,22 +44,27 @@ namespace mRemoteNG.Themes /// /// /// - public static ThemeInfo LoadFromXmlFile(string filename, ThemeInfo defaultTheme=null) - { + public static ThemeInfo LoadFromXmlFile(string filename, ThemeInfo defaultTheme = null) + { var bytes = File.ReadAllBytes(filename); //Load the dockpanel part - var themeBaseLoad= new MremoteNGThemeBase(bytes); + var themeBaseLoad = new MremoteNGThemeBase(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, VisualStudioToolStripExtender.VsVersion.Vs2015, extColorLoader.getColors()); - if(new[] { "darcula", "vs2015blue", "vs2015dark" , "vs2015light" }.Contains(Path.GetFileNameWithoutExtension(filename))) + //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, + VisualStudioToolStripExtender.VsVersion.Vs2015, extColorLoader.getColors()); + if (new[] {"darcula", "vs2015blue", "vs2015dark", "vs2015light"}.Contains( + Path + .GetFileNameWithoutExtension(filename)) + ) { loadedTheme.IsThemeBase = true; } + loadedTheme.IsExtendable = true; return loadedTheme; - } + } /* private static string EncodeColorName(Color color) @@ -74,6 +79,5 @@ namespace mRemoteNG.Themes return regex.Match(name).Success ? Color.FromArgb(Convert.ToInt32(name, 16)) : Color.FromName(name); } */ - } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tools/Authenticode.cs b/mRemoteV1/Tools/Authenticode.cs index 213015c6..0a29a56f 100644 --- a/mRemoteV1/Tools/Authenticode.cs +++ b/mRemoteV1/Tools/Authenticode.cs @@ -78,7 +78,8 @@ namespace mRemoteNG.Tools var windowHandle = DisplayParentForm?.Handle ?? IntPtr.Zero; - _trustProviderErrorCode = NativeMethods.WinVerifyTrust(windowHandle, NativeMethods.WINTRUST_ACTION_GENERIC_VERIFY_V2, trustDataPointer); + _trustProviderErrorCode = + NativeMethods.WinVerifyTrust(windowHandle, NativeMethods.WINTRUST_ACTION_GENERIC_VERIFY_V2, trustDataPointer); // ReSharper disable once SwitchStatementMissingSomeCases switch (_trustProviderErrorCode) { @@ -103,7 +104,8 @@ namespace mRemoteNG.Tools if (ex is CryptographicException) { - var hResultProperty = ex.GetType().GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance); + var hResultProperty = + ex.GetType().GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance); if (hResultProperty != null) { var hResult = Convert.ToInt32(hResultProperty.GetValue(ex, null)); @@ -270,7 +272,8 @@ namespace mRemoteNG.Tools public const int TRUST_E_SUBJECT_NOT_TRUSTED = unchecked ((int) 0x800B0004); 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}"); + public static readonly Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 = + new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}"); public const uint WTD_CHOICE_FILE = 1; public const uint WTD_DISABLE_MD2_MD4 = 0x2000; diff --git a/mRemoteV1/Tools/Cmdline/CmdArgumentsInterpreter.cs b/mRemoteV1/Tools/Cmdline/CmdArgumentsInterpreter.cs index 20f23b51..c66e47f5 100644 --- a/mRemoteV1/Tools/Cmdline/CmdArgumentsInterpreter.cs +++ b/mRemoteV1/Tools/Cmdline/CmdArgumentsInterpreter.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.Text.RegularExpressions; using mRemoteNG.App; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Tools.Cmdline @@ -55,8 +56,10 @@ namespace mRemoteNG.Tools.Cmdline Parts[0] = remover.Replace(Parts[0], "$1"); _parameters.Add(parameter, Parts[0]); } + parameter = null; } + // else Error: no parameter waiting for a value (skipped) break; case 2: @@ -69,6 +72,7 @@ namespace mRemoteNG.Tools.Cmdline _parameters.Add(parameter, "true"); } } + parameter = Parts[1]; break; case 3: @@ -81,6 +85,7 @@ namespace mRemoteNG.Tools.Cmdline _parameters.Add(parameter, "true"); } } + parameter = Parts[1]; // Remove possible enclosing characters (",') if (!_parameters.ContainsKey(parameter)) @@ -88,10 +93,12 @@ namespace mRemoteNG.Tools.Cmdline Parts[2] = remover.Replace(Parts[2], "$1"); _parameters.Add(parameter, Parts[2]); } + parameter = null; break; } } + // In case a parameter is still waiting if (parameter == null) return; if (!_parameters.ContainsKey(parameter)) diff --git a/mRemoteV1/Tools/Cmdline/CommandLineArguments.cs b/mRemoteV1/Tools/Cmdline/CommandLineArguments.cs index 198d745a..43d5589e 100644 --- a/mRemoteV1/Tools/Cmdline/CommandLineArguments.cs +++ b/mRemoteV1/Tools/Cmdline/CommandLineArguments.cs @@ -4,125 +4,131 @@ using System.Text.RegularExpressions; namespace mRemoteNG.Tools.Cmdline { - // Adapted from http://qntm.org/cmd - public class CommandLineArguments - { - protected List Arguments = new List(); - - public bool EscapeForShell {get; set;} - - #region Public Methods - public void Add(string argument, bool forceQuotes = false) - { - Arguments.Add(new Argument(argument, false, forceQuotes)); - } - - public void Add(params string[] argumentArray) - { - foreach (var argument in argumentArray) - { - Add(argument); - } - } - - public void AddFileName(string fileName, bool forceQuotes = false) - { - Arguments.Add(new Argument(fileName, true, forceQuotes)); - } - - public override string ToString() - { - var argList = Arguments.Select(argument => ProcessArgument(argument, EscapeForShell)); - return string.Join(" ", argList.ToArray()); - } - - public static string PrefixFileName(string argument) - { - if (string.IsNullOrEmpty(argument)) - return argument; - - if (argument.StartsWith("-")) - argument = ".\\" + argument; - - return argument; - } - - public static string EscapeBackslashes(string argument) - { - if (string.IsNullOrEmpty(argument)) - { - return argument; - } - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - return Regex.Replace(argument, "(\\\\*)\"", "$1$1\\\""); - } - - public static string EscapeBackslashesForTrailingQuote(string argument) - { - if (string.IsNullOrEmpty(argument)) - { - return argument; - } - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote): - // double up all the backslashes - return Regex.Replace(argument, "(\\\\*)$", "$1$1"); - } - - public static string QuoteArgument(string argument, bool forceQuotes = false) - { - if (!forceQuotes && !string.IsNullOrEmpty(argument) && !argument.Contains(" ")) - { - return argument; - } - - return "\"" + EscapeBackslashesForTrailingQuote(argument) + "\""; - } - - public static string EscapeShellMetacharacters(string argument) - { - return string.IsNullOrEmpty(argument) ? argument : Regex.Replace(argument, "([()%!^\"<>&|])", "^$1"); - } + // Adapted from http://qntm.org/cmd + public class CommandLineArguments + { + protected List Arguments = new List(); + + public bool EscapeForShell { get; set; } + + #region Public Methods + + public void Add(string argument, bool forceQuotes = false) + { + Arguments.Add(new Argument(argument, false, forceQuotes)); + } + + public void Add(params string[] argumentArray) + { + foreach (var argument in argumentArray) + { + Add(argument); + } + } + + public void AddFileName(string fileName, bool forceQuotes = false) + { + Arguments.Add(new Argument(fileName, true, forceQuotes)); + } + + public override string ToString() + { + var argList = Arguments.Select(argument => ProcessArgument(argument, EscapeForShell)); + return string.Join(" ", argList.ToArray()); + } + + public static string PrefixFileName(string argument) + { + if (string.IsNullOrEmpty(argument)) + return argument; + + if (argument.StartsWith("-")) + argument = ".\\" + argument; + + return argument; + } + + public static string EscapeBackslashes(string argument) + { + if (string.IsNullOrEmpty(argument)) + { + return argument; + } + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + return Regex.Replace(argument, "(\\\\*)\"", "$1$1\\\""); + } + + public static string EscapeBackslashesForTrailingQuote(string argument) + { + if (string.IsNullOrEmpty(argument)) + { + return argument; + } + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote): + // double up all the backslashes + return Regex.Replace(argument, "(\\\\*)$", "$1$1"); + } + + public static string QuoteArgument(string argument, bool forceQuotes = false) + { + if (!forceQuotes && !string.IsNullOrEmpty(argument) && !argument.Contains(" ")) + { + return argument; + } + + return "\"" + EscapeBackslashesForTrailingQuote(argument) + "\""; + } + + public static string EscapeShellMetacharacters(string argument) + { + return string.IsNullOrEmpty(argument) ? argument : Regex.Replace(argument, "([()%!^\"<>&|])", "^$1"); + } + + #endregion - #endregion - #region Protected Methods - protected static string ProcessArgument(Argument argument, bool escapeForShell = false) - { - var text = argument.Text; - - if (argument.IsFileName) - { - text = PrefixFileName(text); - } - text = EscapeBackslashes(text); - text = QuoteArgument(text, argument.ForceQuotes); - if (escapeForShell) - { - text = EscapeShellMetacharacters(text); - } - - return text; - } + + protected static string ProcessArgument(Argument argument, bool escapeForShell = false) + { + var text = argument.Text; + + if (argument.IsFileName) + { + text = PrefixFileName(text); + } + + text = EscapeBackslashes(text); + text = QuoteArgument(text, argument.ForceQuotes); + if (escapeForShell) + { + text = EscapeShellMetacharacters(text); + } + + return text; + } + #endregion - + #region Protected Classes - protected class Argument - { - public Argument(string text, bool isFileName = false, bool forceQuotes = false) - { - Text = text; - IsFileName = isFileName; - ForceQuotes = forceQuotes; - } - - public string Text {get; set;} - public bool IsFileName {get; set;} - public bool ForceQuotes {get; set;} - } + + protected class Argument + { + public Argument(string text, bool isFileName = false, bool forceQuotes = false) + { + Text = text; + IsFileName = isFileName; + ForceQuotes = forceQuotes; + } + + public string Text { get; set; } + public bool IsFileName { get; set; } + public bool ForceQuotes { get; set; } + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/Cmdline/StartupArgumentsInterpreter.cs b/mRemoteV1/Tools/Cmdline/StartupArgumentsInterpreter.cs index b3f37ae2..b1cd36e7 100644 --- a/mRemoteV1/Tools/Cmdline/StartupArgumentsInterpreter.cs +++ b/mRemoteV1/Tools/Cmdline/StartupArgumentsInterpreter.cs @@ -9,7 +9,7 @@ using mRemoteNG.Messages; namespace mRemoteNG.Tools.Cmdline { - public class StartupArgumentsInterpreter + public class StartupArgumentsInterpreter { private readonly MessageCollector _messageCollector; @@ -46,15 +46,15 @@ namespace mRemoteNG.Tools.Cmdline { if (args["resetpos"] == null && args["rp"] == null && args["reset"] == null) return; _messageCollector.AddMessage(MessageClass.DebugMsg, "Cmdline arg: Resetting window positions."); - Settings.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; - Settings.Default.MainFormLocation = new Point(newX, newY); - Settings.Default.MainFormSize = new Size(newWidth, newHeight); - Settings.Default.MainFormState = FormWindowState.Normal; - } + Settings.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; + Settings.Default.MainFormLocation = new Point(newX, newY); + Settings.Default.MainFormSize = new Size(newWidth, newHeight); + Settings.Default.MainFormState = FormWindowState.Normal; + } private void ParseResetPanelsArg(CmdArgumentsInterpreter args) { @@ -73,7 +73,8 @@ namespace mRemoteNG.Tools.Cmdline private void ParseNoReconnectArg(CmdArgumentsInterpreter args) { if (args["noreconnect"] == null && args["norc"] == null) return; - _messageCollector.AddMessage(MessageClass.DebugMsg, "Cmdline arg: Disabling reconnection to previously connected hosts"); + _messageCollector.AddMessage(MessageClass.DebugMsg, + "Cmdline arg: Disabling reconnection to previously connected hosts"); Settings.Default.NoReconnect = true; } @@ -95,9 +96,11 @@ namespace mRemoteNG.Tools.Cmdline Settings.Default.CustomConsPath = Path.Combine(GeneralAppInfo.HomePath, args[consParam]); return; } + if (!File.Exists(Path.Combine(ConnectionsFileInfo.DefaultConnectionsPath, args[consParam]))) return; Settings.Default.LoadConsFromCustomLocation = true; - Settings.Default.CustomConsPath = Path.Combine(ConnectionsFileInfo.DefaultConnectionsPath, args[consParam]); + Settings.Default.CustomConsPath = + Path.Combine(ConnectionsFileInfo.DefaultConnectionsPath, args[consParam]); } else { diff --git a/mRemoteV1/Tools/ConnectionsTreeToMenuItemsConverter.cs b/mRemoteV1/Tools/ConnectionsTreeToMenuItemsConverter.cs index 2157d2ad..dc27c574 100644 --- a/mRemoteV1/Tools/ConnectionsTreeToMenuItemsConverter.cs +++ b/mRemoteV1/Tools/ConnectionsTreeToMenuItemsConverter.cs @@ -10,7 +10,7 @@ using mRemoteNG.Tree; namespace mRemoteNG.Tools { - public class ConnectionsTreeToMenuItemsConverter + public class ConnectionsTreeToMenuItemsConverter { public MouseEventHandler MouseUpEventHandler { get; set; } @@ -32,6 +32,7 @@ namespace mRemoteNG.Tools { Runtime.MessageCollector.AddExceptionMessage("frmMain.AddNodeToMenu() failed", ex); } + return dropDownList; } @@ -69,7 +70,7 @@ namespace mRemoteNG.Tools menuItem.Image = node.OpenConnections.Count > 0 ? Resources.Play : Resources.Pause; menuItem.Tag = node; } - + menuItem.MouseUp += MouseUpEventHandler; return menuItem; } diff --git a/mRemoteV1/Tools/CustomCollections/FullyObservableCollection.cs b/mRemoteV1/Tools/CustomCollections/FullyObservableCollection.cs index 94395465..65bc0fe5 100644 --- a/mRemoteV1/Tools/CustomCollections/FullyObservableCollection.cs +++ b/mRemoteV1/Tools/CustomCollections/FullyObservableCollection.cs @@ -6,14 +6,14 @@ using System.Linq; namespace mRemoteNG.Tools.CustomCollections { - public class FullyObservableCollection : IFullyNotifiableList + public class FullyObservableCollection : IFullyNotifiableList where T : INotifyPropertyChanged - { - private readonly IList _list = new List(); + { + private readonly IList _list = new List(); private bool _eventsAllowed = true; public int Count => _list.Count; - public bool IsReadOnly => _list.IsReadOnly; + public bool IsReadOnly => _list.IsReadOnly; public T this[int index] { @@ -21,22 +21,22 @@ namespace mRemoteNG.Tools.CustomCollections set => _list[index] = value; } - public FullyObservableCollection() - { - } + public FullyObservableCollection() + { + } - public FullyObservableCollection(IEnumerable items) - { + public FullyObservableCollection(IEnumerable items) + { AddRange(items); } - public void Add(T item) - { - _list.Add(item); - SubscribeToChildEvents(item); + public void Add(T item) + { + _list.Add(item); + SubscribeToChildEvents(item); if (_eventsAllowed) RaiseCollectionChangedEvent(ActionType.Added, new[] {item}); - } + } /// /// Adds a range of items to the collection. @@ -44,41 +44,41 @@ namespace mRemoteNG.Tools.CustomCollections /// after all new items are added. /// /// - public void AddRange(IEnumerable items) + public void AddRange(IEnumerable items) { var itemsAsList = items.ToList(); - _eventsAllowed = false; + _eventsAllowed = false; foreach (var item in itemsAsList) Add(item); - _eventsAllowed = true; + _eventsAllowed = true; RaiseCollectionChangedEvent(ActionType.Added, itemsAsList); - } + } public void Insert(int index, T item) { _list.Insert(index, item); SubscribeToChildEvents(item); - RaiseCollectionChangedEvent(ActionType.Added, new[] { item }); + RaiseCollectionChangedEvent(ActionType.Added, new[] {item}); } - public bool Remove(T item) - { - var worked = _list.Remove(item); - if (!worked) return worked; - UnsubscribeFromChildEvents(item); + public bool Remove(T item) + { + var worked = _list.Remove(item); + if (!worked) return worked; + UnsubscribeFromChildEvents(item); RaiseCollectionChangedEvent(ActionType.Removed, new[] {item}); - return worked; - } + return worked; + } - public void RemoveAt(int index) - { - var item = _list[index]; - _list.RemoveAt(index); - UnsubscribeFromChildEvents(item); - RaiseCollectionChangedEvent(ActionType.Removed, new[] { item }); - } + public void RemoveAt(int index) + { + var item = _list[index]; + _list.RemoveAt(index); + UnsubscribeFromChildEvents(item); + RaiseCollectionChangedEvent(ActionType.Removed, new[] {item}); + } public void Clear() { @@ -90,9 +90,9 @@ namespace mRemoteNG.Tools.CustomCollections } private void SubscribeToChildEvents(INotifyPropertyChanged item) - { - item.PropertyChanged += ItemOnPropertyChanged; - } + { + item.PropertyChanged += ItemOnPropertyChanged; + } private void UnsubscribeFromChildEvents(INotifyPropertyChanged item) { @@ -100,12 +100,12 @@ namespace mRemoteNG.Tools.CustomCollections } private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) - { + { if (sender is T) - RaiseCollectionChangedEvent(ActionType.Updated, new []{ (T)sender }); - } + RaiseCollectionChangedEvent(ActionType.Updated, new[] {(T)sender}); + } - public event EventHandler> CollectionUpdated; + public event EventHandler> CollectionUpdated; private void RaiseCollectionChangedEvent(ActionType action, IEnumerable changedItems) { @@ -113,11 +113,13 @@ namespace mRemoteNG.Tools.CustomCollections } #region Forwarded method calls + public int IndexOf(T item) => _list.IndexOf(item); public IEnumerator GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); public bool Contains(T item) => _list.Contains(item); public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/Tools/DisposableOptional.cs b/mRemoteV1/Tools/DisposableOptional.cs index ecc6bff6..371c83b7 100644 --- a/mRemoteV1/Tools/DisposableOptional.cs +++ b/mRemoteV1/Tools/DisposableOptional.cs @@ -25,4 +25,4 @@ namespace mRemoteNG.Tools this.First().Dispose(); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tools/EnumWindows.cs b/mRemoteV1/Tools/EnumWindows.cs index f60ae8ee..d550fe13 100644 --- a/mRemoteV1/Tools/EnumWindows.cs +++ b/mRemoteV1/Tools/EnumWindows.cs @@ -4,49 +4,52 @@ using System.Runtime.InteropServices; namespace mRemoteNG.Tools { - public class EnumWindows - { - public List EnumWindows_Renamed() - { - var handleList = new List(); - - HandleLists.Add(handleList); - var handleIndex = (IntPtr)HandleLists.IndexOf(handleList); - NativeMethods.EnumWindows(EnumCallback, handleIndex); - HandleLists.Remove(handleList); - - return handleList; - } - - public List EnumChildWindows(IntPtr hWndParent) - { - var handleList = new List(); - - HandleLists.Add(handleList); + public class EnumWindows + { + public List EnumWindows_Renamed() + { + var handleList = new List(); + + HandleLists.Add(handleList); var handleIndex = (IntPtr)HandleLists.IndexOf(handleList); - NativeMethods.EnumChildWindows(hWndParent, EnumCallback, handleIndex); - HandleLists.Remove(handleList); - - return handleList; - } - - private readonly List> HandleLists = new List>(); - - private bool EnumCallback(int hwnd, int lParam) - { - HandleLists[lParam].Add((IntPtr)hwnd); - return true; - } - - // ReSharper disable ClassNeverInstantiated.Local - private class NativeMethods - { - // ReSharper restore ClassNeverInstantiated.Local - public delegate bool EnumWindowsProc(int hwnd, int lParam); - [DllImport("user32", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)] - public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); - [DllImport("user32", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)] - public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); - } - } -} + NativeMethods.EnumWindows(EnumCallback, handleIndex); + HandleLists.Remove(handleList); + + return handleList; + } + + public List EnumChildWindows(IntPtr hWndParent) + { + var handleList = new List(); + + HandleLists.Add(handleList); + var handleIndex = (IntPtr)HandleLists.IndexOf(handleList); + NativeMethods.EnumChildWindows(hWndParent, EnumCallback, handleIndex); + HandleLists.Remove(handleList); + + return handleList; + } + + private readonly List> HandleLists = new List>(); + + private bool EnumCallback(int hwnd, int lParam) + { + HandleLists[lParam].Add((IntPtr)hwnd); + return true; + } + + // ReSharper disable ClassNeverInstantiated.Local + private class NativeMethods + { + // ReSharper restore ClassNeverInstantiated.Local + + public delegate bool EnumWindowsProc(int hwnd, int lParam); + + [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] + public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); + + [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] + public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/Extensions.cs b/mRemoteV1/Tools/Extensions.cs index 9d65bd24..5240f0b4 100644 --- a/mRemoteV1/Tools/Extensions.cs +++ b/mRemoteV1/Tools/Extensions.cs @@ -1,5 +1,4 @@ - -using System; +using System; using System.Collections.Generic; using System.Linq; using mRemoteNG.Connection; @@ -8,23 +7,23 @@ using mRemoteNG.Container; namespace mRemoteNG.Tools { public static class Extensions - { + { public static Optional ToOptional(this T value) - { - return new Optional(value); - } + { + return new Optional(value); + } - public static Optional MaybeParse(this T value, Func parseFunc) - { - try - { - return new Optional(parseFunc(value)); - } - catch - { - return new Optional(); - } - } + public static Optional MaybeParse(this T value, Func parseFunc) + { + try + { + return new Optional(parseFunc(value)); + } + catch + { + return new Optional(); + } + } /// /// Throws an if the given value is @@ -35,12 +34,12 @@ namespace mRemoteNG.Tools /// /// The name of the argument /// - public static T ThrowIfNull(this T value, string argName) - { + public static T ThrowIfNull(this T value, string argName) + { if (value == null) throw new ArgumentNullException(argName); - return value; - } + return value; + } /// /// Throws an if the value @@ -48,12 +47,12 @@ namespace mRemoteNG.Tools /// /// /// - public static string ThrowIfNullOrEmpty(this string value, string argName) - { + public static string ThrowIfNullOrEmpty(this string value, string argName) + { if (string.IsNullOrEmpty(value)) throw new ArgumentException("Value cannot be null or empty", argName); - return value; - } + return value; + } /// /// Perform an action for each item in the given collection. The item @@ -63,15 +62,15 @@ namespace mRemoteNG.Tools /// /// /// - public static IEnumerable ForEach(this IEnumerable collection, Action action) + public static IEnumerable ForEach(this IEnumerable collection, Action action) { collection = collection.ToList(); foreach (var item in collection) - action(item); + action(item); - return collection; - } + return collection; + } public static IEnumerable FlattenConnectionTree(this IEnumerable connections) { @@ -84,7 +83,7 @@ namespace mRemoteNG.Tools foreach (var child in FlattenConnectionTree(container.Children)) yield return child; - } + } } } } diff --git a/mRemoteV1/Tools/ExternalTool.cs b/mRemoteV1/Tools/ExternalTool.cs index 7de84eb8..f9370e17 100644 --- a/mRemoteV1/Tools/ExternalTool.cs +++ b/mRemoteV1/Tools/ExternalTool.cs @@ -8,129 +8,135 @@ using mRemoteNG.App; using mRemoteNG.Connection; using mRemoteNG.Connection.Protocol; using mRemoteNG.Messages; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Tools { - public class ExternalTool : INotifyPropertyChanged - { + public class ExternalTool : INotifyPropertyChanged + { private readonly IConnectionInitiator _connectionInitiator = new ConnectionInitiator(Runtime.CredentialService); - private string _displayName; - private string _fileName; - private bool _waitForExit; - private string _arguments; - private string _workingDir; - private bool _tryIntegrate; - private bool _showOnToolbar = true; - private bool _runElevated; + private string _displayName; + private string _fileName; + private bool _waitForExit; + private string _arguments; + private string _workingDir; + private bool _tryIntegrate; + private bool _showOnToolbar = true; + private bool _runElevated; - #region Public Properties + #region Public Properties - public string DisplayName - { - get { return _displayName; } - set { SetField(ref _displayName, value, nameof(DisplayName)); } - } + public string DisplayName + { + get { return _displayName; } + set { SetField(ref _displayName, value, nameof(DisplayName)); } + } - public string FileName - { - get { return _fileName; } - set { SetField(ref _fileName, value, nameof(FileName)); } - } + public string FileName + { + get { return _fileName; } + set { SetField(ref _fileName, value, nameof(FileName)); } + } - public bool WaitForExit - { - get { return _waitForExit; } - set - { - // WaitForExit cannot be turned on when TryIntegrate is true + public bool WaitForExit + { + get { return _waitForExit; } + set + { + // WaitForExit cannot be turned on when TryIntegrate is true if (TryIntegrate) return; SetField(ref _waitForExit, value, nameof(WaitForExit)); - } - } + } + } - public string Arguments - { - get { return _arguments; } - set { SetField(ref _arguments, value, nameof(Arguments)); } - } + public string Arguments + { + get { return _arguments; } + set { SetField(ref _arguments, value, nameof(Arguments)); } + } - public string WorkingDir - { - get { return _workingDir; } - set { SetField(ref _workingDir, value, nameof(WorkingDir)); } - } + public string WorkingDir + { + get { return _workingDir; } + set { SetField(ref _workingDir, value, nameof(WorkingDir)); } + } - public bool TryIntegrate - { - get { return _tryIntegrate; } - set - { + public bool TryIntegrate + { + get { return _tryIntegrate; } + set + { // WaitForExit cannot be turned on when TryIntegrate is true - if (value) - WaitForExit = false; - SetField(ref _tryIntegrate, value, nameof(TryIntegrate)); - } - } + if (value) + WaitForExit = false; + SetField(ref _tryIntegrate, value, nameof(TryIntegrate)); + } + } - public bool ShowOnToolbar - { - get { return _showOnToolbar; } - set { SetField(ref _showOnToolbar, value, nameof(ShowOnToolbar)); } - } + public bool ShowOnToolbar + { + get { return _showOnToolbar; } + set { SetField(ref _showOnToolbar, value, nameof(ShowOnToolbar)); } + } - public bool RunElevated - { - get { return _runElevated; } - set { SetField(ref _runElevated, value, nameof(RunElevated)); } - } + public bool RunElevated + { + get { return _runElevated; } + set { SetField(ref _runElevated, value, nameof(RunElevated)); } + } + + public ConnectionInfo ConnectionInfo { get; set; } - public ConnectionInfo ConnectionInfo { get; set; } - public Icon Icon { get { return File.Exists(FileName) ? MiscTools.GetIconFromFile(FileName) : Resources.mRemoteNG_Icon; } } - public Image Image - { - get { return Icon?.ToBitmap() ?? Resources.mRemoteNG_Icon.ToBitmap(); } - } + public Image Image + { + get { return Icon?.ToBitmap() ?? Resources.mRemoteNG_Icon.ToBitmap(); } + } - #endregion - - public ExternalTool(string displayName = "", string fileName = "", string arguments = "", string workingDir = "", bool runElevated = false) - { - DisplayName = displayName; - FileName = fileName; - Arguments = arguments; + #endregion + + public ExternalTool(string displayName = "", + string fileName = "", + string arguments = "", + string workingDir = "", + bool runElevated = false) + { + DisplayName = displayName; + FileName = fileName; + Arguments = arguments; WorkingDir = workingDir; RunElevated = runElevated; - } + } public void Start(ConnectionInfo startConnectionInfo = null) - { - try - { - if (string.IsNullOrEmpty(FileName)) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "ExternalApp.Start() failed: FileName cannot be blank."); - return; - } - - ConnectionInfo = startConnectionInfo; - - if (TryIntegrate) - StartIntegrated(); + { + try + { + if (string.IsNullOrEmpty(FileName)) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "ExternalApp.Start() failed: FileName cannot be blank."); + return; + } + + ConnectionInfo = startConnectionInfo; + + if (TryIntegrate) + StartIntegrated(); else StartExternalProcess(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("ExternalApp.Start() failed.", ex); - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("ExternalApp.Start() failed.", ex); + } + } private void StartExternalProcess() { @@ -155,17 +161,17 @@ namespace mRemoteNG.Tools } private void StartIntegrated() - { - try - { + { + try + { var newConnectionInfo = BuildConnectionInfoForIntegratedApp(); _connectionInitiator.OpenConnection(newConnectionInfo); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("ExternalApp.StartIntegrated() failed.", ex); - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("ExternalApp.StartIntegrated() failed.", ex); + } + } private ConnectionInfo BuildConnectionInfoForIntegratedApp() { @@ -180,7 +186,7 @@ namespace mRemoteNG.Tools return newConnectionInfo; } - private void SetConnectionInfoFields(ConnectionInfo newConnectionInfo) + private void SetConnectionInfoFields(ConnectionInfo newConnectionInfo) { newConnectionInfo.Protocol = ProtocolType.IntApp; newConnectionInfo.ExtApp = DisplayName; @@ -188,19 +194,19 @@ namespace mRemoteNG.Tools newConnectionInfo.Panel = Language.strMenuExternalTools; } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void RaisePropertyChangedEvent(object sender, string propertyName) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } + protected virtual void RaisePropertyChangedEvent(object sender, string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } - protected bool SetField(ref T field, T value, string propertyName) - { - if (EqualityComparer.Default.Equals(field, value)) return false; - field = value; - RaisePropertyChangedEvent(this, propertyName); - return true; - } + protected bool SetField(ref T field, T value, string propertyName) + { + if (EqualityComparer.Default.Equals(field, value)) return false; + field = value; + RaisePropertyChangedEvent(this, propertyName); + return true; + } } } \ No newline at end of file diff --git a/mRemoteV1/Tools/ExternalToolArgumentParser.cs b/mRemoteV1/Tools/ExternalToolArgumentParser.cs index 3b121de2..2039fafb 100644 --- a/mRemoteV1/Tools/ExternalToolArgumentParser.cs +++ b/mRemoteV1/Tools/ExternalToolArgumentParser.cs @@ -11,7 +11,7 @@ using mRemoteNG.Tools.Cmdline; namespace mRemoteNG.Tools { - public class ExternalToolArgumentParser + public class ExternalToolArgumentParser { private readonly ConnectionInfo _connectionInfo; private readonly ICredentialService _credentialService; @@ -122,7 +122,9 @@ namespace mRemoteNG.Tools if (haveReplacement) { - var trailing = tokenEnd + 2 <= input.Length ? input.Substring(tokenEnd + 1, 1).ToCharArray()[0] : '\0'; + var trailing = tokenEnd + 2 <= input.Length + ? input.Substring(tokenEnd + 1, 1).ToCharArray()[0] + : '\0'; if (escape == EscapeType.All) { @@ -142,6 +144,7 @@ namespace mRemoteNG.Tools index = tokenEnd; } } while (true); + return replacements; } @@ -158,6 +161,7 @@ namespace mRemoteNG.Tools escape = EscapeType.None; break; } + return escape; } @@ -233,6 +237,7 @@ namespace mRemoteNG.Tools result = before + replacement.Value + after; } } + return result; } diff --git a/mRemoteV1/Tools/ExternalToolsService.cs b/mRemoteV1/Tools/ExternalToolsService.cs index a091f6de..5957da98 100644 --- a/mRemoteV1/Tools/ExternalToolsService.cs +++ b/mRemoteV1/Tools/ExternalToolsService.cs @@ -5,7 +5,8 @@ namespace mRemoteNG.Tools { public class ExternalToolsService { - public FullyObservableCollection ExternalTools { get; set; } = new FullyObservableCollection(); + public FullyObservableCollection ExternalTools { get; set; } = + new FullyObservableCollection(); public ExternalTool GetExtAppByName(string name) { diff --git a/mRemoteV1/Tools/ExternalToolsTypeConverter.cs b/mRemoteV1/Tools/ExternalToolsTypeConverter.cs index f409c918..4b1378e8 100644 --- a/mRemoteV1/Tools/ExternalToolsTypeConverter.cs +++ b/mRemoteV1/Tools/ExternalToolsTypeConverter.cs @@ -38,4 +38,4 @@ namespace mRemoteNG.Tools return true; } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tools/IeBrowserEmulation.cs b/mRemoteV1/Tools/IeBrowserEmulation.cs index ad6c85ca..c374626b 100644 --- a/mRemoteV1/Tools/IeBrowserEmulation.cs +++ b/mRemoteV1/Tools/IeBrowserEmulation.cs @@ -8,24 +8,31 @@ using mRemoteNG.App; namespace mRemoteNG.Tools { - public class IeBrowserEmulation + public class IeBrowserEmulation { // found this here: // http://www.neowin.net/forum/topic/1077469-vbnet-webbrowser-control-does-not-load-javascript/#comment-596755046 private static void SetBrowserFeatureControlKey(string feature, string appName, uint value) { - if (Environment.Is64BitOperatingSystem) { - using (var key = Registry.CurrentUser.CreateSubKey(string.Concat("Software\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", feature), RegistryKeyPermissionCheck.ReadWriteSubTree)) + using (var key = Registry.CurrentUser.CreateSubKey( + string + .Concat("Software\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", + feature), + RegistryKeyPermissionCheck.ReadWriteSubTree)) { key?.SetValue(appName, value, RegistryValueKind.DWord); } } - using (var key = Registry.CurrentUser.CreateSubKey(string.Concat("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", feature), RegistryKeyPermissionCheck.ReadWriteSubTree)) + using (var key = Registry.CurrentUser.CreateSubKey( + string + .Concat("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", + feature), + RegistryKeyPermissionCheck.ReadWriteSubTree)) { key?.SetValue(appName, value, RegistryValueKind.DWord); } @@ -34,10 +41,13 @@ namespace mRemoteNG.Tools #if PORTABLE private static void DeleteBrowserFeatureControlKey(string feature, string appName) { - if (Environment.Is64BitOperatingSystem) { - using (var key = Registry.CurrentUser.OpenSubKey(string.Concat("Software\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", feature), RegistryKeyPermissionCheck.ReadWriteSubTree)) + using (var key = Registry.CurrentUser.OpenSubKey( + string + .Concat("Software\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", + feature), + RegistryKeyPermissionCheck.ReadWriteSubTree)) { if (key?.GetValueNames().Contains(appName) ?? false) key.DeleteValue(appName); @@ -45,7 +55,11 @@ namespace mRemoteNG.Tools } - using (var key = Registry.CurrentUser.CreateSubKey(string.Concat("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", feature), RegistryKeyPermissionCheck.ReadWriteSubTree)) + using (var key = Registry.CurrentUser.CreateSubKey( + string + .Concat("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\", + feature), + RegistryKeyPermissionCheck.ReadWriteSubTree)) { if (key?.GetValueNames().Contains(appName) ?? false) key.DeleteValue(appName); @@ -61,7 +75,8 @@ namespace mRemoteNG.Tools var 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 || string.Compare(fileName, "XDesProc.exe", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(fileName, "devenv.exe", StringComparison.OrdinalIgnoreCase) == 0 || + string.Compare(fileName, "XDesProc.exe", StringComparison.OrdinalIgnoreCase) == 0) { return; } @@ -102,7 +117,8 @@ namespace mRemoteNG.Tools var 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 || string.Compare(fileName, "XDesProc.exe", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(fileName, "devenv.exe", StringComparison.OrdinalIgnoreCase) == 0 || + string.Compare(fileName, "XDesProc.exe", StringComparison.OrdinalIgnoreCase) == 0) { return; } @@ -142,7 +158,9 @@ namespace mRemoteNG.Tools var browserVersion = 9; // default to IE9. - using (var ieKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.QueryValues)) + using (var ieKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer", + RegistryKeyPermissionCheck.ReadSubTree, + RegistryRights.QueryValues)) { if (ieKey != null) { @@ -155,6 +173,7 @@ namespace mRemoteNG.Tools throw new ApplicationException("Microsoft Internet Explorer is required!"); } } + int.TryParse(version.ToString().Split('.')[0], out browserVersion); } } diff --git a/mRemoteV1/Tools/MiscTools.cs b/mRemoteV1/Tools/MiscTools.cs index 9cdf2ff2..57d31df9 100644 --- a/mRemoteV1/Tools/MiscTools.cs +++ b/mRemoteV1/Tools/MiscTools.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel; using System.Drawing; +using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Security; @@ -13,197 +14,205 @@ using static System.String; namespace mRemoteNG.Tools { public static class MiscTools - { - public static Icon GetIconFromFile(string FileName) - { - try - { - return File.Exists(FileName) == false ? null : Icon.ExtractAssociatedIcon(FileName); - } - catch (ArgumentException AEx) - { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, - "GetIconFromFile failed (Tools.Misc) - using default icon" + Environment.NewLine + AEx.Message, true); + { + public static Icon GetIconFromFile(string FileName) + { + try + { + return File.Exists(FileName) == false ? null : Icon.ExtractAssociatedIcon(FileName); + } + catch (ArgumentException AEx) + { + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "GetIconFromFile failed (Tools.Misc) - using default icon" + + Environment.NewLine + AEx.Message, + true); return Resources.mRemoteNG_Icon; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "GetIconFromFile failed (Tools.Misc)" + Environment.NewLine + + ex.Message, true); + return null; + } + } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "GetIconFromFile failed (Tools.Misc)" + Environment.NewLine + ex.Message, true); - return null; - } - } - - public static Optional PasswordDialog(string passwordName = null, bool verify = true) - { - var passwordForm = new PasswordForm(passwordName, verify); - return passwordForm.GetKey(); - } - + public static Optional PasswordDialog(string passwordName = null, bool verify = true) + { + var passwordForm = new PasswordForm(passwordName, verify); + return passwordForm.GetKey(); + } - public static string CreateConstantID() - { - return Guid.NewGuid().ToString(); - } - - public static string LeadingZero(string Number) - { - if (Convert.ToInt32(Number) < 10) - { - return "0" + Number; - } - return Number; - } + public static string CreateConstantID() + { + return Guid.NewGuid().ToString(); + } + + + public static string LeadingZero(string Number) + { + if (Convert.ToInt32(Number) < 10) + { + return "0" + Number; + } + + return Number; + } public static string DBDate(DateTime Dt) - { - var strDate = Dt.Year + LeadingZero(Convert.ToString(Dt.Month)) + LeadingZero(Convert.ToString(Dt.Day)) + " " + LeadingZero(Convert.ToString(Dt.Hour)) + ":" + LeadingZero(Convert.ToString(Dt.Minute)) + ":" + LeadingZero(Convert.ToString(Dt.Second)); - return strDate; - } + { + var strDate = Dt.Year + LeadingZero(Convert.ToString(Dt.Month)) + LeadingZero(Convert.ToString(Dt.Day)) + + " " + LeadingZero(Convert.ToString(Dt.Hour)) + ":" + + LeadingZero(Convert.ToString(Dt.Minute)) + ":" + LeadingZero(Convert.ToString(Dt.Second)); + return strDate; + } - public static string PrepareValueForDB(string Text) - { - return Text.Replace("\'", "\'\'"); - } + public static string PrepareValueForDB(string Text) + { + return Text.Replace("\'", "\'\'"); + } public static string GetExceptionMessageRecursive(Exception ex) { return GetExceptionMessageRecursive(ex, Environment.NewLine); } + private static string GetExceptionMessageRecursive(Exception ex, string separator) - { - var message = ex.Message; - if (ex.InnerException == null) return message; - var innerMessage = GetExceptionMessageRecursive(ex.InnerException, separator); - message = Join(separator, message, innerMessage); - return message; - } - + { + var message = ex.Message; + if (ex.InnerException == null) return message; + var innerMessage = GetExceptionMessageRecursive(ex.InnerException, separator); + message = Join(separator, message, innerMessage); + return message; + } - public static Image TakeScreenshot(ConnectionWindow sender) - { - try - { - var LeftStart = sender.TabController.SelectedTab.PointToScreen(new Point(sender.TabController.SelectedTab.Left)).X; //Me.Left + Splitter.SplitterDistance + 11 - var TopStart = sender.TabController.SelectedTab.PointToScreen(new Point(sender.TabController.SelectedTab.Top)).Y; //Me.Top + Splitter.Top + TabController.Top + TabController.SelectedTab.Top * 2 - 3 - var LeftWidth = sender.TabController.SelectedTab.Width; //Me.Width - (Splitter.SplitterDistance + 16) - var TopHeight = sender.TabController.SelectedTab.Height; //Me.Height - (Splitter.Top + TabController.Top + TabController.SelectedTab.Top * 2 + 2) - - var currentFormSize = new Size(LeftWidth, TopHeight); - var ScreenToBitmap = new Bitmap(LeftWidth, TopHeight); - var gGraphics = Graphics.FromImage(ScreenToBitmap); - - gGraphics.CopyFromScreen(new Point(LeftStart, TopStart), new Point(0, 0), currentFormSize); - - return ScreenToBitmap; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("Taking Screenshot failed", ex); - } - - return null; - } - - public class EnumTypeConverter : EnumConverter - { - private readonly Type _enumType; - - public EnumTypeConverter(Type type) : base(type) - { - _enumType = type; - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) - { - return destType == typeof(string); - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) - { - if (value == null) return null; - var fi = _enumType.GetField(Enum.GetName(_enumType, value)); - var dna = (DescriptionAttribute) Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); - - return dna != null ? dna.Description : value.ToString(); - } - - public override bool CanConvertFrom(ITypeDescriptorContext context, Type srcType) - { - return srcType == typeof(string); - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - foreach (var fi in _enumType.GetFields()) - { - var dna = (DescriptionAttribute) Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); - - if (dna != null && (string) value == dna.Description) - { - return Enum.Parse(_enumType, fi.Name); - } - } - return value != null ? Enum.Parse(_enumType, (string) value) : null; - } - } - - public class YesNoTypeConverter : TypeConverter - { - - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - if (!(value is string)) return base.ConvertFrom(context, culture, value); - if (string.Equals(value.ToString(), Language.strYes, StringComparison.CurrentCultureIgnoreCase)) - { - return true; - } - - if (string.Equals(value.ToString(), Language.strNo, StringComparison.CurrentCultureIgnoreCase)) - { - return false; - } - - throw new Exception("Values must be \"Yes\" or \"No\""); - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (destinationType == typeof(string)) - { - return Convert.ToBoolean(value) ? Language.strYes : Language.strNo; - } - - return base.ConvertTo(context, culture, value, destinationType); - } - - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } - - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - bool[] bools = {true, false}; - - var svc = new StandardValuesCollection(bools); - - return svc; - } - } - } + public static Image TakeScreenshot(UI.Tabs.ConnectionTab sender) + { + try + { + if (sender != null) + { + var bmp = new Bitmap(sender.Width, sender.Height, PixelFormat.Format32bppRgb); + Graphics g = Graphics.FromImage(bmp); + g.CopyFromScreen(sender.PointToScreen(Point.Empty), Point.Empty, bmp.Size, + CopyPixelOperation.SourceCopy); + return bmp; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace("Taking Screenshot failed", ex); + } + + return null; + } + + public class EnumTypeConverter : EnumConverter + { + private readonly Type _enumType; + + public EnumTypeConverter(Type type) : base(type) + { + _enumType = type; + } + + public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) + { + return destType == typeof(string); + } + + public override object ConvertTo(ITypeDescriptorContext context, + CultureInfo culture, + object value, + Type destType) + { + if (value == null) return null; + var fi = _enumType.GetField(Enum.GetName(_enumType, value)); + var dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); + + return dna != null ? dna.Description : value.ToString(); + } + + public override bool CanConvertFrom(ITypeDescriptorContext context, Type srcType) + { + return srcType == typeof(string); + } + + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + foreach (var fi in _enumType.GetFields()) + { + var dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); + + if (dna != null && (string)value == dna.Description) + { + return Enum.Parse(_enumType, fi.Name); + } + } + + return value != null ? Enum.Parse(_enumType, (string)value) : null; + } + } + + public class YesNoTypeConverter : TypeConverter + { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); + } + + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (!(value is string)) return base.ConvertFrom(context, culture, value); + if (string.Equals(value.ToString(), Language.strYes, StringComparison.CurrentCultureIgnoreCase)) + { + return true; + } + + if (string.Equals(value.ToString(), Language.strNo, StringComparison.CurrentCultureIgnoreCase)) + { + return false; + } + + throw new Exception("Values must be \"Yes\" or \"No\""); + } + + public override object ConvertTo(ITypeDescriptorContext context, + CultureInfo culture, + object value, + Type destinationType) + { + if (destinationType == typeof(string)) + { + return Convert.ToBoolean(value) ? Language.strYes : Language.strNo; + } + + return base.ConvertTo(context, culture, value, destinationType); + } + + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { + return true; + } + + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + bool[] bools = {true, false}; + + var svc = new StandardValuesCollection(bools); + + return svc; + } + } + } } \ No newline at end of file diff --git a/mRemoteV1/Tools/MouseClickSimulator.cs b/mRemoteV1/Tools/MouseClickSimulator.cs index f39dccd9..d0b70226 100644 --- a/mRemoteV1/Tools/MouseClickSimulator.cs +++ b/mRemoteV1/Tools/MouseClickSimulator.cs @@ -13,7 +13,9 @@ namespace mRemoteNG.Tools var clientMousePosition = controlToClick.PointToClient(currentMousePosition); var tempWLow = clientMousePosition.X; var tempWHigh = clientMousePosition.Y; - NativeMethods.SendMessage(controlToClick.Handle, NativeMethods.WM_LBUTTONDOWN, (IntPtr)NativeMethods.MK_LBUTTON, (IntPtr)NativeMethods.MAKELPARAM(ref tempWLow, ref tempWHigh)); + NativeMethods.SendMessage(controlToClick.Handle, NativeMethods.WM_LBUTTONDOWN, + (IntPtr)NativeMethods.MK_LBUTTON, + (IntPtr)NativeMethods.MAKELPARAM(ref tempWLow, ref tempWHigh)); clientMousePosition.X = tempWLow; clientMousePosition.Y = tempWHigh; controlToClick.Focus(); diff --git a/mRemoteV1/Tools/MultiSSHController.cs b/mRemoteV1/Tools/MultiSSHController.cs index ffc14cdb..d2dc91b8 100644 --- a/mRemoteV1/Tools/MultiSSHController.cs +++ b/mRemoteV1/Tools/MultiSSHController.cs @@ -8,7 +8,7 @@ using mRemoteNG.Connection.Protocol; namespace mRemoteNG.Tools { - public class MultiSSHController + public class MultiSSHController { private readonly ArrayList processHandlers = new ArrayList(); private readonly ArrayList quickConnectConnections = new ArrayList(); @@ -60,13 +60,15 @@ namespace mRemoteNG.Tools { return; } + foreach (PuttyBase proc in processHandlers) { NativeMethods.PostMessage(proc.PuttyHandle, keyType, new IntPtr(keyData), new IntPtr(0)); } } -#region Event Processors + #region Event Processors + private void refreshActiveConnections(object sender, EventArgs e) { processHandlers.Clear(); @@ -75,7 +77,8 @@ namespace mRemoteNG.Tools processHandlers.AddRange(ProcessOpenConnections(connection)); } - var connectionTreeConnections = Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveChildList().Where(item => item.OpenConnections.Count > 0); + var connectionTreeConnections = Runtime.ConnectionsService.ConnectionTreeModel.GetRecursiveChildList() + .Where(item => item.OpenConnections.Count > 0); foreach (var connection in connectionTreeConnections) { @@ -85,7 +88,7 @@ namespace mRemoteNG.Tools private void processKeyPress(object sender, KeyEventArgs e) { - if (!(sender is TextBox txtMultiSSH)) return; + if (!(sender is TextBox txtMultiSSH)) return; if (processHandlers.Count == 0) { @@ -121,6 +124,7 @@ namespace mRemoteNG.Tools { SendAllKeystrokes(NativeMethods.WM_CHAR, Convert.ToByte(chr1)); } + SendAllKeystrokes(NativeMethods.WM_KEYDOWN, 13); // Enter = char13 } @@ -133,6 +137,7 @@ namespace mRemoteNG.Tools { previousCommands.Add(txtMultiSSH.Text.Trim()); } + if (previousCommands.Count >= CommandHistoryLength) { previousCommands.RemoveAt(0); @@ -141,6 +146,7 @@ namespace mRemoteNG.Tools previousCommandIndex = previousCommands.Count - 1; txtMultiSSH.Clear(); } -#endregion + + #endregion } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tools/NotificationAreaIcon.cs b/mRemoteV1/Tools/NotificationAreaIcon.cs index ec2fd979..cd8bef4c 100644 --- a/mRemoteV1/Tools/NotificationAreaIcon.cs +++ b/mRemoteV1/Tools/NotificationAreaIcon.cs @@ -37,7 +37,7 @@ namespace mRemoteNG.Tools _cMen = new ContextMenuStrip { Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, - System.Drawing.GraphicsUnit.Point, Convert.ToByte(0)), + System.Drawing.GraphicsUnit.Point, Convert.ToByte(0)), RenderMode = ToolStripRenderMode.Professional }; _cMen.Items.AddRange(new ToolStripItem[] {_cMenCons, cMenSep1, cMenExit}); @@ -85,7 +85,9 @@ namespace mRemoteNG.Tools }; // ReSharper disable once CoVariantArrayConversion - ToolStripItem[] rootMenuItems = menuItemsConverter.CreateToolStripDropDownItems(Runtime.ConnectionsService.ConnectionTreeModel).ToArray(); + ToolStripItem[] rootMenuItems = menuItemsConverter + .CreateToolStripDropDownItems(Runtime.ConnectionsService + .ConnectionTreeModel).ToArray(); _cMenCons.DropDownItems.AddRange(rootMenuItems); } @@ -119,7 +121,7 @@ namespace mRemoteNG.Tools if (((ToolStripMenuItem)sender).Tag is ContainerInfo) return; if (FrmMain.Visible == false) ShowForm(); - _connectionInitiator.OpenConnection((ConnectionInfo) ((ToolStripMenuItem) sender).Tag); + _connectionInitiator.OpenConnection((ConnectionInfo)((ToolStripMenuItem)sender).Tag); } private static void cMenExit_Click(object sender, EventArgs e) diff --git a/mRemoteV1/Tools/Optional.cs b/mRemoteV1/Tools/Optional.cs index edbf644a..e9e10deb 100644 --- a/mRemoteV1/Tools/Optional.cs +++ b/mRemoteV1/Tools/Optional.cs @@ -12,26 +12,26 @@ namespace mRemoteNG.Tools /// The underlying type that may or may not have a value public class Optional : IEnumerable, IComparable> { - private readonly T[] _optional; + private readonly T[] _optional; /// /// Create a new empty instance of Optional /// - public Optional() - { - _optional = new T[0]; - } + public Optional() + { + _optional = new T[0]; + } /// /// Create a new instance of Optional from the given value. /// If the value is null, the Optional will be empty /// - public Optional(T value) - { - _optional = value != null - ? new[] {value} - : new T[0]; - } + public Optional(T value) + { + _optional = value != null + ? new[] {value} + : new T[0]; + } public override string ToString() { @@ -57,18 +57,21 @@ namespace mRemoteNG.Tools public static Optional Empty => new Optional(); #region IEnumerable - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - public IEnumerator GetEnumerator() - { - return ((IEnumerable)_optional).GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public IEnumerator GetEnumerator() + { + return ((IEnumerable)_optional).GetEnumerator(); + } + #endregion #region IComparable + /// /// Compares this to another instance /// of the same type. For purposes of comparison, empty Optional @@ -96,58 +99,61 @@ namespace mRemoteNG.Tools return ((IComparable)_optional[0]).CompareTo(other.First()); throw new ArgumentException(string.Format( - "Cannot compare objects. Optional type {0} is not comparable to itself", - typeof(T).FullName)); + "Cannot compare objects. Optional type {0} is not comparable to itself", + typeof(T).FullName)); } + #endregion #region Override Equals and GetHashCode public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - return true; + { + if (ReferenceEquals(this, obj)) + return true; - var objAsOptional = obj as Optional; - if (objAsOptional != null) - return Equals(objAsOptional); + var objAsOptional = obj as Optional; + if (objAsOptional != null) + return Equals(objAsOptional); - if (obj is T) - Equals((T)obj); + if (obj is T) + Equals((T)obj); - return false; - } + return false; + } - public bool Equals(Optional other) - { - var otherObj = other.FirstOrDefault(); - var thisObj = _optional.FirstOrDefault(); - if (thisObj == null && otherObj == null) - return true; - if (thisObj == null) - return false; - return thisObj.Equals(otherObj); - } + public bool Equals(Optional other) + { + var otherObj = other.FirstOrDefault(); + var thisObj = _optional.FirstOrDefault(); + if (thisObj == null && otherObj == null) + return true; + if (thisObj == null) + return false; + return thisObj.Equals(otherObj); + } - public override int GetHashCode() - { - return _optional != null - ? _optional.GetHashCode() - : 0; - } - #endregion + public override int GetHashCode() + { + return _optional != null + ? _optional.GetHashCode() + : 0; + } - #region Operators + #endregion - public static bool operator ==(Optional left, Optional right) - { - return Equals(left, right); - } + #region Operators - public static bool operator !=(Optional left, Optional right) - { - return !Equals(left, right); - } - #endregion - } -} + public static bool operator ==(Optional left, Optional right) + { + return Equals(left, right); + } + + public static bool operator !=(Optional left, Optional right) + { + return !Equals(left, right); + } + + #endregion + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/PortScanner.cs b/mRemoteV1/Tools/PortScanner.cs index 3b213542..212c426a 100644 --- a/mRemoteV1/Tools/PortScanner.cs +++ b/mRemoteV1/Tools/PortScanner.cs @@ -11,36 +11,45 @@ using mRemoteNG.Messages; namespace mRemoteNG.Tools { - public class PortScanner - { - private readonly List _ipAddresses = new List(); - private readonly List _ports = new List(); - private Thread _scanThread; - private readonly List _scannedHosts = new List(); - private readonly int _timeoutInMilliseconds; + public class PortScanner + { + private readonly List _ipAddresses = new List(); + private readonly List _ports = new List(); + private Thread _scanThread; + private readonly List _scannedHosts = new List(); + private readonly int _timeoutInMilliseconds; #region Public Methods - public PortScanner(IPAddress ipAddress1, IPAddress ipAddress2, int port1, int port2, int timeoutInMilliseconds = 5000, bool checkDefaultPortsOnly = false) - { + public PortScanner(IPAddress ipAddress1, + IPAddress ipAddress2, + int port1, + int port2, + int timeoutInMilliseconds = 5000, + bool checkDefaultPortsOnly = false) + { var ipAddressStart = IpAddressMin(ipAddress1, ipAddress2); var ipAddressEnd = IpAddressMax(ipAddress1, ipAddress2); var portStart = Math.Min(port1, port2); - var portEnd = Math.Max(port1, port2); + var portEnd = Math.Max(port1, port2); // if only one port was specified, just scan the one port... if (portStart == 0) portStart = portEnd; - if (timeoutInMilliseconds < 0) - throw new ArgumentOutOfRangeException(nameof(timeoutInMilliseconds)); + if (timeoutInMilliseconds < 0) + throw new ArgumentOutOfRangeException(nameof(timeoutInMilliseconds)); - _timeoutInMilliseconds = timeoutInMilliseconds; - _ports.Clear(); + _timeoutInMilliseconds = timeoutInMilliseconds; + _ports.Clear(); if (checkDefaultPortsOnly) - _ports.AddRange(new[] { ScanHost.SshPort, ScanHost.TelnetPort, ScanHost.HttpPort, ScanHost.HttpsPort, ScanHost.RloginPort, ScanHost.RdpPort, ScanHost.VncPort }); + _ports.AddRange(new[] + { + ScanHost.SshPort, ScanHost.TelnetPort, ScanHost.HttpPort, ScanHost.HttpsPort, ScanHost.RloginPort, + ScanHost.RdpPort, ScanHost.VncPort + }); else { for (var port = portStart; port <= portEnd; port++) @@ -54,49 +63,54 @@ namespace mRemoteNG.Tools _scannedHosts.Clear(); } - - public void StartScan() - { - _scanThread = new Thread(ScanAsync); - _scanThread.SetApartmentState(ApartmentState.STA); - _scanThread.IsBackground = true; - _scanThread.Start(); - } - - public void StopScan() - { - foreach(var p in _pings) + + public void StartScan() + { + _scanThread = new Thread(ScanAsync); + _scanThread.SetApartmentState(ApartmentState.STA); + _scanThread.IsBackground = true; + _scanThread.Start(); + } + + public void StopScan() + { + foreach (var p in _pings) { p.SendAsyncCancel(); } - _scanThread.Abort(); + + _scanThread.Abort(); } - - public static bool IsPortOpen(string hostname, string port) - { - try - { - var tcpClient = new TcpClient(hostname, Convert.ToInt32(port)); - tcpClient.Close(); - return true; - } - catch (Exception) - { - return false; - } - } + + public static bool IsPortOpen(string hostname, string port) + { + try + { + var tcpClient = new TcpClient(hostname, Convert.ToInt32(port)); + tcpClient.Close(); + return true; + } + catch (Exception) + { + return false; + } + } + #endregion #region Private Methods private int _hostCount; private readonly List _pings = new List(); + private void ScanAsync() - { - try - { - _hostCount = 0; - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Tools.PortScan: Starting scan of {_ipAddresses.Count} hosts...", true); + { + try + { + _hostCount = 0; + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Tools.PortScan: Starting scan of {_ipAddresses.Count} hosts...", + true); foreach (var ipAddress in _ipAddresses) { RaiseBeginHostScanEvent(ipAddress); @@ -111,15 +125,19 @@ namespace mRemoteNG.Tools } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, $"Tools.PortScan: Ping failed for {ipAddress} {Environment.NewLine} {ex.Message}", true); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + $"Tools.PortScan: Ping failed for {ipAddress} {Environment.NewLine} {ex.Message}", + true); } } } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, $"StartScanBG failed (Tools.PortScan) {Environment.NewLine} {ex.Message}", true); - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + $"StartScanBG failed (Tools.PortScan) {Environment.NewLine} {ex.Message}", + true); + } + } /* Some examples found here: * http://stackoverflow.com/questions/2114266/convert-ping-application-to-multithreaded-version-to-increase-speed-c-sharp @@ -134,12 +152,15 @@ namespace mRemoteNG.Tools var scanHost = new ScanHost(ip); _hostCount++; - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Tools.PortScan: Scanning {_hostCount} of {_ipAddresses.Count} hosts: {scanHost.HostIp}", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Tools.PortScan: Scanning {_hostCount} of {_ipAddresses.Count} hosts: {scanHost.HostIp}", + true); + - if (e.Cancelled) { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Tools.PortScan: CANCELLED host: {scanHost.HostIp}", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Tools.PortScan: CANCELLED host: {scanHost.HostIp}", true); // cleanup p.PingCompleted -= PingSender_PingCompleted; p.Dispose(); @@ -148,7 +169,9 @@ namespace mRemoteNG.Tools if (e.Error != null) { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Ping failed to {e.UserState} {Environment.NewLine} {e.Error.Message}", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Ping failed to {e.UserState} {Environment.NewLine} {e.Error.Message}", + true); scanHost.ClosedPorts.AddRange(_ports); scanHost.SetAllProtocols(false); } @@ -162,8 +185,8 @@ namespace mRemoteNG.Tools catch (Exception dnsex) { Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, - $"Tools.PortScan: Could not resolve {scanHost.HostIp} {Environment.NewLine} {dnsex.Message}", - true); + $"Tools.PortScan: Could not resolve {scanHost.HostIp} {Environment.NewLine} {dnsex.Message}", + true); } if (string.IsNullOrEmpty(scanHost.HostName)) @@ -217,9 +240,10 @@ namespace mRemoteNG.Tools } } } - else if(e.Reply.Status != IPStatus.Success) + else if (e.Reply.Status != IPStatus.Success) { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Ping did not complete to {e.UserState} : {e.Reply.Status}", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Ping did not complete to {e.UserState} : {e.Reply.Status}", true); scanHost.ClosedPorts.AddRange(_ports); scanHost.SetAllProtocols(false); } @@ -229,7 +253,8 @@ namespace mRemoteNG.Tools p.Dispose(); var h = string.IsNullOrEmpty(scanHost.HostName) ? "HostNameNotFound" : scanHost.HostName; - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Tools.PortScan: Scan of {scanHost.HostIp} ({h}) complete.", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Tools.PortScan: Scan of {scanHost.HostIp} ({h}) complete.", true); _scannedHosts.Add(scanHost); RaiseHostScannedEvent(scanHost, _hostCount, _ipAddresses.Count); @@ -237,93 +262,104 @@ namespace mRemoteNG.Tools if (_scannedHosts.Count == _ipAddresses.Count) RaiseScanCompleteEvent(_scannedHosts); } - - private static IEnumerable IpAddressArrayFromRange(IPAddress ipAddress1, IPAddress ipAddress2) - { - var startIpAddress = IpAddressMin(ipAddress1, ipAddress2); - var endIpAddress = IpAddressMax(ipAddress1, ipAddress2); - - var startAddress = IpAddressToInt32(startIpAddress); - var endAddress = IpAddressToInt32(endIpAddress); - var addressCount = endAddress - startAddress; - - var addressArray = new IPAddress[addressCount + 1]; - var index = 0; - for (var address = startAddress; address <= endAddress; address++) - { - addressArray[index] = IpAddressFromInt32(address); - index++; - } - - return addressArray; - } - - private static IPAddress IpAddressMin(IPAddress ipAddress1, IPAddress ipAddress2) - { - return IpAddressCompare(ipAddress1, ipAddress2) < 0 ? ipAddress1 : ipAddress2; - } - private static IPAddress IpAddressMax(IPAddress ipAddress1, IPAddress ipAddress2) - { - return IpAddressCompare(ipAddress1, ipAddress2) > 0 ? ipAddress1 : ipAddress2; - } + private static IEnumerable IpAddressArrayFromRange(IPAddress ipAddress1, IPAddress ipAddress2) + { + var startIpAddress = IpAddressMin(ipAddress1, ipAddress2); + var endIpAddress = IpAddressMax(ipAddress1, ipAddress2); - private static int IpAddressCompare(IPAddress ipAddress1, IPAddress ipAddress2) - { - return IpAddressToInt32(ipAddress1) - IpAddressToInt32(ipAddress2); - } - - private static int IpAddressToInt32(IPAddress ipAddress) - { - if (ipAddress.AddressFamily != AddressFamily.InterNetwork) - { - throw (new ArgumentException("ipAddress")); - } - - var addressBytes = ipAddress.GetAddressBytes(); // in network order (big-endian) - if (BitConverter.IsLittleEndian) - { - Array.Reverse(addressBytes); // to host order (little-endian) - } - Debug.Assert(addressBytes.Length == 4); - - return BitConverter.ToInt32(addressBytes, 0); - } - - private static IPAddress IpAddressFromInt32(int ipAddress) - { - var addressBytes = BitConverter.GetBytes(ipAddress); // in host order - if (BitConverter.IsLittleEndian) - { - Array.Reverse(addressBytes); // to network order (big-endian) - } - Debug.Assert(addressBytes.Length == 4); + var startAddress = IpAddressToInt32(startIpAddress); + var endAddress = IpAddressToInt32(endIpAddress); + var addressCount = endAddress - startAddress; + + var addressArray = new IPAddress[addressCount + 1]; + var index = 0; + for (var address = startAddress; address <= endAddress; address++) + { + addressArray[index] = IpAddressFromInt32(address); + index++; + } + + return addressArray; + } + + private static IPAddress IpAddressMin(IPAddress ipAddress1, IPAddress ipAddress2) + { + return IpAddressCompare(ipAddress1, ipAddress2) < 0 ? ipAddress1 : ipAddress2; + } + + private static IPAddress IpAddressMax(IPAddress ipAddress1, IPAddress ipAddress2) + { + return IpAddressCompare(ipAddress1, ipAddress2) > 0 ? ipAddress1 : ipAddress2; + } + + private static int IpAddressCompare(IPAddress ipAddress1, IPAddress ipAddress2) + { + return IpAddressToInt32(ipAddress1) - IpAddressToInt32(ipAddress2); + } + + private static int IpAddressToInt32(IPAddress ipAddress) + { + if (ipAddress.AddressFamily != AddressFamily.InterNetwork) + { + throw (new ArgumentException("ipAddress")); + } + + var addressBytes = ipAddress.GetAddressBytes(); // in network order (big-endian) + if (BitConverter.IsLittleEndian) + { + Array.Reverse(addressBytes); // to host order (little-endian) + } + + Debug.Assert(addressBytes.Length == 4); + + return BitConverter.ToInt32(addressBytes, 0); + } + + private static IPAddress IpAddressFromInt32(int ipAddress) + { + var addressBytes = BitConverter.GetBytes(ipAddress); // in host order + if (BitConverter.IsLittleEndian) + { + Array.Reverse(addressBytes); // to network order (big-endian) + } + + Debug.Assert(addressBytes.Length == 4); return new IPAddress(addressBytes); - } + } + #endregion - + #region Events - public delegate void BeginHostScanEventHandler(string host); - public event BeginHostScanEventHandler BeginHostScan; + + public delegate void BeginHostScanEventHandler(string host); + + public event BeginHostScanEventHandler BeginHostScan; + private void RaiseBeginHostScanEvent(IPAddress ipAddress) { BeginHostScan?.Invoke(ipAddress.ToString()); } public delegate void HostScannedEventHandler(ScanHost scanHost, int scannedHostCount, int totalHostCount); - public event HostScannedEventHandler HostScanned; - private void RaiseHostScannedEvent(ScanHost scanHost, int scannedHostCount, int totalHostCount) - { + + public event HostScannedEventHandler HostScanned; + + private void RaiseHostScannedEvent(ScanHost scanHost, int scannedHostCount, int totalHostCount) + { HostScanned?.Invoke(scanHost, scannedHostCount, totalHostCount); } - - public delegate void ScanCompleteEventHandler(List hosts); - public event ScanCompleteEventHandler ScanComplete; - private void RaiseScanCompleteEvent(List hosts) - { + + public delegate void ScanCompleteEventHandler(List hosts); + + public event ScanCompleteEventHandler ScanComplete; + + private void RaiseScanCompleteEvent(List hosts) + { ScanComplete?.Invoke(hosts); } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/Tools/ProcessController.cs b/mRemoteV1/Tools/ProcessController.cs index cc8aec59..f0cc1663 100644 --- a/mRemoteV1/Tools/ProcessController.cs +++ b/mRemoteV1/Tools/ProcessController.cs @@ -7,152 +7,161 @@ using mRemoteNG.Tools.Cmdline; namespace mRemoteNG.Tools { - public class ProcessController - { + public class ProcessController + { #region Public Methods - public bool Start(string fileName, CommandLineArguments arguments = null) - { - Process.StartInfo.UseShellExecute = false; - Process.StartInfo.FileName = fileName; - if (arguments != null) - Process.StartInfo.Arguments = arguments.ToString(); - - if (!Process.Start()) - return false; - GetMainWindowHandle(); - - return true; - } - - public bool SetControlVisible(string className, string text, bool visible = true) - { - if (Process == null || Process.HasExited) - return false; - if (Handle == IntPtr.Zero) - return false; - - var controlHandle = GetControlHandle(className, text); - if (controlHandle == IntPtr.Zero) - return false; - var nCmdShow = visible ? NativeMethods.SW_SHOW : NativeMethods.SW_HIDE; + public bool Start(string fileName, CommandLineArguments arguments = null) + { + Process.StartInfo.UseShellExecute = false; + Process.StartInfo.FileName = fileName; + if (arguments != null) + Process.StartInfo.Arguments = arguments.ToString(); + + if (!Process.Start()) + return false; + GetMainWindowHandle(); + + return true; + } + + public bool SetControlVisible(string className, string text, bool visible = true) + { + if (Process == null || Process.HasExited) + return false; + if (Handle == IntPtr.Zero) + return false; + + var controlHandle = GetControlHandle(className, text); + if (controlHandle == IntPtr.Zero) + return false; + + var nCmdShow = visible ? NativeMethods.SW_SHOW : NativeMethods.SW_HIDE; NativeMethods.ShowWindow(controlHandle, (int)nCmdShow); - return true; - } - - public bool SetControlText(string className, string oldText, string newText) - { - if (Process == null || Process.HasExited || Handle == IntPtr.Zero) - return false; + return true; + } - var controlHandle = GetControlHandle(className, oldText); - if (controlHandle == IntPtr.Zero) - return false; - - var result = NativeMethods.SendMessage(controlHandle, NativeMethods.WM_SETTEXT, (IntPtr)0, new StringBuilder(newText)); - return result.ToInt32() == NativeMethods.TRUE; - } - - public bool SelectListBoxItem(string itemText) - { - if (Process == null || Process.HasExited || Handle == IntPtr.Zero) - return false; - - var listBoxHandle = GetControlHandle("ListBox"); - if (listBoxHandle == IntPtr.Zero) - return false; - - var result = NativeMethods.SendMessage(listBoxHandle, NativeMethods.LB_SELECTSTRING, (IntPtr)(-1), new StringBuilder(itemText)); - return result.ToInt32() != NativeMethods.LB_ERR; - } - - public bool ClickButton(string text) - { - if (Process == null || Process.HasExited || Handle == IntPtr.Zero) - return false; - - var buttonHandle = GetControlHandle("Button", text); - if (buttonHandle == IntPtr.Zero) - return false; + public bool SetControlText(string className, string oldText, string newText) + { + if (Process == null || Process.HasExited || Handle == IntPtr.Zero) + return false; + + var controlHandle = GetControlHandle(className, oldText); + if (controlHandle == IntPtr.Zero) + return false; + + var result = NativeMethods.SendMessage(controlHandle, NativeMethods.WM_SETTEXT, (IntPtr)0, + new StringBuilder(newText)); + return result.ToInt32() == NativeMethods.TRUE; + } + + public bool SelectListBoxItem(string itemText) + { + if (Process == null || Process.HasExited || Handle == IntPtr.Zero) + return false; + + var listBoxHandle = GetControlHandle("ListBox"); + if (listBoxHandle == IntPtr.Zero) + return false; + + var result = NativeMethods.SendMessage(listBoxHandle, NativeMethods.LB_SELECTSTRING, (IntPtr)(-1), + new StringBuilder(itemText)); + return result.ToInt32() != NativeMethods.LB_ERR; + } + + public bool ClickButton(string text) + { + if (Process == null || Process.HasExited || Handle == IntPtr.Zero) + return false; + + var buttonHandle = GetControlHandle("Button", text); + if (buttonHandle == IntPtr.Zero) + return false; var buttonControlId = NativeMethods.GetDlgCtrlID(buttonHandle); NativeMethods.SendMessage(Handle, NativeMethods.WM_COMMAND, (IntPtr)buttonControlId, buttonHandle); - - return true; - } - - public void WaitForExit() - { - if (Process == null || Process.HasExited) - return; - Process.WaitForExit(); - } -#endregion - + + return true; + } + + public void WaitForExit() + { + if (Process == null || Process.HasExited) + return; + Process.WaitForExit(); + } + + #endregion + #region Protected Fields - private readonly Process Process = new Process(); + private readonly Process Process = new Process(); private IntPtr Handle = IntPtr.Zero; private List Controls = new List(); + #endregion #region Protected Methods - // ReSharper disable once UnusedMethodReturnValue.Local + + // ReSharper disable once UnusedMethodReturnValue.Local private IntPtr GetMainWindowHandle() - { - if (Process == null || Process.HasExited) - return IntPtr.Zero; - - Process.WaitForInputIdle(Settings.Default.MaxPuttyWaitTime * 1000); - - Handle = IntPtr.Zero; - var startTicks = Environment.TickCount; - while (Handle == IntPtr.Zero && Environment.TickCount < startTicks + (Settings.Default.MaxPuttyWaitTime * 1000)) - { - Process.Refresh(); - Handle = Process.MainWindowHandle; - if (Handle == IntPtr.Zero) - { - System.Threading.Thread.Sleep(0); - } - } - - return Handle; - } + { + if (Process == null || Process.HasExited) + return IntPtr.Zero; + + Process.WaitForInputIdle(Settings.Default.MaxPuttyWaitTime * 1000); + + Handle = IntPtr.Zero; + var startTicks = Environment.TickCount; + while (Handle == IntPtr.Zero && + Environment.TickCount < startTicks + (Settings.Default.MaxPuttyWaitTime * 1000)) + { + Process.Refresh(); + Handle = Process.MainWindowHandle; + if (Handle == IntPtr.Zero) + { + System.Threading.Thread.Sleep(0); + } + } + + return Handle; + } private IntPtr GetControlHandle(string className, string text = "") - { - if (Process == null || Process.HasExited || Handle == IntPtr.Zero) - return IntPtr.Zero; - - if (Controls.Count == 0) - { + { + if (Process == null || Process.HasExited || Handle == IntPtr.Zero) + return IntPtr.Zero; + + if (Controls.Count == 0) + { var windowEnumerator = new EnumWindows(); Controls = windowEnumerator.EnumChildWindows(Handle); - } + } var stringBuilder = new StringBuilder(); - var controlHandle = IntPtr.Zero; - foreach (var control in Controls) - { - NativeMethods.GetClassName(control, stringBuilder, stringBuilder.Capacity); - if (stringBuilder.ToString() != className) continue; - if (string.IsNullOrEmpty(text)) - { - controlHandle = control; - break; - } - else - { - NativeMethods.SendMessage(control, NativeMethods.WM_GETTEXT, new IntPtr(stringBuilder.Capacity), stringBuilder); - if (stringBuilder.ToString() != text) continue; - controlHandle = control; - break; - } - } - - return controlHandle; - } + var controlHandle = IntPtr.Zero; + foreach (var control in Controls) + { + NativeMethods.GetClassName(control, stringBuilder, stringBuilder.Capacity); + if (stringBuilder.ToString() != className) continue; + if (string.IsNullOrEmpty(text)) + { + controlHandle = control; + break; + } + else + { + NativeMethods.SendMessage(control, NativeMethods.WM_GETTEXT, new IntPtr(stringBuilder.Capacity), + stringBuilder); + if (stringBuilder.ToString() != text) continue; + controlHandle = control; + break; + } + } + + return controlHandle; + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/PropertyGridCommandSite.cs b/mRemoteV1/Tools/PropertyGridCommandSite.cs index 828e1ac2..046253a7 100644 --- a/mRemoteV1/Tools/PropertyGridCommandSite.cs +++ b/mRemoteV1/Tools/PropertyGridCommandSite.cs @@ -2,168 +2,171 @@ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Reflection; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Tools { - public class PropertyGridCommandSite : IMenuCommandService, ISite - { - private readonly object TheObject; - public PropertyGridCommandSite(object @object) - { - TheObject = @object; - } - - public DesignerVerbCollection Verbs - { - get - { - var objectVerbs = new DesignerVerbCollection(); - // ReSharper disable VBPossibleMistakenCallToGetType.2 - var methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); - // ReSharper restore VBPossibleMistakenCallToGetType.2 - foreach (var method in methods) - { - var commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); - if (commandAttributes.Length == 0) - { - continue; - } - - var commandAttribute = (CommandAttribute) commandAttributes[0]; - if (!commandAttribute.Command) - { - continue; - } - - var displayName = method.Name; - var displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); - if (displayNameAttributes.Length != 0) - { - var displayNameAttribute = (DisplayNameAttribute) displayNameAttributes[0]; - if (!string.IsNullOrEmpty(displayNameAttribute.DisplayName)) - { - displayName = displayNameAttribute.DisplayName; - } - } - objectVerbs.Add(new DesignerVerb(displayName, new EventHandler(VerbEventHandler))); - } - - return objectVerbs; - } - } - - private void VerbEventHandler(object sender, EventArgs e) - { - var verb = sender as DesignerVerb; - if (verb == null) - { - return; - } - // ReSharper disable VBPossibleMistakenCallToGetType.2 - var methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); - // ReSharper restore VBPossibleMistakenCallToGetType.2 - foreach (var method in methods) - { - var commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); - if (commandAttributes.Length == 0) - { - continue; - } - - var commandAttribute = (CommandAttribute) commandAttributes[0]; - if (!commandAttribute.Command) - { - continue; - } - - var displayName = method.Name; - var displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); - if (displayNameAttributes.Length != 0) - { - var displayNameAttribute = (DisplayNameAttribute) displayNameAttributes[0]; - if (!string.IsNullOrEmpty(displayNameAttribute.DisplayName)) - { - displayName = displayNameAttribute.DisplayName; - } - } + public class PropertyGridCommandSite : IMenuCommandService, ISite + { + private readonly object TheObject; + + public PropertyGridCommandSite(object @object) + { + TheObject = @object; + } + + public DesignerVerbCollection Verbs + { + get + { + var objectVerbs = new DesignerVerbCollection(); + // ReSharper disable VBPossibleMistakenCallToGetType.2 + var methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); + // ReSharper restore VBPossibleMistakenCallToGetType.2 + foreach (var method in methods) + { + var commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); + if (commandAttributes.Length == 0) + { + continue; + } + + var commandAttribute = (CommandAttribute)commandAttributes[0]; + if (!commandAttribute.Command) + { + continue; + } + + var displayName = method.Name; + var displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); + if (displayNameAttributes.Length != 0) + { + var displayNameAttribute = (DisplayNameAttribute)displayNameAttributes[0]; + if (!string.IsNullOrEmpty(displayNameAttribute.DisplayName)) + { + displayName = displayNameAttribute.DisplayName; + } + } + + objectVerbs.Add(new DesignerVerb(displayName, new EventHandler(VerbEventHandler))); + } + + return objectVerbs; + } + } + + private void VerbEventHandler(object sender, EventArgs e) + { + var verb = sender as DesignerVerb; + if (verb == null) + { + return; + } + + // ReSharper disable VBPossibleMistakenCallToGetType.2 + var methods = TheObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); + // ReSharper restore VBPossibleMistakenCallToGetType.2 + foreach (var method in methods) + { + var commandAttributes = method.GetCustomAttributes(typeof(CommandAttribute), true); + if (commandAttributes.Length == 0) + { + continue; + } + + var commandAttribute = (CommandAttribute)commandAttributes[0]; + if (!commandAttribute.Command) + { + continue; + } + + var displayName = method.Name; + var displayNameAttributes = method.GetCustomAttributes(typeof(DisplayNameAttribute), true); + if (displayNameAttributes.Length != 0) + { + var displayNameAttribute = (DisplayNameAttribute)displayNameAttributes[0]; + if (!string.IsNullOrEmpty(displayNameAttribute.DisplayName)) + { + displayName = displayNameAttribute.DisplayName; + } + } + + if (verb.Text != displayName) continue; + method.Invoke(TheObject, null); + return; + } + } + + public object GetService(Type serviceType) + { + return serviceType == typeof(IMenuCommandService) ? this : null; + } - if (verb.Text != displayName) continue; - method.Invoke(TheObject, null); - return; - } - } - - public object GetService(Type serviceType) - { - return serviceType == typeof(IMenuCommandService) ? this : null; - } - public IComponent Component - { - get { throw new NotSupportedException(); } - } - + { + get { throw new NotSupportedException(); } + } + public IContainer Container { get { return null; } } - public bool DesignMode - { - get { return true; } - } + public bool DesignMode + { + get { return true; } + } - public string Name - { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } - } - - public void AddCommand(MenuCommand command) - { - throw new NotSupportedException(); - } - - public void AddVerb(DesignerVerb verb) - { - throw new NotSupportedException(); - } - - public MenuCommand FindCommand(CommandID commandId) - { - throw new NotSupportedException(); - } - - public bool GlobalInvoke(CommandID commandId) - { - throw new NotSupportedException(); - } - - public void RemoveCommand(MenuCommand command) - { - throw new NotSupportedException(); - } - - public void RemoveVerb(DesignerVerb verb) - { - throw new NotSupportedException(); - } - - public void ShowContextMenu(CommandID menuId, int x, int y) - { - throw new NotSupportedException(); - } - - } - - public class CommandAttribute : Attribute - { - public bool Command { get; set; } + public string Name + { + get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } + } - public CommandAttribute(bool isCommand = true) - { - Command = isCommand; - } - } -} + public void AddCommand(MenuCommand command) + { + throw new NotSupportedException(); + } + + public void AddVerb(DesignerVerb verb) + { + throw new NotSupportedException(); + } + + public MenuCommand FindCommand(CommandID commandId) + { + throw new NotSupportedException(); + } + + public bool GlobalInvoke(CommandID commandId) + { + throw new NotSupportedException(); + } + + public void RemoveCommand(MenuCommand command) + { + throw new NotSupportedException(); + } + + public void RemoveVerb(DesignerVerb verb) + { + throw new NotSupportedException(); + } + + public void ShowContextMenu(CommandID menuId, int x, int y) + { + throw new NotSupportedException(); + } + } + + public class CommandAttribute : Attribute + { + public bool Command { get; set; } + + public CommandAttribute(bool isCommand = true) + { + Command = isCommand; + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/PuttyProcessController.cs b/mRemoteV1/Tools/PuttyProcessController.cs index c091e96c..2497b828 100644 --- a/mRemoteV1/Tools/PuttyProcessController.cs +++ b/mRemoteV1/Tools/PuttyProcessController.cs @@ -2,12 +2,14 @@ using mRemoteNG.Tools.Cmdline; namespace mRemoteNG.Tools { - public class PuttyProcessController : ProcessController - { - public bool Start(CommandLineArguments arguments = null) - { - var filename = Settings.Default.UseCustomPuttyPath ? Settings.Default.CustomPuttyPath : App.Info.GeneralAppInfo.PuttyPath; - return Start(filename, arguments); - } - } -} + public class PuttyProcessController : ProcessController + { + public bool Start(CommandLineArguments arguments = null) + { + var filename = Settings.Default.UseCustomPuttyPath + ? Settings.Default.CustomPuttyPath + : App.Info.GeneralAppInfo.PuttyPath; + return Start(filename, arguments); + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/PuttyTypeDetector.cs b/mRemoteV1/Tools/PuttyTypeDetector.cs index 73e85c3f..37e173f3 100644 --- a/mRemoteV1/Tools/PuttyTypeDetector.cs +++ b/mRemoteV1/Tools/PuttyTypeDetector.cs @@ -5,64 +5,84 @@ using System.IO; namespace mRemoteNG.Tools { - public class PuttyTypeDetector - { - public static PuttyType GetPuttyType() - { - return GetPuttyType(PuttyBase.PuttyPath); - } - - public static PuttyType GetPuttyType(string filename) - { - if (IsPuttyNg(filename)) - { - return PuttyType.PuttyNg; - } - if (IsKitty(filename)) - { - return PuttyType.Kitty; - } - if (IsXming(filename)) - { - return PuttyType.Xming; - } - - // Check this last - if (IsPutty(filename)) - { - return PuttyType.Putty; - } - - return PuttyType.Unknown; - } - - private static bool IsPutty(string filename) - { - return !string.IsNullOrEmpty(filename) && File.Exists(filename) && Convert.ToBoolean(FileVersionInfo.GetVersionInfo(filename).InternalName.Contains("PuTTY")); - } + public class PuttyTypeDetector + { + public static PuttyType GetPuttyType() + { + return GetPuttyType(PuttyBase.PuttyPath); + } - private static bool IsPuttyNg(string filename) - { - return !string.IsNullOrEmpty(filename) && File.Exists(filename) && Convert.ToBoolean(FileVersionInfo.GetVersionInfo(filename).InternalName.Contains("PuTTYNG")); - } + public static PuttyType GetPuttyType(string filename) + { + if (IsPuttyNg(filename)) + { + return PuttyType.PuttyNg; + } - private static bool IsKitty(string filename) - { - return !string.IsNullOrEmpty(filename) && File.Exists(filename) && Convert.ToBoolean(FileVersionInfo.GetVersionInfo(filename).InternalName.Contains("PuTTY") && FileVersionInfo.GetVersionInfo(filename).Comments.Contains("KiTTY")); - } + if (IsKitty(filename)) + { + return PuttyType.Kitty; + } - private static bool IsXming(string filename) - { - return !string.IsNullOrEmpty(filename) && File.Exists(filename) && Convert.ToBoolean(FileVersionInfo.GetVersionInfo(filename).InternalName.Contains("PuTTY") && FileVersionInfo.GetVersionInfo(filename).ProductVersion.Contains("Xming")); - } + if (IsXming(filename)) + { + return PuttyType.Xming; + } - public enum PuttyType - { - Unknown = 0, - Putty, - PuttyNg, - Kitty, - Xming - } - } -} + // Check this last + if (IsPutty(filename)) + { + return PuttyType.Putty; + } + + return PuttyType.Unknown; + } + + private static bool IsPutty(string filename) + { + return !string.IsNullOrEmpty(filename) && File.Exists(filename) && + Convert.ToBoolean(FileVersionInfo.GetVersionInfo(filename).InternalName.Contains("PuTTY")); + } + + private static bool IsPuttyNg(string filename) + { + return !string.IsNullOrEmpty(filename) && File.Exists(filename) && + Convert.ToBoolean(FileVersionInfo.GetVersionInfo(filename).InternalName.Contains("PuTTYNG")); + } + + private static bool IsKitty(string filename) + { + return !string.IsNullOrEmpty(filename) && File.Exists(filename) && Convert.ToBoolean( + FileVersionInfo + .GetVersionInfo(filename) + .InternalName + .Contains("PuTTY") && + FileVersionInfo + .GetVersionInfo(filename) + .Comments + .Contains("KiTTY")); + } + + private static bool IsXming(string filename) + { + return !string.IsNullOrEmpty(filename) && File.Exists(filename) && Convert.ToBoolean( + FileVersionInfo + .GetVersionInfo(filename) + .InternalName + .Contains("PuTTY") && + FileVersionInfo + .GetVersionInfo(filename) + .ProductVersion + .Contains("Xming")); + } + + public enum PuttyType + { + Unknown = 0, + Putty, + PuttyNg, + Kitty, + Xming + } + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/ReconnectGroup.cs b/mRemoteV1/Tools/ReconnectGroup.cs index d78361e2..6dd8436c 100644 --- a/mRemoteV1/Tools/ReconnectGroup.cs +++ b/mRemoteV1/Tools/ReconnectGroup.cs @@ -3,127 +3,134 @@ using System.Drawing; namespace mRemoteNG.Tools { - public partial class ReconnectGroup - { - public ReconnectGroup() - { - InitializeComponent(); - } - private bool _ServerReady; + public partial class ReconnectGroup + { + public ReconnectGroup() + { + InitializeComponent(); + } + + private bool _ServerReady; + public bool ServerReady - { - get => _ServerReady; + { + get => _ServerReady; set - { - SetStatusImage(value ? Resources.HostStatus_On : Resources.HostStatus_Off); + { + SetStatusImage(value ? Resources.HostStatus_On : Resources.HostStatus_Off); - _ServerReady = value; - } - } - - private delegate void SetStatusImageCB(Image Img); - private void SetStatusImage(Image Img) - { - if (pbServerStatus.InvokeRequired) - { - var d = new SetStatusImageCB(SetStatusImage); - ParentForm?.Invoke(d, new object[] {Img}); - } - else - { - pbServerStatus.Image = Img; - } - } + _ServerReady = value; + } + } + + private delegate void SetStatusImageCB(Image Img); + + private void SetStatusImage(Image Img) + { + if (pbServerStatus.InvokeRequired) + { + var d = new SetStatusImageCB(SetStatusImage); + ParentForm?.Invoke(d, new object[] {Img}); + } + else + { + pbServerStatus.Image = Img; + } + } + + private void chkReconnectWhenReady_CheckedChanged(object sender, EventArgs e) + { + _ReconnectWhenReady = chkReconnectWhenReady.Checked; + } + + private bool _ReconnectWhenReady; - private void chkReconnectWhenReady_CheckedChanged(object sender, EventArgs e) - { - _ReconnectWhenReady = chkReconnectWhenReady.Checked; - } - - private bool _ReconnectWhenReady; public bool ReconnectWhenReady - { - get => _ReconnectWhenReady; + { + get => _ReconnectWhenReady; set - { - _ReconnectWhenReady = value; - SetCheckbox(value); - } - } - - private delegate void SetCheckboxCB(bool Val); - private void SetCheckbox(bool Val) - { - if (chkReconnectWhenReady.InvokeRequired) - { - var d = new SetCheckboxCB(SetCheckbox); - ParentForm?.Invoke(d, new object[] {Val}); - } - else - { - chkReconnectWhenReady.Checked = Val; - } - } - - public delegate void CloseClickedEventHandler(); - private CloseClickedEventHandler CloseClickedEvent; - - public event CloseClickedEventHandler CloseClicked - { - add => CloseClickedEvent = (CloseClickedEventHandler) Delegate.Combine(CloseClickedEvent, value); - remove => CloseClickedEvent = (CloseClickedEventHandler) Delegate.Remove(CloseClickedEvent, value); + { + _ReconnectWhenReady = value; + SetCheckbox(value); + } + } + + private delegate void SetCheckboxCB(bool Val); + + private void SetCheckbox(bool Val) + { + if (chkReconnectWhenReady.InvokeRequired) + { + var d = new SetCheckboxCB(SetCheckbox); + ParentForm?.Invoke(d, new object[] {Val}); + } + else + { + chkReconnectWhenReady.Checked = Val; + } + } + + public delegate void CloseClickedEventHandler(); + + private CloseClickedEventHandler CloseClickedEvent; + + public event CloseClickedEventHandler CloseClicked + { + add => CloseClickedEvent = (CloseClickedEventHandler)Delegate.Combine(CloseClickedEvent, value); + remove => CloseClickedEvent = (CloseClickedEventHandler)Delegate.Remove(CloseClickedEvent, value); } - private void btnClose_Click(object sender, EventArgs e) - { - CloseClickedEvent?.Invoke(); - } + private void btnClose_Click(object sender, EventArgs e) + { + CloseClickedEvent?.Invoke(); + } - private void tmrAnimation_Tick(object sender, EventArgs e) - { - switch (lblAnimation.Text) - { - case "": - lblAnimation.Text = "»"; - break; - case "»": - lblAnimation.Text = "»»"; - break; - case "»»": - lblAnimation.Text = "»»»"; - break; - case "»»»": - lblAnimation.Text = ""; - break; - } - } - - private delegate void DisposeReconnectGroupCB(); - public void DisposeReconnectGroup() - { - if (InvokeRequired) - { - var d = new DisposeReconnectGroupCB(DisposeReconnectGroup); - ParentForm?.Invoke(d); - } - else - { - Dispose(); - } - } - - public void ReconnectGroup_Load(object sender, EventArgs e) - { - ApplyLanguage(); - } - - private void ApplyLanguage() - { - grpAutomaticReconnect.Text = Language.strGroupboxAutomaticReconnect; - btnClose.Text = Language.strButtonClose; - lblServerStatus.Text = Language.strLabelServerStatus; - chkReconnectWhenReady.Text = Language.strCheckboxReconnectWhenReady; - } - } + private void tmrAnimation_Tick(object sender, EventArgs e) + { + switch (lblAnimation.Text) + { + case "": + lblAnimation.Text = "»"; + break; + case "»": + lblAnimation.Text = "»»"; + break; + case "»»": + lblAnimation.Text = "»»»"; + break; + case "»»»": + lblAnimation.Text = ""; + break; + } + } + + private delegate void DisposeReconnectGroupCB(); + + public void DisposeReconnectGroup() + { + if (InvokeRequired) + { + var d = new DisposeReconnectGroupCB(DisposeReconnectGroup); + ParentForm?.Invoke(d); + } + else + { + Dispose(); + } + } + + public void ReconnectGroup_Load(object sender, EventArgs e) + { + ApplyLanguage(); + } + + private void ApplyLanguage() + { + grpAutomaticReconnect.Text = Language.strGroupboxAutomaticReconnect; + btnClose.Text = Language.strButtonClose; + lblServerStatus.Text = Language.strLabelServerStatus; + chkReconnectWhenReady.Text = Language.strCheckboxReconnectWhenReady; + } + } } \ No newline at end of file diff --git a/mRemoteV1/Tools/ScanHost.cs b/mRemoteV1/Tools/ScanHost.cs index d7c4fa67..6bf15fde 100644 --- a/mRemoteV1/Tools/ScanHost.cs +++ b/mRemoteV1/Tools/ScanHost.cs @@ -15,6 +15,7 @@ namespace mRemoteNG.Tools public class ScanHost { #region Properties + public static int SshPort { get; set; } = (int)ProtocolSSH1.Defaults.Port; public static int TelnetPort { get; set; } = (int)ProtocolTelnet.Defaults.Port; public static int HttpPort { get; set; } = (int)ProtocolHTTP.Defaults.Port; @@ -33,6 +34,7 @@ namespace mRemoteNG.Tools public bool Https { get; set; } public string HostIp { get; set; } public string HostName { get; set; } = ""; + public string HostNameWithoutDomain { get @@ -41,12 +43,15 @@ namespace mRemoteNG.Tools { return HostIp; } + return HostName.Split('.')[0]; } } + #endregion #region Methods + public ScanHost(string host) { HostIp = host; @@ -58,14 +63,16 @@ namespace mRemoteNG.Tools { try { - return "SSH: " + Convert.ToString(Ssh) + " Telnet: " + Convert.ToString(Telnet) + " HTTP: " + Convert.ToString(Http) + " HTTPS: " + Convert.ToString(Https) + " Rlogin: " + Convert.ToString(Rlogin) + " RDP: " + Convert.ToString(Rdp) + " VNC: " + Convert.ToString(Vnc); + return "SSH: " + Convert.ToString(Ssh) + " Telnet: " + Convert.ToString(Telnet) + " HTTP: " + + Convert.ToString(Http) + " HTTPS: " + Convert.ToString(Https) + " Rlogin: " + + Convert.ToString(Rlogin) + " RDP: " + Convert.ToString(Rdp) + " VNC: " + Convert.ToString(Vnc); } catch (Exception) { Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "ToString failed (Tools.PortScan)", true); return ""; } - } + } //Adpating to objectlistview instaed of listview public string HostIPorName @@ -78,23 +85,56 @@ namespace mRemoteNG.Tools return HostName; } } - public string RdpName { get { return BoolToYesNo(Rdp); } } - public string VncName { get { return BoolToYesNo(Vnc); } } - public string SshName { get { return BoolToYesNo(Rdp); } } - public string TelnetName { get { return BoolToYesNo(Telnet); } } - public string RloginName { get { return BoolToYesNo(Rlogin); } } - public string HttpName { get { return BoolToYesNo(Http); } } - public string HttpsName { get { return BoolToYesNo(Https); } } - public string OpenPortsName { - get { + + public string RdpName + { + get { return BoolToYesNo(Rdp); } + } + + public string VncName + { + get { return BoolToYesNo(Vnc); } + } + + public string SshName + { + get { return BoolToYesNo(Rdp); } + } + + public string TelnetName + { + get { return BoolToYesNo(Telnet); } + } + + public string RloginName + { + get { return BoolToYesNo(Rlogin); } + } + + public string HttpName + { + get { return BoolToYesNo(Http); } + } + + public string HttpsName + { + get { return BoolToYesNo(Https); } + } + + public string OpenPortsName + { + get + { var strOpen = ""; foreach (int p in OpenPorts) { strOpen += p + ", "; } + return strOpen; } } + public string ClosedPortsName { get @@ -104,12 +144,12 @@ namespace mRemoteNG.Tools { strClosed += p + ", "; } + return strClosed; } } - private static string BoolToYesNo(bool value) { return value ? Language.strYes : Language.strNo; @@ -125,6 +165,7 @@ namespace mRemoteNG.Tools Https = value; Http = value; } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/Tools/SecureTransfer.cs b/mRemoteV1/Tools/SecureTransfer.cs index 2615fbf7..eec8a79b 100644 --- a/mRemoteV1/Tools/SecureTransfer.cs +++ b/mRemoteV1/Tools/SecureTransfer.cs @@ -24,7 +24,6 @@ namespace mRemoteNG.Tools public SecureTransfer() { - } public SecureTransfer(string host, string user, string pass, int port, SSHTransferProtocol protocol) @@ -36,7 +35,13 @@ namespace mRemoteNG.Tools Protocol = protocol; } - public SecureTransfer(string host, string user, string pass, int port, SSHTransferProtocol protocol, string source, string dest) + public SecureTransfer(string host, + string user, + string pass, + int port, + SSHTransferProtocol protocol, + string source, + string dest) { Host = host; User = user; @@ -49,7 +54,7 @@ namespace mRemoteNG.Tools public void Connect() { - if(Protocol == SSHTransferProtocol.SCP) + if (Protocol == SSHTransferProtocol.SCP) { ScpClt = new ScpClient(Host, Port, User, Password); ScpClt.Connect(); @@ -94,7 +99,9 @@ namespace mRemoteNG.Tools { if (!ScpClt.IsConnected) { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strSSHTransferFailed + Environment.NewLine + "SCP Not Connected!"); + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strSSHTransferFailed + Environment.NewLine + + "SCP Not Connected!"); return; } @@ -105,10 +112,15 @@ namespace mRemoteNG.Tools { if (!SftpClt.IsConnected) { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strSSHTransferFailed + Environment.NewLine + "SFTP Not Connected!"); + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + Language.strSSHTransferFailed + Environment.NewLine + + "SFTP Not Connected!"); return; } - asyncResult = (SftpUploadAsyncResult)SftpClt.BeginUploadFile(new FileStream(SrcFile, Open), $"{DstFile}", asyncCallback); + + asyncResult = + (SftpUploadAsyncResult)SftpClt.BeginUploadFile(new FileStream(SrcFile, Open), $"{DstFile}", + asyncCallback); } } @@ -118,4 +130,4 @@ namespace mRemoteNG.Tools SFTP = 1 } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tools/Tools.LocalizedAttributes.cs b/mRemoteV1/Tools/Tools.LocalizedAttributes.cs index f2838c9e..64821b48 100644 --- a/mRemoteV1/Tools/Tools.LocalizedAttributes.cs +++ b/mRemoteV1/Tools/Tools.LocalizedAttributes.cs @@ -1,149 +1,154 @@ using System; using System.ComponentModel; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.Tools { - public class LocalizedAttributes - { - [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + public class LocalizedAttributes + { + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class LocalizedCategoryAttribute : CategoryAttribute - { - private const int MaxOrder = 10; - private int Order; - - public LocalizedCategoryAttribute(string value, int Order = 1) : base(value) - { - this.Order = Order > MaxOrder ? MaxOrder : Order; - } - - protected override string GetLocalizedString(string value) - { - string OrderPrefix = ""; - for (int x = 0; x <= MaxOrder - Order; x++) - { - OrderPrefix += Convert.ToString("\t"); - } - - return OrderPrefix + Language.ResourceManager.GetString(value); - } - } - - [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + { + private const int MaxOrder = 10; + private int Order; + + public LocalizedCategoryAttribute(string value, int Order = 1) : base(value) + { + this.Order = Order > MaxOrder ? MaxOrder : Order; + } + + protected override string GetLocalizedString(string value) + { + string OrderPrefix = ""; + for (int x = 0; x <= MaxOrder - Order; x++) + { + OrderPrefix += Convert.ToString("\t"); + } + + return OrderPrefix + Language.ResourceManager.GetString(value); + } + } + + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class LocalizedDisplayNameAttribute : DisplayNameAttribute - { - - private bool Localized; - - public LocalizedDisplayNameAttribute(string value) : base(value) - { - Localized = false; - } - + { + private bool Localized; + + public LocalizedDisplayNameAttribute(string value) : base(value) + { + Localized = false; + } + public override string DisplayName - { - get - { - if (!Localized) - { - Localized = true; - DisplayNameValue = Language.ResourceManager.GetString(DisplayNameValue); - } - - return base.DisplayName; - } - } - } - - [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + { + get + { + if (!Localized) + { + Localized = true; + DisplayNameValue = Language.ResourceManager.GetString(DisplayNameValue); + } + + return base.DisplayName; + } + } + } + + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class LocalizedDescriptionAttribute : DescriptionAttribute - { - private bool Localized; - public LocalizedDescriptionAttribute(string value) : base(value) - { - Localized = false; - } - + { + private bool Localized; + + public LocalizedDescriptionAttribute(string value) : base(value) + { + Localized = false; + } + public override string Description - { - get - { - if (!Localized) - { - Localized = true; - DescriptionValue = Language.ResourceManager.GetString(DescriptionValue); - } - - return base.Description; - } - } - } - - [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + { + get + { + if (!Localized) + { + Localized = true; + DescriptionValue = Language.ResourceManager.GetString(DescriptionValue); + } + + return base.Description; + } + } + } + + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class LocalizedDefaultValueAttribute : DefaultValueAttribute - { - public LocalizedDefaultValueAttribute(string name) : base(Language.ResourceManager.GetString(name)) - { - } - - // This allows localized attributes in a derived class to override a matching - // non-localized attribute inherited from its base class + { + public LocalizedDefaultValueAttribute(string name) : base(Language.ResourceManager.GetString(name)) + { + } + + // This allows localized attributes in a derived class to override a matching + // non-localized attribute inherited from its base class public override object TypeId { get { return typeof(DefaultValueAttribute); } } - } - + } + #region Special localization - with String.Format - [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class LocalizedDisplayNameInheritAttribute : DisplayNameAttribute - { - private bool Localized; - public LocalizedDisplayNameInheritAttribute(string value) : base(value) - { - - Localized = false; - } - + { + private bool Localized; + + public LocalizedDisplayNameInheritAttribute(string value) : base(value) + { + Localized = false; + } + public override string DisplayName - { - get - { - if (!Localized) - { - Localized = true; - DisplayNameValue = string.Format(Language.strFormatInherit, Language.ResourceManager.GetString(DisplayNameValue)); - } - - return base.DisplayName; - } - } - } - - [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + { + get + { + if (!Localized) + { + Localized = true; + DisplayNameValue = string.Format(Language.strFormatInherit, + Language.ResourceManager.GetString(DisplayNameValue)); + } + + return base.DisplayName; + } + } + } + + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class LocalizedDescriptionInheritAttribute : DescriptionAttribute - { - private bool Localized; - public LocalizedDescriptionInheritAttribute(string value) : base(value) - { - - Localized = false; - } - + { + private bool Localized; + + public LocalizedDescriptionInheritAttribute(string value) : base(value) + { + Localized = false; + } + public override string Description - { - get - { - if (!Localized) - { - Localized = true; - DescriptionValue = string.Format(Language.strFormatInheritDescription, Language.ResourceManager.GetString(DescriptionValue)); - } - - return base.Description; - } - } - } + { + get + { + if (!Localized) + { + Localized = true; + DescriptionValue = string.Format(Language.strFormatInheritDescription, + Language.ResourceManager.GetString(DescriptionValue)); + } + + return base.Description; + } + } + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/Tools.SystemMenu.cs b/mRemoteV1/Tools/Tools.SystemMenu.cs index 227c242a..13a11ac4 100644 --- a/mRemoteV1/Tools/Tools.SystemMenu.cs +++ b/mRemoteV1/Tools/Tools.SystemMenu.cs @@ -2,58 +2,61 @@ using System; using System.Drawing; using mRemoteNG.App; using Microsoft.Win32.SafeHandles; + // ReSharper disable MemberCanBeMadeStatic.Global namespace mRemoteNG.Tools { - public sealed class SystemMenu : SafeHandleZeroOrMinusOneIsInvalid, IDisposable + public sealed class SystemMenu : SafeHandleZeroOrMinusOneIsInvalid, IDisposable { - [Flags] - public enum Flags - { - MF_STRING = NativeMethods.MF_STRING, - MF_SEPARATOR = NativeMethods.MF_SEPARATOR, - MF_BYCOMMAND = NativeMethods.MF_BYCOMMAND, - MF_BYPOSITION = NativeMethods.MF_BYPOSITION, - MF_POPUP = NativeMethods.MF_POPUP, - WM_SYSCOMMAND = NativeMethods.WM_SYSCOMMAND - } + [Flags] + public enum Flags + { + MF_STRING = NativeMethods.MF_STRING, + MF_SEPARATOR = NativeMethods.MF_SEPARATOR, + MF_BYCOMMAND = NativeMethods.MF_BYCOMMAND, + MF_BYPOSITION = NativeMethods.MF_BYPOSITION, + MF_POPUP = NativeMethods.MF_POPUP, + WM_SYSCOMMAND = NativeMethods.WM_SYSCOMMAND + } private bool disposed; internal IntPtr SystemMenuHandle; private readonly IntPtr FormHandle; - public SystemMenu(IntPtr Handle) :base(true) - { - FormHandle = Handle; + public SystemMenu(IntPtr Handle) : base(true) + { + FormHandle = Handle; SystemMenuHandle = NativeMethods.GetSystemMenu(FormHandle, false); SetHandle(SystemMenuHandle); } - - public void Reset() - { - SystemMenuHandle = NativeMethods.GetSystemMenu(FormHandle, true); - } + + public void Reset() + { + SystemMenuHandle = NativeMethods.GetSystemMenu(FormHandle, true); + } public void AppendMenuItem(IntPtr ParentMenu, Flags Flags, IntPtr ID, string Text) - { - NativeMethods.AppendMenu(ParentMenu, (int)Flags, ID, Text); - } - - public IntPtr CreatePopupMenuItem() - { - return NativeMethods.CreatePopupMenu(); - } - - public bool InsertMenuItem(IntPtr SysMenu, int Position, Flags Flags, IntPtr SubMenu, string Text) - { - return NativeMethods.InsertMenu(SysMenu, Position, (int)Flags, SubMenu, Text); - } - - public IntPtr SetBitmap(IntPtr Menu, int Position, Flags Flags, Bitmap Bitmap) - { - return new IntPtr(Convert.ToInt32(NativeMethods.SetMenuItemBitmaps(Menu, Position, (int)Flags, Bitmap.GetHbitmap(), Bitmap.GetHbitmap()))); - } + { + NativeMethods.AppendMenu(ParentMenu, (int)Flags, ID, Text); + } + + public IntPtr CreatePopupMenuItem() + { + return NativeMethods.CreatePopupMenu(); + } + + public bool InsertMenuItem(IntPtr SysMenu, int Position, Flags Flags, IntPtr SubMenu, string Text) + { + return NativeMethods.InsertMenu(SysMenu, Position, (int)Flags, SubMenu, Text); + } + + public IntPtr SetBitmap(IntPtr Menu, int Position, Flags Flags, Bitmap Bitmap) + { + return new IntPtr(Convert.ToInt32(NativeMethods.SetMenuItemBitmaps(Menu, Position, (int)Flags, + Bitmap.GetHbitmap(), + Bitmap.GetHbitmap()))); + } protected override bool ReleaseHandle() { @@ -72,7 +75,8 @@ namespace mRemoteNG.Tools } */ - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2216:DisposableTypesShouldDeclareFinalizer")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", + "CA2216:DisposableTypesShouldDeclareFinalizer")] public new void Dispose() { Dispose(true); diff --git a/mRemoteV1/Tools/Tools.WindowPlacement.cs b/mRemoteV1/Tools/Tools.WindowPlacement.cs index 60adac28..b6a34d55 100644 --- a/mRemoteV1/Tools/Tools.WindowPlacement.cs +++ b/mRemoteV1/Tools/Tools.WindowPlacement.cs @@ -5,89 +5,90 @@ using mRemoteNG.App; namespace mRemoteNG.Tools { - public class WindowPlacement - { - private Form _form; - + public class WindowPlacement + { + private Form _form; + + + public WindowPlacement(Form form) + { + _form = form; + } - public WindowPlacement(Form form) - { - _form = form; - } - #region Public Properties + public Form Form - { - get - { - return _form; - } - set - { - _form = value; - } - } - + { + get { return _form; } + set { _form = value; } + } + public bool RestoreToMaximized - { - get - { - NativeMethods.WINDOWPLACEMENT windowPlacement = GetWindowPlacement(); - return Convert.ToBoolean(windowPlacement.flags & NativeMethods.WPF_RESTORETOMAXIMIZED); - } - set - { + { + get + { NativeMethods.WINDOWPLACEMENT windowPlacement = GetWindowPlacement(); - if (value) - { - windowPlacement.flags = windowPlacement.flags | NativeMethods.WPF_RESTORETOMAXIMIZED; - } - else - { - windowPlacement.flags = windowPlacement.flags & ~NativeMethods.WPF_RESTORETOMAXIMIZED; - } - SetWindowPlacement(windowPlacement); - } - } + return Convert.ToBoolean(windowPlacement.flags & NativeMethods.WPF_RESTORETOMAXIMIZED); + } + set + { + NativeMethods.WINDOWPLACEMENT windowPlacement = GetWindowPlacement(); + if (value) + { + windowPlacement.flags = windowPlacement.flags | NativeMethods.WPF_RESTORETOMAXIMIZED; + } + else + { + windowPlacement.flags = windowPlacement.flags & ~NativeMethods.WPF_RESTORETOMAXIMIZED; + } + + SetWindowPlacement(windowPlacement); + } + } + #endregion - + #region Private Functions - private NativeMethods.WINDOWPLACEMENT GetWindowPlacement() - { - if (_form == null) - { - throw (new NullReferenceException("WindowPlacement.Form is not set.")); - } + + private NativeMethods.WINDOWPLACEMENT GetWindowPlacement() + { + if (_form == null) + { + throw (new NullReferenceException("WindowPlacement.Form is not set.")); + } + NativeMethods.WINDOWPLACEMENT windowPlacement = new NativeMethods.WINDOWPLACEMENT(); - windowPlacement.length = (uint)Marshal.SizeOf(windowPlacement); - try - { + windowPlacement.length = (uint)Marshal.SizeOf(windowPlacement); + try + { NativeMethods.GetWindowPlacement(_form.Handle, ref windowPlacement); - return windowPlacement; - } - catch (Exception) - { - throw; - } - } - - private bool SetWindowPlacement(NativeMethods.WINDOWPLACEMENT windowPlacement) - { - if (_form == null) - { - throw (new NullReferenceException("WindowPlacement.Form is not set.")); - } - windowPlacement.length = (uint)Marshal.SizeOf(windowPlacement); - try - { - return NativeMethods.SetWindowPlacement(_form.Handle, ref windowPlacement); - } - catch (Exception) - { - throw; - } - } + return windowPlacement; + } + catch (Exception) + { + throw; + } + } + + private bool SetWindowPlacement(NativeMethods.WINDOWPLACEMENT windowPlacement) + { + if (_form == null) + { + throw (new NullReferenceException("WindowPlacement.Form is not set.")); + } + + windowPlacement.length = (uint)Marshal.SizeOf(windowPlacement); + try + { + return NativeMethods.SetWindowPlacement(_form.Handle, ref windowPlacement); + } + catch (Exception) + { + throw; + } + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/Tools/WindowsRegistry/RegistryHive.cs b/mRemoteV1/Tools/WindowsRegistry/RegistryHive.cs index 56f6cbc0..4663bf27 100644 --- a/mRemoteV1/Tools/WindowsRegistry/RegistryHive.cs +++ b/mRemoteV1/Tools/WindowsRegistry/RegistryHive.cs @@ -8,4 +8,4 @@ Users, LocalMachine } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tools/WindowsRegistry/WindowsRegistry.cs b/mRemoteV1/Tools/WindowsRegistry/WindowsRegistry.cs index aa2919bb..b1774502 100644 --- a/mRemoteV1/Tools/WindowsRegistry/WindowsRegistry.cs +++ b/mRemoteV1/Tools/WindowsRegistry/WindowsRegistry.cs @@ -51,4 +51,4 @@ namespace mRemoteNG.Tools.WindowsRegistry } } } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tree/AlwaysConfirmYes.cs b/mRemoteV1/Tree/AlwaysConfirmYes.cs index 5eb7b9fe..ff1f88cd 100644 --- a/mRemoteV1/Tree/AlwaysConfirmYes.cs +++ b/mRemoteV1/Tree/AlwaysConfirmYes.cs @@ -1,5 +1,4 @@ - -namespace mRemoteNG.Tree +namespace mRemoteNG.Tree { public class AlwaysConfirmYes : IConfirm { diff --git a/mRemoteV1/Tree/ClickHandlers/OpenConnectionClickHandler.cs b/mRemoteV1/Tree/ClickHandlers/OpenConnectionClickHandler.cs index 63c2870f..cff2882f 100644 --- a/mRemoteV1/Tree/ClickHandlers/OpenConnectionClickHandler.cs +++ b/mRemoteV1/Tree/ClickHandlers/OpenConnectionClickHandler.cs @@ -19,7 +19,8 @@ namespace mRemoteNG.Tree { if (clickedNode == null) throw new ArgumentNullException(nameof(clickedNode)); - if (clickedNode.GetTreeNodeType() != TreeNodeType.Connection && clickedNode.GetTreeNodeType() != TreeNodeType.PuttySession) return; + if (clickedNode.GetTreeNodeType() != TreeNodeType.Connection && + clickedNode.GetTreeNodeType() != TreeNodeType.PuttySession) return; _connectionInitiator.OpenConnection(clickedNode); } } diff --git a/mRemoteV1/Tree/ClickHandlers/SwitchToConnectionClickHandler.cs b/mRemoteV1/Tree/ClickHandlers/SwitchToConnectionClickHandler.cs index 75b1e5e5..0f5eb8ff 100644 --- a/mRemoteV1/Tree/ClickHandlers/SwitchToConnectionClickHandler.cs +++ b/mRemoteV1/Tree/ClickHandlers/SwitchToConnectionClickHandler.cs @@ -19,7 +19,8 @@ namespace mRemoteNG.Tree { if (clickedNode == null) throw new ArgumentNullException(nameof(clickedNode)); - if (clickedNode.GetTreeNodeType() != TreeNodeType.Connection && clickedNode.GetTreeNodeType() != TreeNodeType.PuttySession) return; + if (clickedNode.GetTreeNodeType() != TreeNodeType.Connection && + clickedNode.GetTreeNodeType() != TreeNodeType.PuttySession) return; _connectionInitiator.SwitchToOpenConnection(clickedNode); } } diff --git a/mRemoteV1/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs b/mRemoteV1/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs index 2e0034cf..3656301a 100644 --- a/mRemoteV1/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs +++ b/mRemoteV1/Tree/ClickHandlers/TreeNodeCompositeClickHandler.cs @@ -7,7 +7,8 @@ namespace mRemoteNG.Tree { public class TreeNodeCompositeClickHandler : ITreeNodeClickHandler { - public IEnumerable> ClickHandlers { get; set; } = new ITreeNodeClickHandler[0]; + public IEnumerable> ClickHandlers { get; set; } = + new ITreeNodeClickHandler[0]; public void Execute(ConnectionInfo clickedNode) { diff --git a/mRemoteV1/Tree/ConnectionTreeDragAndDropHandler.cs b/mRemoteV1/Tree/ConnectionTreeDragAndDropHandler.cs index 95e2a407..09bbecd5 100644 --- a/mRemoteV1/Tree/ConnectionTreeDragAndDropHandler.cs +++ b/mRemoteV1/Tree/ConnectionTreeDragAndDropHandler.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Windows.Forms; using BrightIdeasSoftware; -using mRemoteNG.App; using mRemoteNG.Connection; using mRemoteNG.Container; using mRemoteNG.Tree.Root; @@ -21,27 +20,33 @@ namespace mRemoteNG.Tree public void HandleEvent_ModelDropped(object sender, ModelDropEventArgs e) { - var dropTarget = e.TargetModel as ConnectionInfo; - if (dropTarget == null) return; + if (!(e.TargetModel is ConnectionInfo dropTarget)) return; var dropSource = (ConnectionInfo)e.SourceModels[0]; DropModel(dropSource, dropTarget, e.DropTargetLocation); e.Handled = true; } - public void DropModel(ConnectionInfo dropSource, ConnectionInfo dropTarget, DropTargetLocation dropTargetLocation) + public void DropModel(ConnectionInfo dropSource, + ConnectionInfo dropTarget, + DropTargetLocation dropTargetLocation) { - if (dropTargetLocation == DropTargetLocation.Item) - DropModelOntoTarget(dropSource, dropTarget); - else if (dropTargetLocation == DropTargetLocation.AboveItem) - DropModelAboveTarget(dropSource, dropTarget); - else if (dropTargetLocation == DropTargetLocation.BelowItem) - DropModelBelowTarget(dropSource, dropTarget); + switch (dropTargetLocation) + { + case DropTargetLocation.Item: + DropModelOntoTarget(dropSource, dropTarget); + break; + case DropTargetLocation.AboveItem: + DropModelAboveTarget(dropSource, dropTarget); + break; + case DropTargetLocation.BelowItem: + DropModelBelowTarget(dropSource, dropTarget); + break; + } } private void DropModelOntoTarget(ConnectionInfo dropSource, ConnectionInfo dropTarget) { - var dropTargetAsContainer = dropTarget as ContainerInfo; - if (dropTargetAsContainer == null) return; + if (!(dropTarget is ContainerInfo dropTargetAsContainer)) return; dropSource.SetParent(dropTargetAsContainer); } @@ -76,7 +81,9 @@ namespace mRemoteNG.Tree e.Handled = true; } - public DragDropEffects CanModelDrop(ConnectionInfo dropSource, ConnectionInfo dropTarget, DropTargetLocation dropTargetLocation) + public DragDropEffects CanModelDrop(ConnectionInfo dropSource, + ConnectionInfo dropTarget, + DropTargetLocation dropTargetLocation) { var dragDropEffect = DragDropEffects.None; if (!NodeIsDraggable(dropSource)) @@ -84,10 +91,18 @@ namespace mRemoteNG.Tree _infoMessage = Language.strNodeNotDraggable; _enableFeedback = false; } - else if (dropTargetLocation == DropTargetLocation.Item) - dragDropEffect = HandleCanDropOnItem(dropSource, dropTarget); - else if (dropTargetLocation == DropTargetLocation.AboveItem || dropTargetLocation == DropTargetLocation.BelowItem) - dragDropEffect = HandleCanDropBetweenItems(dropSource, dropTarget); + else + switch (dropTargetLocation) + { + case DropTargetLocation.Item: + dragDropEffect = HandleCanDropOnItem(dropSource, dropTarget); + break; + case DropTargetLocation.AboveItem: + case DropTargetLocation.BelowItem: + dragDropEffect = HandleCanDropBetweenItems(dropSource, dropTarget); + break; + } + return dragDropEffect; } @@ -104,6 +119,7 @@ namespace mRemoteNG.Tree { _enableFeedback = false; } + return dragDropEffect; } @@ -119,6 +135,7 @@ namespace mRemoteNG.Tree dragDropEffect = DragDropEffects.Move; _currentFeedbackColor = DropAllowedFeedbackColor; } + return dragDropEffect; } @@ -148,14 +165,13 @@ namespace mRemoteNG.Tree private bool AncestorDraggingOntoChild(ConnectionInfo source, ConnectionInfo target) { - var sourceAsContainer = source as ContainerInfo; - return sourceAsContainer != null && sourceAsContainer.GetRecursiveChildList().Contains(target); + return source is ContainerInfo sourceAsContainer && + sourceAsContainer.GetRecursiveChildList().Contains(target); } private bool DraggingOntoCurrentParent(ConnectionInfo source, ConnectionInfo target) { - var targetAsContainer = target as ContainerInfo; - return targetAsContainer != null && targetAsContainer.Children.Contains(source); + return target is ContainerInfo targetAsContainer && targetAsContainer.Children.Contains(source); } } } \ No newline at end of file diff --git a/mRemoteV1/Tree/ConnectionTreeModel.cs b/mRemoteV1/Tree/ConnectionTreeModel.cs index a28edd3d..a4b87831 100644 --- a/mRemoteV1/Tree/ConnectionTreeModel.cs +++ b/mRemoteV1/Tree/ConnectionTreeModel.cs @@ -18,7 +18,9 @@ namespace mRemoteNG.Tree RootNodes.Add(rootNode); rootNode.CollectionChanged += RaiseCollectionChangedEvent; rootNode.PropertyChanged += RaisePropertyChangedEvent; - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, rootNode)); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, + rootNode)); } public void RemoveRootNode(ContainerInfo rootNode) @@ -27,7 +29,9 @@ namespace mRemoteNG.Tree rootNode.CollectionChanged -= RaiseCollectionChangedEvent; rootNode.PropertyChanged -= RaisePropertyChangedEvent; RootNodes.Remove(rootNode); - RaiseCollectionChangedEvent(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, rootNode)); + RaiseCollectionChangedEvent(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, + rootNode)); } public IReadOnlyList GetRecursiveChildList() @@ -37,6 +41,7 @@ namespace mRemoteNG.Tree { list.AddRange(GetRecursiveChildList(rootNode)); } + return list; } @@ -59,7 +64,7 @@ namespace mRemoteNG.Tree { if (connectionInfo is RootNodeInfo) return; - + connectionInfo?.RemoveParent(); } diff --git a/mRemoteV1/Tree/NodeSearcher.cs b/mRemoteV1/Tree/NodeSearcher.cs index e8b6c763..abf0aea0 100644 --- a/mRemoteV1/Tree/NodeSearcher.cs +++ b/mRemoteV1/Tree/NodeSearcher.cs @@ -5,7 +5,7 @@ using mRemoteNG.Connection; namespace mRemoteNG.Tree { - public class NodeSearcher + public class NodeSearcher { private readonly IConnectionTreeModel _connectionTreeModel; @@ -31,6 +31,7 @@ namespace mRemoteNG.Tree node.Hostname.ToLowerInvariant().Contains(searchTextLower)) Matches.Add(node); } + if (Matches.Count > 0) CurrentMatch = Matches.First(); return Matches; diff --git a/mRemoteV1/Tree/NodeType.cs b/mRemoteV1/Tree/NodeType.cs index 6f39352b..33ef4705 100644 --- a/mRemoteV1/Tree/NodeType.cs +++ b/mRemoteV1/Tree/NodeType.cs @@ -9,4 +9,4 @@ PuttyRoot = 4, PuttySession = 5 } -} +} \ No newline at end of file diff --git a/mRemoteV1/Tree/PreviousSessionOpener.cs b/mRemoteV1/Tree/PreviousSessionOpener.cs index ff664b98..bc6cffdd 100644 --- a/mRemoteV1/Tree/PreviousSessionOpener.cs +++ b/mRemoteV1/Tree/PreviousSessionOpener.cs @@ -20,12 +20,13 @@ namespace mRemoteNG.Tree public void Execute(IConnectionTree connectionTree) { - var connectionInfoList = connectionTree.GetRootConnectionNode().GetRecursiveChildList().Where(node => !(node is ContainerInfo)); + var connectionInfoList = connectionTree.GetRootConnectionNode().GetRecursiveChildList() + .Where(node => !(node is ContainerInfo)); var previouslyOpenedConnections = connectionInfoList - .Where(item => - item.PleaseConnect && - // ignore items that have already connected - !_connectionInitiator.ActiveConnections.Contains(item.ConstantID)); + .Where(item => + item.PleaseConnect && + //ignore items that have already connected + !_connectionInitiator.ActiveConnections.Contains(item.ConstantID)); foreach (var connectionInfo in previouslyOpenedConnections) { diff --git a/mRemoteV1/Tree/PreviouslyOpenedFolderExpander.cs b/mRemoteV1/Tree/PreviouslyOpenedFolderExpander.cs index 8b26236f..2cbd278d 100644 --- a/mRemoteV1/Tree/PreviouslyOpenedFolderExpander.cs +++ b/mRemoteV1/Tree/PreviouslyOpenedFolderExpander.cs @@ -10,7 +10,8 @@ namespace mRemoteNG.Tree public void Execute(IConnectionTree connectionTree) { var rootNode = connectionTree.GetRootConnectionNode(); - var containerList = connectionTree.ConnectionTreeModel.GetRecursiveChildList(rootNode).OfType(); + var containerList = connectionTree.ConnectionTreeModel.GetRecursiveChildList(rootNode) + .OfType(); var previouslyExpandedNodes = containerList.Where(container => container.IsExpanded); connectionTree.ExpandedObjects = previouslyExpandedNodes; connectionTree.InvokeRebuildAll(true); diff --git a/mRemoteV1/Tree/Root/RootNodeInfo.cs b/mRemoteV1/Tree/Root/RootNodeInfo.cs index 47e863a7..c9a0c6c8 100644 --- a/mRemoteV1/Tree/Root/RootNodeInfo.cs +++ b/mRemoteV1/Tree/Root/RootNodeInfo.cs @@ -7,62 +7,57 @@ using mRemoteNG.Tools; namespace mRemoteNG.Tree.Root { - [DefaultProperty("Name")] + [DefaultProperty("Name")] public class RootNodeInfo : ContainerInfo - { - private string _name; - private string _customPassword = ""; + { + private string _name; + private string _customPassword = ""; - public RootNodeInfo(RootNodeType rootType, string uniqueId) - : base(uniqueId) - { + public RootNodeInfo(RootNodeType rootType, string uniqueId) + : base(uniqueId) + { _name = Language.strConnections; - Type = rootType; - } + Type = rootType; + } + + public RootNodeInfo(RootNodeType rootType) + : this(rootType, Guid.NewGuid().ToString()) + { + } - public RootNodeInfo(RootNodeType rootType) - : this(rootType, Guid.NewGuid().ToString()) - { - } - #region Public Properties - [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), - Browsable(true), - LocalizedAttributes.LocalizedDefaultValue("strConnections"), - LocalizedAttributes.LocalizedDisplayName("strPropertyNameName"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionName")] - public override string Name - { - get { return _name; } + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), + Browsable(true), + LocalizedAttributes.LocalizedDefaultValue("strConnections"), + LocalizedAttributes.LocalizedDisplayName("strPropertyNameName"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionName")] + public override string Name + { + get { return _name; } set { _name = value; } - } + } - [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), - Browsable(true), - LocalizedAttributes.LocalizedDisplayName("strPasswordProtect"), - TypeConverter(typeof(MiscTools.YesNoTypeConverter))] + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), + Browsable(true), + LocalizedAttributes.LocalizedDisplayName("strPasswordProtect"), + TypeConverter(typeof(MiscTools.YesNoTypeConverter))] public new bool Password { get; set; } - [Browsable(false)] - public string PasswordString - { - get - { - return Password ? _customPassword : DefaultPassword; - } - set - { - _customPassword = value; - Password = !string.IsNullOrEmpty(value) && _customPassword != DefaultPassword; - } - } - [Browsable(false)] - public string DefaultPassword { get; } = "mR3m"; - - [Browsable(false)] - public RootNodeType Type {get; set;} + public string PasswordString + { + get { return Password ? _customPassword : DefaultPassword; } + set + { + _customPassword = value; + Password = !string.IsNullOrEmpty(value) && _customPassword != DefaultPassword; + } + } + + [Browsable(false)] public string DefaultPassword { get; } = "mR3m"; + + [Browsable(false)] public RootNodeType Type { get; set; } public override TreeNodeType GetTreeNodeType() { @@ -70,18 +65,19 @@ namespace mRemoteNG.Tree.Root ? TreeNodeType.Root : TreeNodeType.PuttyRoot; } + #endregion - public override void AddChildAt(ConnectionInfo newChildItem, int index) - { + public override void AddChildAt(ConnectionInfo newChildItem, int index) + { newChildItem.Inheritance.DisableInheritance(); - base.AddChildAt(newChildItem, index); - } + base.AddChildAt(newChildItem, index); + } - public override void RemoveChild(ConnectionInfo removalTarget) - { + public override void RemoveChild(ConnectionInfo removalTarget) + { removalTarget.Inheritance.EnableInheritance(); - base.RemoveChild(removalTarget); - } - } + base.RemoveChild(removalTarget); + } + } } \ No newline at end of file diff --git a/mRemoteV1/Tree/Root/RootPuttySessionsNodeInfo.cs b/mRemoteV1/Tree/Root/RootPuttySessionsNodeInfo.cs index 85c9be9d..2b78cd9a 100644 --- a/mRemoteV1/Tree/Root/RootPuttySessionsNodeInfo.cs +++ b/mRemoteV1/Tree/Root/RootPuttySessionsNodeInfo.cs @@ -2,7 +2,7 @@ using mRemoteNG.Tools; namespace mRemoteNG.Tree.Root { - public class RootPuttySessionsNodeInfo : RootNodeInfo + public class RootPuttySessionsNodeInfo : RootNodeInfo { private string _name; private string _panel; @@ -15,37 +15,39 @@ namespace mRemoteNG.Tree.Root string.IsNullOrEmpty(Settings.Default.PuttySavedSessionsPanel) ? Language.strGeneral : Settings.Default.PuttySavedSessionsPanel; - } + } #region Public Properties + [LocalizedAttributes.LocalizedDefaultValue("strPuttySavedSessionsRootName")] public override string Name - { - get { return _name; } - set - { - _name = value; + { + get { return _name; } + set + { + _name = value; //Settings.Default.PuttySavedSessionsName = value; - } - } - + } + } + [LocalizedAttributes.LocalizedCategory("strCategoryDisplay"), - LocalizedAttributes.LocalizedDisplayName("strPropertyNamePanel"), - LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPanel")] + LocalizedAttributes.LocalizedDisplayName("strPropertyNamePanel"), + LocalizedAttributes.LocalizedDescription("strPropertyDescriptionPanel")] public override string Panel - { - get { return _panel; } - set - { - _panel = value; + { + get { return _panel; } + set + { + _panel = value; Settings.Default.PuttySavedSessionsPanel = value; - } + } } public override TreeNodeType GetTreeNodeType() { return TreeNodeType.PuttyRoot; } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGButton.cs b/mRemoteV1/UI/Controls/Base/NGButton.cs index c4f266a3..746032dc 100644 --- a/mRemoteV1/UI/Controls/Base/NGButton.cs +++ b/mRemoteV1/UI/Controls/Base/NGButton.cs @@ -11,7 +11,7 @@ namespace mRemoteNG.UI.Controls.Base //Extended button class, the button onPaint completely repaint the control public class NGButton : Button { - private ThemeManager _themeManager ; + private ThemeManager _themeManager; /// /// Store the mouse state, required for coloring the component according to the mouse state @@ -35,7 +35,7 @@ namespace mRemoteNG.UI.Controls.Base /// protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); if (_themeManager.ThemingActive) { @@ -65,7 +65,7 @@ namespace mRemoteNG.UI.Controls.Base Invalidate(); }; Invalidate(); - } + } } @@ -75,20 +75,20 @@ namespace mRemoteNG.UI.Controls.Base /// protected override void OnPaint(PaintEventArgs e) { - if (!_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; } + Color back; Color fore; Color border; if (Enabled) { - switch (_mice) { - case MouseState.HOVER: + case MouseState.HOVER: back = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Hover_Background"); fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Hover_Foreground"); border = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Hover_Border"); @@ -103,17 +103,16 @@ namespace mRemoteNG.UI.Controls.Base fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Foreground"); border = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Border"); break; - } + } } else { - back = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Disabled_Background"); + back = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Disabled_Background"); fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Disabled_Foreground"); border = _themeManager.ActiveTheme.ExtendedPalette.getColor("Button_Disabled_Border"); } - e.Graphics.FillRectangle(new SolidBrush(back), e.ClipRectangle); e.Graphics.DrawRectangle(new Pen(border, 1), 0, 0, Width - 1, Height - 1); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; @@ -124,9 +123,12 @@ namespace mRemoteNG.UI.Controls.Base { SizeF stringSize = e.Graphics.MeasureString(Text, Font); - e.Graphics.DrawImageUnscaled(Image, Width / 2 - (int)stringSize.Width / 2 - Image.Width , Height / 2 - Image.Height/2); + e.Graphics.DrawImageUnscaled(Image, Width / 2 - (int)stringSize.Width / 2 - Image.Width, + Height / 2 - Image.Height / 2); } - TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, fore, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); + + TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, fore, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); } private void InitializeComponent() @@ -135,9 +137,9 @@ namespace mRemoteNG.UI.Controls.Base // // NGButton // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGCheckBox.cs b/mRemoteV1/UI/Controls/Base/NGCheckBox.cs index 3b1c81de..f5a650b2 100644 --- a/mRemoteV1/UI/Controls/Base/NGCheckBox.cs +++ b/mRemoteV1/UI/Controls/Base/NGCheckBox.cs @@ -1,13 +1,13 @@ -using mRemoteNG.Themes; -using System.Drawing; +using System.Drawing; using System.Windows.Forms; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Controls.Base { //Extended CheckBox class, the NGCheckBox onPaint completely repaint the control // - // If this causes design issues in the future, may want to think about migrating to + // If this causes design issues in the future, may want to think about migrating to // CheckBoxRenderer: // https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.checkboxrenderer?view=netframework-4.6 // @@ -40,7 +40,7 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); if (!_themeManager.ThemingActive) return; _mice = MouseState.OUT; @@ -73,16 +73,17 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnPaint(PaintEventArgs e) { - if ( !_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; } + //Get the colors Color fore; Color glyph; Color checkBorder; - + var back = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Background"); if (Enabled) { @@ -104,11 +105,10 @@ namespace mRemoteNG.UI.Controls.Base } else { - fore = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Text_Disabled"); glyph = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Glyph_Disabled"); checkBorder = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Border_Disabled"); - } + } e.Graphics.Clear(Parent.BackColor); @@ -126,19 +126,18 @@ namespace mRemoteNG.UI.Controls.Base } var textRect = new Rectangle(_textXCoord, 0, Width - 16, Height); - TextRenderer.DrawText(e.Graphics, Text, Font, textRect, fore, Parent.BackColor, TextFormatFlags.PathEllipsis); + TextRenderer.DrawText(e.Graphics, Text, Font, textRect, fore, Parent.BackColor, + TextFormatFlags.PathEllipsis); } private void InitializeComponent() { - this.SuspendLayout(); + SuspendLayout(); // // NGCheckBox // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.ResumeLayout(false); - + Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + ResumeLayout(false); } } -} - +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGComboBox.cs b/mRemoteV1/UI/Controls/Base/NGComboBox.cs index 4fb41640..76446b51 100644 --- a/mRemoteV1/UI/Controls/Base/NGComboBox.cs +++ b/mRemoteV1/UI/Controls/Base/NGComboBox.cs @@ -11,12 +11,14 @@ namespace mRemoteNG.UI.Controls.Base internal class NGComboBox : ComboBox { private ThemeManager _themeManager; + public enum MouseState { HOVER, DOWN, OUT } + public MouseState _mice { get; set; } public NGComboBox() @@ -26,17 +28,16 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnCreateControl() { - base.OnCreateControl(); - _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); + if (!_themeManager.ActiveAndExtended) return; BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Background"); ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Foreground"); DrawMode = DrawMode.OwnerDrawFixed; SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true); DrawItem += NG_DrawItem; - _mice = MouseState.OUT; + _mice = MouseState.OUT; MouseEnter += (sender, args) => { _mice = MouseState.HOVER; @@ -65,27 +66,39 @@ namespace mRemoteNG.UI.Controls.Base private void NG_DrawItem(object sender, DrawItemEventArgs e) { var index = e.Index >= 0 ? e.Index : 0; - Brush itemBrush= new SolidBrush(_themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Foreground")); + Brush itemBrush = new SolidBrush(_themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Foreground")); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { - itemBrush = new SolidBrush(_themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Selected_Foreground")); - e.Graphics.FillRectangle(new SolidBrush(_themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Selected_Background")), e.Bounds); + itemBrush = new SolidBrush( + _themeManager + .ActiveTheme.ExtendedPalette.getColor("List_Item_Selected_Foreground")); + e.Graphics.FillRectangle( + new SolidBrush(_themeManager + .ActiveTheme.ExtendedPalette + .getColor("List_Item_Selected_Background")), + e.Bounds); } else - e.Graphics.FillRectangle(new SolidBrush(_themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Background")), e.Bounds); + e.Graphics.FillRectangle( + new SolidBrush(_themeManager + .ActiveTheme.ExtendedPalette.getColor("ComboBox_Background")), + e.Bounds); if (Items.Count > 0) { if (string.IsNullOrEmpty(DisplayMember)) - e.Graphics.DrawString(Items[index].ToString(), e.Font, itemBrush, e.Bounds, StringFormat.GenericDefault); + e.Graphics.DrawString(Items[index].ToString(), e.Font, itemBrush, e.Bounds, + StringFormat.GenericDefault); else { if (Items[index].GetType().GetProperty(DisplayMember) != null) { e.Graphics.DrawString( - Items[index].GetType().GetProperty(DisplayMember)?.GetValue(Items[index], null).ToString(), - e.Font, itemBrush, e.Bounds, StringFormat.GenericDefault); + Items[index] + .GetType().GetProperty(DisplayMember)?.GetValue(Items[index], null) + .ToString(), + e.Font, itemBrush, e.Bounds, StringFormat.GenericDefault); } } } @@ -95,11 +108,12 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnPaint(PaintEventArgs e) { - if ( !_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; } + //Colors var Border = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Border"); var Back = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Background"); @@ -112,23 +126,25 @@ namespace mRemoteNG.UI.Controls.Base Border = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_MouseOver_Border"); ButtBack = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_MouseOver_Background"); ButtFore = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_MouseOver_Foreground"); - }if (DroppedDown) + } + + if (DroppedDown) { Border = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_MouseOver_Border"); ButtBack = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_Pressed_Background"); ButtFore = _themeManager.ActiveTheme.ExtendedPalette.getColor("ComboBox_Button_Pressed_Foreground"); } - - + e.Graphics.Clear(Back); - + //Border using (var p = new Pen(Border)) { var boxRect = new Rectangle(0, 0, Width - 1, Height - 1); e.Graphics.DrawRectangle(p, boxRect); } + //Button using (var b = new SolidBrush(ButtBack)) { @@ -136,11 +152,12 @@ namespace mRemoteNG.UI.Controls.Base } //Arrow - e.Graphics.DrawString("\u25BC", Font, new SolidBrush(ButtFore), Width-17, Height/2 -5); - + e.Graphics.DrawString("\u25BC", Font, new SolidBrush(ButtFore), Width - 17, Height / 2 - 5); + //Text var textRect = new Rectangle(2, 2, Width - 20, Height - 4); - TextRenderer.DrawText(e.Graphics, Text, Font, textRect, Fore, Back, TextFormatFlags.Left | TextFormatFlags.VerticalCenter); + TextRenderer.DrawText(e.Graphics, Text, Font, textRect, Fore, Back, + TextFormatFlags.Left | TextFormatFlags.VerticalCenter); } private void InitializeComponent() @@ -149,10 +166,10 @@ namespace mRemoteNG.UI.Controls.Base // // NGComboBox // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); } - public T GetSelectedItemAs() where T : class { diff --git a/mRemoteV1/UI/Controls/Base/NGGroupBox.cs b/mRemoteV1/UI/Controls/Base/NGGroupBox.cs index 8b52dbb8..7e50a271 100644 --- a/mRemoteV1/UI/Controls/Base/NGGroupBox.cs +++ b/mRemoteV1/UI/Controls/Base/NGGroupBox.cs @@ -18,7 +18,7 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); if (_themeManager.ThemingActive) { @@ -28,14 +28,15 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnPaint(PaintEventArgs e) { - if ( !_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; } + //Reusing the textbox colors - var titleColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Foreground"); - //var backColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Backgorund"); + var titleColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Foreground"); + //var backColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Backgorund"); var lineColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Line"); if (!Enabled) @@ -43,24 +44,26 @@ namespace mRemoteNG.UI.Controls.Base titleColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Disabled_Foreground"); //backColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Disabled_Background"); lineColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("GroupBox_Disabled_Line"); - } + } //var state = Enabled ? GroupBoxState.Normal : GroupBoxState.Disabled; - var flags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.TextBoxControl |TextFormatFlags.WordBreak; - + var flags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping | + TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak; + if (!ShowKeyboardCues) flags |= TextFormatFlags.HidePrefix; if (RightToLeft == RightToLeft.Yes) flags |= TextFormatFlags.RightToLeft | TextFormatFlags.Right; - //No clear backgorund, this control is transparently + //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.Width -= 8; - var size = TextRenderer.MeasureText(e.Graphics, Text, Font, new Size(rectangle.Width, rectangle.Height), flags); + var size = TextRenderer.MeasureText(e.Graphics, Text, Font, new Size(rectangle.Width, rectangle.Height), + flags); rectangle.Width = size.Width; rectangle.Height = size.Height; if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right) @@ -68,23 +71,29 @@ namespace mRemoteNG.UI.Controls.Base else rectangle.X += 8; TextRenderer.DrawText(e.Graphics, Text, Font, rectangle, titleColor, flags); - + if (rectangle.Width > 0) rectangle.Inflate(2, 0); using (var pen = new Pen(lineColor)) { var 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); + e.Graphics.DrawLine(pen, bounds.Left + Padding.Left, num - Padding.Top, bounds.Left + Padding.Left, + bounds.Height - Padding.Bottom); //Bottom line - e.Graphics.DrawLine(pen, bounds.Left + Padding.Left, bounds.Height - Padding.Bottom, bounds.Width -Padding.Right, bounds.Height -Padding.Bottom); + e.Graphics.DrawLine(pen, bounds.Left + Padding.Left, bounds.Height - Padding.Bottom, + bounds.Width - Padding.Right, bounds.Height - Padding.Bottom); //Beside text line - e.Graphics.DrawLine(pen, bounds.Left +Padding.Left, num - Padding.Top, rectangle.X - 3, num - Padding.Top); + e.Graphics.DrawLine(pen, bounds.Left + Padding.Left, num - Padding.Top, rectangle.X - 3, + num - Padding.Top); //Top line cutted - e.Graphics.DrawLine(pen, rectangle.X + rectangle.Width + 2, num - Padding.Top, bounds.Width - Padding.Right, num - Padding.Top); + e.Graphics.DrawLine(pen, rectangle.X + rectangle.Width + 2, num - Padding.Top, + bounds.Width - Padding.Right, num - Padding.Top); //Right line - e.Graphics.DrawLine(pen, bounds.Width - Padding.Right, num - Padding.Top, bounds.Width - Padding.Right, bounds.Height - Padding.Bottom); + e.Graphics.DrawLine(pen, bounds.Width - Padding.Right, num - Padding.Top, bounds.Width - Padding.Right, + bounds.Height - Padding.Bottom); } + RaisePaintEvent(this, e); } @@ -94,9 +103,9 @@ namespace mRemoteNG.UI.Controls.Base // // NGGroupBox // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGLabel.cs b/mRemoteV1/UI/Controls/Base/NGLabel.cs index 987bc55d..28cdd43a 100644 --- a/mRemoteV1/UI/Controls/Base/NGLabel.cs +++ b/mRemoteV1/UI/Controls/Base/NGLabel.cs @@ -25,7 +25,7 @@ namespace mRemoteNG.UI.Controls.Base { base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; // Use the Dialog_* colors since Labels generally have the same colors as panels/dialogs/windows/etc... BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); @@ -78,7 +78,7 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnPaint(PaintEventArgs e) { - if (!_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; @@ -93,7 +93,8 @@ namespace mRemoteNG.UI.Controls.Base } else { - var disabledtextLabel = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Disabled_Foreground"); + var disabledtextLabel = + _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Disabled_Foreground"); TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, disabledtextLabel, _textFormatFlags); } } @@ -104,9 +105,9 @@ namespace mRemoteNG.UI.Controls.Base // // NGLabel // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGListView.cs b/mRemoteV1/UI/Controls/Base/NGListView.cs index 3c551d73..b05986ef 100644 --- a/mRemoteV1/UI/Controls/Base/NGListView.cs +++ b/mRemoteV1/UI/Controls/Base/NGListView.cs @@ -1,6 +1,7 @@ -using BrightIdeasSoftware; -using mRemoteNG.Themes; +using System.ComponentModel; using System.Drawing; +using BrightIdeasSoftware; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Controls.Base { @@ -8,40 +9,42 @@ namespace mRemoteNG.UI.Controls.Base //This is subclassed to avoid repeating the code in multiple places internal class NGListView : ObjectListView { - private CellBorderDecoration deco; + //Control if the gridlines are styled, must be set before the OnCreateControl is fired public bool DecorateLines { get; set; } = true; - public NGListView() { + InitializeComponent(); ThemeManager.getInstance().ThemeChanged += OnCreateControl; } - - - protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); var _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; //List back color BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Background"); ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Foreground"); //Selected item SelectedBackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Selected_Background"); SelectedForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Selected_Foreground"); - + //Header style HeaderUsesThemes = false; - var headerStylo = new HeaderFormatStyle(); - headerStylo.Normal.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Header_Background"); - headerStylo.Normal.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Header_Foreground"); + var headerStylo = new HeaderFormatStyle + { + Normal = + { + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Header_Background"), + ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Header_Foreground") + } + }; HeaderFormatStyle = headerStylo; //Border style - if(DecorateLines) + if (DecorateLines) { UseCellFormatEvents = true; GridLines = false; @@ -54,6 +57,7 @@ namespace mRemoteNG.UI.Controls.Base }; FormatCell += NGListView_FormatCell; } + if (Items != null && Items.Count != 0) BuildList(); Invalidate(); @@ -69,15 +73,14 @@ namespace mRemoteNG.UI.Controls.Base private void InitializeComponent() { - ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); - this.SuspendLayout(); + ((ISupportInitialize)(this)).BeginInit(); + SuspendLayout(); // // NGListView // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); - this.ResumeLayout(false); - + Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + ((ISupportInitialize)(this)).EndInit(); + ResumeLayout(false); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGNumericUpDown.cs b/mRemoteV1/UI/Controls/Base/NGNumericUpDown.cs index 532470e1..0ab03087 100644 --- a/mRemoteV1/UI/Controls/Base/NGNumericUpDown.cs +++ b/mRemoteV1/UI/Controls/Base/NGNumericUpDown.cs @@ -2,15 +2,15 @@ using System.Drawing; using System.Windows.Forms; using mRemoteNG.Themes; + // ReSharper disable LocalizableElement namespace mRemoteNG.UI.Controls.Base { - //Repaint of the NumericUpDown, the composite control buttons are replaced because the - //original ones cannot be themed due to protected inheritance + //Repaint of the NumericUpDown, the composite control buttons are replaced because the + //original ones cannot be themed due to protected inheritance internal class NGNumericUpDown : NumericUpDown { - private readonly ThemeManager _themeManager; private NGButton Up; private NGButton Down; @@ -23,12 +23,12 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnCreateControl() { - base.OnCreateControl(); - if (!_themeManager.ThemingActive) return; + base.OnCreateControl(); + if (!_themeManager.ActiveAndExtended) return; ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); - BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true); - + if (Controls.Count > 0) { for (var i = 0; i < Controls.Count; i++) @@ -63,7 +63,7 @@ namespace mRemoteNG.UI.Controls.Base Text = "\u25BC", Font = new Font(Font.FontFamily, 5f) }; - Down.SetBounds(Controls.Owner.Width - 17, Controls.Owner.Height /2 + 1, 16, Controls.Owner.Height / 2 - 1); + Down.SetBounds(Controls.Owner.Width - 17, Controls.Owner.Height / 2 + 1, 16, Controls.Owner.Height / 2 - 1); Down.Click += Down_Click; Controls.Add(Up); Controls.Add(Down); @@ -82,8 +82,7 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnEnabledChanged(EventArgs e) { - - if (_themeManager.ThemingActive) + if (_themeManager.ActiveAndExtended) { if (Enabled) { @@ -94,7 +93,8 @@ namespace mRemoteNG.UI.Controls.Base { BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Disabled_Background"); } - } + } + base.OnEnabledChanged(e); Invalidate(); } @@ -102,12 +102,15 @@ namespace mRemoteNG.UI.Controls.Base //Redrawing border protected override void OnPaint(PaintEventArgs e) - { + { base.OnPaint(e); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; //Fix Border if (BorderStyle != BorderStyle.None) - e.Graphics.DrawRectangle(new Pen(_themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Border"), 1), 0, 0, Width - 1, Height - 1); + e.Graphics.DrawRectangle( + new Pen(_themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Border"), + 1), 0, 0, Width - 1, + Height - 1); } private void InitializeComponent() @@ -117,10 +120,10 @@ namespace mRemoteNG.UI.Controls.Base // // NGNumericUpDown // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); this.ResumeLayout(false); - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGPictureBox.cs b/mRemoteV1/UI/Controls/Base/NGPictureBox.cs index 04a59b5c..8b34aef5 100644 --- a/mRemoteV1/UI/Controls/Base/NGPictureBox.cs +++ b/mRemoteV1/UI/Controls/Base/NGPictureBox.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; using System.Windows.Forms; using mRemoteNG.Themes; @@ -25,10 +24,10 @@ namespace mRemoteNG.UI.Controls.Base { base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); Invalidate(); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGProgressBar.cs b/mRemoteV1/UI/Controls/Base/NGProgressBar.cs index f45bfe73..2b098da3 100644 --- a/mRemoteV1/UI/Controls/Base/NGProgressBar.cs +++ b/mRemoteV1/UI/Controls/Base/NGProgressBar.cs @@ -4,7 +4,6 @@ using System.Windows.Forms; namespace mRemoteNG.UI.Controls.Base { - // Repaint of a ProgressBar on a flat style internal class NGProgressBar : ProgressBar { @@ -18,7 +17,7 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); if (!_themeManager.ThemingActive) return; SetStyle(ControlStyles.UserPaint, true); @@ -28,16 +27,18 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnPaint(PaintEventArgs e) { - if ( !_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); 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)); 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); + e.Graphics.FillRectangle(new SolidBrush(back), doneProgress, 0, e.ClipRectangle.Width, + e.ClipRectangle.Height); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGRadioButton.cs b/mRemoteV1/UI/Controls/Base/NGRadioButton.cs index fc16b226..e80a7b1e 100644 --- a/mRemoteV1/UI/Controls/Base/NGRadioButton.cs +++ b/mRemoteV1/UI/Controls/Base/NGRadioButton.cs @@ -19,10 +19,12 @@ namespace mRemoteNG.UI.Controls.Base { var display = new DisplayProperties(); - _circleSmall = new Rectangle(display.ScaleWidth(4), display.ScaleHeight(4), display.ScaleWidth(6), display.ScaleHeight(6)); - _circle = new Rectangle(display.ScaleWidth(1), display.ScaleHeight(1), display.ScaleWidth(12), display.ScaleHeight(12)); + _circleSmall = new Rectangle(display.ScaleWidth(4), display.ScaleHeight(4), display.ScaleWidth(6), + display.ScaleHeight(6)); + _circle = new Rectangle(display.ScaleWidth(1), display.ScaleHeight(1), display.ScaleWidth(12), + display.ScaleHeight(12)); _textXCoord = display.ScaleWidth(16); - ThemeManager.getInstance().ThemeChanged += OnCreateControl; + ThemeManager.getInstance().ThemeChanged += OnCreateControl; } @@ -38,7 +40,7 @@ namespace mRemoteNG.UI.Controls.Base protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); if (!_themeManager.ThemingActive) return; // Allows for Overlaying @@ -74,12 +76,13 @@ namespace mRemoteNG.UI.Controls.Base //This class is painted with the checkbox colors, the glyph color is used for the radio inside protected override void OnPaint(PaintEventArgs e) { - if ( !_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; } - // Init + + // Init var g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; @@ -93,7 +96,7 @@ namespace mRemoteNG.UI.Controls.Base if (Enabled) { if (Checked) - { + { center = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Glyph"); } else @@ -104,7 +107,6 @@ namespace mRemoteNG.UI.Controls.Base outline = _themeManager.ActiveTheme.ExtendedPalette.getColor("CheckBox_Border_Hover"); } } - } else { @@ -113,10 +115,11 @@ namespace mRemoteNG.UI.Controls.Base } var textRect = new Rectangle(_textXCoord, Padding.Top, Width - 16, Height); - TextRenderer.DrawText(e.Graphics, Text, Font, textRect, fore, Parent.BackColor, TextFormatFlags.PathEllipsis); - + TextRenderer.DrawText(e.Graphics, Text, Font, textRect, fore, Parent.BackColor, + TextFormatFlags.PathEllipsis); + g.FillEllipse(new SolidBrush(centerBack), _circle); - g.FillEllipse(new SolidBrush(center), _circleSmall); + g.FillEllipse(new SolidBrush(center), _circleSmall); g.DrawEllipse(new Pen(outline), _circle); } @@ -126,9 +129,9 @@ namespace mRemoteNG.UI.Controls.Base // // NGRadioButton // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/Base/NGTextBox.cs b/mRemoteV1/UI/Controls/Base/NGTextBox.cs index 0356bf1d..e50fd8fa 100644 --- a/mRemoteV1/UI/Controls/Base/NGTextBox.cs +++ b/mRemoteV1/UI/Controls/Base/NGTextBox.cs @@ -1,6 +1,7 @@ -using mRemoteNG.Themes; -using System; +using System; +using System.Drawing; using System.Windows.Forms; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Controls.Base { @@ -8,57 +9,55 @@ namespace mRemoteNG.UI.Controls.Base //There are some glitches on the initial draw of some controls public class NGTextBox : TextBox { - private ThemeManager _themeManager; + private ThemeManager _themeManager; - public NGTextBox() - { + public NGTextBox() + { + InitializeComponent(); ThemeManager.getInstance().ThemeChanged += OnCreateControl; } protected override void OnCreateControl() { - base.OnCreateControl(); + base.OnCreateControl(); _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); - BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor(ReadOnly + ? "TextBox_Disabled_Background" + : "TextBox_Background"); Invalidate(); } - - protected override void OnEnabledChanged(EventArgs e) { _themeManager = ThemeManager.getInstance(); - if (_themeManager.ThemingActive) + _themeManager = ThemeManager.getInstance(); + if (_themeManager.ActiveAndExtended) { - _themeManager = ThemeManager.getInstance(); - if(_themeManager.ThemingActive) - { - if (Enabled) - { - ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); - BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); - } - else - { - BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Disabled_Background"); - } + if (Enabled) + { + ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); } - } + else + { + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Disabled_Background"); + } + } + base.OnEnabledChanged(e); Invalidate(); } private void InitializeComponent() { - this.SuspendLayout(); + SuspendLayout(); // // NGTextBox // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.ResumeLayout(false); - + Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + ResumeLayout(false); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/ConnectionContextMenu.cs b/mRemoteV1/UI/Controls/ConnectionContextMenu.cs index d3b17ef3..ab109f2b 100644 --- a/mRemoteV1/UI/Controls/ConnectionContextMenu.cs +++ b/mRemoteV1/UI/Controls/ConnectionContextMenu.cs @@ -10,6 +10,7 @@ using mRemoteNG.Security; using mRemoteNG.Tools; using mRemoteNG.Tree; using mRemoteNG.Tree.Root; + // ReSharper disable UnusedParameter.Local @@ -57,7 +58,7 @@ namespace mRemoteNG.UI.Controls _connectionTree = connectionTree; _connectionInitiator = new ConnectionInitiator(Runtime.CredentialService); InitializeComponent(); - ApplyLanguage(); + ApplyLanguage(); EnableShortcutKeys(); Opening += (sender, args) => { @@ -67,6 +68,7 @@ namespace mRemoteNG.UI.Controls args.Cancel = true; return; } + ShowHideMenuItems(); }; } @@ -109,8 +111,10 @@ namespace mRemoteNG.UI.Controls // // cMenTree // - Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); - Items.AddRange(new ToolStripItem[] { + Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, 0); + Items.AddRange(new ToolStripItem[] + { _cMenTreeConnect, _cMenTreeConnectWithOptions, _cMenTreeDisconnect, @@ -147,7 +151,8 @@ namespace mRemoteNG.UI.Controls // // cMenTreeConnectWithOptions // - _cMenTreeConnectWithOptions.DropDownItems.AddRange(new ToolStripItem[] { + _cMenTreeConnectWithOptions.DropDownItems.AddRange(new ToolStripItem[] + { _cMenTreeConnectWithOptionsConnectToConsoleSession, _cMenTreeConnectWithOptionsDontConnectToConsoleSession, _cMenTreeConnectWithOptionsConnectInFullscreen, @@ -161,7 +166,8 @@ namespace mRemoteNG.UI.Controls // cMenTreeConnectWithOptionsConnectToConsoleSession // _cMenTreeConnectWithOptionsConnectToConsoleSession.Image = Resources.monitor_go; - _cMenTreeConnectWithOptionsConnectToConsoleSession.Name = "_cMenTreeConnectWithOptionsConnectToConsoleSession"; + _cMenTreeConnectWithOptionsConnectToConsoleSession.Name = + "_cMenTreeConnectWithOptionsConnectToConsoleSession"; _cMenTreeConnectWithOptionsConnectToConsoleSession.Size = new System.Drawing.Size(245, 22); _cMenTreeConnectWithOptionsConnectToConsoleSession.Text = "Connect to console session"; _cMenTreeConnectWithOptionsConnectToConsoleSession.Click += OnConnectToConsoleSessionClicked; @@ -169,7 +175,8 @@ namespace mRemoteNG.UI.Controls // cMenTreeConnectWithOptionsDontConnectToConsoleSession // _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Image = Resources.monitor_delete; - _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Name = "_cMenTreeConnectWithOptionsDontConnectToConsoleSession"; + _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Name = + "_cMenTreeConnectWithOptionsDontConnectToConsoleSession"; _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Size = new System.Drawing.Size(245, 22); _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Text = "Don\'t connect to console session"; _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Visible = false; @@ -194,7 +201,8 @@ namespace mRemoteNG.UI.Controls // cMenTreeConnectWithOptionsChoosePanelBeforeConnecting // _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Image = Resources.Panels; - _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Name = "_cMenTreeConnectWithOptionsChoosePanelBeforeConnecting"; + _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Name = + "_cMenTreeConnectWithOptionsChoosePanelBeforeConnecting"; _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Size = new System.Drawing.Size(245, 22); _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Text = "Choose panel before connecting"; _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Click += OnChoosePanelBeforeConnectingClicked; @@ -270,7 +278,8 @@ namespace mRemoteNG.UI.Controls // // cMenTreeImport // - _cMenTreeImport.DropDownItems.AddRange(new ToolStripItem[] { + _cMenTreeImport.DropDownItems.AddRange(new ToolStripItem[] + { _cMenTreeImportFile, _cMenTreeImportActiveDirectory, _cMenTreeImportPortScan @@ -335,7 +344,8 @@ namespace mRemoteNG.UI.Controls // // cMenTreeToolsSort // - _cMenTreeToolsSort.DropDownItems.AddRange(new ToolStripItem[] { + _cMenTreeToolsSort.DropDownItems.AddRange(new ToolStripItem[] + { _cMenTreeToolsSortAscending, _cMenTreeToolsSortDescending }); @@ -381,7 +391,8 @@ namespace mRemoteNG.UI.Controls _cMenTreeConnect.Text = Language.strConnect; _cMenTreeConnectWithOptions.Text = Language.strConnectWithOptions; _cMenTreeConnectWithOptionsConnectToConsoleSession.Text = Language.strConnectToConsoleSession; - _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Text = Language.strDontConnectToConsoleSessionMenuItem; + _cMenTreeConnectWithOptionsDontConnectToConsoleSession.Text = + Language.strDontConnectToConsoleSessionMenuItem; _cMenTreeConnectWithOptionsConnectInFullscreen.Text = Language.strConnectInFullscreen; _cMenTreeConnectWithOptionsNoCredentials.Text = Language.strConnectNoCredentials; _cMenTreeConnectWithOptionsChoosePanelBeforeConnecting.Text = Language.strChoosePanelBeforeConnecting; @@ -440,7 +451,9 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("ShowHideMenuItems (UI.Controls.ConnectionContextMenu) failed", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "ShowHideMenuItems (UI.Controls.ConnectionContextMenu) failed", + ex); } } @@ -564,6 +577,7 @@ namespace mRemoteNG.UI.Controls { continue; } + menuItem.Enabled = enable; if (menuItem.HasDropDownItems) { @@ -593,7 +607,9 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("cMenTreeTools_DropDownOpening failed (UI.Window.ConnectionTreeWindow)", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "cMenTreeTools_DropDownOpening failed (UI.Window.ConnectionTreeWindow)", + ex); } } @@ -607,6 +623,7 @@ namespace mRemoteNG.UI.Controls } #region Click handlers + private void OnConnectClicked(object sender, EventArgs e) { var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; @@ -620,27 +637,37 @@ namespace mRemoteNG.UI.Controls { var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) - _connectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.UseConsoleSession | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(selectedNodeAsContainer, + ConnectionInfo.Force.UseConsoleSession | + ConnectionInfo.Force.DoNotJump); else - _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, ConnectionInfo.Force.UseConsoleSession | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, + ConnectionInfo.Force.UseConsoleSession | + ConnectionInfo.Force.DoNotJump); } private void OnDontConnectToConsoleSessionClicked(object sender, EventArgs e) { var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) - _connectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.DontUseConsoleSession | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(selectedNodeAsContainer, + ConnectionInfo.Force.DontUseConsoleSession | + ConnectionInfo.Force.DoNotJump); else - _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, ConnectionInfo.Force.DontUseConsoleSession | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, + ConnectionInfo.Force.DontUseConsoleSession | + ConnectionInfo.Force.DoNotJump); } private void OnConnectInFullscreenClicked(object sender, EventArgs e) { var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) - _connectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.Fullscreen | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(selectedNodeAsContainer, + ConnectionInfo.Force.Fullscreen | ConnectionInfo.Force.DoNotJump); else - _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, ConnectionInfo.Force.Fullscreen | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, + ConnectionInfo.Force.Fullscreen | ConnectionInfo.Force.DoNotJump); } private void OnConnectWithNoCredentialsClick(object sender, EventArgs e) @@ -656,9 +683,13 @@ namespace mRemoteNG.UI.Controls { var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo; if (selectedNodeAsContainer != null) - _connectionInitiator.OpenConnection(selectedNodeAsContainer, ConnectionInfo.Force.OverridePanel | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(selectedNodeAsContainer, + ConnectionInfo.Force.OverridePanel | + ConnectionInfo.Force.DoNotJump); else - _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, ConnectionInfo.Force.OverridePanel | ConnectionInfo.Force.DoNotJump); + _connectionInitiator.OpenConnection(_connectionTree.SelectedNode, + ConnectionInfo.Force.OverridePanel | + ConnectionInfo.Force.DoNotJump); } private void OnDisconnectClicked(object sender, EventArgs e) @@ -692,7 +723,9 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("DisconnectConnection (UI.Window.ConnectionTreeWindow) failed", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "DisconnectConnection (UI.Window.ConnectionTreeWindow) failed", + ex); } } @@ -713,7 +746,9 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("SSHTransferFile (UI.Window.ConnectionTreeWindow) failed", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "SSHTransferFile (UI.Window.ConnectionTreeWindow) failed", + ex); } } @@ -743,7 +778,8 @@ namespace mRemoteNG.UI.Controls if (_connectionTree.SelectedNode == null) selectedNodeAsContainer = Runtime.ConnectionsService.ConnectionTreeModel.RootNodes.First(); else - selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo ?? _connectionTree.SelectedNode.Parent; + selectedNodeAsContainer = + _connectionTree.SelectedNode as ContainerInfo ?? _connectionTree.SelectedNode.Parent; Import.ImportFromFile(selectedNodeAsContainer); } @@ -801,14 +837,18 @@ namespace mRemoteNG.UI.Controls { try { - if (_connectionTree.SelectedNode.GetTreeNodeType() == TreeNodeType.Connection | _connectionTree.SelectedNode.GetTreeNodeType() == TreeNodeType.PuttySession) + if (_connectionTree.SelectedNode.GetTreeNodeType() == TreeNodeType.Connection | + _connectionTree.SelectedNode.GetTreeNodeType() == TreeNodeType.PuttySession) externalTool.Start(_connectionTree.SelectedNode); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("cMenTreeToolsExternalAppsEntry_Click failed (UI.Window.ConnectionTreeWindow)", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "cMenTreeToolsExternalAppsEntry_Click failed (UI.Window.ConnectionTreeWindow)", + ex); } } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTree.cs b/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTree.cs index 2a371e2c..913c0373 100644 --- a/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTree.cs +++ b/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTree.cs @@ -19,14 +19,17 @@ namespace mRemoteNG.UI.Controls { private readonly ConnectionTreeDragAndDropHandler _dragAndDropHandler = new ConnectionTreeDragAndDropHandler(); private readonly PuttySessionsManager _puttySessionsManager = PuttySessionsManager.Instance; - private readonly StatusImageList _statusImageList = new StatusImageList(); - private readonly ConnectionTreeSearchTextFilter _connectionTreeSearchTextFilter = new ConnectionTreeSearchTextFilter(); + private readonly StatusImageList _statusImageList = new StatusImageList(); + + private readonly ConnectionTreeSearchTextFilter _connectionTreeSearchTextFilter = + new ConnectionTreeSearchTextFilter(); + private bool _nodeInEditMode; private bool _allowEdit; private ConnectionContextMenu _contextMenu; private IConnectionTreeModel _connectionTreeModel; - public ConnectionInfo SelectedNode => (ConnectionInfo) SelectedObject; + public ConnectionInfo SelectedNode => (ConnectionInfo)SelectedObject; public NodeSearcher NodeSearcher { get; private set; } @@ -34,9 +37,11 @@ namespace mRemoteNG.UI.Controls public IEnumerable PostSetupActions { get; set; } = new IConnectionTreeDelegate[0]; - 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 IConnectionTreeModel ConnectionTreeModel { @@ -66,11 +71,13 @@ namespace mRemoteNG.UI.Controls components?.Dispose(); _statusImageList?.Dispose(); } + base.Dispose(disposing); } #region ConnectionTree Setup + private void SetupConnectionTreeView() { SmallImageList = _statusImageList.ImageList; @@ -111,14 +118,14 @@ namespace mRemoteNG.UI.Controls { if (!(args.Model is ContainerInfo container)) return; container.IsExpanded = false; - AutoResizeColumn(Columns[0]); - }; + AutoResizeColumn(Columns[0]); + }; Expanded += (sender, args) => { if (!(args.Model is ContainerInfo container)) return; container.IsExpanded = true; - AutoResizeColumn(Columns[0]); - }; + AutoResizeColumn(Columns[0]); + }; SelectionChanged += tvConnections_AfterSelect; MouseDoubleClick += OnMouse_DoubleClick; MouseClick += OnMouse_SingleClick; @@ -129,34 +136,35 @@ namespace mRemoteNG.UI.Controls AfterLabelEdit += OnAfterLabelEdit; } - /// - /// Resizes the given column to ensure that all content is shown - /// - private void AutoResizeColumn(ColumnHeader column) - { - if (InvokeRequired) - { - Invoke((MethodInvoker) (() => AutoResizeColumn(column))); - return; - } + /// + /// Resizes the given column to ensure that all content is shown + /// + private void AutoResizeColumn(ColumnHeader column) + { + if (InvokeRequired) + { + Invoke((MethodInvoker)(() => AutoResizeColumn(column))); + return; + } - var longestIndentationAndTextWidth = int.MinValue; - var horizontalScrollOffset = LowLevelScrollPosition.X; - const int padding = 10; + var longestIndentationAndTextWidth = int.MinValue; + var horizontalScrollOffset = LowLevelScrollPosition.X; + const int padding = 10; - for (var i = 0; i < Items.Count; i++) - { - var rowIndentation = Items[i].Position.X; - var rowTextWidth = TextRenderer.MeasureText(Items[i].Text, Font).Width; + for (var i = 0; i < Items.Count; i++) + { + var rowIndentation = Items[i].Position.X; + var 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(IConnectionTreeModel newModel) { @@ -164,8 +172,8 @@ namespace mRemoteNG.UI.Controls RegisterModelUpdateHandlers(newModel); NodeSearcher = new NodeSearcher(newModel); ExecutePostSetupActions(); - AutoResizeColumn(Columns[0]); - } + AutoResizeColumn(Columns[0]); + } private void RegisterModelUpdateHandlers(IConnectionTreeModel newModel) { @@ -196,8 +204,8 @@ namespace mRemoteNG.UI.Controls // Removed "TO DO" from above comment. Per #142 it apperas that this no longer occurs with ObjectListView 2.9.1 var property = propertyChangedEventArgs.PropertyName; if (property != nameof(ConnectionInfo.Name) - && property != nameof(ConnectionInfo.OpenConnections) - && property != nameof(ConnectionInfo.Icon)) + && property != nameof(ConnectionInfo.OpenConnections) + && property != nameof(ConnectionInfo.Icon)) { return; } @@ -206,8 +214,8 @@ namespace mRemoteNG.UI.Controls return; RefreshObject(senderAsConnectionInfo); - AutoResizeColumn(Columns[0]); - } + AutoResizeColumn(Columns[0]); + } private void ExecutePostSetupActions() { @@ -216,9 +224,11 @@ namespace mRemoteNG.UI.Controls action.Execute(this); } } + #endregion #region ConnectionTree Behavior + public RootNodeInfo GetRootConnectionNode() { return (RootNodeInfo)ConnectionTreeModel.RootNodes.FirstOrDefault(item => item is RootNodeInfo); @@ -271,7 +281,8 @@ namespace mRemoteNG.UI.Controls private void AddNode(ConnectionInfo newNode) { - if (SelectedNode?.GetTreeNodeType() == TreeNodeType.PuttyRoot || SelectedNode?.GetTreeNodeType() == TreeNodeType.PuttySession) + if (SelectedNode?.GetTreeNodeType() == TreeNodeType.PuttyRoot || + SelectedNode?.GetTreeNodeType() == TreeNodeType.PuttySession) return; // the new node will survive filtering if filtering is active @@ -321,7 +332,7 @@ namespace mRemoteNG.UI.Controls public void CopyHostnameSelectedNode() { - Clipboard.SetText(SelectedNode.Hostname); + Clipboard.SetText(SelectedNode.IsContainer ? SelectedNode.Name : SelectedNode.Hostname); } public void SortRecursive(ConnectionInfo sortTarget, ListSortDirection sortDirection) @@ -371,23 +382,23 @@ namespace mRemoteNG.UI.Controls private void HandleCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { - // disable filtering if necessary. prevents RefreshObjects from - // throwing an exception - var filteringEnabled = IsFiltering; - var filter = ModelFilter; - if (filteringEnabled) - { - ResetColumnFiltering(); - } + // disable filtering if necessary. prevents RefreshObjects from + // throwing an exception + var filteringEnabled = IsFiltering; + var filter = ModelFilter; + if (filteringEnabled) + { + ResetColumnFiltering(); + } if (sender is IConnectionTree) RebuildAll(true); else - RefreshObject(sender); + RefreshObject(sender); - AutoResizeColumn(Columns[0]); + AutoResizeColumn(Columns[0]); - // turn filtering back on + // turn filtering back on if (!filteringEnabled) return; ModelFilter = filter; UpdateFiltering(); @@ -407,7 +418,9 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("tvConnections_AfterSelect (UI.Window.ConnectionTreeWindow) failed", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "tvConnections_AfterSelect (UI.Window.ConnectionTreeWindow) failed", + ex); } } @@ -447,7 +460,9 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("tvConnections_MouseMove (UI.Window.ConnectionTreeWindow) failed", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "tvConnections_MouseMove (UI.Window.ConnectionTreeWindow) failed", + ex); } } @@ -484,9 +499,12 @@ namespace mRemoteNG.UI.Controls } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("tvConnections_AfterLabelEdit (UI.Window.ConnectionTreeWindow) failed", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "tvConnections_AfterLabelEdit (UI.Window.ConnectionTreeWindow) failed", + ex); } } + #endregion } } diff --git a/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs b/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs index 425c329d..f2d782e6 100644 --- a/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs +++ b/mRemoteV1/UI/Controls/ConnectionTree/ConnectionTreeSearchTextFilter.cs @@ -30,4 +30,4 @@ namespace mRemoteNG.UI.Controls objectAsConnectionInfo.Description.ToLowerInvariant().Contains(filterTextLower); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/ConnectionTree/IConnectionTreeDelegate.cs b/mRemoteV1/UI/Controls/ConnectionTree/IConnectionTreeDelegate.cs index 77643a1e..bf063f54 100644 --- a/mRemoteV1/UI/Controls/ConnectionTree/IConnectionTreeDelegate.cs +++ b/mRemoteV1/UI/Controls/ConnectionTree/IConnectionTreeDelegate.cs @@ -1,5 +1,4 @@ - -namespace mRemoteNG.UI.Controls +namespace mRemoteNG.UI.Controls { public interface IConnectionTreeDelegate { diff --git a/mRemoteV1/UI/Controls/ConnectionTree/NameColumn.cs b/mRemoteV1/UI/Controls/ConnectionTree/NameColumn.cs index ca275a04..848bfa2c 100644 --- a/mRemoteV1/UI/Controls/ConnectionTree/NameColumn.cs +++ b/mRemoteV1/UI/Controls/ConnectionTree/NameColumn.cs @@ -3,13 +3,13 @@ using mRemoteNG.Connection; namespace mRemoteNG.UI.Controls { - public class NameColumn : OLVColumn + public class NameColumn : OLVColumn { public NameColumn(ImageGetterDelegate imageGetterDelegate) { AspectName = "Name"; FillsFreeSpace = false; - AspectGetter = item => ((ConnectionInfo) item).Name; + AspectGetter = item => ((ConnectionInfo)item).Name; ImageGetter = imageGetterDelegate; AutoCompleteEditor = false; } diff --git a/mRemoteV1/UI/Controls/CredentialRecordListBox.cs b/mRemoteV1/UI/Controls/CredentialRecordListBox.cs index 86f0dd7d..0fd99488 100644 --- a/mRemoteV1/UI/Controls/CredentialRecordListBox.cs +++ b/mRemoteV1/UI/Controls/CredentialRecordListBox.cs @@ -9,7 +9,7 @@ namespace mRemoteNG.UI.Controls { public new ICredentialRecord SelectedItem => (ICredentialRecord)base.SelectedItem; public ICredentialRecord NoneSelection { get; } = new NullCredentialRecord(); - public ICredentialRecord AddNewSelection { get; } = new CredentialRecord { Title = $"--{Language.strAdd}--" }; + public ICredentialRecord AddNewSelection { get; } = new CredentialRecord {Title = $"--{Language.strAdd}--"}; public CredentialRecordListBox(IEnumerable listOfCredentialRecords) { diff --git a/mRemoteV1/UI/Controls/CredentialRecordListView.cs b/mRemoteV1/UI/Controls/CredentialRecordListView.cs index 42d20d3c..8507a95f 100644 --- a/mRemoteV1/UI/Controls/CredentialRecordListView.cs +++ b/mRemoteV1/UI/Controls/CredentialRecordListView.cs @@ -28,11 +28,12 @@ namespace mRemoteNG.UI.Controls } } - public KeyValuePair SelectedObject => CastRowObject(objectListView1.SelectedObject); + public KeyValuePair SelectedObject => + CastRowObject(objectListView1.SelectedObject); - public IEnumerable> SelectedObjects => + public IEnumerable> SelectedObjects => from object item - in objectListView1.SelectedObjects + in objectListView1.SelectedObjects select CastRowObject(item); public bool MultipleObjectsSelected => objectListView1.SelectedObjects.Count > 1; @@ -115,28 +116,35 @@ namespace mRemoteNG.UI.Controls private KeyValuePair CastRowObject(object model) { - if (!(model is KeyValuePair)) return default(KeyValuePair); + if (!(model is KeyValuePair)) + return default(KeyValuePair); var keyValuePair = (KeyValuePair)model; return keyValuePair; } - private void CredentialRepositoryListOnRepositoriesUpdated(object sender, CollectionUpdatedEventArgs arg) + private void CredentialRepositoryListOnRepositoriesUpdated(object sender, + CollectionUpdatedEventArgs + arg) { SetObjectList(); } - private void CredentialRepositoryListOnCredentialsUpdated(object sender, CollectionUpdatedEventArgs collectionUpdatedEventArgs) + private void CredentialRepositoryListOnCredentialsUpdated(object sender, + CollectionUpdatedEventArgs + collectionUpdatedEventArgs) { SetObjectList(); } public event EventHandler SelectionChanged; + private void RaiseSelectionChangedEvent() { SelectionChanged?.Invoke(this, EventArgs.Empty); } public event EventHandler CellClick; + private void RaiseCellClickEvent(object sender, CellClickEventArgs args) { CellClick?.Invoke(sender, args); diff --git a/mRemoteV1/UI/Controls/CredentialRepositoryListView.cs b/mRemoteV1/UI/Controls/CredentialRepositoryListView.cs index 725fbe35..74805d0b 100644 --- a/mRemoteV1/UI/Controls/CredentialRepositoryListView.cs +++ b/mRemoteV1/UI/Controls/CredentialRepositoryListView.cs @@ -28,7 +28,7 @@ namespace mRemoteNG.UI.Controls public Func RepositoryFilter { get; set; } public ICredentialRepository SelectedRepository => GetSelectedRepository(); - public Func DoubleClickHandler { get; set; } + public Func DoubleClickHandler { get; set; } public CredentialRepositoryListView() { @@ -44,11 +44,11 @@ namespace mRemoteNG.UI.Controls private void SetupObjectListView() { - olvColumnTitle.AspectGetter = rowObject => ((ICredentialRepository) rowObject).Config.Title; - olvColumnProvider.AspectGetter = rowObject => ((ICredentialRepository) rowObject).Config.TypeName; - olvColumnSource.AspectGetter = rowObject => ((ICredentialRepository) rowObject).Config.Source; - olvColumnId.AspectGetter = rowObject => ((ICredentialRepository) rowObject).Config.Id; - olvColumnIsLoaded.AspectGetter = rowObject => ((ICredentialRepository) rowObject).IsLoaded; + olvColumnTitle.AspectGetter = rowObject => ((ICredentialRepository)rowObject).Config.Title; + olvColumnProvider.AspectGetter = rowObject => ((ICredentialRepository)rowObject).Config.TypeName; + olvColumnSource.AspectGetter = rowObject => ((ICredentialRepository)rowObject).Config.Source; + olvColumnId.AspectGetter = rowObject => ((ICredentialRepository)rowObject).Config.Id; + olvColumnIsLoaded.AspectGetter = rowObject => ((ICredentialRepository)rowObject).IsLoaded; SetListObjects(CredentialRepositoryList.CredentialProviders); objectListView1.SelectionChanged += (sender, args) => RaiseSelectionChangedEvent(); objectListView1.MouseDoubleClick += ObjectListView1OnMouseDoubleClick; @@ -61,9 +61,7 @@ namespace mRemoteNG.UI.Controls private void SetListObjects(IEnumerable repositories) { - var filteredRepositories = RepositoryFilter == null ? - repositories : - repositories.Where(RepositoryFilter); + var filteredRepositories = RepositoryFilter == null ? repositories : repositories.Where(RepositoryFilter); objectListView1.SetObjects(filteredRepositories); } @@ -83,6 +81,7 @@ namespace mRemoteNG.UI.Controls } public event EventHandler SelectionChanged; + private void RaiseSelectionChangedEvent() { SelectionChanged?.Invoke(this, EventArgs.Empty); @@ -95,6 +94,7 @@ namespace mRemoteNG.UI.Controls _credentialRepositoryList.RepositoriesUpdated -= OnRepositoriesUpdated; components?.Dispose(); } + base.Dispose(disposing); } } diff --git a/mRemoteV1/UI/Controls/ExternalToolsToolStrip.cs b/mRemoteV1/UI/Controls/ExternalToolsToolStrip.cs index 4b26f842..91a35a5e 100644 --- a/mRemoteV1/UI/Controls/ExternalToolsToolStrip.cs +++ b/mRemoteV1/UI/Controls/ExternalToolsToolStrip.cs @@ -16,8 +16,9 @@ namespace mRemoteNG.UI.Controls public ExternalToolsToolStrip() { - Initialize(); - Runtime.ExternalToolsService.ExternalTools.CollectionUpdated += (sender, args) => AddExternalToolsToToolBar(); + Initialize(); + Runtime.ExternalToolsService.ExternalTools.CollectionUpdated += + (sender, args) => AddExternalToolsToToolBar(); } private void Initialize() @@ -53,6 +54,7 @@ namespace mRemoteNG.UI.Controls } #region Ext Apps Toolbar + private void cMenToolbarShowText_Click(object sender, EventArgs e) { SwitchToolBarText(!CMenToolbarShowText.Checked); @@ -70,16 +72,16 @@ namespace mRemoteNG.UI.Controls foreach (var tool in Runtime.ExternalToolsService.ExternalTools) { - if (tool.ShowOnToolbar) - { - var button = (ToolStripButton)Items.Add(tool.DisplayName, tool.Image, tsExtAppEntry_Click); - if (CMenToolbarShowText.Checked) - button.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; - else - button.DisplayStyle = button.Image != null ? ToolStripItemDisplayStyle.Image : ToolStripItemDisplayStyle.ImageAndText; + if (!tool.ShowOnToolbar) continue; + var button = (ToolStripButton)Items.Add(tool.DisplayName, tool.Image, tsExtAppEntry_Click); + if (CMenToolbarShowText.Checked) + button.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; + else + button.DisplayStyle = button.Image != null + ? ToolStripItemDisplayStyle.Image + : ToolStripItemDisplayStyle.ImageAndText; - button.Tag = tool; - } + button.Tag = tool; } } catch (Exception ex) @@ -102,7 +104,9 @@ namespace mRemoteNG.UI.Controls extA.Start(selectedTreeNode); else { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "No connection was selected, external tool may return errors.", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + "No connection was selected, external tool may return errors.", + true); extA.Start(); } } @@ -114,15 +118,19 @@ namespace mRemoteNG.UI.Controls if (show) tItem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; else - tItem.DisplayStyle = tItem.Image != null ? ToolStripItemDisplayStyle.Image : ToolStripItemDisplayStyle.ImageAndText; + tItem.DisplayStyle = tItem.Image != null + ? ToolStripItemDisplayStyle.Image + : ToolStripItemDisplayStyle.ImageAndText; } CMenToolbarShowText.Checked = show; } + #endregion // CodeAyalysis doesn't like null propagation - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "components")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", + MessageId = "components")] protected override void Dispose(bool disposing) { try diff --git a/mRemoteV1/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs b/mRemoteV1/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs index 57c74538..32b919cb 100644 --- a/mRemoteV1/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs +++ b/mRemoteV1/UI/Controls/FilteredPropertyGrid/FilteredPropertyGrid.cs @@ -12,191 +12,206 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// It also allows to hide (or filter) the properties of the SelectedObject displayed by the PropertyGrid. /// public partial class FilteredPropertyGrid : PropertyGrid - { - /// - /// 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(); + { + /// + /// 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(); - /// - /// Contain a reference to the array of properties to display in the PropertyGrid. - /// - private AttributeCollection _hiddenAttributes; - private AttributeCollection _browsableAttributes; + /// + /// Contain a reference to the array of properties to display in the PropertyGrid. + /// + private AttributeCollection _hiddenAttributes; - /// - /// Contain references to the arrays of properties or categories to hide. - /// - private string[] _mBrowsableProperties; - private string[] _mHiddenProperties; - /// - /// Contain a reference to the wrapper that contains the object to be displayed into the PropertyGrid. - /// - private ObjectWrapper _mWrapper; + private AttributeCollection _browsableAttributes; - /// - /// Public constructor. - /// - public FilteredPropertyGrid() - { - InitializeComponent(); - base.SelectedObject = _mWrapper; - } + /// + /// Contain references to the arrays of properties or categories to hide. + /// + private string[] _mBrowsableProperties; - /// - /// A list of all currently properties being shown by the property grid. - /// - public IEnumerable VisibleProperties => _propertyDescriptors.Select(p => p.Name); + private string[] _mHiddenProperties; - public new AttributeCollection BrowsableAttributes { - get => _browsableAttributes; - set { - if (_browsableAttributes == value) return; - _hiddenAttributes = null; - _browsableAttributes = value; - RefreshProperties(); - } - } + /// + /// Contain a reference to the wrapper that contains the object to be displayed into the PropertyGrid. + /// + private ObjectWrapper _mWrapper; - /// - /// Get or set the categories to hide. - /// - public AttributeCollection HiddenAttributes { - get => _hiddenAttributes; - set { - if (value == _hiddenAttributes) return; - _hiddenAttributes = value; - _browsableAttributes = null; - RefreshProperties(); - } - } + /// + /// Public constructor. + /// + public FilteredPropertyGrid() + { + InitializeComponent(); + base.SelectedObject = _mWrapper; + } - /// - /// Get or set the properties to show. - /// - /// if one or several properties don't exist. - public string[] BrowsableProperties { - get => _mBrowsableProperties; - set { - if (value == _mBrowsableProperties) return; - _mBrowsableProperties = value; - RefreshProperties(); - } - } + /// + /// A list of all currently properties being shown by the property grid. + /// + public IEnumerable VisibleProperties => _propertyDescriptors.Select(p => p.Name); - /// Get or set the properties to hide. - public string[] HiddenProperties { - get => _mHiddenProperties; - set { - if (value == _mHiddenProperties) return; - _mHiddenProperties = value; - RefreshProperties(); - } - } + public new AttributeCollection BrowsableAttributes + { + get => _browsableAttributes; + set + { + if (_browsableAttributes == value) return; + _hiddenAttributes = null; + _browsableAttributes = value; + RefreshProperties(); + } + } - /// - /// Overwrite the PropertyGrid.SelectedObject property. - /// - /// The object passed to the base PropertyGrid is the wrapper. - public new object SelectedObject { - get => - _mWrapper != null - ? ((ObjectWrapper)base.SelectedObject).SelectedObject + /// + /// Get or set the categories to hide. + /// + public AttributeCollection HiddenAttributes + { + get => _hiddenAttributes; + set + { + if (value == _hiddenAttributes) return; + _hiddenAttributes = value; + _browsableAttributes = null; + RefreshProperties(); + } + } + + /// + /// Get or set the properties to show. + /// + /// if one or several properties don't exist. + public string[] BrowsableProperties + { + get => _mBrowsableProperties; + set + { + if (value == _mBrowsableProperties) return; + _mBrowsableProperties = value; + RefreshProperties(); + } + } + + /// Get or set the properties to hide. + public string[] HiddenProperties + { + get => _mHiddenProperties; + set + { + if (value == _mHiddenProperties) return; + _mHiddenProperties = value; + RefreshProperties(); + } + } + + /// + /// Overwrite the PropertyGrid.SelectedObject property. + /// + /// The object passed to the base PropertyGrid is the wrapper. + public new object SelectedObject + { + get => + _mWrapper != null + ? ((ObjectWrapper)base.SelectedObject).SelectedObject : null; - set { - // Set the new object to the wrapper and create one if necessary. - if(_mWrapper == null) - { - _mWrapper = new ObjectWrapper(value); - RefreshProperties(); - } - else if(_mWrapper.SelectedObject != value) - { - var needrefresh = value.GetType() != _mWrapper.SelectedObject.GetType(); - _mWrapper.SelectedObject = value; - if(needrefresh) - RefreshProperties(); - } - // Set the list of properties to the wrapper. - _mWrapper.PropertyDescriptors = _propertyDescriptors; - // Link the wrapper to the parent PropertyGrid. - base.SelectedObject = _mWrapper; - } - } + set + { + // Set the new object to the wrapper and create one if necessary. + if (_mWrapper == null) + { + _mWrapper = new ObjectWrapper(value); + RefreshProperties(); + } + else if (_mWrapper.SelectedObject != value) + { + var needrefresh = value.GetType() != _mWrapper.SelectedObject.GetType(); + _mWrapper.SelectedObject = value; + if (needrefresh) + RefreshProperties(); + } - /// - /// Build the list of the properties to be displayed in the PropertyGrid, following the filters defined the Browsable and Hidden properties. - /// - private void RefreshProperties() - { - if(_mWrapper == null) - return; + // Set the list of properties to the wrapper. + _mWrapper.PropertyDescriptors = _propertyDescriptors; + // Link the wrapper to the parent PropertyGrid. + base.SelectedObject = _mWrapper; + } + } - // Clear the list of properties to be displayed. - _propertyDescriptors.Clear(); - // Check whether the list is filtered - if(_browsableAttributes != null && _browsableAttributes.Count > 0) - { - // Add to the list the attributes that need to be displayed. - foreach(Attribute attribute in _browsableAttributes) - ShowAttribute(attribute); - } - else - { - // Fill the collection with all the properties. - var originalPropertyDescriptors = TypeDescriptor - .GetProperties(_mWrapper.SelectedObject) - .OfType() - .Where(PropertyDoesntHaveBrowsableFalseAttribute); + /// + /// Build the list of the properties to be displayed in the PropertyGrid, following the filters defined the Browsable and Hidden properties. + /// + private void RefreshProperties() + { + if (_mWrapper == null) + return; - foreach(PropertyDescriptor propertyDescriptor in originalPropertyDescriptors) - _propertyDescriptors.Add(propertyDescriptor); + // Clear the list of properties to be displayed. + _propertyDescriptors.Clear(); + // Check whether the list is filtered + if (_browsableAttributes != null && _browsableAttributes.Count > 0) + { + // Add to the list the attributes that need to be displayed. + foreach (Attribute attribute in _browsableAttributes) + ShowAttribute(attribute); + } + else + { + // Fill the collection with all the properties. + var originalPropertyDescriptors = TypeDescriptor + .GetProperties(_mWrapper.SelectedObject) + .OfType() + .Where(PropertyDoesntHaveBrowsableFalseAttribute); - // Remove from the list the attributes that mustn't be displayed. - if(_hiddenAttributes != null) - foreach (Attribute attribute in _hiddenAttributes) - HideAttribute(attribute); - } + foreach (PropertyDescriptor propertyDescriptor in originalPropertyDescriptors) + _propertyDescriptors.Add(propertyDescriptor); - // Get all the properties of the SelectedObject - var allproperties = TypeDescriptor.GetProperties(_mWrapper.SelectedObject); - - // Hide if necessary, some properties - if(_mHiddenProperties != null && _mHiddenProperties.Length > 0) - { - // Remove from the list the properties that mustn't be displayed. - foreach(var propertyname in _mHiddenProperties) - { - try - { - var property = allproperties[propertyname]; - // Remove from the list the property - HideProperty(property); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("FilteredPropertyGrid: Could not hide Property.", ex); + // Remove from the list the attributes that mustn't be displayed. + if (_hiddenAttributes != null) + foreach (Attribute attribute in _hiddenAttributes) + HideAttribute(attribute); + } + + // Get all the properties of the SelectedObject + var allproperties = TypeDescriptor.GetProperties(_mWrapper.SelectedObject); + + // Hide if necessary, some properties + if (_mHiddenProperties != null && _mHiddenProperties.Length > 0) + { + // Remove from the list the properties that mustn't be displayed. + foreach (var propertyname in _mHiddenProperties) + { + try + { + var property = allproperties[propertyname]; + // Remove from the list the property + HideProperty(property); } - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("FilteredPropertyGrid: Could not hide Property.", + ex); + } + } + } - // Display if necessary, some properties - if(_mBrowsableProperties != null && _mBrowsableProperties.Length > 0) - { - foreach(var propertyname in _mBrowsableProperties) - { - try - { - ShowProperty(allproperties[propertyname]); - } - catch (Exception ex) - { + // Display if necessary, some properties + if (_mBrowsableProperties != null && _mBrowsableProperties.Length > 0) + { + foreach (var propertyname in _mBrowsableProperties) + { + try + { + ShowProperty(allproperties[propertyname]); + } + catch (Exception ex) + { Runtime.MessageCollector.AddExceptionMessage("FilteredPropertyGrid: Property not found", ex); - } - } - } - } + } + } + } + } /// /// Predicate to determine if a property has a Browsable(false) attribute @@ -204,25 +219,26 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// /// /// - private bool PropertyDoesntHaveBrowsableFalseAttribute(PropertyDescriptor propertyDescriptor) - { - return !propertyDescriptor.Attributes.Contains(new BrowsableAttribute(false)); - } + private bool PropertyDoesntHaveBrowsableFalseAttribute(PropertyDescriptor propertyDescriptor) + { + return !propertyDescriptor.Attributes.Contains(new BrowsableAttribute(false)); + } - /// + /// /// Allows to hide a set of properties to the parent PropertyGrid. /// /// A set of attributes that filter the original collection of properties. /// For better performance, include the BrowsableAttribute with true value. private void HideAttribute(Attribute attribute) { - var filteredoriginalpropertydescriptors = TypeDescriptor.GetProperties(_mWrapper.SelectedObject,new[] { attribute }); - if(filteredoriginalpropertydescriptors == null || filteredoriginalpropertydescriptors.Count == 0) - throw new ArgumentException("Attribute not found", attribute.ToString()); + var filteredoriginalpropertydescriptors = + TypeDescriptor.GetProperties(_mWrapper.SelectedObject, new[] {attribute}); + if (filteredoriginalpropertydescriptors == null || filteredoriginalpropertydescriptors.Count == 0) + throw new ArgumentException("Attribute not found", attribute.ToString()); - foreach(PropertyDescriptor propertydescriptor in filteredoriginalpropertydescriptors) - HideProperty(propertydescriptor); - } + foreach (PropertyDescriptor propertydescriptor in filteredoriginalpropertydescriptors) + HideProperty(propertydescriptor); + } /// /// Add all the properties that match an attribute to the list of properties to be displayed in the PropertyGrid. @@ -230,23 +246,24 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// The attribute to be added. private void ShowAttribute(Attribute attribute) { - var filteredoriginalpropertydescriptors = TypeDescriptor.GetProperties(_mWrapper.SelectedObject,new[] { attribute }); - if(filteredoriginalpropertydescriptors == null || filteredoriginalpropertydescriptors.Count == 0) - throw new ArgumentException("Attribute not found", attribute.ToString()); + var filteredoriginalpropertydescriptors = + TypeDescriptor.GetProperties(_mWrapper.SelectedObject, new[] {attribute}); + if (filteredoriginalpropertydescriptors == null || filteredoriginalpropertydescriptors.Count == 0) + throw new ArgumentException("Attribute not found", attribute.ToString()); - foreach(PropertyDescriptor propertydescriptor in filteredoriginalpropertydescriptors) - ShowProperty(propertydescriptor); - } + foreach (PropertyDescriptor propertydescriptor in filteredoriginalpropertydescriptors) + ShowProperty(propertydescriptor); + } - /// - /// Add a property to the list of properties to be displayed in the PropertyGrid. - /// - /// The property to be added. - private void ShowProperty(PropertyDescriptor property) - { - if(!_propertyDescriptors.Contains(property)) - _propertyDescriptors.Add(property); - } + /// + /// Add a property to the list of properties to be displayed in the PropertyGrid. + /// + /// The property to be added. + private void ShowProperty(PropertyDescriptor property) + { + if (!_propertyDescriptors.Contains(property)) + _propertyDescriptors.Add(property); + } /// /// Allows to hide a property to the parent PropertyGrid. @@ -254,8 +271,8 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// The name of the property to be hidden. private void HideProperty(PropertyDescriptor property) { - if(_propertyDescriptors.Contains(property)) - _propertyDescriptors.Remove(property); - } - } + if (_propertyDescriptors.Contains(property)) + _propertyDescriptors.Remove(property); + } + } } \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs b/mRemoteV1/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs index a67abef4..221edec3 100644 --- a/mRemoteV1/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs +++ b/mRemoteV1/UI/Controls/FilteredPropertyGrid/ObjectWrapper.cs @@ -8,115 +8,117 @@ namespace mRemoteNG.UI.Controls.FilteredPropertyGrid /// This class is a wrapper. It contains the object the PropertyGrid has to display. /// internal class ObjectWrapper : ICustomTypeDescriptor - { - /// - /// Creates a new instance of an with the given object to be wrapped. - /// - /// A reference to the selected object that will linked to the parent PropertyGrid. - internal ObjectWrapper(object obj) - { - SelectedObject = obj; - } + { + /// + /// Creates a new instance of an with the given object to be wrapped. + /// + /// A reference to the selected object that will linked to the parent PropertyGrid. + internal ObjectWrapper(object obj) + { + SelectedObject = obj; + } - /// - /// Get or set a reference to the selected objet that will linked to the parent PropertyGrid. - /// - public object SelectedObject { get; set; } + /// + /// Get or set a reference to the selected objet that will linked to the parent PropertyGrid. + /// + public object SelectedObject { get; set; } - /// - /// Get or set a reference to the collection of properties to show in the parent PropertyGrid - /// - public List PropertyDescriptors { get; set; } = new List(); + /// + /// Get or set a reference to the collection of properties to show in the parent PropertyGrid + /// + public List PropertyDescriptors { get; set; } = new List(); - #region ICustomTypeDescriptor Members - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { - return GetProperties(); - } + #region ICustomTypeDescriptor Members - public PropertyDescriptorCollection GetProperties() - { - return new PropertyDescriptorCollection(PropertyDescriptors.ToArray(), true); - } + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) + { + return GetProperties(); + } - /// - /// GetAttributes - /// - /// AttributeCollection - public AttributeCollection GetAttributes() - { - return TypeDescriptor.GetAttributes(SelectedObject, true); - } + public PropertyDescriptorCollection GetProperties() + { + return new PropertyDescriptorCollection(PropertyDescriptors.ToArray(), true); + } - /// - /// Get Class Name - /// - /// String - public string GetClassName() - { - return TypeDescriptor.GetClassName(SelectedObject, true); - } + /// + /// GetAttributes + /// + /// AttributeCollection + public AttributeCollection GetAttributes() + { + return TypeDescriptor.GetAttributes(SelectedObject, true); + } - /// - /// GetComponentName - /// - /// String - public string GetComponentName() - { - return TypeDescriptor.GetComponentName(SelectedObject, true); - } + /// + /// Get Class Name + /// + /// String + public string GetClassName() + { + return TypeDescriptor.GetClassName(SelectedObject, true); + } - /// - /// GetConverter - /// - /// TypeConverter - public TypeConverter GetConverter() - { - return TypeDescriptor.GetConverter(SelectedObject, true); - } + /// + /// GetComponentName + /// + /// String + public string GetComponentName() + { + return TypeDescriptor.GetComponentName(SelectedObject, true); + } - /// - /// GetDefaultEvent - /// - /// EventDescriptor - public EventDescriptor GetDefaultEvent() - { - return TypeDescriptor.GetDefaultEvent(SelectedObject, true); - } + /// + /// GetConverter + /// + /// TypeConverter + public TypeConverter GetConverter() + { + return TypeDescriptor.GetConverter(SelectedObject, true); + } - /// - /// GetDefaultProperty - /// - /// PropertyDescriptor - public PropertyDescriptor GetDefaultProperty() - { - return TypeDescriptor.GetDefaultProperty(SelectedObject, true); - } + /// + /// GetDefaultEvent + /// + /// EventDescriptor + public EventDescriptor GetDefaultEvent() + { + return TypeDescriptor.GetDefaultEvent(SelectedObject, true); + } - /// - /// GetEditor - /// - /// editorBaseType - /// object - public object GetEditor(Type editorBaseType) - { - return TypeDescriptor.GetEditor(this,editorBaseType, true); - } + /// + /// GetDefaultProperty + /// + /// PropertyDescriptor + public PropertyDescriptor GetDefaultProperty() + { + return TypeDescriptor.GetDefaultProperty(SelectedObject, true); + } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { - return TypeDescriptor.GetEvents(SelectedObject, attributes, true); - } + /// + /// GetEditor + /// + /// editorBaseType + /// object + public object GetEditor(Type editorBaseType) + { + return TypeDescriptor.GetEditor(this, editorBaseType, true); + } - public EventDescriptorCollection GetEvents() - { - return TypeDescriptor.GetEvents(SelectedObject, true); - } + public EventDescriptorCollection GetEvents(Attribute[] attributes) + { + return TypeDescriptor.GetEvents(SelectedObject, attributes, true); + } - public object GetPropertyOwner(PropertyDescriptor pd) - { - return SelectedObject; - } - #endregion - } -} + public EventDescriptorCollection GetEvents() + { + return TypeDescriptor.GetEvents(SelectedObject, true); + } + + public object GetPropertyOwner(PropertyDescriptor pd) + { + return SelectedObject; + } + + #endregion + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/HeadlessTabControl.cs b/mRemoteV1/UI/Controls/HeadlessTabControl.cs index d9c821ba..07b06960 100644 --- a/mRemoteV1/UI/Controls/HeadlessTabControl.cs +++ b/mRemoteV1/UI/Controls/HeadlessTabControl.cs @@ -21,9 +21,9 @@ namespace mRemoteNG.UI.Controls // // HeadlessTabControl // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); - } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/IPTextBox.cs b/mRemoteV1/UI/Controls/IPTextBox.cs index 7fb4063b..b3f31ad7 100644 --- a/mRemoteV1/UI/Controls/IPTextBox.cs +++ b/mRemoteV1/UI/Controls/IPTextBox.cs @@ -2,105 +2,107 @@ * http://www.codeproject.com/Articles/11576/IP-TextBox * Original Author: mawnkay */ + using System; using System.Windows.Forms; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Controls { - /** \class IPTextBox - * \brief An IP Address Box - * - * A TextBox that only allows entry of a valid ip address - ** - */ - public class IPTextBox: UserControl - { - private Panel panel1; - public Base.NGTextBox Octet1; - public Base.NGTextBox Octet2; - public Base.NGTextBox Octet3; - public Base.NGTextBox Octet4; + /* class IPTextBox + * An IP Address Box + * A TextBox that only allows entry of a valid ip address + */ + public class IPTextBox : UserControl + { + private Panel panel1; + public Base.NGTextBox Octet1; + public Base.NGTextBox Octet2; + public Base.NGTextBox Octet3; + public Base.NGTextBox Octet4; private Base.NGLabel label1; private Base.NGLabel label2; - private Base.NGLabel label3; - private ToolTip toolTip1; - private System.ComponentModel.IContainer components; - - /** Sets and Gets the tooltiptext on toolTip1 */ - public string ToolTipText - { - get => toolTip1.GetToolTip(Octet1); - set - { - toolTip1.SetToolTip(Octet1,value); - toolTip1.SetToolTip(Octet2,value); - toolTip1.SetToolTip(Octet3,value); - toolTip1.SetToolTip(Octet4,value); - toolTip1.SetToolTip(label1,value); - toolTip1.SetToolTip(label2,value); - toolTip1.SetToolTip(label3,value); - } - } + private Base.NGLabel label3; + private ToolTip toolTip1; + private System.ComponentModel.IContainer components; - /** Set or Get the string that represents the value in the box */ - public override string Text - { - get => Octet1.Text + @"." + Octet2.Text + @"." + Octet3.Text + @"." + Octet4.Text; - set - { - if (!string.IsNullOrEmpty(value)) - { - var pieces = value.Split(@".".ToCharArray(),4); - Octet1.Text = pieces[0]; - Octet2.Text = pieces[1]; - Octet3.Text = pieces[2]; - Octet4.Text = pieces[3]; - } - else - { - Octet1.Text = ""; - Octet2.Text = ""; - Octet3.Text = ""; - Octet4.Text = ""; - } - } - } + /* Sets and Gets the tooltiptext on toolTip1 */ + public string ToolTipText + { + get => toolTip1.GetToolTip(Octet1); + set + { + toolTip1.SetToolTip(Octet1, value); + toolTip1.SetToolTip(Octet2, value); + toolTip1.SetToolTip(Octet3, value); + toolTip1.SetToolTip(Octet4, value); + toolTip1.SetToolTip(label1, value); + toolTip1.SetToolTip(label2, value); + toolTip1.SetToolTip(label3, value); + } + } - public IPTextBox() - { - // This call is required by the Windows.Forms Form Designer. - InitializeComponent(); + /* Set or Get the string that represents the value in the box */ + public override string Text + { + get => Octet1.Text + @"." + Octet2.Text + @"." + Octet3.Text + @"." + Octet4.Text; + set + { + if (!string.IsNullOrEmpty(value)) + { + var pieces = value.Split(@".".ToCharArray(), 4); + Octet1.Text = pieces[0]; + Octet2.Text = pieces[1]; + Octet3.Text = pieces[2]; + Octet4.Text = pieces[3]; + } + else + { + Octet1.Text = ""; + Octet2.Text = ""; + Octet3.Text = ""; + Octet4.Text = ""; + } + } + } + + public IPTextBox() + { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); ApplyTheme(); - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + ThemeManager.getInstance().ThemeChanged += ApplyTheme; } private void ApplyTheme() - { - if (Themes.ThemeManager.getInstance().ThemingActive) - panel1.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); + { + if (!ThemeManager.getInstance().ActiveAndExtended) return; + panel1.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); } - protected override void Dispose( bool disposing ) - { - if( disposing ) - { - // ReSharper disable once UseNullPropagation - if(components != null) - components.Dispose(); - } - base.Dispose( disposing ); - } - #region Component Designer generated code - - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - private void InitializeComponent() - { + protected override void Dispose(bool disposing) + { + if (disposing) + { + // ReSharper disable once UseNullPropagation + if (components != null) + components.Dispose(); + } + + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); this.panel1 = new System.Windows.Forms.Panel(); this.Octet4 = new mRemoteNG.UI.Controls.Base.NGTextBox(); @@ -179,7 +181,8 @@ namespace mRemoteNG.UI.Controls // this.Octet1.BackColor = System.Drawing.SystemColors.Menu; this.Octet1.BorderStyle = System.Windows.Forms.BorderStyle.None; - this.Octet1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Octet1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Octet1.Location = new System.Drawing.Point(1, 1); this.Octet1.MaxLength = 3; this.Octet1.Name = "Octet1"; @@ -216,209 +219,204 @@ namespace mRemoteNG.UI.Controls // IPTextBox // this.Controls.Add(this.panel1); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "IPTextBox"; this.Size = new System.Drawing.Size(124, 18); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); + } - } - #endregion - - /** - * \ifnot hide_events + #endregion + + /* IsValid(string inString) * Checks that a string passed in resolves to an integer value between 0 and 255 - * \param inString The string passed in for testing - * \return True if the string is between 0 and 255 inclusively, false otherwise - * \endif - * */ - private static bool IsValid(string inString) - { - try - { - var theValue = int.Parse(inString); - if(theValue >=0 && theValue <= 255) - return true; + * param inString: The string passed in for testing + * return: True if the string is between 0 and 255 inclusively, false otherwise + * endif + */ + private static bool IsValid(string inString) + { + try + { + var theValue = int.Parse(inString); + if (theValue >= 0 && theValue <= 255) + return true; - MessageBox.Show(Language.strIPRange,Language.strOutOfRange); - return false; - } - catch - { - return false; - } - } + MessageBox.Show(Language.strIPRange, Language.strOutOfRange); + return false; + } + catch + { + return false; + } + } - /// \ifnot hide_events - /// Performs KeyPress analysis and handling to ensure a valid ip octet is - /// being entered in Box1. - /// \endif - private void Box1_KeyPress(object sender, KeyPressEventArgs e) - { - //Only Accept a '.', a numeral, or backspace - if(e.KeyChar.ToString() == "." || char.IsDigit(e.KeyChar) || e.KeyChar == 8) - { - //If the key pressed is a '.' - if(e.KeyChar.ToString() == ".") - { - //If the Text is a valid ip octet move to the next box - if(Octet1.Text != "" && Octet1.Text.Length != Octet1.SelectionLength) - { - if(IsValid(Octet1.Text)) - Octet2.Focus(); - else - Octet1.SelectAll(); - } - e.Handled = true; - } - - //If we are not overwriting the whole text - else if(Octet1.SelectionLength != Octet1.Text.Length) - { - //Check that the new Text value will be a valid - // ip octet then move on to next box - if (Octet1.Text.Length != 2) return; - if(!IsValid(Octet1.Text + e.KeyChar)) - { - Octet1.SelectAll(); - e.Handled = true; - } - else - { - Octet2.Focus(); - } - } - } - //Do nothing if the keypress is not numeral, backspace, or '.' - else - e.Handled = true; - } + /* Performs KeyPress analysis and handling to ensure a valid ip octet is + * being entered in Box1. + */ + private void Box1_KeyPress(object sender, KeyPressEventArgs e) + { + //Only Accept a '.', a numeral, or backspace + if (e.KeyChar.ToString() == "." || char.IsDigit(e.KeyChar) || e.KeyChar == 8) + { + //If the key pressed is a '.' + if (e.KeyChar.ToString() == ".") + { + //If the Text is a valid ip octet move to the next box + if (Octet1.Text != "" && Octet1.Text.Length != Octet1.SelectionLength) + { + if (IsValid(Octet1.Text)) + Octet2.Focus(); + else + Octet1.SelectAll(); + } - /// \ifnot hide_events - /// Performs KeyPress analysis and handling to ensure a valid ip octet is - /// being entered in Box2. - /// \endif - private void Box2_KeyPress(object sender, KeyPressEventArgs e) - { - //Similar to Box1_KeyPress but in special case for backspace moves cursor - //to the previouse box (Box1) - if(e.KeyChar.ToString() == "." || char.IsDigit(e.KeyChar) || e.KeyChar == 8) - { - if(e.KeyChar.ToString() == ".") - { - if(Octet2.Text != "" && Octet2.Text.Length != Octet2.SelectionLength) - { - if(IsValid(Octet1.Text)) - Octet3.Focus(); - else - Octet2.SelectAll(); - } - e.Handled = true; - } - else if(Octet2.SelectionLength != Octet2.Text.Length) - { - if (Octet2.Text.Length != 2) return; - if(!IsValid(Octet2.Text + e.KeyChar)) - { - Octet2.SelectAll(); - e.Handled = true; - } - else - { - Octet3.Focus(); - } - } - else if(Octet2.Text.Length == 0 && e.KeyChar == 8) - { - Octet1.Focus(); - Octet1.SelectionStart = Octet1.Text.Length; - } - } - else - e.Handled = true; - - } + e.Handled = true; + } - /// \ifnot hide_events - /// Performs KeyPress analysis and handling to ensure a valid ip octet is - /// being entered in Box3. - /// \endif - private void Box3_KeyPress(object sender, KeyPressEventArgs e) - { - //Identical to Box2_KeyPress except that previous box is Box2 and - //next box is Box3 - if(e.KeyChar.ToString() == "." || char.IsDigit(e.KeyChar) || e.KeyChar == 8) - { - if(e.KeyChar.ToString() == ".") - { - if(Octet3.Text != "" && Octet3.SelectionLength != Octet3.Text.Length) - { - if(IsValid(Octet1.Text)) - Octet4.Focus(); - else - Octet3.SelectAll(); - } - e.Handled = true; - } - else if(Octet3.SelectionLength != Octet3.Text.Length) - { - if (Octet3.Text.Length != 2) return; - if(!IsValid(Octet3.Text + e.KeyChar)) - { - Octet3.SelectAll(); - e.Handled = true; - } - else - { - Octet4.Focus(); - } - } - else if(Octet3.Text.Length == 0 && e.KeyChar == 8) - { - Octet2.Focus(); - Octet2.SelectionStart = Octet2.Text.Length; - } - } - else - e.Handled = true; - } + //If we are not overwriting the whole text + else if (Octet1.SelectionLength != Octet1.Text.Length) + { + //Check that the new Text value will be a valid + // ip octet then move on to next box + if (Octet1.Text.Length != 2) return; + if (!IsValid(Octet1.Text + e.KeyChar)) + { + Octet1.SelectAll(); + e.Handled = true; + } + else + { + Octet2.Focus(); + } + } + } + //Do nothing if the keypress is not numeral, backspace, or '.' + else + e.Handled = true; + } - /// \ifnot hide_events - /// Performs KeyPress analysis and handling to ensure a valid ip octet is - /// being entered in Box4. - /// \endif - private void Box4_KeyPress(object sender, KeyPressEventArgs e) - { - //Similar to Box3 but ignores the '.' character and does not advance - //to the next box. Also Box3 is previous box for backspace case. - if(char.IsDigit(e.KeyChar) || e.KeyChar == 8) - { - if(Octet4.SelectionLength != Octet4.Text.Length) - { - if (Octet4.Text.Length != 2) return; - if (IsValid(Octet4.Text + e.KeyChar)) return; - Octet4.SelectAll(); - e.Handled = true; - } - else if(Octet4.Text.Length == 0 && e.KeyChar == 8) - { - Octet3.Focus(); - Octet3.SelectionStart = Octet3.Text.Length; - } - } - else - e.Handled = true; - } + /* Performs KeyPress analysis and handling to ensure a valid ip octet is + * being entered in Box2. + */ + private void Box2_KeyPress(object sender, KeyPressEventArgs e) + { + //Similar to Box1_KeyPress but in special case for backspace moves cursor + //to the previous box (Box1) + if (e.KeyChar.ToString() == "." || char.IsDigit(e.KeyChar) || e.KeyChar == 8) + { + if (e.KeyChar.ToString() == ".") + { + if (Octet2.Text != "" && Octet2.Text.Length != Octet2.SelectionLength) + { + if (IsValid(Octet1.Text)) + Octet3.Focus(); + else + Octet2.SelectAll(); + } - /// \ifnot hide_events - /// Selects All text in a box for overwriting upon entering the box - /// \endif - private void Box_Enter(object sender, EventArgs e) - { - var tb = (TextBox) sender; - tb.SelectAll(); - } + e.Handled = true; + } + else if (Octet2.SelectionLength != Octet2.Text.Length) + { + if (Octet2.Text.Length != 2) return; + if (!IsValid(Octet2.Text + e.KeyChar)) + { + Octet2.SelectAll(); + e.Handled = true; + } + else + { + Octet3.Focus(); + } + } + else if (Octet2.Text.Length == 0 && e.KeyChar == 8) + { + Octet1.Focus(); + Octet1.SelectionStart = Octet1.Text.Length; + } + } + else + e.Handled = true; + } + /* Performs KeyPress analysis and handling to ensure a valid ip octet is + * being entered in Box3. + */ + private void Box3_KeyPress(object sender, KeyPressEventArgs e) + { + //Identical to Box2_KeyPress except that previous box is Box2 and + //next box is Box3 + if (e.KeyChar.ToString() == "." || char.IsDigit(e.KeyChar) || e.KeyChar == 8) + { + if (e.KeyChar.ToString() == ".") + { + if (Octet3.Text != "" && Octet3.SelectionLength != Octet3.Text.Length) + { + if (IsValid(Octet1.Text)) + Octet4.Focus(); + else + Octet3.SelectAll(); + } + + e.Handled = true; + } + else if (Octet3.SelectionLength != Octet3.Text.Length) + { + if (Octet3.Text.Length != 2) return; + if (!IsValid(Octet3.Text + e.KeyChar)) + { + Octet3.SelectAll(); + e.Handled = true; + } + else + { + Octet4.Focus(); + } + } + else if (Octet3.Text.Length == 0 && e.KeyChar == 8) + { + Octet2.Focus(); + Octet2.SelectionStart = Octet2.Text.Length; + } + } + else + e.Handled = true; + } + + /* Performs KeyPress analysis and handling to ensure a valid ip octet is + * being entered in Box4. + */ + private void Box4_KeyPress(object sender, KeyPressEventArgs e) + { + //Similar to Box3 but ignores the '.' character and does not advance + //to the next box. Also Box3 is previous box for backspace case. + if (char.IsDigit(e.KeyChar) || e.KeyChar == 8) + { + if (Octet4.SelectionLength != Octet4.Text.Length) + { + if (Octet4.Text.Length != 2) return; + if (IsValid(Octet4.Text + e.KeyChar)) return; + Octet4.SelectAll(); + e.Handled = true; + } + else if (Octet4.Text.Length == 0 && e.KeyChar == 8) + { + Octet3.Focus(); + Octet3.SelectionStart = Octet3.Text.Length; + } + } + else + e.Handled = true; + } + + // Selects All text in a box for overwriting upon entering the box + private void Box_Enter(object sender, EventArgs e) + { + var tb = (TextBox)sender; + tb.SelectAll(); + } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/MultiSshToolStrip.cs b/mRemoteV1/UI/Controls/MultiSshToolStrip.cs index 4771d1e4..96ade99c 100644 --- a/mRemoteV1/UI/Controls/MultiSshToolStrip.cs +++ b/mRemoteV1/UI/Controls/MultiSshToolStrip.cs @@ -5,64 +5,68 @@ using mRemoteNG.Tools; namespace mRemoteNG.UI.Controls { - public class MultiSshToolStrip : ToolStrip - { - private IContainer components; - private ToolStripLabel _lblMultiSsh; - private ToolStripTextBox _txtMultiSsh; + public class MultiSshToolStrip : ToolStrip + { + private IContainer components; + private ToolStripLabel _lblMultiSsh; + private ToolStripTextBox _txtMultiSsh; + // ReSharper disable once NotAccessedField.Local private MultiSSHController _multiSshController; - private readonly ThemeManager _themeManager; + private readonly ThemeManager _themeManager; public MultiSshToolStrip() - { - InitializeComponent(); - _themeManager = ThemeManager.getInstance(); - _themeManager.ThemeChanged += ApplyTheme; - ApplyTheme(); + { + InitializeComponent(); + _themeManager = ThemeManager.getInstance(); + _themeManager.ThemeChanged += ApplyTheme; + ApplyTheme(); _multiSshController = new MultiSSHController(_txtMultiSsh); - } + } - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - _lblMultiSsh = new ToolStripLabel(); - _txtMultiSsh = new ToolStripTextBox(); - SuspendLayout(); - // - // lblMultiSSH - // - _lblMultiSsh.Name = "_lblMultiSsh"; - _lblMultiSsh.Size = new System.Drawing.Size(77, 22); - _lblMultiSsh.Text = "Multi SSH:"; - // - // txtMultiSSH - // - _txtMultiSsh.Name = "_txtMultiSsh"; - _txtMultiSsh.Size = new System.Drawing.Size(new DisplayProperties().ScaleWidth(300), 25); - _txtMultiSsh.ToolTipText = "Press ENTER to send. Ctrl+C is sent immediately."; + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + _lblMultiSsh = new ToolStripLabel(); + _txtMultiSsh = new ToolStripTextBox(); + SuspendLayout(); + // + // lblMultiSSH + // + _lblMultiSsh.Name = "_lblMultiSsh"; + _lblMultiSsh.Size = new System.Drawing.Size(77, 22); + _lblMultiSsh.Text = "Multi SSH:"; + // + // txtMultiSSH + // + _txtMultiSsh.Name = "_txtMultiSsh"; + _txtMultiSsh.Size = new System.Drawing.Size(new DisplayProperties().ScaleWidth(300), 25); + _txtMultiSsh.ToolTipText = "Press ENTER to send. Ctrl+C is sent immediately."; - Items.AddRange(new ToolStripItem[] { - _lblMultiSsh, - _txtMultiSsh}); - ResumeLayout(true); - } + Items.AddRange(new ToolStripItem[] + { + _lblMultiSsh, + _txtMultiSsh + }); + ResumeLayout(true); + } - private void ApplyTheme() - { - if (!_themeManager.ThemingActive) return; - _txtMultiSsh.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); - _txtMultiSsh.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); - } + private void ApplyTheme() + { + if (!_themeManager.ActiveAndExtended) return; + _txtMultiSsh.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); + _txtMultiSsh.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); + } protected override void Dispose(bool disposing) - { - if (disposing) - { - components?.Dispose(); - } - base.Dispose(disposing); - } - } -} + { + if (disposing) + { + components?.Dispose(); + } + + base.Dispose(disposing); + } + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/NewPasswordWithVerification.cs b/mRemoteV1/UI/Controls/NewPasswordWithVerification.cs index 88382eee..109a92fd 100644 --- a/mRemoteV1/UI/Controls/NewPasswordWithVerification.cs +++ b/mRemoteV1/UI/Controls/NewPasswordWithVerification.cs @@ -13,11 +13,9 @@ namespace mRemoteNG.UI.Controls private char _passwordChar; - [Browsable(false)] - public SecureString SecureString { get; private set; } + [Browsable(false)] public SecureString SecureString { get; private set; } - [Browsable(false)] - public bool PasswordsMatch { get; private set; } + [Browsable(false)] public bool PasswordsMatch { get; private set; } [Browsable(true)] public char PasswordChar @@ -97,6 +95,7 @@ namespace mRemoteNG.UI.Controls SecureString = null; RaiseNotVerifiedEvent(); } + TogglePasswordMatchIndicator(PasswordsMatch); } diff --git a/mRemoteV1/UI/Controls/PageSequence/PageSequence.cs b/mRemoteV1/UI/Controls/PageSequence/PageSequence.cs index 2384518e..fe11dc3e 100644 --- a/mRemoteV1/UI/Controls/PageSequence/PageSequence.cs +++ b/mRemoteV1/UI/Controls/PageSequence/PageSequence.cs @@ -13,7 +13,8 @@ namespace mRemoteNG.UI.Controls.PageSequence public IEnumerable Pages => _pages; public int CurrentPageIndex { get; private set; } - public PageSequence(Control pageContainer, IEnumerable pages) : this(pageContainer, pages.ToArray()) + public PageSequence(Control pageContainer, IEnumerable pages) : this(pageContainer, + pages.ToArray()) { } @@ -59,6 +60,7 @@ namespace mRemoteNG.UI.Controls.PageSequence indexModifier++; break; } + var pageIndexToReplace = CurrentPageIndex + indexModifier; UnsubscribeFromPageEvents(_pages[pageIndexToReplace]); SubscribeToPageEvents(newPage); diff --git a/mRemoteV1/UI/Controls/PageSequence/SequencedControl.cs b/mRemoteV1/UI/Controls/PageSequence/SequencedControl.cs index f503f997..4e4f4681 100644 --- a/mRemoteV1/UI/Controls/PageSequence/SequencedControl.cs +++ b/mRemoteV1/UI/Controls/PageSequence/SequencedControl.cs @@ -1,5 +1,6 @@ using System; using System.Windows.Forms; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Controls.PageSequence { @@ -11,7 +12,7 @@ namespace mRemoteNG.UI.Controls.PageSequence public SequencedControl() { - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + ThemeManager.getInstance().ThemeChanged += ApplyTheme; InitializeComponent(); } @@ -22,9 +23,9 @@ namespace mRemoteNG.UI.Controls.PageSequence protected virtual void ApplyTheme() { - if (!Themes.ThemeManager.getInstance().ThemingActive) return; - BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + if (!ThemeManager.getInstance().ActiveAndExtended) return; + BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } protected virtual void RaisePreviousPageEvent() @@ -43,10 +44,10 @@ namespace mRemoteNG.UI.Controls.PageSequence // // SequencedControl // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "SequencedControl"; this.ResumeLayout(false); - } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/QuickConnectComboBox.cs b/mRemoteV1/UI/Controls/QuickConnectComboBox.cs index 2161a1e6..2773849b 100644 --- a/mRemoteV1/UI/Controls/QuickConnectComboBox.cs +++ b/mRemoteV1/UI/Controls/QuickConnectComboBox.cs @@ -7,235 +7,240 @@ using mRemoteNG.Connection.Protocol; namespace mRemoteNG.UI.Controls { - public class QuickConnectComboBox : ToolStripComboBox - { - private readonly ComboBox _comboBox; - private bool _ignoreEnter; - - public QuickConnectComboBox() - { - _comboBox = ComboBox; - if (_comboBox == null) return; - _comboBox.PreviewKeyDown += ComboBox_PreviewKeyDown; - _comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; - _comboBox.DrawItem += ComboBox_DrawItem; - _comboBox.DrawMode = DrawMode.OwnerDrawFixed; - - // This makes it so that _ignoreEnter works correctly before any items are added to the combo box - _comboBox.Items.Clear(); - } - - private void ComboBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) - { - if (e.KeyCode == Keys.Enter & _comboBox.DroppedDown) - { - _ignoreEnter = true; - } - } - - protected override void OnKeyDown(KeyEventArgs e) - { - base.OnKeyDown(e); - if (e.KeyCode == Keys.Enter) - { - // Only connect if Enter was not pressed while the combo box was dropped down - if (!_ignoreEnter) - { - OnConnectRequested(new ConnectRequestedEventArgs(_comboBox.Text)); - } - _ignoreEnter = false; - e.Handled = true; - } - else if (e.KeyCode == Keys.Delete & _comboBox.DroppedDown) - { - if (_comboBox.SelectedIndex != -1) - { - // 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; - _comboBox.DroppedDown = false; - _comboBox.Items.Remove(item); - _comboBox.SelectedIndex = -1; - if (_comboBox.Items.Count != 0) - { - _comboBox.DroppedDown = true; - } - } - e.Handled = true; - } - } - - private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) - { - if (!(_comboBox.SelectedItem is HistoryItem)) - { - return; - } - var historyItem = (HistoryItem) _comboBox.SelectedItem; - OnProtocolChanged(new ProtocolChangedEventArgs(historyItem.ConnectionInfo.Protocol)); - } - - private static void ComboBox_DrawItem(object sender, DrawItemEventArgs e) - { - var comboBox = sender as ComboBox; - if (comboBox == null) - { - return; - } - var drawItem = comboBox.Items[e.Index]; - - string drawString; - if (drawItem is HistoryItem) - { - var historyItem = (HistoryItem) drawItem; - drawString = historyItem.ToString(true); - } - else - { - drawString = drawItem.ToString(); - } - - e.DrawBackground(); - e.Graphics.DrawString(drawString, e.Font, new SolidBrush(e.ForeColor), new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)); - e.DrawFocusRectangle(); - } - - private struct HistoryItem : IEquatable - { - - public ConnectionInfo ConnectionInfo {get; set;} - - public bool Equals(HistoryItem other) - { - if (ConnectionInfo.Hostname != other.ConnectionInfo.Hostname) - { - return false; - } - if (ConnectionInfo.Port != other.ConnectionInfo.Port) - { - return false; - } + public class QuickConnectComboBox : ToolStripComboBox + { + private readonly ComboBox _comboBox; + private bool _ignoreEnter; - return ConnectionInfo.Protocol == other.ConnectionInfo.Protocol; - } - - public override string ToString() - { - return ToString(false); - } - - public string ToString(bool includeProtocol) - { - var port = string.Empty; - if (ConnectionInfo.Port != ConnectionInfo.GetDefaultPort()) - { - port = $":{ConnectionInfo.Port}"; - } + public QuickConnectComboBox() + { + _comboBox = ComboBox; + if (_comboBox == null) return; + _comboBox.PreviewKeyDown += ComboBox_PreviewKeyDown; + _comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; + _comboBox.DrawItem += ComboBox_DrawItem; + _comboBox.DrawMode = DrawMode.OwnerDrawFixed; + + // This makes it so that _ignoreEnter works correctly before any items are added to the combo box + _comboBox.Items.Clear(); + } + + private void ComboBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) + { + if (e.KeyCode == Keys.Enter & _comboBox.DroppedDown) + { + _ignoreEnter = true; + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.KeyCode == Keys.Enter) + { + // Only connect if Enter was not pressed while the combo box was dropped down + if (!_ignoreEnter) + { + OnConnectRequested(new ConnectRequestedEventArgs(_comboBox.Text)); + } + + _ignoreEnter = false; + e.Handled = true; + } + else if (e.KeyCode == Keys.Delete & _comboBox.DroppedDown) + { + if (_comboBox.SelectedIndex != -1) + { + // 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; + _comboBox.DroppedDown = false; + _comboBox.Items.Remove(item); + _comboBox.SelectedIndex = -1; + if (_comboBox.Items.Count != 0) + { + _comboBox.DroppedDown = true; + } + } + + e.Handled = true; + } + } + + private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) + { + if (!(_comboBox.SelectedItem is HistoryItem)) + { + return; + } + + var historyItem = (HistoryItem)_comboBox.SelectedItem; + OnProtocolChanged(new ProtocolChangedEventArgs(historyItem.ConnectionInfo.Protocol)); + } + + private static void ComboBox_DrawItem(object sender, DrawItemEventArgs e) + { + var comboBox = sender as ComboBox; + if (comboBox == null) + { + return; + } + + var drawItem = comboBox.Items[e.Index]; + + string drawString; + if (drawItem is HistoryItem) + { + var historyItem = (HistoryItem)drawItem; + drawString = historyItem.ToString(true); + } + else + { + drawString = drawItem.ToString(); + } + + e.DrawBackground(); + e.Graphics.DrawString(drawString, e.Font, new SolidBrush(e.ForeColor), + new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)); + e.DrawFocusRectangle(); + } + + private struct HistoryItem : IEquatable + { + public ConnectionInfo ConnectionInfo { get; set; } + + public bool Equals(HistoryItem other) + { + if (ConnectionInfo.Hostname != other.ConnectionInfo.Hostname) + { + return false; + } + + if (ConnectionInfo.Port != other.ConnectionInfo.Port) + { + return false; + } + + return ConnectionInfo.Protocol == other.ConnectionInfo.Protocol; + } + + public override string ToString() + { + return ToString(false); + } + + public string ToString(bool includeProtocol) + { + var port = string.Empty; + if (ConnectionInfo.Port != ConnectionInfo.GetDefaultPort()) + { + port = $":{ConnectionInfo.Port}"; + } + + return includeProtocol + ? $"{ConnectionInfo.Hostname}{port} ({ConnectionInfo.Protocol})" + : $"{ConnectionInfo.Hostname}{port}"; + } + } + + private bool Exists(HistoryItem searchItem) + { + foreach (var item in _comboBox.Items) + { + if (!(item is HistoryItem)) + { + continue; + } + + var historyItem = (HistoryItem)item; + if (historyItem.Equals(searchItem)) + { + return true; + } + } + + return false; + } + + public void Add(ConnectionInfo connectionInfo) + { + try + { + var historyItem = new HistoryItem {ConnectionInfo = connectionInfo}; + if (!Exists(historyItem)) + { + _comboBox.Items.Insert(0, historyItem); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strQuickConnectAddFailed, ex); + } + } - return includeProtocol ? $"{ConnectionInfo.Hostname}{port} ({ConnectionInfo.Protocol})" : $"{ConnectionInfo.Hostname}{port}"; - } - } - - private bool Exists(HistoryItem searchItem) - { - foreach (var item in _comboBox.Items) - { - if (!(item is HistoryItem)) - { - continue; - } - var historyItem = (HistoryItem) item; - if (historyItem.Equals(searchItem)) - { - return true; - } - } - return false; - } - - public void Add(ConnectionInfo connectionInfo) - { - try - { - var historyItem = new HistoryItem {ConnectionInfo = connectionInfo}; - if (!Exists(historyItem)) - { - _comboBox.Items.Insert(0, historyItem); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strQuickConnectAddFailed, ex); - } - } - #region Events - public class ConnectRequestedEventArgs : EventArgs - { - - public ConnectRequestedEventArgs(string connectionString) - { - ConnectionString = connectionString; - } - public string ConnectionString { get; } - } - - public delegate void ConnectRequestedEventHandler(object sender, ConnectRequestedEventArgs e); - private ConnectRequestedEventHandler ConnectRequestedEvent; - - public event ConnectRequestedEventHandler ConnectRequested - { - add - { - ConnectRequestedEvent = (ConnectRequestedEventHandler) Delegate.Combine(ConnectRequestedEvent, value); - } - remove - { - ConnectRequestedEvent = (ConnectRequestedEventHandler) Delegate.Remove(ConnectRequestedEvent, value); - } - } + public class ConnectRequestedEventArgs : EventArgs + { + public ConnectRequestedEventArgs(string connectionString) + { + ConnectionString = connectionString; + } + + public string ConnectionString { get; } + } + + public delegate void ConnectRequestedEventHandler(object sender, ConnectRequestedEventArgs e); + + private ConnectRequestedEventHandler ConnectRequestedEvent; + + public event ConnectRequestedEventHandler ConnectRequested + { + add + { + ConnectRequestedEvent = (ConnectRequestedEventHandler)Delegate.Combine(ConnectRequestedEvent, value); + } + remove + { + ConnectRequestedEvent = (ConnectRequestedEventHandler)Delegate.Remove(ConnectRequestedEvent, value); + } + } - private void OnConnectRequested(ConnectRequestedEventArgs e) - { + private void OnConnectRequested(ConnectRequestedEventArgs e) + { // TODO: Any reason to not jsut pass "e"? ConnectRequestedEvent?.Invoke(this, new ConnectRequestedEventArgs(e.ConnectionString)); - } - - public class ProtocolChangedEventArgs : EventArgs - { - - public ProtocolChangedEventArgs(ProtocolType protocol) - { - Protocol = protocol; - } + } - public ProtocolType Protocol { get; } - } - - public delegate void ProtocolChangedEventHandler(object sender, ProtocolChangedEventArgs e); - private ProtocolChangedEventHandler ProtocolChangedEvent; - - public event ProtocolChangedEventHandler ProtocolChanged - { - add - { - ProtocolChangedEvent = (ProtocolChangedEventHandler) Delegate.Combine(ProtocolChangedEvent, value); - } - remove - { - ProtocolChangedEvent = (ProtocolChangedEventHandler) Delegate.Remove(ProtocolChangedEvent, value); - } - } + public class ProtocolChangedEventArgs : EventArgs + { + public ProtocolChangedEventArgs(ProtocolType protocol) + { + Protocol = protocol; + } + + public ProtocolType Protocol { get; } + } + + public delegate void ProtocolChangedEventHandler(object sender, ProtocolChangedEventArgs e); + + private ProtocolChangedEventHandler ProtocolChangedEvent; + + public event ProtocolChangedEventHandler ProtocolChanged + { + add { ProtocolChangedEvent = (ProtocolChangedEventHandler)Delegate.Combine(ProtocolChangedEvent, value); } + remove { ProtocolChangedEvent = (ProtocolChangedEventHandler)Delegate.Remove(ProtocolChangedEvent, value); } + } - private void OnProtocolChanged(ProtocolChangedEventArgs e) - { + private void OnProtocolChanged(ProtocolChangedEventArgs e) + { // TODO: Any reason to not jsut pass "e"? - ProtocolChangedEvent?.Invoke(this, new ProtocolChangedEventArgs(e.Protocol)); - } + ProtocolChangedEvent?.Invoke(this, new ProtocolChangedEventArgs(e.Protocol)); + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/QuickConnectToolStrip.cs b/mRemoteV1/UI/Controls/QuickConnectToolStrip.cs index dbef64c8..1fb29993 100644 --- a/mRemoteV1/UI/Controls/QuickConnectToolStrip.cs +++ b/mRemoteV1/UI/Controls/QuickConnectToolStrip.cs @@ -22,13 +22,13 @@ namespace mRemoteNG.UI.Controls private QuickConnectComboBox _cmbQuickConnect; private ContextMenuStrip _mnuConnections; private IConnectionInitiator _connectionInitiator = new ConnectionInitiator(Runtime.CredentialService); - private ThemeManager _themeManager; + private readonly ThemeManager _themeManager; private WeifenLuo.WinFormsUI.Docking.VisualStudioToolStripExtender vsToolStripExtender; private readonly DisplayProperties _display; public IConnectionInitiator ConnectionInitiator { - get { return _connectionInitiator; } + get => _connectionInitiator; set { if (value == null) @@ -82,11 +82,13 @@ namespace mRemoteNG.UI.Controls // tsQuickConnect // Dock = DockStyle.None; - Items.AddRange(new ToolStripItem[] { - _lblQuickConnect, - _cmbQuickConnect, - _btnQuickConnect, - _btnConnections}); + Items.AddRange(new ToolStripItem[] + { + _lblQuickConnect, + _cmbQuickConnect, + _btnQuickConnect, + _btnConnections + }); Location = new Point(3, 24); Name = "tsQuickConnect"; Size = new Size(_display.ScaleWidth(387), 25); @@ -136,13 +138,18 @@ namespace mRemoteNG.UI.Controls private void ApplyTheme() { if (!_themeManager.ThemingActive) return; - vsToolStripExtender.SetStyle(_mnuQuickConnectProtocol, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - vsToolStripExtender.SetStyle(_mnuConnections, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(_mnuQuickConnectProtocol, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(_mnuConnections, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + + if (!_themeManager.ActiveAndExtended) return; _cmbQuickConnect.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); _cmbQuickConnect.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); } #region Quick Connect + private void PopulateQuickConnectProtocolMenu() { try @@ -157,6 +164,7 @@ namespace mRemoteNG.UI.Controls menuItem.Checked = true; _btnQuickConnect.Text = Settings.Default.QuickConnectProtocol; } + _mnuQuickConnectProtocol.Items.Add(menuItem); } } @@ -180,12 +188,16 @@ namespace mRemoteNG.UI.Controls { try { - var connectionInfo = Runtime.ConnectionsService.CreateQuickConnect(_cmbQuickConnect.Text.Trim(), Converter.StringToProtocol(Settings.Default.QuickConnectProtocol)); + var connectionInfo = Runtime.ConnectionsService.CreateQuickConnect(_cmbQuickConnect.Text.Trim(), + Converter.StringToProtocol(Settings + .Default + .QuickConnectProtocol)); if (connectionInfo == null) { _cmbQuickConnect.Focus(); return; } + _cmbQuickConnect.Add(connectionInfo); ConnectionInitiator.OpenConnection(connectionInfo, ConnectionInfo.Force.DoNotJump); } @@ -203,7 +215,10 @@ namespace mRemoteNG.UI.Controls private void btnQuickConnect_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { SetQuickConnectProtocol(e.ClickedItem.Text); - btnQuickConnect_ButtonClick(this, e); + if (string.IsNullOrEmpty(_cmbQuickConnect.Text)) + _cmbQuickConnect.Focus(); + else + btnQuickConnect_ButtonClick(this, e); } private void SetQuickConnectProtocol(string protocol) @@ -215,9 +230,11 @@ namespace mRemoteNG.UI.Controls menuItem.Checked = menuItem.Text.Equals(protocol); } } + #endregion #region Connections DropDown + private void btnConnections_DropDownOpening(object sender, EventArgs e) { _btnConnections.DropDownItems.Clear(); @@ -227,33 +244,35 @@ namespace mRemoteNG.UI.Controls }; // ReSharper disable once CoVariantArrayConversion - ToolStripItem[] rootMenuItems = menuItemsConverter.CreateToolStripDropDownItems(Runtime.ConnectionsService.ConnectionTreeModel).ToArray(); + ToolStripItem[] rootMenuItems = menuItemsConverter + .CreateToolStripDropDownItems(Runtime.ConnectionsService + .ConnectionTreeModel).ToArray(); _btnConnections.DropDownItems.AddRange(rootMenuItems); - } private void ConnectionsMenuItem_MouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; - var menuItem = (ToolStripMenuItem) sender; + var menuItem = (ToolStripMenuItem)sender; - // While we can connect to a whole folder at once, it is - // probably not the expected behavior when navigating through - // a nested menu. Just return - var containerInfo = menuItem.Tag as ContainerInfo; - if (containerInfo != null) - return; - - var connectionInfo = menuItem.Tag as ConnectionInfo; - if (connectionInfo != null) + switch (menuItem.Tag) { - ConnectionInitiator.OpenConnection(connectionInfo); + // While we can connect to a whole folder at once, it is + // probably not the expected behavior when navigating through + // a nested menu. Just return + case ContainerInfo _: + return; + case ConnectionInfo connectionInfo: + ConnectionInitiator.OpenConnection(connectionInfo); + break; } } + #endregion // CodeAyalysis doesn't like null propagation - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "components")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", + MessageId = "components")] protected override void Dispose(bool disposing) { try diff --git a/mRemoteV1/UI/Controls/SecureTextBox.cs b/mRemoteV1/UI/Controls/SecureTextBox.cs index d07e2ef4..7026c931 100644 --- a/mRemoteV1/UI/Controls/SecureTextBox.cs +++ b/mRemoteV1/UI/Controls/SecureTextBox.cs @@ -18,7 +18,5 @@ namespace mRemoteNG.UI.Controls { SecString = Text.ConvertToSecureString(); } - - } } \ No newline at end of file diff --git a/mRemoteV1/UI/Controls/StatusImageList.cs b/mRemoteV1/UI/Controls/StatusImageList.cs index 6211d581..419b8e63 100644 --- a/mRemoteV1/UI/Controls/StatusImageList.cs +++ b/mRemoteV1/UI/Controls/StatusImageList.cs @@ -21,8 +21,8 @@ namespace mRemoteNG.UI.Controls { ColorDepth = ColorDepth.Depth32Bit, ImageSize = new Size( - (int)Math.Round(16 * display.ResolutionScalingFactor.Width), - (int)Math.Round(16 * display.ResolutionScalingFactor.Height)), + (int)Math.Round(16 * display.ResolutionScalingFactor.Width), + (int)Math.Round(16 * display.ResolutionScalingFactor.Height)), TransparentColor = Color.Transparent }; @@ -48,7 +48,7 @@ namespace mRemoteNG.UI.Controls if (connectionInfo is RootPuttySessionsNodeInfo) return "PuttySessions"; if (connectionInfo is RootNodeInfo) return "Root"; if (connectionInfo is ContainerInfo) return "Folder"; - + return GetConnectionIcon(connectionInfo); } @@ -77,7 +77,8 @@ namespace mRemoteNG.UI.Controls } ImageList.Images.Add(BuildConnectionIconName(connection.Icon, false), image); - ImageList.Images.Add(BuildConnectionIconName(connection.Icon, true), Overlay(image, Resources.ConnectedOverlay)); + ImageList.Images.Add(BuildConnectionIconName(connection.Icon, true), + Overlay(image, Resources.ConnectedOverlay)); return name; } @@ -88,6 +89,7 @@ namespace mRemoteNG.UI.Controls { gr.DrawImage(foreground, new Rectangle(0, 0, foreground.Width, foreground.Height)); } + return result; } @@ -101,7 +103,9 @@ namespace mRemoteNG.UI.Controls } 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/mRemoteV1/UI/Controls/TextBoxExtensions.cs b/mRemoteV1/UI/Controls/TextBoxExtensions.cs index 8c951b49..81bb0ddd 100644 --- a/mRemoteV1/UI/Controls/TextBoxExtensions.cs +++ b/mRemoteV1/UI/Controls/TextBoxExtensions.cs @@ -10,14 +10,16 @@ namespace mRemoteNG.UI.Controls 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) Convert.ToInt32(showCueWhenFocused), cueText); + var 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, new IntPtr(cueBannerText.Capacity)); + var result = NativeMethods.SendMessage(textBox.Handle, NativeMethods.EM_GETCUEBANNER, cueBannerText, + new IntPtr(cueBannerText.Capacity)); return result.ToInt64() != 0 ? cueBannerText.ToString() : null; } } diff --git a/mRemoteV1/UI/Controls/ToolStripSplitButton.cs b/mRemoteV1/UI/Controls/ToolStripSplitButton.cs index ed709085..1386136f 100644 --- a/mRemoteV1/UI/Controls/ToolStripSplitButton.cs +++ b/mRemoteV1/UI/Controls/ToolStripSplitButton.cs @@ -3,56 +3,57 @@ using System.Windows.Forms; namespace mRemoteNG.UI.Controls { - public class ToolStripSplitButton : System.Windows.Forms.ToolStripSplitButton - { + public class ToolStripSplitButton : System.Windows.Forms.ToolStripSplitButton + { public new ToolStripDropDown DropDown - { - get { return base.DropDown; } - set - { - if (base.DropDown != value) - { - base.DropDown = value; - base.DropDown.Closing += DropDown_Closing; - } - } - } - - private void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e) - { - if (e.CloseReason != ToolStripDropDownCloseReason.AppClicked) - { - return; - } - - Rectangle dropDownButtonBoundsClient = DropDownButtonBounds; // Relative to the ToolStripSplitButton - dropDownButtonBoundsClient.Offset(Bounds.Location); // Relative to the parent of the ToolStripSplitButton - Rectangle dropDownButtonBoundsScreen = GetCurrentParent().RectangleToScreen(dropDownButtonBoundsClient); // Relative to the screen - - if (dropDownButtonBoundsScreen.Contains(Control.MousePosition)) - { - e.Cancel = true; - } - } - - protected override void OnMouseDown(MouseEventArgs e) - { - _dropDownVisibleOnMouseDown = DropDown.Visible; - base.OnMouseDown(e); - } - - protected override void OnMouseUp(MouseEventArgs e) - { - if (_dropDownVisibleOnMouseDown) - { - DropDown.Close(); - } - else - { - base.OnMouseUp(e); - } - } - - private bool _dropDownVisibleOnMouseDown; - } -} + { + get { return base.DropDown; } + set + { + if (base.DropDown != value) + { + base.DropDown = value; + base.DropDown.Closing += DropDown_Closing; + } + } + } + + private void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e) + { + if (e.CloseReason != ToolStripDropDownCloseReason.AppClicked) + { + return; + } + + Rectangle dropDownButtonBoundsClient = DropDownButtonBounds; // Relative to the ToolStripSplitButton + dropDownButtonBoundsClient.Offset(Bounds.Location); // Relative to the parent of the ToolStripSplitButton + Rectangle dropDownButtonBoundsScreen = + GetCurrentParent().RectangleToScreen(dropDownButtonBoundsClient); // Relative to the screen + + if (dropDownButtonBoundsScreen.Contains(Control.MousePosition)) + { + e.Cancel = true; + } + } + + protected override void OnMouseDown(MouseEventArgs e) + { + _dropDownVisibleOnMouseDown = DropDown.Visible; + base.OnMouseDown(e); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + if (_dropDownVisibleOnMouseDown) + { + DropDown.Close(); + } + else + { + base.OnMouseUp(e); + } + } + + private bool _dropDownVisibleOnMouseDown; + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/DialogFactory.cs b/mRemoteV1/UI/DialogFactory.cs index 6ffbf1ad..f5eae4d8 100644 --- a/mRemoteV1/UI/DialogFactory.cs +++ b/mRemoteV1/UI/DialogFactory.cs @@ -28,7 +28,9 @@ namespace mRemoteNG.UI /// /// /// - public static void ShowLoadConnectionsFailedDialog(string connectionFileName, string messageText, bool showCancelButton) + public static void ShowLoadConnectionsFailedDialog(string connectionFileName, + string messageText, + bool showCancelButton) { var commandButtons = new List { @@ -46,13 +48,13 @@ namespace mRemoteNG.UI try { CTaskDialog.ShowTaskDialogBox( - GeneralAppInfo.ProductName, - messageText, - "", "", "", "", "", - string.Join(" | ", commandButtons), - ETaskDialogButtons.None, - ESysIcons.Question, - ESysIcons.Question); + GeneralAppInfo.ProductName, + messageText, + "", "", "", "", "", + string.Join(" | ", commandButtons), + ETaskDialogButtons.None, + ESysIcons.Question, + ESysIcons.Question); switch (CTaskDialog.CommandButtonResult) { @@ -78,9 +80,11 @@ namespace mRemoteNG.UI catch (Exception exception) { Runtime.MessageCollector.AddExceptionMessage( - string.Format(Language.strConnectionsFileCouldNotBeLoadedNew, connectionFileName), - exception, - MessageClass.WarningMsg); + string + .Format(Language.strConnectionsFileCouldNotBeLoadedNew, + connectionFileName), + exception, + MessageClass.WarningMsg); } } } diff --git a/mRemoteV1/UI/DisplayProperties.cs b/mRemoteV1/UI/DisplayProperties.cs index dae5ee06..2cf4ff15 100644 --- a/mRemoteV1/UI/DisplayProperties.cs +++ b/mRemoteV1/UI/DisplayProperties.cs @@ -17,7 +17,7 @@ namespace mRemoteNG.UI /// Creates a new instance with the default /// of type /// - public DisplayProperties() + public DisplayProperties() : this(new GdiPlusGraphicsProvider()) { } @@ -116,4 +116,4 @@ namespace mRemoteNG.UI return (int)Math.Round(value * scalingValue); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/FontOverrider.cs b/mRemoteV1/UI/FontOverrider.cs index 693cda27..a1267c69 100644 --- a/mRemoteV1/UI/FontOverrider.cs +++ b/mRemoteV1/UI/FontOverrider.cs @@ -11,7 +11,8 @@ namespace mRemoteNG.UI foreach (Control tempLoopVarCtlChild in ctlParent.Controls) { var ctlChild = tempLoopVarCtlChild; - ctlChild.Font = new Font(SystemFonts.MessageBoxFont.Name, ctlChild.Font.Size, ctlChild.Font.Style, ctlChild.Font.Unit, ctlChild.Font.GdiCharSet); + ctlChild.Font = new Font(SystemFonts.MessageBoxFont.Name, ctlChild.Font.Size, ctlChild.Font.Style, + ctlChild.Font.Unit, ctlChild.Font.GdiCharSet); if (ctlChild.Controls.Count > 0) { FontOverride(ctlChild); diff --git a/mRemoteV1/UI/FormExtensions.cs b/mRemoteV1/UI/FormExtensions.cs index cf60601a..a3fcb6c5 100644 --- a/mRemoteV1/UI/FormExtensions.cs +++ b/mRemoteV1/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; + var targetFormCenterX = formToCenterOn.Location.X + formToCenterOn.Width / 2; + var targetFormCenterY = formToCenterOn.Location.Y + formToCenterOn.Height / 2; - var thisFormCenterX = formToMove.Location.X + formToMove.Width/2; - var thisFormCenterY = formToMove.Location.Y + formToMove.Height/2; + var thisFormCenterX = formToMove.Location.X + formToMove.Width / 2; + var thisFormCenterY = formToMove.Location.Y + formToMove.Height / 2; formToMove.Location = new Point(targetFormCenterX - thisFormCenterX, targetFormCenterY - thisFormCenterY); } diff --git a/mRemoteV1/UI/Forms/ExportForm.cs b/mRemoteV1/UI/Forms/ExportForm.cs index d4396d8c..b5198609 100644 --- a/mRemoteV1/UI/Forms/ExportForm.cs +++ b/mRemoteV1/UI/Forms/ExportForm.cs @@ -14,97 +14,100 @@ namespace mRemoteNG.UI.Forms private ThemeManager _themeManager; #region Public Properties + public string FileName - { - get => txtFileName.Text; + { + get => txtFileName.Text; set => txtFileName.Text = value; } - + public SaveFormat SaveFormat - { - get - { - var exportFormat = cboFileFormat.SelectedItem as ExportFormat; - return exportFormat?.Format ?? SaveFormat.mRXML; - } + { + get + { + var exportFormat = cboFileFormat.SelectedItem as ExportFormat; + return exportFormat?.Format ?? SaveFormat.mRXML; + } set - { - foreach (var item in cboFileFormat.Items) - { - var exportFormat = item as ExportFormat; - if (exportFormat?.Format != value) continue; - cboFileFormat.SelectedItem = item; - break; - } - } - } - + { + foreach (var item in cboFileFormat.Items) + { + var exportFormat = item as ExportFormat; + if (exportFormat?.Format != value) continue; + cboFileFormat.SelectedItem = item; + break; + } + } + } + public ExportScope Scope - { - get - { - if (rdoExportSelectedFolder.Checked) - return ExportScope.SelectedFolder; - if (rdoExportSelectedConnection.Checked) - return ExportScope.SelectedConnection; - return ExportScope.Everything; - } + { + get + { + if (rdoExportSelectedFolder.Checked) + return ExportScope.SelectedFolder; + if (rdoExportSelectedConnection.Checked) + return ExportScope.SelectedConnection; + return ExportScope.Everything; + } set - { - switch (value) - { - case ExportScope.Everything: - rdoExportEverything.Checked = true; - break; - case ExportScope.SelectedFolder: - rdoExportSelectedFolder.Checked = true; - break; - case ExportScope.SelectedConnection: - rdoExportSelectedConnection.Checked = true; - break; - } - } - } - - private ContainerInfo _selectedFolder; + { + switch (value) + { + case ExportScope.Everything: + rdoExportEverything.Checked = true; + break; + case ExportScope.SelectedFolder: + rdoExportSelectedFolder.Checked = true; + break; + case ExportScope.SelectedConnection: + rdoExportSelectedConnection.Checked = true; + break; + } + } + } + + private ContainerInfo _selectedFolder; + public ContainerInfo SelectedFolder - { - get => _selectedFolder; + { + get => _selectedFolder; set - { - _selectedFolder = value; - lblSelectedFolder.Text = value?.Name; - rdoExportSelectedFolder.Enabled = value != null; - } - } - - private ConnectionInfo _selectedConnection; + { + _selectedFolder = value; + lblSelectedFolder.Text = value?.Name; + rdoExportSelectedFolder.Enabled = value != null; + } + } + + private ConnectionInfo _selectedConnection; + public ConnectionInfo SelectedConnection - { - get => _selectedConnection; + { + get => _selectedConnection; set - { - _selectedConnection = value; - lblSelectedConnection.Text = value?.Name; - rdoExportSelectedConnection.Enabled = value != null; - } - } - + { + _selectedConnection = value; + lblSelectedConnection.Text = value?.Name; + rdoExportSelectedConnection.Enabled = value != null; + } + } + public bool IncludeUsername - { - get => chkUsername.Checked; + { + get => chkUsername.Checked; set => chkUsername.Checked = value; } - + public bool IncludePassword - { - get => chkPassword.Checked; + { + get => chkPassword.Checked; set => chkPassword.Checked = value; } - + public bool IncludeDomain - { - get => chkDomain.Checked; + { + get => chkDomain.Checked; set => chkDomain.Checked = value; } @@ -115,63 +118,68 @@ namespace mRemoteNG.UI.Forms } public bool IncludeInheritance - { - get => chkInheritance.Checked; + { + get => chkInheritance.Checked; set => chkInheritance.Checked = value; } + #endregion - + #region Constructors - public ExportForm() - { - InitializeComponent(); + + public ExportForm() + { + InitializeComponent(); FontOverrider.FontOverride(this); - SelectedFolder = null; - SelectedConnection = null; - btnOK.Enabled = false; - } + SelectedFolder = null; + SelectedConnection = null; + btnOK.Enabled = false; + } + #endregion - + #region Private Methods + #region Event Handlers + private void ExportForm_Load(object sender, EventArgs e) - { - cboFileFormat.Items.Clear(); + { + cboFileFormat.Items.Clear(); cboFileFormat.Items.Add(new ExportFormat(SaveFormat.mRXML)); cboFileFormat.Items.Add(new ExportFormat(SaveFormat.mRCSV)); - cboFileFormat.SelectedIndex = 0; + cboFileFormat.SelectedIndex = 0; ApplyTheme(); ThemeManager.getInstance().ThemeChanged += ApplyTheme; ApplyLanguage(); - } + } private void txtFileName_TextChanged(object sender, EventArgs e) - { - btnOK.Enabled = !string.IsNullOrEmpty(txtFileName.Text); - } + { + btnOK.Enabled = !string.IsNullOrEmpty(txtFileName.Text); + } private void btnBrowse_Click(object sender, EventArgs e) - { - using (var saveFileDialog = new SaveFileDialog()) - { - saveFileDialog.CheckPathExists = true; - saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); - saveFileDialog.OverwritePrompt = true; - - var fileTypes = new List(); - fileTypes.AddRange(new[] {Language.strFiltermRemoteXML, "*.xml"}); - fileTypes.AddRange(new[] {Language.strFiltermRemoteCSV, "*.csv"}); - fileTypes.AddRange(new[] {Language.strFilterAll, "*.*"}); - - saveFileDialog.Filter = string.Join("|", fileTypes.ToArray()); - SelectFileTypeBasedOnSaveFormat(saveFileDialog); + { + using (var saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.CheckPathExists = true; + saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); + saveFileDialog.OverwritePrompt = true; + + var fileTypes = new List(); + fileTypes.AddRange(new[] {Language.strFiltermRemoteXML, "*.xml"}); + fileTypes.AddRange(new[] {Language.strFiltermRemoteCSV, "*.csv"}); + fileTypes.AddRange(new[] {Language.strFilterAll, "*.*"}); + + saveFileDialog.Filter = string.Join("|", fileTypes.ToArray()); + SelectFileTypeBasedOnSaveFormat(saveFileDialog); if (saveFileDialog.ShowDialog(this) != DialogResult.OK) - return; - - txtFileName.Text = saveFileDialog.FileName; + return; + + txtFileName.Text = saveFileDialog.FileName; } - } + } private void SelectFileTypeBasedOnSaveFormat(FileDialog saveFileDialog) { @@ -179,14 +187,14 @@ namespace mRemoteNG.UI.Forms } private void btnOK_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.OK; - } + { + DialogResult = DialogResult.OK; + } private void btnCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - } + { + DialogResult = DialogResult.Cancel; + } private void cboFileformat_SelectedIndexChanged(object sender, EventArgs e) { @@ -206,85 +214,95 @@ namespace mRemoteNG.UI.Forms // chkAssignedCredential.Enabled = false; //} } + #endregion - + private void ApplyTheme() { _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } private void ApplyLanguage() - { - Text = Language.strExport; - - grpFile.Text = Language.strExportFile; - lblFileName.Text = Language.strLabelFilename; - btnBrowse.Text = Language.strButtonBrowse; - lblFileFormat.Text = Language.strFileFormatLabel; - - grpItems.Text = Language.strExportItems; - rdoExportEverything.Text = Language.strExportEverything; - rdoExportSelectedFolder.Text = Language.strExportSelectedFolder; - rdoExportSelectedConnection.Text = Language.strExportSelectedConnection; - - grpProperties.Text = Language.strExportProperties; - chkUsername.Text = Language.strCheckboxUsername; - chkPassword.Text = Language.strCheckboxPassword; - chkDomain.Text = Language.strCheckboxDomain; - chkAssignedCredential.Text = Language.strAssignedCredential; - chkInheritance.Text = Language.strCheckboxInheritance; - lblUncheckProperties.Text = Language.strUncheckProperties; - - btnOK.Text = Language.strButtonOK; - btnCancel.Text = Language.strButtonCancel; - } + { + Text = Language.strExport; + + grpFile.Text = Language.strExportFile; + lblFileName.Text = Language.strLabelFilename; + btnBrowse.Text = Language.strButtonBrowse; + lblFileFormat.Text = Language.strFileFormatLabel; + + grpItems.Text = Language.strExportItems; + rdoExportEverything.Text = Language.strExportEverything; + rdoExportSelectedFolder.Text = Language.strExportSelectedFolder; + rdoExportSelectedConnection.Text = Language.strExportSelectedConnection; + + grpProperties.Text = Language.strExportProperties; + chkUsername.Text = Language.strCheckboxUsername; + chkPassword.Text = Language.strCheckboxPassword; + chkDomain.Text = Language.strCheckboxDomain; + chkAssignedCredential.Text = Language.strAssignedCredential; + chkInheritance.Text = Language.strCheckboxInheritance; + lblUncheckProperties.Text = Language.strUncheckProperties; + + btnOK.Text = Language.strButtonOK; + btnCancel.Text = Language.strButtonCancel; + } + #endregion - + #region Public Enumerations - public enum ExportScope - { - Everything, - SelectedFolder, - SelectedConnection - } + + public enum ExportScope + { + Everything, + SelectedFolder, + SelectedConnection + } + #endregion - + #region Private Classes - [ImmutableObject(true)] + + [ImmutableObject(true)] private class ExportFormat - { + { #region Public Properties - public SaveFormat Format { get; } + public SaveFormat Format { get; } + + #endregion - #endregion - #region Constructors - public ExportFormat(SaveFormat format) - { - Format = format; - } + + public ExportFormat(SaveFormat format) + { + Format = format; + } + #endregion - + #region Public Methods - public override string ToString() - { - switch (Format) - { - case SaveFormat.mRXML: - return Language.strMremoteNgXml; + + public override string ToString() + { + switch (Format) + { + case SaveFormat.mRXML: + return Language.strMremoteNgXml; case SaveFormat.mRCSV: - return Language.strMremoteNgCsv; - default: - return Format.ToString(); - } - } + return Language.strMremoteNgCsv; + default: + return Format.ToString(); + } + } + #endregion - } + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/FrmSplashScreen.cs b/mRemoteV1/UI/Forms/FrmSplashScreen.cs index bf28eaca..f8882e8d 100644 --- a/mRemoteV1/UI/Forms/FrmSplashScreen.cs +++ b/mRemoteV1/UI/Forms/FrmSplashScreen.cs @@ -26,4 +26,4 @@ namespace mRemoteNG.UI.Forms } } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/FullscreenHandler.cs b/mRemoteV1/UI/Forms/FullscreenHandler.cs index b601a8e2..55086a11 100644 --- a/mRemoteV1/UI/Forms/FullscreenHandler.cs +++ b/mRemoteV1/UI/Forms/FullscreenHandler.cs @@ -41,8 +41,10 @@ namespace mRemoteNG.UI.Forms { _handledForm.WindowState = FormWindowState.Normal; } + _handledForm.WindowState = FormWindowState.Maximized; } + private void ExitFullscreen() { _handledForm.FormBorderStyle = _savedBorderStyle; diff --git a/mRemoteV1/UI/Forms/Input/FrmInputBox.Designer.cs b/mRemoteV1/UI/Forms/Input/FrmInputBox.Designer.cs index daf744f8..46136546 100644 --- a/mRemoteV1/UI/Forms/Input/FrmInputBox.Designer.cs +++ b/mRemoteV1/UI/Forms/Input/FrmInputBox.Designer.cs @@ -1,6 +1,6 @@ namespace mRemoteNG.UI.Forms.Input { - partial class FrmInputBox + sealed partial class FrmInputBox { /// /// Required designer variable. diff --git a/mRemoteV1/UI/Forms/Input/FrmInputBox.cs b/mRemoteV1/UI/Forms/Input/FrmInputBox.cs index a0f1c6c6..e55b51e5 100644 --- a/mRemoteV1/UI/Forms/Input/FrmInputBox.cs +++ b/mRemoteV1/UI/Forms/Input/FrmInputBox.cs @@ -3,12 +3,11 @@ using mRemoteNG.Themes; namespace mRemoteNG.UI.Forms.Input { - public partial class FrmInputBox : Form + public sealed partial class FrmInputBox : Form { - private readonly DisplayProperties _display = new DisplayProperties(); internal string returnValue; - public FrmInputBox(string title, string promptText, ref string value) + public FrmInputBox(string title, string promptText, string value) { InitializeComponent(); @@ -27,9 +26,10 @@ namespace mRemoteNG.UI.Forms.Input private void ApplyTheme() { - var activeTheme = ThemeManager.getInstance().ActiveTheme; - BackColor = activeTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = activeTheme.ExtendedPalette.getColor("Dialog_Foreground"); + var _themeManager = ThemeManager.getInstance(); + if (!_themeManager.ActiveAndExtended) return; + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } private void buttonOk_Click(object sender, System.EventArgs e) @@ -45,4 +45,4 @@ namespace mRemoteNG.UI.Forms.Input Close(); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/OptionsPages/AdvancedPage.cs b/mRemoteV1/UI/Forms/OptionsPages/AdvancedPage.cs index 466a8378..2d590885 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/AdvancedPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/AdvancedPage.cs @@ -1,5 +1,4 @@ using System; -using System.Drawing; using System.IO; using System.Windows.Forms; using mRemoteNG.App; @@ -23,6 +22,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages } #region Public Methods + public override string PageName { get => Language.strTabAdvanced; @@ -47,8 +47,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); - chkAutomaticallyGetSessionInfo.Checked = Settings.Default.AutomaticallyGetSessionInfo; chkAutomaticReconnect.Checked = Settings.Default.ReconnectOnDisconnect; chkLoadBalanceInfoUseUtf8.Checked = Settings.Default.RdpLoadBalanceInfoUseUtf8; @@ -73,21 +71,23 @@ namespace mRemoteNG.UI.Forms.OptionsPages puttyPathChanged = true; Settings.Default.CustomPuttyPath = txtCustomPuttyPath.Text; } + if (Settings.Default.UseCustomPuttyPath != chkUseCustomPuttyPath.Checked) { puttyPathChanged = true; Settings.Default.UseCustomPuttyPath = chkUseCustomPuttyPath.Checked; } + if (puttyPathChanged) { - PuttyBase.PuttyPath = Settings.Default.UseCustomPuttyPath ? Settings.Default.CustomPuttyPath : GeneralAppInfo.PuttyPath; + PuttyBase.PuttyPath = Settings.Default.UseCustomPuttyPath + ? Settings.Default.CustomPuttyPath + : GeneralAppInfo.PuttyPath; PuttySessionsManager.Instance.AddSessions(); } - Settings.Default.MaxPuttyWaitTime = (int) numPuttyWaitTime.Value; - Settings.Default.UVNCSCPort = (int) numUVNCSCPort.Value; - - Settings.Default.Save(); + Settings.Default.MaxPuttyWaitTime = (int)numPuttyWaitTime.Value; + Settings.Default.UVNCSCPort = (int)numUVNCSCPort.Value; } #endregion @@ -160,7 +160,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages lblConfigurePuttySessions.Enabled = exists; btnLaunchPutty.Enabled = exists; - } #endregion diff --git a/mRemoteV1/UI/Forms/OptionsPages/AppearancePage.cs b/mRemoteV1/UI/Forms/OptionsPages/AppearancePage.cs index d9da8cd2..ad9f6101 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/AppearancePage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/AppearancePage.cs @@ -1,5 +1,4 @@ using System; -using System.Drawing; using System.Windows.Forms; using mRemoteNG.App; using mRemoteNG.Tools; @@ -26,7 +25,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages base.ApplyLanguage(); lblLanguage.Text = Language.strLanguage; - lblLanguageRestartRequired.Text = string.Format(Language.strLanguageRestartRequired, Application.ProductName); + lblLanguageRestartRequired.Text = + string.Format(Language.strLanguageRestartRequired, Application.ProductName); chkShowDescriptionTooltipsInTree.Text = Language.strShowDescriptionTooltips; chkShowFullConnectionsFilePathInTitle.Text = Language.strShowFullConsFilePath; chkShowSystemTrayIcon.Text = Language.strAlwaysShowSysTrayIcon; @@ -35,8 +35,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); - cboLanguage.Items.Clear(); cboLanguage.Items.Add(Language.strLanguageDefault); @@ -44,11 +42,13 @@ namespace mRemoteNG.UI.Forms.OptionsPages { cboLanguage.Items.Add(nativeName); } + if (!string.IsNullOrEmpty(Settings.Default.OverrideUICulture) && SupportedCultures.IsNameSupported(Settings.Default.OverrideUICulture)) { cboLanguage.SelectedItem = SupportedCultures.get_CultureNativeName(Settings.Default.OverrideUICulture); } + if (cboLanguage.SelectedIndex == -1) { cboLanguage.SelectedIndex = 0; @@ -62,7 +62,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void SaveSettings() { - if (cboLanguage.SelectedIndex > 0 && SupportedCultures.IsNativeNameSupported(Convert.ToString(cboLanguage.SelectedItem))) { @@ -96,8 +95,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages } Settings.Default.MinimizeToTray = chkMinimizeToSystemTray.Checked; - - Settings.Default.Save(); } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.Designer.cs b/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.Designer.cs index 08c694b5..a3a2fa23 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.Designer.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.Designer.cs @@ -323,7 +323,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.Controls.Add(this.chkHostnameLikeDisplayName); this.Controls.Add(this.chkSingleClickOnOpenedConnectionSwitchesToIt); this.Controls.Add(this.pnlConfirmCloseConnection); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "ConnectionsPage"; this.Size = new System.Drawing.Size(610, 490); ((System.ComponentModel.ISupportInitialize)(this.numRDPConTimeout)).EndInit(); diff --git a/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.cs b/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.cs index 29ca59f2..785a4023 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/ConnectionsPage.cs @@ -45,8 +45,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); - chkSingleClickOnConnectionOpensIt.Checked = Settings.Default.SingleClickOnConnectionOpensIt; chkSingleClickOnOpenedConnectionSwitchesToIt.Checked = Settings.Default.SingleClickSwitchesToOpenConnection; chkConnectionTreeTrackActiveConnection.Checked = Settings.Default.TrackActiveConnectionInConnectionTree; @@ -61,13 +59,13 @@ namespace mRemoteNG.UI.Forms.OptionsPages switch (Settings.Default.ConfirmCloseConnection) { - case (int) ConfirmCloseEnum.Never: + case (int)ConfirmCloseEnum.Never: radCloseWarnNever.Checked = true; break; - case (int) ConfirmCloseEnum.Exit: + case (int)ConfirmCloseEnum.Exit: radCloseWarnExit.Checked = true; break; - case (int) ConfirmCloseEnum.Multiple: + case (int)ConfirmCloseEnum.Multiple: radCloseWarnMultiple.Checked = true; break; default: @@ -86,12 +84,12 @@ namespace mRemoteNG.UI.Forms.OptionsPages Settings.Default.UseFilterSearch = chkUseFilterSearch.Checked; Settings.Default.PlaceSearchBarAboveConnectionTree = chkPlaceSearchBarAboveConnectionTree.Checked; - Settings.Default.RdpReconnectionCount = (int) numRdpReconnectionCount.Value; - Settings.Default.ConRDPOverallConnectionTimeout = (int) numRDPConTimeout.Value; - Settings.Default.AutoSaveEveryMinutes = (int) numAutoSave.Value; + Settings.Default.RdpReconnectionCount = (int)numRdpReconnectionCount.Value; + Settings.Default.ConRDPOverallConnectionTimeout = (int)numRDPConTimeout.Value; + Settings.Default.AutoSaveEveryMinutes = (int)numAutoSave.Value; if (Settings.Default.AutoSaveEveryMinutes > 0) { - _frmMain.tmrAutoSave.Interval = Settings.Default.AutoSaveEveryMinutes*60000; + _frmMain.tmrAutoSave.Interval = Settings.Default.AutoSaveEveryMinutes * 60000; _frmMain.tmrAutoSave.Enabled = true; } else @@ -101,22 +99,23 @@ namespace mRemoteNG.UI.Forms.OptionsPages if (radCloseWarnAll.Checked) { - Settings.Default.ConfirmCloseConnection = (int) ConfirmCloseEnum.All; - } - if (radCloseWarnMultiple.Checked) - { - Settings.Default.ConfirmCloseConnection = (int) ConfirmCloseEnum.Multiple; - } - if (radCloseWarnExit.Checked) - { - Settings.Default.ConfirmCloseConnection = (int) ConfirmCloseEnum.Exit; - } - if (radCloseWarnNever.Checked) - { - Settings.Default.ConfirmCloseConnection = (int) ConfirmCloseEnum.Never; + Settings.Default.ConfirmCloseConnection = (int)ConfirmCloseEnum.All; } - Settings.Default.Save(); + if (radCloseWarnMultiple.Checked) + { + Settings.Default.ConfirmCloseConnection = (int)ConfirmCloseEnum.Multiple; + } + + if (radCloseWarnExit.Checked) + { + Settings.Default.ConfirmCloseConnection = (int)ConfirmCloseEnum.Exit; + } + + if (radCloseWarnNever.Checked) + { + Settings.Default.ConfirmCloseConnection = (int)ConfirmCloseEnum.Never; + } } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/OptionsPages/CredentialsPage.cs b/mRemoteV1/UI/Forms/OptionsPages/CredentialsPage.cs index 1b9c37d5..86b0db4d 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/CredentialsPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/CredentialsPage.cs @@ -18,8 +18,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages ApplyTheme(); PageIcon = Resources.Key_Icon; } - - public override string PageName { + + public override string PageName + { get => Language.Credentials; set { } } @@ -37,10 +38,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); checkBoxUnlockOnStartup.Checked = Settings.Default.PromptUnlockCredReposOnStartup; - // ReSharper disable once SwitchStatementMissingSomeCases switch (Settings.Default.EmptyCredentials) { diff --git a/mRemoteV1/UI/Forms/OptionsPages/NotificationsPage.cs b/mRemoteV1/UI/Forms/OptionsPages/NotificationsPage.cs index 01319c62..e00b844e 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/NotificationsPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/NotificationsPage.cs @@ -1,5 +1,4 @@ using System.Diagnostics; -using System.Drawing; using System.IO; using System.Windows.Forms; using mRemoteNG.App; @@ -61,7 +60,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); LoadNotificationPanelSettings(); LoadLoggingSettings(); LoadPopupSettings(); @@ -72,7 +70,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages SaveNotificationPanelSettings(); SaveLoggingSettings(); SavePopupSettings(); - Settings.Default.Save(); } private void LoadNotificationPanelSettings() @@ -113,7 +110,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages Settings.Default.SwitchToMCOnInformation = chkSwitchToMCInformation.Checked; Settings.Default.SwitchToMCOnWarning = chkSwitchToMCWarnings.Checked; Settings.Default.SwitchToMCOnError = chkSwitchToMCErrors.Checked; - } private void SaveLoggingSettings() diff --git a/mRemoteV1/UI/Forms/OptionsPages/OptionsPage.cs b/mRemoteV1/UI/Forms/OptionsPages/OptionsPage.cs index bb5c7855..550ccf3e 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/OptionsPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/OptionsPage.cs @@ -1,82 +1,67 @@ using System.ComponentModel; using System.Drawing; using System.Windows.Forms; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Forms.OptionsPages { - public class OptionsPage : UserControl - { - protected OptionsPage() - { - //InitializeComponent(); - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + public class OptionsPage : UserControl + { + protected OptionsPage() + { + InitializeComponent(); + ThemeManager.getInstance().ThemeChanged += ApplyTheme; } - + #region Public Properties - // ReSharper disable once UnusedAutoPropertyAccessor.Global - [Browsable(false)]public virtual string PageName {get; set;} - - public virtual Icon PageIcon {get; protected set;} + + // ReSharper disable once UnusedAutoPropertyAccessor.Global + [Browsable(false)] public virtual string PageName { get; set; } + + public virtual Icon PageIcon { get; protected set; } public virtual Image IconImage => PageIcon?.ToBitmap(); - #endregion - - #region Public Methods - public virtual void ApplyLanguage() - { - - } - - public virtual void LoadSettings() - { - - } - - public virtual void SaveSettings() - { - - } - - public virtual void RevertSettings() - { - - } #endregion - /* + #region Public Methods + + public virtual void ApplyLanguage() + { + } + + public virtual void LoadSettings() + { + } + + public virtual void SaveSettings() + { + } + + public virtual void RevertSettings() + { + } + + #endregion + + protected virtual void ApplyTheme() + { + if (!ThemeManager.getInstance().ActiveAndExtended) return; + BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + Invalidate(); + } + private void InitializeComponent() { SuspendLayout(); // // OptionsPage // + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); Name = "OptionsPage"; - Size = new Size(610, 489); ResumeLayout(false); - - } - */ - - protected virtual void ApplyTheme() - { - if (!Themes.ThemeManager.getInstance().ThemingActive) return; - BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - Invalidate(); - } - - private void InitializeComponent() - { - this.SuspendLayout(); - // - // OptionsPage - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.Name = "OptionsPage"; - this.ResumeLayout(false); - } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/OptionsPages/SecurityPage.cs b/mRemoteV1/UI/Forms/OptionsPages/SecurityPage.cs index 417a68d3..2aca2c0c 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/SecurityPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/SecurityPage.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel; -using System.Drawing; using mRemoteNG.Security; namespace mRemoteNG.UI.Forms.OptionsPages @@ -35,24 +34,23 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); chkEncryptCompleteFile.Checked = Settings.Default.EncryptCompleteConnectionsFile; comboBoxEncryptionEngine.Text = Enum.GetName(typeof(BlockCipherEngines), Settings.Default.EncryptionEngine); - comboBoxBlockCipher.Text = Enum.GetName(typeof(BlockCipherModes), Settings.Default.EncryptionBlockCipherMode); + comboBoxBlockCipher.Text = + Enum.GetName(typeof(BlockCipherModes), Settings.Default.EncryptionBlockCipherMode); numberBoxKdfIterations.Value = Settings.Default.EncryptionKeyDerivationIterations; } public override void SaveSettings() { Settings.Default.EncryptCompleteConnectionsFile = chkEncryptCompleteFile.Checked; - Settings.Default.EncryptionEngine = (BlockCipherEngines) comboBoxEncryptionEngine.SelectedItem; - Settings.Default.EncryptionBlockCipherMode = (BlockCipherModes) comboBoxBlockCipher.SelectedItem; + Settings.Default.EncryptionEngine = (BlockCipherEngines)comboBoxEncryptionEngine.SelectedItem; + Settings.Default.EncryptionBlockCipherMode = (BlockCipherModes)comboBoxBlockCipher.SelectedItem; Settings.Default.EncryptionKeyDerivationIterations = (int)numberBoxKdfIterations.Value; } public override void RevertSettings() { - } private void PopulateEncryptionEngineDropDown() diff --git a/mRemoteV1/UI/Forms/OptionsPages/SqlServerPage.cs b/mRemoteV1/UI/Forms/OptionsPages/SqlServerPage.cs index f737b85b..5710a0eb 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/SqlServerPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/SqlServerPage.cs @@ -1,5 +1,4 @@ using System; -using System.Drawing; using mRemoteNG.App; using mRemoteNG.Config.Connections; using mRemoteNG.Config.Connections.Multiuser; @@ -8,7 +7,7 @@ using mRemoteNG.Security.SymmetricEncryption; namespace mRemoteNG.UI.Forms.OptionsPages { - public sealed partial class SqlServerPage + public sealed partial class SqlServerPage { private readonly SqlDatabaseConnectionTester _databaseConnectionTester; @@ -44,8 +43,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); - chkUseSQLServer.Checked = Settings.Default.UseSQLServer; txtSQLServer.Text = Settings.Default.SQLHost; txtSQLDatabaseName.Text = Settings.Default.SQLDatabaseName; @@ -53,7 +50,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); txtSQLPassword.Text = cryptographyProvider.Decrypt(Settings.Default.SQLPass, Runtime.EncryptionKey); chkSQLReadOnly.Checked = Settings.Default.SQLReadOnly; - lblTestConnectionResults.Text = ""; + lblTestConnectionResults.Text = ""; } public override void SaveSettings() @@ -73,14 +70,13 @@ namespace mRemoteNG.UI.Forms.OptionsPages ReinitializeSqlUpdater(); else if (!Settings.Default.UseSQLServer && sqlServerWasPreviouslyEnabled) DisableSql(); - - Settings.Default.Save(); } private static void ReinitializeSqlUpdater() { Runtime.ConnectionsService.RemoteConnectionsSyncronizer?.Dispose(); - Runtime.ConnectionsService.RemoteConnectionsSyncronizer = new RemoteConnectionsSyncronizer(new SqlConnectionsUpdateChecker()); + Runtime.ConnectionsService.RemoteConnectionsSyncronizer = + new RemoteConnectionsSyncronizer(new SqlConnectionsUpdateChecker()); Runtime.ConnectionsService.LoadConnections(true, ""); } @@ -122,7 +118,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages imgConnectionStatus.Image = Resources.loading_spinner; btnTestConnection.Enabled = false; - var connectionTestResult = await _databaseConnectionTester.TestConnectivity(server, database, username, password); + var connectionTestResult = + await _databaseConnectionTester.TestConnectivity(server, database, username, password); btnTestConnection.Enabled = true; @@ -134,15 +131,18 @@ namespace mRemoteNG.UI.Forms.OptionsPages break; case ConnectionTestResult.ServerNotAccessible: UpdateConnectionImage(false); - lblTestConnectionResults.Text = BuildTestFailedMessage(string.Format(Language.ServerNotAccessible, server)); + lblTestConnectionResults.Text = + BuildTestFailedMessage(string.Format(Language.ServerNotAccessible, server)); break; case ConnectionTestResult.CredentialsRejected: UpdateConnectionImage(false); - lblTestConnectionResults.Text = BuildTestFailedMessage(string.Format(Language.LoginFailedForUser, username)); + lblTestConnectionResults.Text = + BuildTestFailedMessage(string.Format(Language.LoginFailedForUser, username)); break; case ConnectionTestResult.UnknownDatabase: UpdateConnectionImage(false); - lblTestConnectionResults.Text = BuildTestFailedMessage(string.Format(Language.DatabaseNotAvailable, database)); + lblTestConnectionResults.Text = + BuildTestFailedMessage(string.Format(Language.DatabaseNotAvailable, database)); break; case ConnectionTestResult.UnknownError: UpdateConnectionImage(false); diff --git a/mRemoteV1/UI/Forms/OptionsPages/StartupExitPage.cs b/mRemoteV1/UI/Forms/OptionsPages/StartupExitPage.cs index 22b9cc58..73ea8cfd 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/StartupExitPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/StartupExitPage.cs @@ -1,5 +1,4 @@ using System; -using System.Drawing; namespace mRemoteNG.UI.Forms.OptionsPages { @@ -36,8 +35,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages Settings.Default.OpenConsFromLastSession = chkReconnectOnStart.Checked; Settings.Default.SingleInstance = chkSingleInstance.Checked; Settings.Default.StartupComponentsCheck = chkProperInstallationOfComponentsAtStartup.Checked; - - Settings.Default.Save(); } private void StartupExitPage_Load(object sender, EventArgs e) diff --git a/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.Designer.cs b/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.Designer.cs index d08cbd18..db575871 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.Designer.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.Designer.cs @@ -32,8 +32,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages private void InitializeComponent() { this.chkAlwaysShowPanelTabs = new mRemoteNG.UI.Controls.Base.NGCheckBox(); - this.chkAlwaysShowConnectionTabs = new mRemoteNG.UI.Controls.Base.NGCheckBox(); - this.chkIdentifyQuickConnectTabs = new mRemoteNG.UI.Controls.Base.NGCheckBox(); + this.chkAlwaysShowConnectionTabs = new mRemoteNG.UI.Controls.Base.NGCheckBox(); + this.chkIdentifyQuickConnectTabs = new mRemoteNG.UI.Controls.Base.NGCheckBox(); this.chkOpenNewTabRightOfSelected = new mRemoteNG.UI.Controls.Base.NGCheckBox(); this.chkAlwaysShowPanelSelectionDlg = new mRemoteNG.UI.Controls.Base.NGCheckBox(); this.chkShowLogonInfoOnTabs = new mRemoteNG.UI.Controls.Base.NGCheckBox(); @@ -55,22 +55,23 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.chkAlwaysShowPanelTabs.TabIndex = 0; this.chkAlwaysShowPanelTabs.Text = "Always show panel tabs"; this.chkAlwaysShowPanelTabs.UseVisualStyleBackColor = true; - // - // chkAlwaysShowConnectionTabs - // - this.chkAlwaysShowConnectionTabs._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; - this.chkAlwaysShowConnectionTabs.AutoSize = true; + // + // chkAlwaysShowConnectionTabs + // + this.chkAlwaysShowConnectionTabs._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; + this.chkAlwaysShowConnectionTabs.AutoSize = true; this.chkAlwaysShowConnectionTabs.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.chkAlwaysShowConnectionTabs.Location = new System.Drawing.Point(3, 26); - this.chkAlwaysShowConnectionTabs.Name = "chkAlwaysShowConnectionTabs"; - this.chkAlwaysShowConnectionTabs.Size = new System.Drawing.Size(200, 17); - this.chkAlwaysShowConnectionTabs.TabIndex = 0; - this.chkAlwaysShowConnectionTabs.Text = "Always show connection tabs"; - this.chkAlwaysShowConnectionTabs.UseVisualStyleBackColor = true; - // - // chkIdentifyQuickConnectTabs - // - this.chkIdentifyQuickConnectTabs._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; + this.chkAlwaysShowConnectionTabs.Location = new System.Drawing.Point(3, 26); + this.chkAlwaysShowConnectionTabs.Name = "chkAlwaysShowConnectionTabs"; + this.chkAlwaysShowConnectionTabs.Size = new System.Drawing.Size(178, 17); + this.chkAlwaysShowConnectionTabs.TabIndex = 0; + this.chkAlwaysShowConnectionTabs.Text = "Always show connection tabs"; + this.chkAlwaysShowConnectionTabs.UseVisualStyleBackColor = true; + this.chkAlwaysShowConnectionTabs.Visible = false; + // + // chkIdentifyQuickConnectTabs + // + this.chkIdentifyQuickConnectTabs._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; this.chkIdentifyQuickConnectTabs.AutoSize = true; this.chkIdentifyQuickConnectTabs.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.chkIdentifyQuickConnectTabs.Location = new System.Drawing.Point(3, 118); @@ -155,6 +156,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages // // txtBoxPanelName // + this.txtBoxPanelName.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtBoxPanelName.Location = new System.Drawing.Point(43, 246); this.txtBoxPanelName.Name = "txtBoxPanelName"; this.txtBoxPanelName.Size = new System.Drawing.Size(213, 22); @@ -177,14 +179,13 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.Controls.Add(this.txtBoxPanelName); this.Controls.Add(this.chkCreateEmptyPanelOnStart); this.Controls.Add(this.chkAlwaysShowPanelTabs); - this.Controls.Add(this.chkAlwaysShowConnectionTabs); - this.Controls.Add(this.chkIdentifyQuickConnectTabs); + this.Controls.Add(this.chkAlwaysShowConnectionTabs); + this.Controls.Add(this.chkIdentifyQuickConnectTabs); this.Controls.Add(this.chkOpenNewTabRightOfSelected); this.Controls.Add(this.chkAlwaysShowPanelSelectionDlg); this.Controls.Add(this.chkShowLogonInfoOnTabs); this.Controls.Add(this.chkDoubleClickClosesTab); this.Controls.Add(this.chkShowProtocolOnTabs); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "TabsPanelsPage"; this.Size = new System.Drawing.Size(610, 490); this.ResumeLayout(false); diff --git a/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.cs b/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.cs index 4fde148e..07802f78 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/TabsPanelsPage.cs @@ -1,5 +1,3 @@ -using System.Drawing; - namespace mRemoteNG.UI.Forms.OptionsPages { public sealed partial class TabsPanelsPage @@ -22,8 +20,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages base.ApplyLanguage(); chkAlwaysShowPanelTabs.Text = Language.strAlwaysShowPanelTabs; - chkAlwaysShowConnectionTabs.Text = Language.strAlwaysShowConnectionTabs; - chkOpenNewTabRightOfSelected.Text = Language.strOpenNewTabRight; + chkAlwaysShowConnectionTabs.Text = Language.strAlwaysShowConnectionTabs; + chkOpenNewTabRightOfSelected.Text = Language.strOpenNewTabRight; chkShowLogonInfoOnTabs.Text = Language.strShowLogonInfoOnTabs; chkShowProtocolOnTabs.Text = Language.strShowProtocolOnTabs; chkIdentifyQuickConnectTabs.Text = Language.strIdentifyQuickConnectTabs; @@ -35,11 +33,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); - chkAlwaysShowPanelTabs.Checked = Settings.Default.AlwaysShowPanelTabs; - chkAlwaysShowConnectionTabs.Checked = Settings.Default.AlwaysShowConnectionTabs; - chkOpenNewTabRightOfSelected.Checked = Settings.Default.OpenTabsRightOfSelected; + chkAlwaysShowConnectionTabs.Checked = Settings.Default.AlwaysShowConnectionTabs; + chkOpenNewTabRightOfSelected.Checked = Settings.Default.OpenTabsRightOfSelected; chkShowLogonInfoOnTabs.Checked = Settings.Default.ShowLogonInfoOnTabs; chkShowProtocolOnTabs.Checked = Settings.Default.ShowProtocolOnTabs; chkIdentifyQuickConnectTabs.Checked = Settings.Default.IdentifyQuickConnectTabs; @@ -55,8 +51,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages base.SaveSettings(); Settings.Default.AlwaysShowPanelTabs = chkAlwaysShowPanelTabs.Checked; - Settings.Default.AlwaysShowConnectionTabs = chkAlwaysShowConnectionTabs.Checked; - FrmMain.Default.ShowHidePanelTabs(); + Settings.Default.AlwaysShowConnectionTabs = chkAlwaysShowConnectionTabs.Checked; + FrmMain.Default.ShowHidePanelTabs(); Settings.Default.OpenTabsRightOfSelected = chkOpenNewTabRightOfSelected.Checked; Settings.Default.ShowLogonInfoOnTabs = chkShowLogonInfoOnTabs.Checked; @@ -66,8 +62,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages Settings.Default.AlwaysShowPanelSelectionDlg = chkAlwaysShowPanelSelectionDlg.Checked; Settings.Default.CreateEmptyPanelOnStartUp = chkCreateEmptyPanelOnStart.Checked; Settings.Default.StartUpPanelName = txtBoxPanelName.Text; - - Settings.Default.Save(); } private void UpdatePanelNameTextBox() diff --git a/mRemoteV1/UI/Forms/OptionsPages/ThemePage.Designer.cs b/mRemoteV1/UI/Forms/OptionsPages/ThemePage.Designer.cs index e96de049..db0215ec 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/ThemePage.Designer.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/ThemePage.Designer.cs @@ -3,7 +3,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages { - public partial class ThemePage : OptionsPage + public sealed partial class ThemePage : OptionsPage { //UserControl overrides dispose to clean up the component list. @@ -33,7 +33,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.btnThemeDelete = new mRemoteNG.UI.Controls.Base.NGButton(); this.btnThemeNew = new mRemoteNG.UI.Controls.Base.NGButton(); this.cboTheme = new mRemoteNG.UI.Controls.Base.NGComboBox(); - this.themeEnableChk = new mRemoteNG.UI.Controls.Base.NGCheckBox(); this.listPalette = new mRemoteNG.UI.Controls.Base.NGListView(); this.keyCol = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.ColorCol = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); @@ -84,20 +83,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.cboTheme.TabIndex = 0; this.cboTheme.SelectionChangeCommitted += new System.EventHandler(this.cboTheme_SelectionChangeCommitted); // - // themeEnableChk - // - this.themeEnableChk._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; - this.themeEnableChk.AutoSize = true; - this.themeEnableChk.Dock = System.Windows.Forms.DockStyle.Fill; - this.themeEnableChk.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.themeEnableChk.Location = new System.Drawing.Point(3, 3); - this.themeEnableChk.Name = "themeEnableChk"; - this.themeEnableChk.Size = new System.Drawing.Size(141, 22); - this.themeEnableChk.TabIndex = 5; - this.themeEnableChk.Text = "Enable Themes"; - this.themeEnableChk.UseVisualStyleBackColor = true; - this.themeEnableChk.CheckedChanged += new System.EventHandler(this.ThemeEnableChkCheckedChanged); - // // listPalette // this.listPalette.AllColumns.Add(this.keyCol); @@ -111,6 +96,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.listPalette.Cursor = System.Windows.Forms.Cursors.Default; this.listPalette.DecorateLines = true; this.listPalette.Dock = System.Windows.Forms.DockStyle.Fill; + this.listPalette.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.listPalette.Location = new System.Drawing.Point(3, 37); this.listPalette.Name = "listPalette"; this.listPalette.ShowGroups = false; @@ -144,12 +130,11 @@ namespace mRemoteNG.UI.Forms.OptionsPages // this.labelRestart.AutoSize = true; this.labelRestart.Dock = System.Windows.Forms.DockStyle.Fill; - this.labelRestart.Location = new System.Drawing.Point(150, 0); + this.labelRestart.Location = new System.Drawing.Point(3, 0); this.labelRestart.Name = "labelRestart"; - this.labelRestart.Size = new System.Drawing.Size(451, 28); + this.labelRestart.Size = new System.Drawing.Size(598, 28); this.labelRestart.TabIndex = 4; - this.labelRestart.Text = "Warning: Restart is required to disable the themes or to completely apply a new o" + - "ne"; + this.labelRestart.Text = "Warning: Restart is required..."; this.labelRestart.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tableLayoutPanel1 @@ -171,11 +156,10 @@ namespace mRemoteNG.UI.Forms.OptionsPages // // tableLayoutPanel2 // - this.tableLayoutPanel2.ColumnCount = 2; - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 24.33775F)); - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 75.66225F)); - this.tableLayoutPanel2.Controls.Add(this.labelRestart, 1, 0); - this.tableLayoutPanel2.Controls.Add(this.themeEnableChk, 0, 0); + this.tableLayoutPanel2.ColumnCount = 1; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.Controls.Add(this.labelRestart, 0, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 459); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; @@ -207,7 +191,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Controls.Add(this.tlpMain); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "ThemePage"; this.Size = new System.Drawing.Size(610, 490); ((System.ComponentModel.ISupportInitialize)(this.listPalette)).EndInit(); @@ -221,7 +204,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages internal Controls.Base.NGButton btnThemeDelete; internal Controls.Base.NGButton btnThemeNew; internal Controls.Base.NGComboBox cboTheme; - private Controls.Base.NGCheckBox themeEnableChk; private Controls.Base.NGListView listPalette; private Controls.Base.NGLabel labelRestart; private BrightIdeasSoftware.OLVColumn keyCol; diff --git a/mRemoteV1/UI/Forms/OptionsPages/ThemePage.cs b/mRemoteV1/UI/Forms/OptionsPages/ThemePage.cs index 0f584ce2..77d47e18 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/ThemePage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/ThemePage.cs @@ -5,17 +5,18 @@ using System.Linq; using System.Collections.Generic; using BrightIdeasSoftware; using mRemoteNG.UI.Forms.Input; +using mRemoteNG.UI.TaskDialog; namespace mRemoteNG.UI.Forms.OptionsPages { - public partial class ThemePage + public sealed partial class ThemePage { - #region Private Fields + private readonly ThemeManager _themeManager; - private readonly ThemeInfo _oriTheme; private readonly bool _oriActiveTheming; private readonly List modifiedThemes = new List(); + #endregion public ThemePage() @@ -26,7 +27,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages if (!_themeManager.ThemingActive) return; _themeManager = ThemeManager.getInstance(); _themeManager.ThemeChanged += ApplyTheme; - _oriTheme = _themeManager.ActiveTheme; _oriActiveTheming = _themeManager.ThemingActive; } @@ -43,20 +43,17 @@ namespace mRemoteNG.UI.Forms.OptionsPages btnThemeDelete.Text = Language.strOptionsThemeButtonDelete; btnThemeNew.Text = Language.strOptionsThemeButtonNew; labelRestart.Text = Language.strOptionsThemeThemeChaangeWarning; - themeEnableChk.Text = Language.strOptionsThemeEnableTheming; } private new void ApplyTheme() { if (!_themeManager.ThemingActive) return; - base.ApplyTheme(); + base.ApplyTheme(); } public override void LoadSettings() { - themeEnableChk.CheckedChanged -= ThemeEnableChkCheckedChanged; - base.SaveSettings(); //At first we cannot create or delete themes, depends later on the type of selected theme btnThemeNew.Enabled = false; btnThemeDelete.Enabled = false; @@ -67,21 +64,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages cboTheme.SelectedItem = _themeManager.ActiveTheme; cboTheme_SelectionChangeCommitted(this, new EventArgs()); cboTheme.DisplayMember = "Name"; - //Color cell formatter - listPalette.FormatCell += ListPalette_FormatCell; - //Load theming active property and disable controls - if (_themeManager.ThemingActive) - { - themeEnableChk.Checked = true; - } - else - { - themeEnableChk.Checked = false; - cboTheme.Enabled = false; - // reset to the default theme when disabling theme support - _themeManager.ActiveTheme = _themeManager.DefaultTheme; - } - themeEnableChk.CheckedChanged += ThemeEnableChkCheckedChanged; + + listPalette.FormatCell += ListPalette_FormatCell; //Color cell formatter } private void ListPalette_FormatCell(object sender, FormatCellEventArgs e) @@ -95,7 +79,25 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void SaveSettings() { base.SaveSettings(); - foreach(var updatedTheme in modifiedThemes) + + Settings.Default.ThemingActive = true; + + // Save the theme settings form close so we don't run into unexpected results while modifying... + // Prompt the user that a restart is required to apply the new theme... + if (cboTheme.SelectedItem != null + ) // LoadSettings calls SaveSettings, so these might be null the first time around + { + if (!Settings.Default.ThemeName.Equals(((ThemeInfo)cboTheme.SelectedItem).Name)) + { + Settings.Default.ThemeName = ((ThemeInfo)cboTheme.SelectedItem).Name; + + CTaskDialog.MessageBox("Theme Changed", "Restart Required.", + "Please restart mRemoteNG to apply the selected theme.", + ETaskDialogButtons.Ok, ESysIcons.Information); + } + } + + foreach (var updatedTheme in modifiedThemes) { _themeManager.updateTheme(updatedTheme); } @@ -104,37 +106,44 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void RevertSettings() { base.RevertSettings(); - _themeManager.ActiveTheme = _oriTheme; _themeManager.ThemingActive = _oriActiveTheming; } - #region Private Methods #region Event Handlers - - private void cboTheme_SelectionChangeCommitted(object sender, EventArgs e) { btnThemeNew.Enabled = false; btnThemeDelete.Enabled = false; - if (!_themeManager.ThemingActive) return; - _themeManager.ActiveTheme = (ThemeInfo)cboTheme.SelectedItem; - listPalette.ClearObjects(); - if (!_themeManager.ActiveTheme.IsExtendable || !_themeManager.ThemingActive) return; - btnThemeNew.Enabled = true; - listPalette.ClearObjects(); + + // don't display listPalette if it's not an Extendable theme... + listPalette.CellClick -= ListPalette_CellClick; listPalette.Enabled = false; - ColorMeList(); - if (_themeManager.ActiveTheme.IsThemeBase) return; - listPalette.Enabled = true; + listPalette.Visible = false; + + if (!_themeManager.ThemingActive) return; + + btnThemeNew.Enabled = true; + + var selectedTheme = (ThemeInfo)cboTheme.SelectedItem; + + if (selectedTheme != null && selectedTheme.IsExtendable) + { + // it's Extendable, so now we can do this more expensive operations... + listPalette.ClearObjects(); + ColorMeList(selectedTheme); + listPalette.Enabled = true; + listPalette.Visible = true; + listPalette.CellClick += ListPalette_CellClick; + } + + if (selectedTheme != null && selectedTheme.IsThemeBase) return; + btnThemeDelete.Enabled = true; - listPalette.CellClick += ListPalette_CellClick; } - - /// /// Edit an object, since KeyValuePair value cannot be set without creating a new object, a parallel object model exist in the list /// besides the one in the active theme, so any modification must be done to the two models @@ -143,7 +152,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages /// private void ListPalette_CellClick(object sender, CellClickEventArgs e) { - var colorElem = (PseudoKeyColor)e.Model; var colorDlg = new ColorDialog @@ -161,19 +169,19 @@ namespace mRemoteNG.UI.Forms.OptionsPages colorElem.Value = colorDlg.Color; listPalette.RefreshObject(e.Model); _themeManager.refreshUI(); - } - private void ColorMeList() + private void ColorMeList(ThemeInfo ti) { - foreach (var colorElem in _themeManager.ActiveTheme.ExtendedPalette.ExtColorPalette) + foreach (var colorElem in ti.ExtendedPalette.ExtColorPalette) listPalette.AddObject(new PseudoKeyColor(colorElem.Key, colorElem.Value)); } private void btnThemeNew_Click(object sender, EventArgs e) { - var name = _themeManager.ActiveTheme.Name; - using (var frmInputBox = new FrmInputBox(Language.strOptionsThemeNewThemeCaption, Language.strOptionsThemeNewThemeText, ref name)) + using (var frmInputBox = new FrmInputBox(Language.strOptionsThemeNewThemeCaption, + Language.strOptionsThemeNewThemeText, + _themeManager.ActiveTheme.Name)) { var dr = frmInputBox.ShowDialog(); if (dr != DialogResult.OK) return; @@ -185,15 +193,19 @@ namespace mRemoteNG.UI.Forms.OptionsPages } else { - TaskDialog.CTaskDialog.ShowTaskDialogBox(this, Language.strErrors, Language.strOptionsThemeNewThemeError, "", "", "", "", "", "", TaskDialog.ETaskDialogButtons.Ok, TaskDialog.ESysIcons.Error, TaskDialog.ESysIcons.Information, 0); + CTaskDialog.ShowTaskDialogBox(this, Language.strErrors, Language.strOptionsThemeNewThemeError, "", + "", "", "", "", "", ETaskDialogButtons.Ok, ESysIcons.Error, + ESysIcons.Information, 0); } } } private void btnThemeDelete_Click(object sender, EventArgs e) { - - var res = TaskDialog.CTaskDialog.ShowTaskDialogBox(this, Language.strWarnings , Language.strOptionsThemeDeleteConfirmation, "", "", "", "", "", "", TaskDialog.ETaskDialogButtons.YesNo, TaskDialog.ESysIcons.Question, TaskDialog.ESysIcons.Information, 0); + var res = CTaskDialog.ShowTaskDialogBox(this, Language.strWarnings, + Language.strOptionsThemeDeleteConfirmation, "", "", "", "", "", "", + ETaskDialogButtons.YesNo, + ESysIcons.Question, ESysIcons.Information, 0); if (res != DialogResult.Yes) return; if (modifiedThemes.Contains(_themeManager.ActiveTheme)) @@ -205,32 +217,5 @@ namespace mRemoteNG.UI.Forms.OptionsPages #endregion #endregion - - private void ThemeEnableChkCheckedChanged(object sender, EventArgs e) - { - if (themeEnableChk.Checked) - { - - if(_themeManager.ThemesCount > 0) - { - _themeManager.ThemingActive = true; - cboTheme.Enabled = true; - } - else - { - TaskDialog.CTaskDialog.ShowTaskDialogBox(this, Language.strErrors, Language.strOptionsThemeErrorNoThemes, "", "", "", "", "", "", TaskDialog.ETaskDialogButtons.Ok, TaskDialog.ESysIcons.Error, TaskDialog.ESysIcons.Information, 0); - themeEnableChk.Checked = false; - _themeManager.ThemingActive = false; - cboTheme.Enabled = false; - } - } - else - { - _themeManager.ThemingActive = false; - themeEnableChk.Checked = false; - cboTheme.Enabled = false; - } - LoadSettings(); - } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/OptionsPages/UpdatesPage.cs b/mRemoteV1/UI/Forms/OptionsPages/UpdatesPage.cs index ad2f3d61..e1bdfd5e 100644 --- a/mRemoteV1/UI/Forms/OptionsPages/UpdatesPage.cs +++ b/mRemoteV1/UI/Forms/OptionsPages/UpdatesPage.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel; -using System.Drawing; using System.Windows.Forms; using mRemoteNG.App; using mRemoteNG.App.Info; @@ -27,6 +26,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages } #region Public Methods + public override string PageName { get => Language.strTabUpdates; @@ -37,7 +37,7 @@ namespace mRemoteNG.UI.Forms.OptionsPages { base.ApplyLanguage(); - lblUpdatesExplanation.Text = Language.strUpdateCheck; + lblUpdatesExplanation.Text = Language.strUpdateCheck; chkCheckForUpdatesOnStartup.Text = Language.strCheckForUpdatesOnStartup; btnUpdateCheckNow.Text = Language.strCheckNow; @@ -55,8 +55,6 @@ namespace mRemoteNG.UI.Forms.OptionsPages public override void LoadSettings() { - base.SaveSettings(); - chkCheckForUpdatesOnStartup.Checked = Settings.Default.CheckForUpdatesOnStartup; cboUpdateCheckFrequency.Enabled = chkCheckForUpdatesOnStartup.Checked; cboUpdateCheckFrequency.Items.Clear(); @@ -68,24 +66,26 @@ namespace mRemoteNG.UI.Forms.OptionsPages chkCheckForUpdatesOnStartup.Checked = false; cboUpdateCheckFrequency.SelectedIndex = nDaily; } // Daily - else switch (Settings.Default.CheckForUpdatesFrequencyDays) - { - case 1: - cboUpdateCheckFrequency.SelectedIndex = nDaily; - break; - case 7: - cboUpdateCheckFrequency.SelectedIndex = nWeekly; - break; - case 31: - cboUpdateCheckFrequency.SelectedIndex = nMonthly; - break; - default: - var nCustom = - cboUpdateCheckFrequency.Items.Add(string.Format(Language.strUpdateFrequencyCustom, - Settings.Default.CheckForUpdatesFrequencyDays)); - cboUpdateCheckFrequency.SelectedIndex = nCustom; - break; - } + else + switch (Settings.Default.CheckForUpdatesFrequencyDays) + { + case 1: + cboUpdateCheckFrequency.SelectedIndex = nDaily; + break; + case 7: + cboUpdateCheckFrequency.SelectedIndex = nWeekly; + break; + case 31: + cboUpdateCheckFrequency.SelectedIndex = nMonthly; + break; + default: + var nCustom = + cboUpdateCheckFrequency.Items.Add(string.Format(Language.strUpdateFrequencyCustom, + Settings + .Default.CheckForUpdatesFrequencyDays)); + cboUpdateCheckFrequency.SelectedIndex = nCustom; + break; + } var stable = cboReleaseChannel.Items.Add(UpdateChannelInfo.STABLE); var beta = cboReleaseChannel.Items.Add(UpdateChannelInfo.BETA); @@ -115,7 +115,8 @@ namespace mRemoteNG.UI.Forms.OptionsPages pnlProxyAuthentication.Enabled = Settings.Default.UpdateProxyUseAuthentication; txtProxyUsername.Text = Settings.Default.UpdateProxyAuthUser; var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); - txtProxyPassword.Text = cryptographyProvider.Decrypt(Settings.Default.UpdateProxyAuthPass, Runtime.EncryptionKey); + txtProxyPassword.Text = + cryptographyProvider.Decrypt(Settings.Default.UpdateProxyAuthPass, Runtime.EncryptionKey); btnTestProxy.Enabled = Settings.Default.UpdateUseProxy; } @@ -142,14 +143,13 @@ namespace mRemoteNG.UI.Forms.OptionsPages Settings.Default.UpdateUseProxy = chkUseProxyForAutomaticUpdates.Checked; Settings.Default.UpdateProxyAddress = txtProxyAddress.Text; - Settings.Default.UpdateProxyPort = (int) numProxyPort.Value; + Settings.Default.UpdateProxyPort = (int)numProxyPort.Value; Settings.Default.UpdateProxyUseAuthentication = chkUseProxyAuthentication.Checked; Settings.Default.UpdateProxyAuthUser = txtProxyUsername.Text; var cryptographyProvider = new LegacyRijndaelCryptographyProvider(); - Settings.Default.UpdateProxyAuthPass = cryptographyProvider.Encrypt(txtProxyPassword.Text, Runtime.EncryptionKey); - - Settings.Default.Save(); + Settings.Default.UpdateProxyAuthPass = + cryptographyProvider.Encrypt(txtProxyPassword.Text, Runtime.EncryptionKey); } #endregion @@ -202,8 +202,9 @@ namespace mRemoteNG.UI.Forms.OptionsPages _appUpdate = new AppUpdater(); //_appUpdate.Load += _appUpdate.Update_Load; _appUpdate.SetProxySettings(chkUseProxyForAutomaticUpdates.Checked, txtProxyAddress.Text, - (int) numProxyPort.Value, chkUseProxyAuthentication.Checked, txtProxyUsername.Text, - txtProxyPassword.Text); + (int)numProxyPort.Value, chkUseProxyAuthentication.Checked, + txtProxyUsername.Text, + txtProxyPassword.Text); btnTestProxy.Enabled = false; btnTestProxy.Text = Language.strOptionsProxyTesting; @@ -243,18 +244,22 @@ namespace mRemoteNG.UI.Forms.OptionsPages { return; } + if (e.Error != null) { throw e.Error; } - CTaskDialog.ShowCommandBox(this, Application.ProductName, Language.strProxyTestSucceeded, "", Language.strButtonOK, false); + CTaskDialog.ShowCommandBox(this, Application.ProductName, Language.strProxyTestSucceeded, "", + Language.strButtonOK, false); } catch (Exception ex) { CTaskDialog.ShowCommandBox(this, Application.ProductName, Language.strProxyTestFailed, - MiscTools.GetExceptionMessageRecursive(ex), "", "", "", Language.strButtonOK, false, ESysIcons.Error, - 0); + MiscTools.GetExceptionMessageRecursive(ex), "", "", "", Language.strButtonOK, + false, + ESysIcons.Error, + 0); } } diff --git a/mRemoteV1/UI/Forms/PasswordForm.cs b/mRemoteV1/UI/Forms/PasswordForm.cs index 33b05d27..e9246f46 100644 --- a/mRemoteV1/UI/Forms/PasswordForm.cs +++ b/mRemoteV1/UI/Forms/PasswordForm.cs @@ -7,7 +7,7 @@ using mRemoteNG.Tools; namespace mRemoteNG.UI.Forms { public partial class PasswordForm : IKeyProvider - { + { private readonly string _passwordName; private SecureString _password = new SecureString(); @@ -16,7 +16,7 @@ namespace mRemoteNG.UI.Forms /// password box is shown which must match the first password /// to continue. /// - private bool NewPasswordMode { get; } + private bool NewPasswordMode { get; } /// /// Creates a new password form for entering or setting a password. @@ -27,12 +27,12 @@ namespace mRemoteNG.UI.Forms /// password box is shown which must match the first password /// to continue. /// - public PasswordForm(string passwordName = null, bool newPasswordMode = true) - { - InitializeComponent(); - _passwordName = passwordName; - NewPasswordMode = newPasswordMode; - } + public PasswordForm(string passwordName = null, bool newPasswordMode = true) + { + InitializeComponent(); + _passwordName = passwordName; + NewPasswordMode = newPasswordMode; + } /// /// Dispaly a dialog box requesting that the user @@ -48,17 +48,18 @@ namespace mRemoteNG.UI.Forms } #region Event Handlers + private void frmPassword_Load(object sender, EventArgs e) - { - ApplyLanguage(); + { + ApplyLanguage(); var display = new DisplayProperties(); - pbLock.Image = display.ScaleImage(pbLock.Image); - Height = tableLayoutPanel1.Height; + pbLock.Image = display.ScaleImage(pbLock.Image); + Height = tableLayoutPanel1.Height; if (NewPasswordMode) return; lblVerify.Visible = false; - txtVerify.Visible = false; - } + txtVerify.Visible = false; + } private void PasswordForm_FormClosed(object sender, FormClosedEventArgs e) { @@ -68,60 +69,66 @@ namespace mRemoteNG.UI.Forms } private void btnCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; + { + DialogResult = DialogResult.Cancel; Close(); - } + } - private void btnOK_Click(object sender, EventArgs e) - { + private void btnOK_Click(object sender, EventArgs e) + { if (NewPasswordMode) - VerifyNewPassword(); + VerifyNewPassword(); - DialogResult = DialogResult.OK; - } + DialogResult = DialogResult.OK; + } + + private void txtPassword_TextChanged(object sender, EventArgs e) + { + HideStatus(); + } - private void txtPassword_TextChanged(object sender, EventArgs e) - { - HideStatus(); - } #endregion - + #region Private Methods - private void ApplyLanguage() - { - Text = string.IsNullOrEmpty(_passwordName) ? Language.strTitlePassword : string.Format(Language.strTitlePasswordWithName, _passwordName); - - lblPassword.Text = Language.strLabelPassword; - lblVerify.Text = Language.strLabelVerify; - btnCancel.Text = Language.strButtonCancel; - btnOK.Text = Language.strButtonOK; - } - + + private void ApplyLanguage() + { + Text = string.IsNullOrEmpty(_passwordName) + ? Language.strTitlePassword + : string.Format(Language.strTitlePasswordWithName, _passwordName); + + lblPassword.Text = Language.strLabelPassword; + lblVerify.Text = Language.strLabelVerify; + btnCancel.Text = Language.strButtonCancel; + btnOK.Text = Language.strButtonOK; + } + // ReSharper disable once UnusedMethodReturnValue.Local private bool VerifyNewPassword() - { - if (txtPassword.Text.Length >= 3) - { - if (txtPassword.Text == txtVerify.Text) - return true; - ShowStatus(Language.strPasswordStatusMustMatch); - return false; - } - ShowStatus(Language.strPasswordStatusTooShort); - return false; - } - - private void ShowStatus(string status) - { - lblStatus.Visible = true; - lblStatus.Text = status; - } - - private void HideStatus() - { - lblStatus.Visible = false; - } + { + if (txtPassword.Text.Length >= 3) + { + if (txtPassword.Text == txtVerify.Text) + return true; + ShowStatus(Language.strPasswordStatusMustMatch); + return false; + } + + ShowStatus(Language.strPasswordStatusTooShort); + return false; + } + + private void ShowStatus(string status) + { + lblStatus.Visible = true; + lblStatus.Text = status; + } + + private void HideStatus() + { + lblStatus.Visible = false; + } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/TextBox.cs b/mRemoteV1/UI/Forms/TextBox.cs index 38b238d6..1b7329fa 100644 --- a/mRemoteV1/UI/Forms/TextBox.cs +++ b/mRemoteV1/UI/Forms/TextBox.cs @@ -6,50 +6,59 @@ using System.Windows.Forms; namespace mRemoteNG.UI.Forms { - public class TextBox : Controls.Base.NGTextBox - { + public class TextBox : Controls.Base.NGTextBox + { #region Public Properties - [Category("Behavior"), - DefaultValue(false)]private bool _SelectAllOnFocus; + + [Category("Behavior"), + DefaultValue(false)] + private bool _SelectAllOnFocus; + public bool SelectAllOnFocus - { - get => _SelectAllOnFocus; + { + get => _SelectAllOnFocus; set => _SelectAllOnFocus = value; } + #endregion - + #region Protected Methods - protected override void OnEnter(EventArgs e) - { - base.OnEnter(e); + + protected override void OnEnter(EventArgs e) + { + base.OnEnter(e); if (MouseButtons != MouseButtons.None) return; SelectAll(); _focusHandled = true; } - - protected override void OnLeave(EventArgs e) - { - base.OnLeave(e); - - _focusHandled = false; - } - - protected override void OnMouseUp(MouseEventArgs e) - { - base.OnMouseUp(e); + + protected override void OnLeave(EventArgs e) + { + base.OnLeave(e); + + _focusHandled = false; + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); if (_focusHandled) return; if (SelectionLength == 0) { SelectAll(); } + _focusHandled = true; } + #endregion - + #region Private Fields - private bool _focusHandled; + + private bool _focusHandled; + #endregion private void InitializeComponent() @@ -58,9 +67,9 @@ namespace mRemoteNG.UI.Forms // // TextBox // - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ResumeLayout(false); - } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/UnhandledExceptionWindow.cs b/mRemoteV1/UI/Forms/UnhandledExceptionWindow.cs index 6147851b..a06cffad 100644 --- a/mRemoteV1/UI/Forms/UnhandledExceptionWindow.cs +++ b/mRemoteV1/UI/Forms/UnhandledExceptionWindow.cs @@ -32,27 +32,27 @@ namespace mRemoteNG.UI.Forms Text = Language.mRemoteNGUnhandledException; labelExceptionCaught.Text = Language.UnhandledExceptionOccured; - labelExceptionIsFatalHeader.Text = _isFatal - ? Language.ExceptionForcesmRemoteNGToClose + labelExceptionIsFatalHeader.Text = _isFatal + ? Language.ExceptionForcesmRemoteNGToClose : string.Empty; labelExceptionMessageHeader.Text = Language.ExceptionMessage; labelStackTraceHeader.Text = Language.StackTrace; buttonCopyAll.Text = Language.strMenuNotificationsCopyAll; buttonClose.Text = _isFatal - ? Language.strMenuExit + ? Language.strMenuExit : Language.strButtonClose; } private void buttonCopyAll_Click(object sender, EventArgs e) { var text = new StringBuilder() - .AppendLine(labelExceptionMessageHeader.Text) - .AppendLine("\"" + textBoxExceptionMessage.Text + "\"") - .AppendLine() - .AppendLine(labelStackTraceHeader.Text) - .AppendLine(textBoxStackTrace.Text) - .ToString(); + .AppendLine(labelExceptionMessageHeader.Text) + .AppendLine("\"" + textBoxExceptionMessage.Text + "\"") + .AppendLine() + .AppendLine(labelStackTraceHeader.Text) + .AppendLine(textBoxStackTrace.Text) + .ToString(); Clipboard.SetText(text); } @@ -65,4 +65,4 @@ namespace mRemoteNG.UI.Forms Close(); } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/frmChoosePanel.cs b/mRemoteV1/UI/Forms/frmChoosePanel.cs index 0f7f38a0..e038e761 100644 --- a/mRemoteV1/UI/Forms/frmChoosePanel.cs +++ b/mRemoteV1/UI/Forms/frmChoosePanel.cs @@ -1,75 +1,79 @@ using System.Windows.Forms; using mRemoteNG.App; +using mRemoteNG.Themes; using mRemoteNG.UI.Forms.Input; using mRemoteNG.UI.Panels; namespace mRemoteNG.UI.Forms { - public partial class FrmChoosePanel - { - private readonly PanelAdder _panelAdder; + public partial class FrmChoosePanel + { + private readonly PanelAdder _panelAdder; - public FrmChoosePanel() - { - InitializeComponent(); + public FrmChoosePanel() + { + InitializeComponent(); _panelAdder = new PanelAdder(); - } + } + public string Panel - { - get => cbPanels.SelectedItem.ToString(); + { + get => cbPanels.SelectedItem.ToString(); set => cbPanels.SelectedItem = value; } - private void frmChoosePanel_Load(object sender, System.EventArgs e) - { - ApplyLanguage(); - ApplyTheme(); - AddAvailablePanels(); - } - - private void ApplyLanguage() - { - btnOK.Text = Language.strButtonOK; - lblDescription.Text = Language.strLabelSelectPanel; - btnNew.Text = Language.strButtonNew; - Text = Language.strTitleSelectPanel; - } + private void frmChoosePanel_Load(object sender, System.EventArgs e) + { + ApplyLanguage(); + ApplyTheme(); + AddAvailablePanels(); + } - private void ApplyTheme() - { - if (!Themes.ThemeManager.getInstance().ThemingActive) return; - BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - lblDescription.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - lblDescription.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + private void ApplyLanguage() + { + btnOK.Text = Language.strButtonOK; + lblDescription.Text = Language.strLabelSelectPanel; + btnNew.Text = Language.strButtonNew; + Text = Language.strTitleSelectPanel; + } + + private void ApplyTheme() + { + if (!ThemeManager.getInstance().ActiveAndExtended) return; + BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + lblDescription.BackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + lblDescription.ForeColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } private void AddAvailablePanels() - { - cbPanels.Items.Clear(); - - for (var i = 0; i <= Runtime.WindowList.Count - 1; i++) - { - cbPanels.Items.Add(Runtime.WindowList[i].Text.Replace("&&", "&")); - } - - if (cbPanels.Items.Count > 0) - { - cbPanels.SelectedItem = cbPanels.Items[0]; - cbPanels.Enabled = true; - btnOK.Enabled = true; - } - else - { - cbPanels.Enabled = false; - btnOK.Enabled = false; - } - } + { + cbPanels.Items.Clear(); - private void btnNew_Click(object sender, System.EventArgs e) - { - var pnlName = Language.strNewPanel; - using (var frmInputBox = new FrmInputBox(Language.strNewPanel, Language.strPanelName + ":", ref pnlName)) + for (var i = 0; i <= Runtime.WindowList.Count - 1; i++) + { + cbPanels.Items.Add(Runtime.WindowList[i].Text.Replace("&&", "&")); + } + + if (cbPanels.Items.Count > 0) + { + cbPanels.SelectedItem = cbPanels.Items[0]; + cbPanels.Enabled = true; + btnOK.Enabled = true; + } + else + { + cbPanels.Enabled = false; + btnOK.Enabled = false; + } + } + + private void btnNew_Click(object sender, System.EventArgs e) + { + using (var frmInputBox = + new FrmInputBox(Language.strNewPanel, Language.strPanelName + ":", Language.strNewPanel)) { var dr = frmInputBox.ShowDialog(); if (dr != DialogResult.OK || string.IsNullOrEmpty(frmInputBox.returnValue)) return; @@ -78,11 +82,11 @@ namespace mRemoteNG.UI.Forms cbPanels.SelectedItem = frmInputBox.returnValue; cbPanels.Focus(); } - } + } - private void btnOK_Click(object sender, System.EventArgs e) - { + private void btnOK_Click(object sender, System.EventArgs e) + { DialogResult = DialogResult.OK; - } - } -} + } + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/frmMain.cs b/mRemoteV1/UI/Forms/frmMain.cs index f1728f53..66c8d9cd 100644 --- a/mRemoteV1/UI/Forms/frmMain.cs +++ b/mRemoteV1/UI/Forms/frmMain.cs @@ -28,11 +28,11 @@ using mRemoteNG.Security.Factories; using mRemoteNG.Themes; using mRemoteNG.Tools; using mRemoteNG.UI.Menu; -using mRemoteNG.UI.Panels; +using mRemoteNG.UI.Tabs; using mRemoteNG.UI.TaskDialog; using mRemoteNG.UI.Window; +using mRemoteNG.UI.Panels; using WeifenLuo.WinFormsUI.Docking; -using TabControl = Crownwood.Magic.Controls.TabControl; // ReSharper disable MemberCanBePrivate.Global @@ -58,14 +58,14 @@ namespace mRemoteNG.UI.Forms private readonly SaveConnectionsOnEdit _saveConnectionsOnEdit = new SaveConnectionsOnEdit(); internal FullscreenHandler Fullscreen { get; set; } - + //Added theming support private readonly ToolStripRenderer _toolStripProfessionalRenderer = new ToolStripProfessionalRenderer(); private FrmMain() - { - _showFullPathInTitle = Settings.Default.ShowCompleteConsPathInTitle; - InitializeComponent(); + { + _showFullPathInTitle = Settings.Default.ShowCompleteConsPathInTitle; + InitializeComponent(); Fullscreen = new FullscreenHandler(this); //Theming support @@ -77,68 +77,75 @@ namespace mRemoteNG.UI.Forms } #region Properties + public FormWindowState PreviousWindowState { get; set; } - public bool IsClosing { get; private set; } + public bool IsClosing { get; private set; } public bool AreWeUsingSqlServerForSavingConnections - { - get => _usingSqlServer; + { + get => _usingSqlServer; set - { - if (_usingSqlServer == value) - { - return; - } - _usingSqlServer = value; - UpdateWindowTitle(); - } - } - + { + if (_usingSqlServer == value) + { + return; + } + + _usingSqlServer = value; + UpdateWindowTitle(); + } + } + public string ConnectionsFileName - { - get => _connectionsFileName; + { + get => _connectionsFileName; set - { - if (_connectionsFileName == value) - { - return; - } - _connectionsFileName = value; - UpdateWindowTitle(); - } - } - + { + if (_connectionsFileName == value) + { + return; + } + + _connectionsFileName = value; + UpdateWindowTitle(); + } + } + public bool ShowFullPathInTitle - { - get => _showFullPathInTitle; + { + get => _showFullPathInTitle; set - { - if (_showFullPathInTitle == value) - { - return; - } - _showFullPathInTitle = value; - UpdateWindowTitle(); - } - } - + { + if (_showFullPathInTitle == value) + { + return; + } + + _showFullPathInTitle = value; + UpdateWindowTitle(); + } + } + public ConnectionInfo SelectedConnection - { - get => _selectedConnection; + { + get => _selectedConnection; set - { - if (_selectedConnection == value) - { - return; - } - _selectedConnection = value; - UpdateWindowTitle(); - } - } + { + if (_selectedConnection == value) + { + return; + } + + _selectedConnection = value; + UpdateWindowTitle(); + } + } + #endregion #region Startup & Shutdown + private void frmMain_Load(object sender, EventArgs e) { var messageCollector = Runtime.MessageCollector; @@ -148,7 +155,8 @@ namespace mRemoteNG.UI.Forms Startup.Instance.InitializeProgram(messageCollector); msMain.Location = Point.Empty; - var settingsLoader = new SettingsLoader(this, messageCollector, _quickConnectToolStrip, _externalToolsToolStrip, _multiSshToolStrip, msMain); + var settingsLoader = new SettingsLoader(this, messageCollector, _quickConnectToolStrip, + _externalToolsToolStrip, _multiSshToolStrip, msMain); settingsLoader.LoadSettings(); SetMenuDependencies(); @@ -156,12 +164,12 @@ namespace mRemoteNG.UI.Forms var uiLoader = new DockPanelLayoutLoader(this, messageCollector); uiLoader.LoadPanelsFromXml(); - LockToolbarPositions(Settings.Default.LockToolbars); - Settings.Default.PropertyChanged += OnApplicationSettingChanged; + LockToolbarPositions(Settings.Default.LockToolbars); + Settings.Default.PropertyChanged += OnApplicationSettingChanged; - _themeManager.ThemeChanged += ApplyTheme; + _themeManager.ThemeChanged += ApplyTheme; - _fpChainedWindowHandle = NativeMethods.SetClipboardViewer(Handle); + _fpChainedWindowHandle = NativeMethods.SetClipboardViewer(Handle); InitializeCredRepoFactories(); @@ -179,30 +187,30 @@ namespace mRemoteNG.UI.Forms Windows.TreeForm.ConnectionTree.ConnectionTreeModel = Runtime.ConnectionsService.ConnectionTreeModel; PuttySessionsManager.Instance.StartWatcher(); - if (Settings.Default.StartupComponentsCheck) + if (Settings.Default.StartupComponentsCheck) Windows.Show(WindowType.ComponentsCheck); Startup.Instance.CreateConnectionsProvider(messageCollector); _screenSystemMenu.BuildScreenList(); - SystemEvents.DisplaySettingsChanged += _screenSystemMenu.OnDisplayChanged; + SystemEvents.DisplaySettingsChanged += _screenSystemMenu.OnDisplayChanged; ApplyLanguage(); Opacity = 1; - //Fix missing general panel at the first run - if (Settings.Default.CreateEmptyPanelOnStartUp) - { - var panelName = !string.IsNullOrEmpty(Settings.Default.StartUpPanelName) - ? Settings.Default.StartUpPanelName - : Language.strNewPanel; + //Fix MagicRemove , revision on panel strategy for mdi - var panelAdder = new PanelAdder(); - if (!panelAdder.DoesPanelExist(panelName)) - panelAdder.AddPanel(panelName); - } - - FrmSplashScreen frmSplashScreen = FrmSplashScreen.getInstance(); - frmSplashScreen.Close(); + pnlDock.ShowDocumentIcon = true; + + FrmSplashScreen.getInstance().Close(); + + if (!Settings.Default.CreateEmptyPanelOnStartUp) return; + var panelName = !string.IsNullOrEmpty(Settings.Default.StartUpPanelName) + ? Settings.Default.StartUpPanelName + : Language.strNewPanel; + + var panelAdder = new PanelAdder(); + if (!panelAdder.DoesPanelExist(panelName)) + panelAdder.AddPanel(panelName); } private static void InitializeCredRepoFactories() @@ -226,35 +234,39 @@ namespace mRemoteNG.UI.Forms } private void OnApplicationSettingChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) - { - if (propertyChangedEventArgs.PropertyName != nameof(Settings.LockToolbars)) - return; + { + if (propertyChangedEventArgs.PropertyName != nameof(Settings.LockToolbars)) + return; - LockToolbarPositions(Settings.Default.LockToolbars); - } + LockToolbarPositions(Settings.Default.LockToolbars); + } - private void LockToolbarPositions(bool shouldBeLocked) - { - var toolbars = new ToolStrip[] { _quickConnectToolStrip, _multiSshToolStrip, _externalToolsToolStrip, msMain }; - foreach (var toolbar in toolbars) - { - toolbar.GripStyle = shouldBeLocked - ? ToolStripGripStyle.Hidden - : ToolStripGripStyle.Visible; - } - } + private void LockToolbarPositions(bool shouldBeLocked) + { + var toolbars = new ToolStrip[] + {_quickConnectToolStrip, _multiSshToolStrip, _externalToolsToolStrip, msMain}; + foreach (var toolbar in toolbars) + { + toolbar.GripStyle = shouldBeLocked + ? ToolStripGripStyle.Hidden + : ToolStripGripStyle.Visible; + } + } - private void ConnectionsServiceOnConnectionsLoaded(object sender, ConnectionsLoadedEventArgs connectionsLoadedEventArgs) + private void ConnectionsServiceOnConnectionsLoaded(object sender, + ConnectionsLoadedEventArgs connectionsLoadedEventArgs) { UpdateWindowTitle(); } - private void ConnectionsServiceOnConnectionsSaved(object sender, ConnectionsSavedEventArgs connectionsSavedEventArgs) + private void ConnectionsServiceOnConnectionsSaved(object sender, + ConnectionsSavedEventArgs connectionsSavedEventArgs) { if (connectionsSavedEventArgs.UsingDatabase) return; - _backupPruner.PruneBackupFiles(connectionsSavedEventArgs.ConnectionFileName, Settings.Default.BackupFileKeepCount); + _backupPruner.PruneBackupFiles(connectionsSavedEventArgs.ConnectionFileName, + Settings.Default.BackupFileKeepCount); } private void SetMenuDependencies() @@ -265,7 +277,7 @@ namespace mRemoteNG.UI.Forms viewMenu.TsExternalTools = _externalToolsToolStrip; viewMenu.TsQuickConnect = _quickConnectToolStrip; - viewMenu.TsMultiSsh = _multiSshToolStrip; + viewMenu.TsMultiSsh = _multiSshToolStrip; viewMenu.FullscreenHandler = Fullscreen; viewMenu.MainForm = this; @@ -278,35 +290,46 @@ namespace mRemoteNG.UI.Forms //Theming support private void ApplyTheme() - { - if (!_themeManager.ThemingActive) return; + { + if (!_themeManager.ThemingActive) + { + pnlDock.Theme = _themeManager.DefaultTheme.Theme; + return; + } - try - { + try + { // this will always throw when turning themes on from // the options menu. - pnlDock.Theme = _themeManager.ActiveTheme.Theme; - } - catch (Exception) - { - // intentionally ignore exception - } - - // Persist settings when rebuilding UI - try - { - vsToolStripExtender.SetStyle(msMain, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - vsToolStripExtender.SetStyle(_quickConnectToolStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - vsToolStripExtender.SetStyle(_externalToolsToolStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - vsToolStripExtender.SetStyle(_multiSshToolStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - tsContainer.TopToolStripPanel.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("CommandBarMenuDefault_Background"); - BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - } - catch (Exception ex) - { + pnlDock.Theme = _themeManager.ActiveTheme.Theme; + } + catch (Exception) + { + // intentionally ignore exception + } + + // Persist settings when rebuilding UI + try + { + vsToolStripExtender.SetStyle(msMain, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(_quickConnectToolStrip, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(_externalToolsToolStrip, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(_multiSshToolStrip, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + + if (!_themeManager.ActiveAndExtended) return; + tsContainer.TopToolStripPanel.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("CommandBarMenuDefault_Background"); + BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + } + catch (Exception ex) + { Runtime.MessageCollector.AddExceptionStackTrace("Error applying theme", ex, MessageClass.WarningMsg); - } + } } private void frmMain_Shown(object sender, EventArgs e) @@ -326,8 +349,11 @@ namespace mRemoteNG.UI.Forms Language.strAskUpdatesCommandAskLater }; - CTaskDialog.ShowTaskDialogBox(this, GeneralAppInfo.ProductName, Language.strAskUpdatesMainInstruction, string.Format(Language.strAskUpdatesContent, GeneralAppInfo.ProductName), - "", "", "", "", string.Join(" | ", commandButtons), ETaskDialogButtons.None, ESysIcons.Question, ESysIcons.Question); + CTaskDialog.ShowTaskDialogBox(this, GeneralAppInfo.ProductName, Language.strAskUpdatesMainInstruction, + string.Format(Language.strAskUpdatesContent, GeneralAppInfo.ProductName), + "", "", "", "", string.Join(" | ", commandButtons), ETaskDialogButtons.None, + ESysIcons.Question, + ESysIcons.Question); if (CTaskDialog.CommandButtonResult == 0 | CTaskDialog.CommandButtonResult == 1) { @@ -347,11 +373,16 @@ namespace mRemoteNG.UI.Forms if (!Settings.Default.CheckForUpdatesOnStartup) return; var nextUpdateCheck = Convert.ToDateTime( - Settings.Default.CheckForUpdatesLastCheck.Add( - TimeSpan.FromDays(Convert.ToDouble(Settings.Default.CheckForUpdatesFrequencyDays)))); + Settings.Default.CheckForUpdatesLastCheck.Add( + TimeSpan + .FromDays(Convert + .ToDouble(Settings + .Default + .CheckForUpdatesFrequencyDays)))); if (!Settings.Default.UpdatePending && DateTime.UtcNow <= nextUpdateCheck) return; - if (!IsHandleCreated) CreateHandle(); // Make sure the handle is created so that InvokeRequired returns the correct result + if (!IsHandleCreated) + CreateHandle(); // Make sure the handle is created so that InvokeRequired returns the correct result Startup.Instance.CheckForUpdate(); } @@ -369,270 +400,301 @@ namespace mRemoteNG.UI.Forms } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) - { + { if (!(Runtime.WindowList == null || Runtime.WindowList.Count == 0)) - { - var openConnections = 0; - foreach (BaseWindow window in Runtime.WindowList) + { + var openConnections = 0; + if (pnlDock.Contents.Count > 0) { - var connectionWindow = window as ConnectionWindow; - if (connectionWindow != null) - openConnections = openConnections + connectionWindow.TabController.TabPages.Count; + foreach (var dc in pnlDock.Contents) + { + if (!(dc is ConnectionWindow cw)) continue; + if (cw.Controls.Count < 1) continue; + if (!(cw.Controls[0] is DockPanel dp)) continue; + if (dp.Contents.Count > 0) + openConnections += dp.Contents.Count; + } } - if (openConnections > 0 && (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All | (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple & openConnections > 1) || Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Exit)) - { - var result = CTaskDialog.MessageBox(this, Application.ProductName, Language.strConfirmExitMainInstruction, "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); - if (CTaskDialog.VerificationChecked) - { + if (openConnections > 0 && + (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All | + (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple & + openConnections > 1) || Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Exit)) + { + var result = CTaskDialog.MessageBox(this, Application.ProductName, + Language.strConfirmExitMainInstruction, "", "", "", + Language.strCheckboxDoNotShowThisMessageAgain, + ETaskDialogButtons.YesNo, ESysIcons.Question, + ESysIcons.Question); + if (CTaskDialog.VerificationChecked) + { Settings.Default.ConfirmCloseConnection--; - } - if (result == DialogResult.No) - { - e.Cancel = true; - return; - } - } - } + } + + if (result == DialogResult.No) + { + e.Cancel = true; + return; + } + } + } _saveConnectionsOnEdit.Unsubscribe(); Shutdown.Cleanup(_quickConnectToolStrip, _externalToolsToolStrip, _multiSshToolStrip, this); - - IsClosing = true; + + IsClosing = true; if (Runtime.WindowList != null) - { + { foreach (BaseWindow window in Runtime.WindowList) - { - window.Close(); - } - } + { + window.Close(); + } + } Shutdown.StartUpdate(); - - Debug.Print("[END] - " + Convert.ToString(DateTime.Now, CultureInfo.InvariantCulture)); - } + + Debug.Print("[END] - " + Convert.ToString(DateTime.Now, CultureInfo.InvariantCulture)); + } + #endregion - + #region Timer - private void tmrAutoSave_Tick(object sender, EventArgs e) - { + + private void tmrAutoSave_Tick(object sender, EventArgs e) + { Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, "Doing AutoSave"); - Runtime.ConnectionsService.SaveConnectionsAsync(); - } + Runtime.ConnectionsService.SaveConnectionsAsync(); + } + #endregion - + #region Window Overrides and DockPanel Stuff + private void frmMain_ResizeBegin(object sender, EventArgs e) - { - _inSizeMove = true; - } + { + _inSizeMove = true; + } private void frmMain_Resize(object sender, EventArgs e) - { - if (WindowState == FormWindowState.Minimized) - { - if (!Settings.Default.MinimizeToTray) return; - if (Runtime.NotificationAreaIcon == null) - { - Runtime.NotificationAreaIcon = new NotificationAreaIcon(); - } - Hide(); - } - else - { - PreviousWindowState = WindowState; - } - } + { + if (WindowState == FormWindowState.Minimized) + { + if (!Settings.Default.MinimizeToTray) return; + if (Runtime.NotificationAreaIcon == null) + { + Runtime.NotificationAreaIcon = new NotificationAreaIcon(); + } + + Hide(); + } + else + { + PreviousWindowState = WindowState; + } + } private void frmMain_ResizeEnd(object sender, EventArgs e) - { - _inSizeMove = false; - // This handles activations from clicks that started a size/move operation - ActivateConnection(); - } - - protected override void WndProc(ref System.Windows.Forms.Message m) - { + { + _inSizeMove = false; + // This handles activations from clicks that started a size/move operation + ActivateConnection(); + } + + protected override void WndProc(ref System.Windows.Forms.Message m) + { // Listen for and handle operating system messages - try - { - // ReSharper disable once SwitchStatementMissingSomeCases - switch (m.Msg) - { - case NativeMethods.WM_MOUSEACTIVATE: - _inMouseActivate = true; - break; - case NativeMethods.WM_ACTIVATEAPP: - _inMouseActivate = false; - break; - case NativeMethods.WM_ACTIVATE: - // 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)) - ?? GetChildAtPoint(MousePosition); - if (controlThatWasClicked != null) - { - if (controlThatWasClicked is TreeView || - controlThatWasClicked is ComboBox || - controlThatWasClicked is TextBox || + try + { + // ReSharper disable once SwitchStatementMissingSomeCases + switch (m.Msg) + { + case NativeMethods.WM_MOUSEACTIVATE: + _inMouseActivate = true; + break; + case NativeMethods.WM_ACTIVATEAPP: + var candidateTabToFocus = FromChildHandle(NativeMethods.WindowFromPoint(MousePosition)) + ?? GetChildAtPoint(MousePosition); + + if (candidateTabToFocus is InterfaceControl) + { + candidateTabToFocus.Parent.Focus(); + } + + _inMouseActivate = false; + break; + case NativeMethods.WM_ACTIVATE: + // 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)) + ?? GetChildAtPoint(MousePosition); + if (controlThatWasClicked != null) + { + if (controlThatWasClicked is TreeView || + controlThatWasClicked is ComboBox || + controlThatWasClicked is TextBox || controlThatWasClicked is FrmMain) - { - controlThatWasClicked.Focus(); - } - else if (controlThatWasClicked.CanSelect || - controlThatWasClicked is MenuStrip || - controlThatWasClicked is ToolStrip || - controlThatWasClicked is Crownwood.Magic.Controls.TabControl || - controlThatWasClicked is Crownwood.Magic.Controls.InertButton) - { + { + controlThatWasClicked.Focus(); + } + else if (controlThatWasClicked.CanSelect || + controlThatWasClicked is MenuStrip || + controlThatWasClicked is ToolStrip) + { // Simulate a mouse event since one wasn't generated by Windows SimulateClick(controlThatWasClicked); controlThatWasClicked.Focus(); } else if (controlThatWasClicked is AutoHideStripBase) - { + { // only focus the autohide toolstrip controlThatWasClicked.Focus(); - } - else - { - // This handles activations from clicks that did not start a size/move operation - ActivateConnection(); - } - } - } - break; - case NativeMethods.WM_WINDOWPOSCHANGED: - // Ignore this message if the window wasn't activated - var windowPos = (NativeMethods.WINDOWPOS)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.WINDOWPOS)); - if ((windowPos.flags & NativeMethods.SWP_NOACTIVATE) == 0) - { - if (!_inMouseActivate && !_inSizeMove) - ActivateConnection(); - } - break; - case NativeMethods.WM_SYSCOMMAND: - var screen = _screenSystemMenu.GetScreenById(m.WParam.ToInt32()); + } + else + { + // This handles activations from clicks that did not start a size/move operation + ActivateConnection(); + } + } + } + + break; + case NativeMethods.WM_WINDOWPOSCHANGED: + // Ignore this message if the window wasn't activated + var windowPos = + (NativeMethods.WINDOWPOS)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.WINDOWPOS)); + if ((windowPos.flags & NativeMethods.SWP_NOACTIVATE) == 0) + { + if (!_inMouseActivate && !_inSizeMove) + ActivateConnection(); + } + + break; + case NativeMethods.WM_SYSCOMMAND: + var screen = _screenSystemMenu.GetScreenById(m.WParam.ToInt32()); if (screen != null) Screens.SendFormToScreen(screen); - break; - case NativeMethods.WM_DRAWCLIPBOARD: - NativeMethods.SendMessage(_fpChainedWindowHandle, m.Msg, m.LParam, m.WParam); - _clipboardChangedEvent?.Invoke(); - break; - case NativeMethods.WM_CHANGECBCHAIN: - //Send to the next window - NativeMethods.SendMessage(_fpChainedWindowHandle, m.Msg, m.LParam, m.WParam); - _fpChainedWindowHandle = m.LParam; - break; - } - } - catch (Exception ex) - { + break; + case NativeMethods.WM_DRAWCLIPBOARD: + NativeMethods.SendMessage(_fpChainedWindowHandle, m.Msg, m.LParam, m.WParam); + _clipboardChangedEvent?.Invoke(); + break; + case NativeMethods.WM_CHANGECBCHAIN: + //Send to the next window + NativeMethods.SendMessage(_fpChainedWindowHandle, m.Msg, m.LParam, m.WParam); + _fpChainedWindowHandle = m.LParam; + break; + } + } + catch (Exception ex) + { Runtime.MessageCollector.AddExceptionStackTrace("frmMain WndProc failed", ex); } - - base.WndProc(ref m); - } + + base.WndProc(ref m); + } private void SimulateClick(Control control) { var clientMousePosition = control.PointToClient(MousePosition); var temp_wLow = clientMousePosition.X; var temp_wHigh = clientMousePosition.Y; - NativeMethods.SendMessage(control.Handle, NativeMethods.WM_LBUTTONDOWN, (IntPtr)NativeMethods.MK_LBUTTON, (IntPtr)NativeMethods.MAKELPARAM(ref temp_wLow, ref temp_wHigh)); + NativeMethods.SendMessage(control.Handle, NativeMethods.WM_LBUTTONDOWN, (IntPtr)NativeMethods.MK_LBUTTON, + (IntPtr)NativeMethods.MAKELPARAM(ref temp_wLow, ref temp_wHigh)); clientMousePosition.X = temp_wLow; clientMousePosition.Y = temp_wHigh; } - private void ActivateConnection() - { - var w = pnlDock.ActiveDocument as ConnectionWindow; - if (w?.TabController.SelectedTab == null) return; - var tab = w.TabController.SelectedTab; - var ifc = (InterfaceControl)tab.Tag; + private void ActivateConnection() + { + var cw = pnlDock.ActiveDocument as ConnectionWindow; + var dp = cw?.ActiveControl as DockPane; - if (ifc == null) return; + if (!(dp?.ActiveContent is ConnectionTab tab)) return; + var ifc = InterfaceControl.FindInterfaceControl(tab); + if (ifc == null) return; - ifc.Protocol.Focus(); - ((ConnectionWindow) ifc.FindForm())?.RefreshInterfaceController(); - } + ifc.Protocol.Focus(); + var conFormWindow = ifc.FindForm(); + ((ConnectionTab)conFormWindow)?.RefreshInterfaceController(); + } private void pnlDock_ActiveDocumentChanged(object sender, EventArgs e) - { - ActivateConnection(); - var connectionWindow = pnlDock.ActiveDocument as ConnectionWindow; - connectionWindow?.UpdateSelectedConnection(); - } - - internal void UpdateWindowTitle() - { - if (InvokeRequired) - { - Invoke(new MethodInvoker(UpdateWindowTitle)); - return; - } - - var titleBuilder = new StringBuilder(Application.ProductName); - const string separator = " - "; - - if (Runtime.ConnectionsService.IsConnectionsFileLoaded) - { - if (Runtime.ConnectionsService.UsingDatabase) - { - titleBuilder.Append(separator); - titleBuilder.Append(Language.strSQLServer.TrimEnd(':')); - } - else - { - if (!string.IsNullOrEmpty(Runtime.ConnectionsService.ConnectionFileName)) - { - titleBuilder.Append(separator); - titleBuilder.Append(Settings.Default.ShowCompleteConsPathInTitle - ? Runtime.ConnectionsService.ConnectionFileName - : Path.GetFileName(Runtime.ConnectionsService.ConnectionFileName)); - } - } - } - - if (!string.IsNullOrEmpty(SelectedConnection?.Name)) - { - titleBuilder.Append(separator); - titleBuilder.Append(SelectedConnection.Name); + { + ActivateConnection(); + } + + internal void UpdateWindowTitle() + { + if (InvokeRequired) + { + Invoke(new MethodInvoker(UpdateWindowTitle)); + return; + } + + var titleBuilder = new StringBuilder(Application.ProductName); + const string separator = " - "; + + if (Runtime.ConnectionsService.IsConnectionsFileLoaded) + { + if (Runtime.ConnectionsService.UsingDatabase) + { + titleBuilder.Append(separator); + titleBuilder.Append(Language.strSQLServer.TrimEnd(':')); + } + else + { + if (!string.IsNullOrEmpty(Runtime.ConnectionsService.ConnectionFileName)) + { + titleBuilder.Append(separator); + titleBuilder.Append(Settings.Default.ShowCompleteConsPathInTitle + ? Runtime.ConnectionsService.ConnectionFileName + : Path.GetFileName(Runtime.ConnectionsService.ConnectionFileName)); + } + } + } + + if (!string.IsNullOrEmpty(SelectedConnection?.Name)) + { + titleBuilder.Append(separator); + titleBuilder.Append(SelectedConnection.Name); if (Settings.Default.TrackActiveConnectionInConnectionTree) Windows.TreeForm.JumpToNode(SelectedConnection); - } + } Text = titleBuilder.ToString(); - } - - public void ShowHidePanelTabs(DockContent closingDocument = null) - { - DocumentStyle newDocumentStyle; - - if (Settings.Default.AlwaysShowPanelTabs) - { - newDocumentStyle = DocumentStyle.DockingWindow; // Show the panel tabs - } - else - { - var nonConnectionPanelCount = 0; - foreach (var dockContent in pnlDock.Documents) - { - var document = (DockContent) dockContent; - if ((closingDocument == null || document != closingDocument) && !(document is ConnectionWindow)) - { - nonConnectionPanelCount++; - } - } + } - newDocumentStyle = nonConnectionPanelCount == 0 ? DocumentStyle.DockingSdi : DocumentStyle.DockingWindow; - } + public void ShowHidePanelTabs(DockContent closingDocument = null) + { + DocumentStyle newDocumentStyle; - foreach (var dockContent in pnlDock.Documents) + if (Settings.Default.AlwaysShowPanelTabs) + { + newDocumentStyle = DocumentStyle.DockingWindow; // Show the panel tabs + } + else + { + var nonConnectionPanelCount = 0; + foreach (var dockContent in pnlDock.Documents) + { + var document = (DockContent)dockContent; + if ((closingDocument == null || document != closingDocument) && !(document is ConnectionWindow)) + { + nonConnectionPanelCount++; + } + } + + newDocumentStyle = nonConnectionPanelCount == 0 + ? DocumentStyle.DockingSdi + : DocumentStyle.DockingWindow; + } + + // TODO: See if we can get this to work with DPS +#if false + foreach (var dockContent in pnlDock.Documents) { var document = (DockContent)dockContent; if (document is ConnectionWindow) @@ -648,42 +710,17 @@ namespace mRemoteNG.UI.Forms } } } - - if (pnlDock.DocumentStyle == newDocumentStyle) return; - pnlDock.DocumentStyle = newDocumentStyle; - pnlDock.Size = new Size(1, 1); - } - -#if false - private void SelectTabRelative(int relativeIndex) - { - if (!(pnlDock.ActiveDocument is ConnectionWindow)) - { - return; - } - - var connectionWindow = (ConnectionWindow)pnlDock.ActiveDocument; - var tabController = connectionWindow.TabController; - - var newIndex = tabController.SelectedIndex + relativeIndex; - while (newIndex < 0 | newIndex >= tabController.TabPages.Count) - { - if (newIndex < 0) - { - newIndex = tabController.TabPages.Count + newIndex; - } - if (newIndex >= tabController.TabPages.Count) - { - newIndex = newIndex - tabController.TabPages.Count; - } - } - - tabController.SelectedIndex = newIndex; - } #endif + + if (pnlDock.DocumentStyle == newDocumentStyle) return; + pnlDock.DocumentStyle = newDocumentStyle; + pnlDock.Size = new Size(1, 1); + } + #endregion - + #region Screen Stuff + public void SetDefaultLayout() { pnlDock.Visible = false; @@ -693,23 +730,37 @@ namespace mRemoteNG.UI.Forms pnlDock.DockTopPortion = pnlDock.Height * 0.25; pnlDock.DockBottomPortion = pnlDock.Height * 0.25; + Windows.TreeForm.DockAreas = DockAreas.DockBottom | DockAreas.DockLeft | DockAreas.DockRight | + DockAreas.DockTop | DockAreas.Float; Windows.TreeForm.Show(pnlDock, DockState.DockLeft); + Windows.ConfigForm.DockAreas = DockAreas.DockBottom | DockAreas.DockLeft | DockAreas.DockRight | + DockAreas.DockTop | DockAreas.Float; Windows.ConfigForm.Show(pnlDock); Windows.ConfigForm.DockTo(Windows.TreeForm.Pane, DockStyle.Bottom, -1); - Windows.ErrorsForm.Show( pnlDock, DockState.DockBottomAutoHide ); - Windows.ScreenshotForm.Hide(); + Windows.ErrorsForm.DockAreas = DockAreas.DockBottom | DockAreas.DockLeft | DockAreas.DockRight | + DockAreas.DockTop | DockAreas.Float; + Windows.ErrorsForm.Show(pnlDock, DockState.DockBottomAutoHide); + Windows.ScreenshotForm.Hide(); pnlDock.Visible = true; } + #endregion #region Events + public delegate void ClipboardchangeEventHandler(); + public static event ClipboardchangeEventHandler ClipboardChanged { - add => _clipboardChangedEvent = (ClipboardchangeEventHandler)Delegate.Combine(_clipboardChangedEvent, value); - remove => _clipboardChangedEvent = (ClipboardchangeEventHandler)Delegate.Remove(_clipboardChangedEvent, value); + add => + _clipboardChangedEvent = + (ClipboardchangeEventHandler)Delegate.Combine(_clipboardChangedEvent, value); + remove => + _clipboardChangedEvent = + (ClipboardchangeEventHandler)Delegate.Remove(_clipboardChangedEvent, value); } + #endregion private void ViewMenu_Opening(object sender, EventArgs e) diff --git a/mRemoteV1/UI/Forms/frmOptions.Designer.cs b/mRemoteV1/UI/Forms/frmOptions.Designer.cs index 7371c779..a2163b13 100644 --- a/mRemoteV1/UI/Forms/frmOptions.Designer.cs +++ b/mRemoteV1/UI/Forms/frmOptions.Designer.cs @@ -30,6 +30,7 @@ { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmOptions)); this.pnlBottom = new System.Windows.Forms.Panel(); + this.btnApply = new mRemoteNG.UI.Controls.Base.NGButton(); this.btnCancel = new mRemoteNG.UI.Controls.Base.NGButton(); this.btnOK = new mRemoteNG.UI.Controls.Base.NGButton(); this.splitter1 = new System.Windows.Forms.Splitter(); @@ -43,6 +44,7 @@ // // pnlBottom // + this.pnlBottom.Controls.Add(this.btnApply); this.pnlBottom.Controls.Add(this.btnCancel); this.pnlBottom.Controls.Add(this.btnOK); this.pnlBottom.Dock = System.Windows.Forms.DockStyle.Bottom; @@ -51,11 +53,22 @@ this.pnlBottom.Size = new System.Drawing.Size(764, 35); this.pnlBottom.TabIndex = 0; // + // btnApply + // + this.btnApply._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.OUT; + this.btnApply.Location = new System.Drawing.Point(677, 5); + this.btnApply.Name = "btnApply"; + this.btnApply.Size = new System.Drawing.Size(75, 23); + this.btnApply.TabIndex = 2; + this.btnApply.Text = "Apply"; + this.btnApply.UseVisualStyleBackColor = true; + this.btnApply.Click += new System.EventHandler(this.btnOK_Click); + // // btnCancel // - this.btnCancel._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.HOVER; + this.btnCancel._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.OUT; this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.btnCancel.Location = new System.Drawing.Point(681, 6); + this.btnCancel.Location = new System.Drawing.Point(596, 5); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 1; @@ -65,9 +78,9 @@ // // btnOK // - this.btnOK._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.HOVER; + this.btnOK._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.OUT; this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; - this.btnOK.Location = new System.Drawing.Point(600, 6); + this.btnOK.Location = new System.Drawing.Point(515, 5); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 23); this.btnOK.TabIndex = 0; @@ -111,6 +124,7 @@ this.lstOptionPages.Cursor = System.Windows.Forms.Cursors.Default; this.lstOptionPages.DecorateLines = true; this.lstOptionPages.Dock = System.Windows.Forms.DockStyle.Left; + this.lstOptionPages.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lstOptionPages.FullRowSelect = true; this.lstOptionPages.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.lstOptionPages.HideSelection = false; @@ -172,5 +186,6 @@ private Controls.Base.NGButton btnOK; private Controls.Base.NGButton btnCancel; private BrightIdeasSoftware.OLVColumn PageName; + private Controls.Base.NGButton btnApply; } } \ No newline at end of file diff --git a/mRemoteV1/UI/Forms/frmOptions.cs b/mRemoteV1/UI/Forms/frmOptions.cs index 0b0bee9f..e9e2b0ec 100644 --- a/mRemoteV1/UI/Forms/frmOptions.cs +++ b/mRemoteV1/UI/Forms/frmOptions.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.Linq; using System.Windows.Forms; using mRemoteNG.App; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Forms { @@ -14,7 +15,7 @@ namespace mRemoteNG.UI.Forms private readonly string _pageName; private readonly DisplayProperties _display = new DisplayProperties(); - public FrmOptions(): this(Language.strStartupExit) + public FrmOptions() : this(Language.strStartupExit) { } @@ -33,20 +34,24 @@ namespace mRemoteNG.UI.Forms FontOverrider.FontOverride(this); AddOptionsPagesToListView(); SetInitiallyActivatedPage(); - ApplyLanguage(); + // ApplyLanguage(); + // Handle the main page here and the individual pages in + // AddOptionsPagesToListView() -- one less foreach loop.... + Text = Language.strOptionsPageTitle; ApplyTheme(); - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + ThemeManager.getInstance().ThemeChanged += ApplyTheme; lstOptionPages.SelectedIndexChanged += LstOptionPages_SelectedIndexChanged; lstOptionPages.SelectedIndex = 0; } private void ApplyTheme() { - if (!Themes.ThemeManager.getInstance().ThemingActive) return; - BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + if (!ThemeManager.getInstance().ActiveAndExtended) return; + BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } +#if false private void ApplyLanguage() { Text = Language.strOptionsPageTitle; @@ -55,7 +60,7 @@ namespace mRemoteNG.UI.Forms optionPage.ApplyLanguage(); } } - +#endif private void CompileListOfOptionsPages() { _pages = new Dictionary @@ -81,6 +86,7 @@ namespace mRemoteNG.UI.Forms foreach (var page in _pages.Select(keyValuePair => keyValuePair.Value)) { + page.ApplyLanguage(); page.LoadSettings(); lstOptionPages.AddObject(page); } @@ -103,10 +109,15 @@ namespace mRemoteNG.UI.Forms break; } - if(!isSet) + if (!isSet) lstOptionPages.Items[0].Selected = true; } + /* + * This gets called by both OK and Apply buttons. + * OK sets DialogResult = OK, Apply does not (None). + * Apply will no close the dialog. + */ private void btnOK_Click(object sender, EventArgs e) { foreach (var page in _pages.Values) @@ -114,6 +125,7 @@ namespace mRemoteNG.UI.Forms Debug.WriteLine(page.PageName); page.SaveSettings(); } + Debug.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); Settings.Default.Save(); } @@ -135,7 +147,8 @@ namespace mRemoteNG.UI.Forms Debug.WriteLine(page.PageName); page.RevertSettings(); } - Debug.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); + + Debug.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); } } } \ No newline at end of file diff --git a/mRemoteV1/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs b/mRemoteV1/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs index d6fdc481..074093c0 100644 --- a/mRemoteV1/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs +++ b/mRemoteV1/UI/GraphicsUtilities/GdiPlusGraphicsProvider.cs @@ -11,12 +11,16 @@ namespace mRemoteNG.UI.GraphicsUtilities // Dpi of a 'normal' definition screen private const int BaselineDpi = 96; + public SizeF GetResolutionScalingFactor() { - using (var g = new Form().CreateGraphics()) + //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()) { + var g = f.CreateGraphics(); return new SizeF(g.DpiX / BaselineDpi, g.DpiY / BaselineDpi); } } } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/GraphicsUtilities/IGraphicsProvider.cs b/mRemoteV1/UI/GraphicsUtilities/IGraphicsProvider.cs index 918a5b7e..ac9451a3 100644 --- a/mRemoteV1/UI/GraphicsUtilities/IGraphicsProvider.cs +++ b/mRemoteV1/UI/GraphicsUtilities/IGraphicsProvider.cs @@ -6,4 +6,4 @@ namespace mRemoteNG.UI.GraphicsUtilities { SizeF GetResolutionScalingFactor(); } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Menu/HelpMenu.cs b/mRemoteV1/UI/Menu/HelpMenu.cs index 74db6e2f..ec4eb70b 100644 --- a/mRemoteV1/UI/Menu/HelpMenu.cs +++ b/mRemoteV1/UI/Menu/HelpMenu.cs @@ -40,17 +40,19 @@ namespace mRemoteNG.UI.Menu // // mMenInfo // - DropDownItems.AddRange(new ToolStripItem[] { - _mMenInfoHelp, - _mMenInfoSep1, - _mMenInfoWebsite, - _mMenInfoDonate, - _mMenInfoForum, - _mMenInfoBugReport, - _toolStripSeparator2, - _mMenToolsUpdate, - _mMenInfoSep2, - _mMenInfoAbout}); + DropDownItems.AddRange(new ToolStripItem[] + { + _mMenInfoHelp, + _mMenInfoSep1, + _mMenInfoWebsite, + _mMenInfoDonate, + _mMenInfoForum, + _mMenInfoBugReport, + _toolStripSeparator2, + _mMenToolsUpdate, + _mMenInfoSep2, + _mMenInfoAbout + }); Name = "mMenInfo"; Size = new System.Drawing.Size(44, 20); Text = Language.strMenuHelp; @@ -142,6 +144,7 @@ namespace mRemoteNG.UI.Menu } #region Info + private void mMenToolsUpdate_Click(object sender, EventArgs e) => Windows.Show(WindowType.Update); private void mMenInfoHelp_Click(object sender, EventArgs e) => Windows.Show(WindowType.Help); @@ -155,6 +158,7 @@ namespace mRemoteNG.UI.Menu private void mMenInfoDonate_Click(object sender, EventArgs e) => Process.Start(GeneralAppInfo.UrlDonate); private void mMenInfoAbout_Click(object sender, EventArgs e) => Windows.Show(WindowType.About); + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Menu/MainFileMenu.cs b/mRemoteV1/UI/Menu/MainFileMenu.cs index e656e95c..49ac393f 100644 --- a/mRemoteV1/UI/Menu/MainFileMenu.cs +++ b/mRemoteV1/UI/Menu/MainFileMenu.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using mRemoteNG.App; @@ -71,7 +70,8 @@ namespace mRemoteNG.UI.Menu // // mMenFile // - DropDownItems.AddRange(new ToolStripItem[] { + DropDownItems.AddRange(new ToolStripItem[] + { _mMenFileNewConnection, _mMenFileNewFolder, _mMenFileSep1, @@ -111,7 +111,7 @@ namespace mRemoteNG.UI.Menu _mMenFileNewFolder.Image = Resources.Folder_Add; _mMenFileNewFolder.Name = "mMenFileNewFolder"; _mMenFileNewFolder.ShortcutKeys = (Keys.Control | Keys.Shift) - | Keys.N; + | Keys.N; _mMenFileNewFolder.Size = new System.Drawing.Size(281, 22); _mMenFileNewFolder.Text = Language.strNewFolder; _mMenFileNewFolder.Click += mMenFileNewFolder_Click; @@ -152,7 +152,7 @@ namespace mRemoteNG.UI.Menu _mMenFileSaveAs.Image = Resources.Connections_SaveAs; _mMenFileSaveAs.Name = "mMenFileSaveAs"; _mMenFileSaveAs.ShortcutKeys = (Keys.Control | Keys.Shift) - | Keys.S; + | Keys.S; _mMenFileSaveAs.Size = new System.Drawing.Size(281, 22); _mMenFileSaveAs.Text = Language.strMenuSaveConnectionFileAs; _mMenFileSaveAs.Click += mMenFileSaveAs_Click; @@ -206,10 +206,12 @@ namespace mRemoteNG.UI.Menu // // mMenFileImport // - _mMenFileImport.DropDownItems.AddRange(new ToolStripItem[] { - _mMenFileImportFromFile, - _mMenFileImportFromActiveDirectory, - _mMenFileImportFromPortScan}); + _mMenFileImport.DropDownItems.AddRange(new ToolStripItem[] + { + _mMenFileImportFromFile, + _mMenFileImportFromActiveDirectory, + _mMenFileImportFromPortScan + }); _mMenFileImport.Name = "mMenFileImport"; _mMenFileImport.Size = new System.Drawing.Size(281, 22); _mMenFileImport.Text = Language.strImportMenuItem; @@ -275,6 +277,7 @@ namespace mRemoteNG.UI.Menu } #region File + internal void mMenFile_DropDownOpening(object sender, EventArgs e) { var selectedNodeType = TreeWindow.SelectedNode?.GetTreeNodeType(); @@ -382,7 +385,8 @@ namespace mRemoteNG.UI.Menu { if (Runtime.ConnectionsService.IsConnectionsFileLoaded) { - var msgBoxResult = MessageBox.Show(Language.strSaveConnectionsFileBeforeOpeningAnother, Language.strSave, MessageBoxButtons.YesNoCancel); + var msgBoxResult = MessageBox.Show(Language.strSaveConnectionsFileBeforeOpeningAnother, + Language.strSave, MessageBoxButtons.YesNoCancel); // ReSharper disable once SwitchStatementMissingSomeCases switch (msgBoxResult) { @@ -411,7 +415,8 @@ namespace mRemoteNG.UI.Menu var newFileName = saveFileDialog.FileName; - Runtime.ConnectionsService.SaveConnections(Runtime.ConnectionsService.ConnectionTreeModel, false, new SaveFilter(), newFileName); + Runtime.ConnectionsService.SaveConnections(Runtime.ConnectionsService.ConnectionTreeModel, false, + new SaveFilter(), newFileName); if (newFileName == Runtime.ConnectionsService.GetDefaultStartupConnectionFileName()) { @@ -448,24 +453,7 @@ namespace mRemoteNG.UI.Menu if (!(window is ConnectionWindow connectionWindow)) return; - var icList = new List(); - foreach (Crownwood.Magic.Controls.TabPage tab in connectionWindow.TabController.TabPages) - { - if (tab.Tag is InterfaceControl tag) - { - icList.Add(tag); - } - } - - foreach (var i in icList) - { - i.Protocol.Close(); - ConnectionInitiator.OpenConnection(i.Info, ConnectionInfo.Force.DoNotJump); - } - - // throw it on the garbage collector - // ReSharper disable once RedundantAssignment - icList = null; + connectionWindow.reconnectAll(ConnectionInitiator); } } @@ -499,6 +487,7 @@ namespace mRemoteNG.UI.Menu { Shutdown.Quit(); } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Menu/ScreenSelectionSystemMenu.cs b/mRemoteV1/UI/Menu/ScreenSelectionSystemMenu.cs index 749961f8..9aaa455f 100644 --- a/mRemoteV1/UI/Menu/ScreenSelectionSystemMenu.cs +++ b/mRemoteV1/UI/Menu/ScreenSelectionSystemMenu.cs @@ -22,6 +22,7 @@ namespace mRemoteNG.UI.Menu if (_sysMenSubItems[i] != id) continue; return Screen.AllScreens[i]; } + return null; } @@ -43,11 +44,16 @@ namespace mRemoteNG.UI.Menu for (var i = 0; i <= Screen.AllScreens.Length - 1; i++) { _sysMenSubItems[i] = 200 + i; - _systemMenu.AppendMenuItem(popMen, SystemMenu.Flags.MF_STRING, new IntPtr(_sysMenSubItems[i]), Language.strScreen + " " + Convert.ToString(i + 1)); + _systemMenu.AppendMenuItem(popMen, SystemMenu.Flags.MF_STRING, new IntPtr(_sysMenSubItems[i]), + Language.strScreen + " " + Convert.ToString(i + 1)); } - _systemMenu.InsertMenuItem(_systemMenu.SystemMenuHandle, 0, SystemMenu.Flags.MF_POPUP | SystemMenu.Flags.MF_BYPOSITION, popMen, Language.strSendTo); - _systemMenu.InsertMenuItem(_systemMenu.SystemMenuHandle, 1, SystemMenu.Flags.MF_BYPOSITION | SystemMenu.Flags.MF_SEPARATOR, IntPtr.Zero, null); + _systemMenu.InsertMenuItem(_systemMenu.SystemMenuHandle, 0, + SystemMenu.Flags.MF_POPUP | SystemMenu.Flags.MF_BYPOSITION, popMen, + Language.strSendTo); + _systemMenu.InsertMenuItem(_systemMenu.SystemMenuHandle, 1, + SystemMenu.Flags.MF_BYPOSITION | SystemMenu.Flags.MF_SEPARATOR, IntPtr.Zero, + null); } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Menu/ToolsMenu.cs b/mRemoteV1/UI/Menu/ToolsMenu.cs index bae6a547..f77be44e 100644 --- a/mRemoteV1/UI/Menu/ToolsMenu.cs +++ b/mRemoteV1/UI/Menu/ToolsMenu.cs @@ -7,7 +7,7 @@ using mRemoteNG.UI.Forms.CredentialManager; namespace mRemoteNG.UI.Menu { - public class ToolsMenu : ToolStripMenuItem + public class ToolsMenu : ToolStripMenuItem { private ToolStripSeparator _mMenToolsSep1; private ToolStripMenuItem _mMenToolsOptions; @@ -42,7 +42,8 @@ namespace mRemoteNG.UI.Menu // // mMenTools // - DropDownItems.AddRange(new ToolStripItem[] { + DropDownItems.AddRange(new ToolStripItem[] + { _credentialManagerToolStripMenuItem, _mMenToolsSshTransfer, _mMenToolsUvncsc, @@ -51,7 +52,8 @@ namespace mRemoteNG.UI.Menu _mMenViewScreenshotManager, _mMenToolsSep1, _mMenToolsComponentsCheck, - _mMenToolsOptions}); + _mMenToolsOptions + }); Name = "mMenTools"; Size = new System.Drawing.Size(48, 20); Text = Language.strMenuTools; @@ -180,6 +182,7 @@ namespace mRemoteNG.UI.Menu { Windows.Show(WindowType.Options); } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Menu/ViewMenu.cs b/mRemoteV1/UI/Menu/ViewMenu.cs index 38b294d7..e9cb01d5 100644 --- a/mRemoteV1/UI/Menu/ViewMenu.cs +++ b/mRemoteV1/UI/Menu/ViewMenu.cs @@ -7,7 +7,7 @@ using mRemoteNG.UI.Window; namespace mRemoteNG.UI.Menu { - public class ViewMenu : ToolStripMenuItem + public class ViewMenu : ToolStripMenuItem { private ToolStripMenuItem _mMenViewConnectionPanels; private ToolStripSeparator _mMenViewSep1; @@ -28,11 +28,11 @@ namespace mRemoteNG.UI.Menu private ToolStripMenuItem _mMenViewLockToolbars; private ToolStripSeparator _toolStripSeparator1; private readonly PanelAdder _panelAdder; - - public ToolStrip TsExternalTools { get; set; } + + public ToolStrip TsExternalTools { get; set; } public ToolStrip TsQuickConnect { get; set; } - public ToolStrip TsMultiSsh { get; set; } + public ToolStrip TsMultiSsh { get; set; } public FullscreenHandler FullscreenHandler { get; set; } public FrmMain MainForm { get; set; } @@ -41,7 +41,7 @@ namespace mRemoteNG.UI.Menu { Initialize(); _panelAdder = new PanelAdder(); - } + } private void Initialize() { @@ -55,35 +55,37 @@ namespace mRemoteNG.UI.Menu _mMenViewJumpToConnectionsConfig = new ToolStripMenuItem(); _mMenViewJumpToErrorsInfos = new ToolStripMenuItem(); _mMenViewResetLayout = new ToolStripMenuItem(); - _mMenViewLockToolbars = new ToolStripMenuItem(); + _mMenViewLockToolbars = new ToolStripMenuItem(); _mMenViewSep2 = new ToolStripSeparator(); _mMenViewQuickConnectToolbar = new ToolStripMenuItem(); _mMenViewExtAppsToolbar = new ToolStripMenuItem(); - _mMenViewMultiSshToolbar = new ToolStripMenuItem(); - _mMenViewSep3 = new ToolStripSeparator(); + _mMenViewMultiSshToolbar = new ToolStripMenuItem(); + _mMenViewSep3 = new ToolStripSeparator(); _mMenViewFullscreen = new ToolStripMenuItem(); _toolStripSeparator1 = new ToolStripSeparator(); // // mMenView // - DropDownItems.AddRange(new ToolStripItem[] { - _mMenViewAddConnectionPanel, - _mMenViewConnectionPanels, - _mMenViewSep1, - _mMenViewConnections, - _mMenViewConfig, - _mMenViewErrorsAndInfos, - _toolStripSeparator1, - _mMenViewJumpTo, - _mMenViewResetLayout, - _mMenViewLockToolbars, - _mMenViewSep2, - _mMenViewQuickConnectToolbar, - _mMenViewExtAppsToolbar, - _mMenViewMultiSshToolbar, - _mMenViewSep3, - _mMenViewFullscreen}); + DropDownItems.AddRange(new ToolStripItem[] + { + _mMenViewAddConnectionPanel, + _mMenViewConnectionPanels, + _mMenViewSep1, + _mMenViewConnections, + _mMenViewConfig, + _mMenViewErrorsAndInfos, + _toolStripSeparator1, + _mMenViewJumpTo, + _mMenViewResetLayout, + _mMenViewLockToolbars, + _mMenViewSep2, + _mMenViewQuickConnectToolbar, + _mMenViewExtAppsToolbar, + _mMenViewMultiSshToolbar, + _mMenViewSep3, + _mMenViewFullscreen + }); Name = "mMenView"; Size = new System.Drawing.Size(44, 20); Text = Language.strMenuView; @@ -146,9 +148,11 @@ namespace mRemoteNG.UI.Menu // // mMenViewJumpTo // - _mMenViewJumpTo.DropDownItems.AddRange(new ToolStripItem[] { - _mMenViewJumpToConnectionsConfig, - _mMenViewJumpToErrorsInfos}); + _mMenViewJumpTo.DropDownItems.AddRange(new ToolStripItem[] + { + _mMenViewJumpToConnectionsConfig, + _mMenViewJumpToErrorsInfos + }); _mMenViewJumpTo.Image = Resources.JumpTo; _mMenViewJumpTo.Name = "mMenViewJumpTo"; _mMenViewJumpTo.Size = new System.Drawing.Size(228, 22); @@ -179,18 +183,18 @@ namespace mRemoteNG.UI.Menu _mMenViewResetLayout.Size = new System.Drawing.Size(228, 22); _mMenViewResetLayout.Text = Language.strMenuResetLayout; _mMenViewResetLayout.Click += mMenViewResetLayout_Click; - // - // mMenViewLockToolbars - // - _mMenViewLockToolbars.Image = Resources.application_side_tree; - _mMenViewLockToolbars.Name = "mMenViewLockToolbars"; - _mMenViewLockToolbars.Size = new System.Drawing.Size(228, 22); - _mMenViewLockToolbars.Text = Language.strMenuLockToolbars; + // + // mMenViewLockToolbars + // + _mMenViewLockToolbars.Image = Resources.application_side_tree; + _mMenViewLockToolbars.Name = "mMenViewLockToolbars"; + _mMenViewLockToolbars.Size = new System.Drawing.Size(228, 22); + _mMenViewLockToolbars.Text = Language.strMenuLockToolbars; _mMenViewLockToolbars.Click += mMenViewLockToolbars_Click; - // - // mMenViewSep2 - // - _mMenViewSep2.Name = "mMenViewSep2"; + // + // mMenViewSep2 + // + _mMenViewSep2.Name = "mMenViewSep2"; _mMenViewSep2.Size = new System.Drawing.Size(225, 6); // // mMenViewQuickConnectToolbar @@ -208,18 +212,18 @@ namespace mRemoteNG.UI.Menu _mMenViewExtAppsToolbar.Size = new System.Drawing.Size(228, 22); _mMenViewExtAppsToolbar.Text = Language.strMenuExternalToolsToolbar; _mMenViewExtAppsToolbar.Click += mMenViewExtAppsToolbar_Click; - // - // mMenViewMultiSSHToolbar - // - _mMenViewMultiSshToolbar.Image = Resources.Panels; - _mMenViewMultiSshToolbar.Name = "mMenViewMultiSSHToolbar"; - _mMenViewMultiSshToolbar.Size = new System.Drawing.Size(279, 26); - _mMenViewMultiSshToolbar.Text = Language.strMenuMultiSshToolbar; + // + // mMenViewMultiSSHToolbar + // + _mMenViewMultiSshToolbar.Image = Resources.Panels; + _mMenViewMultiSshToolbar.Name = "mMenViewMultiSSHToolbar"; + _mMenViewMultiSshToolbar.Size = new System.Drawing.Size(279, 26); + _mMenViewMultiSshToolbar.Text = Language.strMenuMultiSshToolbar; _mMenViewMultiSshToolbar.Click += mMenViewMultiSSHToolbar_Click; - // - // mMenViewSep3 - // - _mMenViewSep3.Name = "mMenViewSep3"; + // + // mMenViewSep3 + // + _mMenViewSep3.Name = "mMenViewSep3"; _mMenViewSep3.Size = new System.Drawing.Size(225, 6); // // mMenViewFullscreen @@ -233,9 +237,8 @@ namespace mRemoteNG.UI.Menu _mMenViewFullscreen.Click += mMenViewFullscreen_Click; } - - public void ApplyLanguage() + public void ApplyLanguage() { Text = Language.strMenuView; _mMenViewAddConnectionPanel.Text = Language.strMenuAddConnectionPanel; @@ -255,24 +258,25 @@ namespace mRemoteNG.UI.Menu } #region View + internal void mMenView_DropDownOpening(object sender, EventArgs e) { _mMenViewConnections.Checked = !Windows.TreeForm.IsHidden; _mMenViewConfig.Checked = !Windows.ConfigForm.IsHidden; _mMenViewErrorsAndInfos.Checked = !Windows.ErrorsForm.IsHidden; - _mMenViewLockToolbars.Checked = Settings.Default.LockToolbars; + _mMenViewLockToolbars.Checked = Settings.Default.LockToolbars; _mMenViewExtAppsToolbar.Checked = TsExternalTools.Visible; _mMenViewQuickConnectToolbar.Checked = TsQuickConnect.Visible; - _mMenViewMultiSshToolbar.Checked = TsMultiSsh.Visible; + _mMenViewMultiSshToolbar.Checked = TsMultiSsh.Visible; - _mMenViewConnectionPanels.DropDownItems.Clear(); + _mMenViewConnectionPanels.DropDownItems.Clear(); for (var i = 0; i <= Runtime.WindowList.Count - 1; i++) { var tItem = new ToolStripMenuItem(Runtime.WindowList[i].Text, - Runtime.WindowList[i].Icon.ToBitmap(), ConnectionPanelMenuItem_Click) - { Tag = Runtime.WindowList[i] }; + Runtime.WindowList[i].Icon.ToBitmap(), ConnectionPanelMenuItem_Click) + {Tag = Runtime.WindowList[i]}; _mMenViewConnectionPanels.DropDownItems.Add(tItem); } @@ -347,28 +351,28 @@ namespace mRemoteNG.UI.Menu private void mMenViewResetLayout_Click(object sender, EventArgs e) { var msgBoxResult = MessageBox.Show(Language.strConfirmResetLayout, string.Empty, MessageBoxButtons.YesNo, - MessageBoxIcon.Question); + MessageBoxIcon.Question); if (msgBoxResult == DialogResult.Yes) { MainForm.SetDefaultLayout(); } } - private void mMenViewLockToolbars_Click(object sender, EventArgs eventArgs) - { - if (Settings.Default.LockToolbars) - { - Settings.Default.LockToolbars = false; - _mMenViewLockToolbars.Checked = false; - } - else - { - Settings.Default.LockToolbars = true; - _mMenViewLockToolbars.Checked = true; - } - } + private void mMenViewLockToolbars_Click(object sender, EventArgs eventArgs) + { + if (Settings.Default.LockToolbars) + { + Settings.Default.LockToolbars = false; + _mMenViewLockToolbars.Checked = false; + } + else + { + Settings.Default.LockToolbars = true; + _mMenViewLockToolbars.Checked = true; + } + } - private void mMenViewAddConnectionPanel_Click(object sender, EventArgs e) + private void mMenViewAddConnectionPanel_Click(object sender, EventArgs e) { _panelAdder.AddPanel(); } @@ -401,25 +405,26 @@ namespace mRemoteNG.UI.Menu } } - private void mMenViewMultiSSHToolbar_Click(object sender, EventArgs e) - { - if (_mMenViewMultiSshToolbar.Checked == false) - { - TsMultiSsh.Visible = true; - _mMenViewMultiSshToolbar.Checked = true; - } - else - { - TsMultiSsh.Visible = false; - _mMenViewMultiSshToolbar.Checked = false; - } - } + private void mMenViewMultiSSHToolbar_Click(object sender, EventArgs e) + { + if (_mMenViewMultiSshToolbar.Checked == false) + { + TsMultiSsh.Visible = true; + _mMenViewMultiSshToolbar.Checked = true; + } + else + { + TsMultiSsh.Visible = false; + _mMenViewMultiSshToolbar.Checked = false; + } + } - private void mMenViewFullscreen_Click(object sender, EventArgs e) + private void mMenViewFullscreen_Click(object sender, EventArgs e) { FullscreenHandler.Value = !FullscreenHandler.Value; _mMenViewFullscreen.Checked = FullscreenHandler.Value; } + #endregion } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Panels/PanelAdder.cs b/mRemoteV1/UI/Panels/PanelAdder.cs index 23871029..438ffbff 100644 --- a/mRemoteV1/UI/Panels/PanelAdder.cs +++ b/mRemoteV1/UI/Panels/PanelAdder.cs @@ -13,7 +13,7 @@ namespace mRemoteNG.UI.Panels { public class PanelAdder { - public ConnectionWindow AddPanel(string title = "", bool noTabber = false) + public ConnectionWindow AddPanel(string title = "") { try { @@ -21,12 +21,13 @@ namespace mRemoteNG.UI.Panels BuildConnectionWindowContextMenu(connectionForm); SetConnectionWindowTitle(title, connectionForm); ShowConnectionWindow(connectionForm); - PrepareTabControllerSupport(noTabber, connectionForm); + PrepareTabSupport(connectionForm); return connectionForm; } catch (Exception ex) { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "Couldn\'t add panel" + Environment.NewLine + ex.Message); + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "Couldn\'t add panel" + Environment.NewLine + ex.Message); return null; } } @@ -42,17 +43,14 @@ namespace mRemoteNG.UI.Panels connectionForm.Show(FrmMain.Default.pnlDock, DockState.Document); } - private static void PrepareTabControllerSupport(bool noTabber, ConnectionWindow connectionForm) + private static void PrepareTabSupport(ConnectionWindow connectionForm) { - if (noTabber) - connectionForm.TabController.Dispose(); - else - Runtime.WindowList.Add(connectionForm); + Runtime.WindowList.Add(connectionForm); } private static void SetConnectionWindowTitle(string title, ConnectionWindow connectionForm) { - if (title == "") + if (string.IsNullOrEmpty(title)) title = Language.strNewPanel; connectionForm.SetFormText(title.Replace("&", "&&")); } @@ -62,7 +60,7 @@ namespace mRemoteNG.UI.Panels var cMen = new ContextMenuStrip(); var cMenRen = CreateRenameMenuItem(pnlcForm); var cMenScreens = CreateScreensMenuItem(pnlcForm); - cMen.Items.AddRange(new ToolStripItem[] { cMenRen, cMenScreens }); + cMen.Items.AddRange(new ToolStripItem[] {cMenRen, cMenScreens}); pnlcForm.TabPageContextMenuStrip = cMen; } @@ -96,17 +94,15 @@ namespace mRemoteNG.UI.Panels try { var conW = (ConnectionWindow)((ToolStripMenuItem)sender).Tag; - var nTitle = ""; - using (var frmInputBox = new FrmInputBox(Language.strNewTitle, Language.strNewTitle + ":", ref nTitle)) - { - var dr = frmInputBox.ShowDialog(); - if (dr == DialogResult.OK && string.IsNullOrEmpty(frmInputBox.returnValue)) - conW.SetFormText(frmInputBox.returnValue); - } + + using (var newTitle = new FrmInputBox(Language.strNewTitle, Language.strNewTitle + ":", "")) + if (newTitle.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(newTitle.returnValue)) + conW.SetFormText(newTitle.returnValue.Replace("&", "&&")); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("cMenConnectionPanelRename_Click: Caught Exception: ", ex); + Runtime.MessageCollector.AddExceptionStackTrace("cMenConnectionPanelRename_Click: Caught Exception: ", + ex); } } @@ -132,7 +128,9 @@ namespace mRemoteNG.UI.Panels } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("cMenConnectionPanelScreens_DropDownOpening: Caught Exception: ", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "cMenConnectionPanelScreens_DropDownOpening: Caught Exception: ", + ex); } } @@ -155,11 +153,13 @@ namespace mRemoteNG.UI.Panels panel = (DockContent)obj; } } + Screens.SendPanelToScreen(panel, screen); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("cMenConnectionPanelScreen_Click: Caught Exception: ", ex); + Runtime.MessageCollector.AddExceptionStackTrace("cMenConnectionPanelScreen_Click: Caught Exception: ", + ex); } } } diff --git a/mRemoteV1/UI/Tabs/ConnectionTab.Designer.cs b/mRemoteV1/UI/Tabs/ConnectionTab.Designer.cs new file mode 100644 index 00000000..52f07702 --- /dev/null +++ b/mRemoteV1/UI/Tabs/ConnectionTab.Designer.cs @@ -0,0 +1,47 @@ +namespace mRemoteNG.UI.Tabs +{ + partial class ConnectionTab + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // ConnectionTab + // + this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; + this.ClientSize = new System.Drawing.Size(284, 261); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Name = "ConnectionTab"; + this.Text = "ConnectionTab"; + this.ResumeLayout(false); + + } + + #endregion + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/ConnectionTab.cs b/mRemoteV1/UI/Tabs/ConnectionTab.cs new file mode 100644 index 00000000..b3be1cef --- /dev/null +++ b/mRemoteV1/UI/Tabs/ConnectionTab.cs @@ -0,0 +1,100 @@ +using System; +using System.Windows.Forms; +using mRemoteNG.App; +using mRemoteNG.App.Info; +using mRemoteNG.Config; +using mRemoteNG.Connection; +using mRemoteNG.Connection.Protocol; +using mRemoteNG.Connection.Protocol.VNC; +using mRemoteNG.UI.TaskDialog; +using WeifenLuo.WinFormsUI.Docking; + +namespace mRemoteNG.UI.Tabs +{ + public partial class ConnectionTab : DockContent + { + /// + ///Silent close ignores the popup asking for confirmation + /// + public bool silentClose { get; set; } + + /// + /// Protocol close ignores the interface controller cleanup and the user confirmation dialog + /// + public bool protocolClose { get; set; } + + public ConnectionTab() + { + InitializeComponent(); + GotFocus += ConnectionTab_GotFocus; + } + + private void ConnectionTab_GotFocus(object sender, EventArgs e) + { + TabHelper.Instance.CurrentTab = this; + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + if (!protocolClose) + { + if (!silentClose) + { + if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All) + { + var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, + string + .Format(Language.strConfirmCloseConnectionPanelMainInstruction, + TabText), "", "", "", + Language.strCheckboxDoNotShowThisMessageAgain, + ETaskDialogButtons.YesNo, ESysIcons.Question, + ESysIcons.Question); + if (CTaskDialog.VerificationChecked) + { + Settings.Default.ConfirmCloseConnection--; + } + + if (result == DialogResult.No) + { + e.Cancel = true; + } + else + { + ((InterfaceControl)Tag)?.Protocol.Close(); + } + } + else + { + // close without the confirmation prompt... + ((InterfaceControl)Tag)?.Protocol.Close(); + } + } + else + { + ((InterfaceControl)Tag)?.Protocol.Close(); + } + } + + base.OnFormClosing(e); + } + + + #region HelperFunctions + + public void RefreshInterfaceController() + { + try + { + var interfaceControl = Tag as InterfaceControl; + if (interfaceControl?.Info.Protocol == ProtocolType.VNC) + ((ProtocolVNC)interfaceControl.Protocol).RefreshScreen(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("RefreshIC (UI.Window.Connection) failed", ex); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/ConnectionTab.resx b/mRemoteV1/UI/Tabs/ConnectionTab.resx new file mode 100644 index 00000000..1af7de15 --- /dev/null +++ b/mRemoteV1/UI/Tabs/ConnectionTab.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/DockPaneStripNG.cs b/mRemoteV1/UI/Tabs/DockPaneStripNG.cs new file mode 100644 index 00000000..af5fcd30 --- /dev/null +++ b/mRemoteV1/UI/Tabs/DockPaneStripNG.cs @@ -0,0 +1,1409 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Security.Permissions; +using System.Windows.Forms; +using mRemoteNG.Connection; +using WeifenLuo.WinFormsUI.Docking; + +namespace mRemoteNG.UI.Tabs +{ + /// + /// This class is lifted from VS2013DockPaneStrip from DockPanelSuite and customized for MremoteNG + /// + [ToolboxItem(false)] + internal class DockPaneStripNG : DockPaneStripBase + { + private class MremoteNGTab : Tab + { + public MremoteNGTab(IDockContent content) + : base(content) + { + } + + public int TabX { get; set; } + + public int TabWidth { get; set; } + + public int MaxWidth { get; set; } + + protected internal bool Flag { get; set; } + } + + protected override Tab CreateTab(IDockContent content) + { + return new MremoteNGTab(content); + } + + [ToolboxItem(false)] + private sealed class InertButton : InertButtonBase + { + public InertButton(Bitmap hovered, Bitmap normal, Bitmap pressed) + { + HoverImage = hovered; + Image = normal; + PressImage = pressed; + } + + public override Bitmap Image { get; } + + public override Bitmap HoverImage { get; } + + public override Bitmap PressImage { get; } + } + + #region Constants + + private const int _ToolWindowStripGapTop = 0; + private const int _ToolWindowStripGapBottom = 0; + private const int _ToolWindowStripGapLeft = 0; + private const int _ToolWindowStripGapRight = 0; + private const int _ToolWindowImageHeight = 16; + private const int _ToolWindowImageWidth = 0; //16; + private const int _ToolWindowImageGapTop = 3; + private const int _ToolWindowImageGapBottom = 1; + private const int _ToolWindowImageGapLeft = 2; + private const int _ToolWindowImageGapRight = 0; + private const int _ToolWindowTextGapRight = 3; + private const int _ToolWindowTabSeperatorGapTop = 3; + private const int _ToolWindowTabSeperatorGapBottom = 3; + + private const int _DocumentStripGapTop = 0; + private const int _DocumentStripGapBottom = 1; + private const int _DocumentTabMaxWidth = 200; + private const int _DocumentButtonGapTop = 3; + private const int _DocumentButtonGapBottom = 3; + private const int _DocumentButtonGapBetween = 0; + private const int _DocumentButtonGapRight = 3; + private const int _DocumentTabGapTop = 0; //3; + private const int _DocumentTabGapLeft = 0; //3; + private const int _DocumentTabGapRight = 0; //3; + private const int _DocumentIconGapBottom = 2; //2; + private const int _DocumentIconGapLeft = 8; + private const int _DocumentIconGapRight = 0; + private const int _DocumentIconHeight = 16; + private const int _DocumentIconWidth = 16; + private const int _DocumentTextGapRight = 6; + + #endregion + + #region Members + + private InertButton m_buttonOverflow; + private InertButton m_buttonWindowList; + private ToolTip m_toolTip; + private Font m_font; + private Font m_boldFont; + private int m_startDisplayingTab; + private bool m_documentTabsOverflow; + private static string m_toolTipSelect; + private bool m_suspendDrag; + + #endregion + + #region Properties + + private Rectangle TabStripRectangle => + Appearance == DockPane.AppearanceStyle.Document + ? TabStripRectangle_Document + : TabStripRectangle_ToolWindow; + + private Rectangle TabStripRectangle_ToolWindow + { + get + { + var rect = ClientRectangle; + return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, + rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); + } + } + + private Rectangle TabStripRectangle_Document + { + get + { + var rect = ClientRectangle; + return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, + rect.Height + DocumentStripGapTop - DocumentStripGapBottom); + } + } + + private Rectangle TabsRectangle + { + get + { + 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; + + x += DocumentTabGapLeft; + width -= DocumentTabGapLeft + + DocumentTabGapRight + + DocumentButtonGapRight + + ButtonOverflow.Width + + ButtonWindowList.Width + + 2 * DocumentButtonGapBetween; + + return new Rectangle(x, y, width, height); + } + } + + private ContextMenuStrip SelectMenu { get; } + + public int SelectMenuMargin { get; set; } = 5; + + private InertButton ButtonOverflow + { + get + { + if (m_buttonOverflow != null) return m_buttonOverflow; + m_buttonOverflow = new InertButton( + DockPane.DockPanel.Theme.ImageService.DockPaneHover_OptionOverflow, + DockPane.DockPanel.Theme.ImageService.DockPane_OptionOverflow, + DockPane.DockPanel.Theme.ImageService.DockPanePress_OptionOverflow); + m_buttonOverflow.Click += WindowList_Click; + Controls.Add(m_buttonOverflow); + + return m_buttonOverflow; + } + } + + private InertButton ButtonWindowList + { + get + { + if (m_buttonWindowList != null) return m_buttonWindowList; + m_buttonWindowList = new InertButton( + DockPane.DockPanel.Theme.ImageService.DockPaneHover_List, + DockPane.DockPanel.Theme.ImageService.DockPane_List, + DockPane.DockPanel.Theme.ImageService.DockPanePress_List); + m_buttonWindowList.Click += WindowList_Click; + Controls.Add(m_buttonWindowList); + + return m_buttonWindowList; + } + } + + private static GraphicsPath GraphicsPath => MremoteNGAutoHideStrip.GraphicsPath; + + private IContainer Components { get; } + + public Font TextFont => DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.TextFont; + + private Font BoldFont + { + get + { + if (IsDisposed) + return null; + + if (m_boldFont == null) + { + m_font = TextFont; + m_boldFont = new Font(TextFont, FontStyle.Bold); + } + else if (!Equals(m_font, TextFont)) + { + m_boldFont.Dispose(); + m_font = TextFont; + m_boldFont = new Font(TextFont, FontStyle.Bold); + } + + return m_boldFont; + } + } + + private int StartDisplayingTab + { + get => m_startDisplayingTab; + set + { + m_startDisplayingTab = value; + Invalidate(); + } + } + + private int EndDisplayingTab { get; set; } + + private int FirstDisplayingTab { get; set; } + + private bool DocumentTabsOverflow + { + set + { + if (m_documentTabsOverflow == value) + return; + + m_documentTabsOverflow = value; + SetInertButtons(); + } + } + + #region Customizable Properties + + private static int ToolWindowStripGapTop => _ToolWindowStripGapTop; + + private static int ToolWindowStripGapBottom => _ToolWindowStripGapBottom; + + private static int ToolWindowStripGapLeft => _ToolWindowStripGapLeft; + + private static int ToolWindowStripGapRight => _ToolWindowStripGapRight; + + private static int ToolWindowImageHeight => _ToolWindowImageHeight; + + private static int ToolWindowImageWidth => _ToolWindowImageWidth; + + private static int ToolWindowImageGapTop => _ToolWindowImageGapTop; + + private static int ToolWindowImageGapBottom => _ToolWindowImageGapBottom; + + private static int ToolWindowImageGapLeft => _ToolWindowImageGapLeft; + + private static int ToolWindowImageGapRight => _ToolWindowImageGapRight; + + private static int ToolWindowTextGapRight => _ToolWindowTextGapRight; + + private static int ToolWindowTabSeperatorGapTop => _ToolWindowTabSeperatorGapTop; + + private static int ToolWindowTabSeperatorGapBottom => _ToolWindowTabSeperatorGapBottom; + + private static string ToolTipSelect => m_toolTipSelect ?? (m_toolTipSelect = Language.strTabsAndPanels); + + private TextFormatFlags ToolWindowTextFormat + { + get + { + const TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | + TextFormatFlags.HorizontalCenter | + TextFormatFlags.SingleLine | + TextFormatFlags.VerticalCenter; + if (RightToLeft == RightToLeft.Yes) + return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; + return textFormat; + } + } + + private static int DocumentStripGapTop => _DocumentStripGapTop; + + private static int DocumentStripGapBottom => _DocumentStripGapBottom; + + private TextFormatFlags DocumentTextFormat + { + get + { + const TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | + TextFormatFlags.SingleLine | + TextFormatFlags.VerticalCenter | + TextFormatFlags.HorizontalCenter; + if (RightToLeft == RightToLeft.Yes) + return textFormat | TextFormatFlags.RightToLeft; + return textFormat; + } + } + + private static int DocumentTabMaxWidth => _DocumentTabMaxWidth; + + private static int DocumentButtonGapTop => _DocumentButtonGapTop; + + private static int DocumentButtonGapBottom => _DocumentButtonGapBottom; + + private static int DocumentButtonGapBetween => _DocumentButtonGapBetween; + + private static int DocumentButtonGapRight => _DocumentButtonGapRight; + + private static int DocumentTabGapTop => _DocumentTabGapTop; + + private static int DocumentTabGapLeft => _DocumentTabGapLeft; + + private static int DocumentTabGapRight => _DocumentTabGapRight; + + private static int DocumentIconGapBottom => _DocumentIconGapBottom; + + private static int DocumentIconGapLeft => _DocumentIconGapLeft; + + private static int DocumentIconGapRight => _DocumentIconGapRight; + + private static int DocumentIconWidth => _DocumentIconWidth; + + private static int DocumentIconHeight => _DocumentIconHeight; + + private static int DocumentTextGapRight => _DocumentTextGapRight; + + #endregion + + #endregion + + public DockPaneStripNG(DockPane pane) + : base(pane) + { + SetStyle(ControlStyles.ResizeRedraw | + ControlStyles.UserPaint | + ControlStyles.AllPaintingInWmPaint | + ControlStyles.OptimizedDoubleBuffer, true); + + SuspendLayout(); + + Components = new System.ComponentModel.Container(); + m_toolTip = new ToolTip(Components); + SelectMenu = new ContextMenuStrip(Components); + pane.DockPanel.Theme.ApplyTo(SelectMenu); + + ResumeLayout(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + Components.Dispose(); + if (m_boldFont != null) + { + m_boldFont.Dispose(); + m_boldFont = null; + } + } + + base.Dispose(disposing); + } + + protected override int MeasureHeight() + { + if (Appearance == DockPane.AppearanceStyle.ToolWindow) + return MeasureHeight_ToolWindow(); + return MeasureHeight_Document(); + } + + private int MeasureHeight_ToolWindow() + { + if (DockPane.IsAutoHide || Tabs.Count <= 1) + return 0; + + var height = Math.Max(TextFont.Height + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), + ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + + ToolWindowStripGapTop + ToolWindowStripGapBottom; + + return height; + } + + private int MeasureHeight_Document() + { + var height = + Math.Max( + TextFont.Height + DocumentTabGapTop + + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), + ButtonOverflow.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + + DocumentStripGapBottom + DocumentStripGapTop; + + return height; + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + CalculateTabs(); + if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) + { + if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) + CalculateTabs(); + } + + DrawTabStrip(e.Graphics); + } + + protected override void OnRefreshChanges() + { + SetInertButtons(); + Invalidate(); + } + + public override GraphicsPath GetOutline(int index) + { + return Appearance == DockPane.AppearanceStyle.Document + ? GetOutline_Document(index) + : GetOutline_ToolWindow(index); + } + + private GraphicsPath GetOutline_Document(int index) + { + var rectangle = Tabs[index].Rectangle; + if (rectangle == null) return null; + var rectTab = rectangle.Value; + rectTab.X -= rectTab.Height / 2; + rectTab.Intersect(TabsRectangle); + rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); + var rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); + + var path = new GraphicsPath(); + var pathTab = GetTabOutline_Document(Tabs[index], true, true, true); + path.AddPath(pathTab, true); + + if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) + { + path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); + path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); + path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); + path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); + path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); + } + else + { + path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); + path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); + path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); + path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); + path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); + } + + return path; + } + + private GraphicsPath GetOutline_ToolWindow(int index) + { + var rectangle = Tabs[index].Rectangle; + if (rectangle == null) return null; + var rectTab = rectangle.Value; + rectTab.Intersect(TabsRectangle); + rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); + var rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); + + var path = new GraphicsPath(); + var 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); + path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); + path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); + path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); + return path; + } + + private void CalculateTabs() + { + if (Appearance == DockPane.AppearanceStyle.ToolWindow) + CalculateTabs_ToolWindow(); + else + CalculateTabs_Document(); + } + + private void CalculateTabs_ToolWindow() + { + if (Tabs.Count <= 1 || DockPane.IsAutoHide) + return; + + var rectTabStrip = TabStripRectangle; + + // Calculate tab widths + var countTabs = Tabs.Count; + foreach (var tab1 in Tabs) + { + var 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; + for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0;) + { + anyWidthWithinAverage = false; + foreach (var tab1 in Tabs) + { + var tab = (MremoteNGTab)tab1; + if (tab.Flag) + continue; + + if (tab.MaxWidth > averageWidth) continue; + tab.Flag = true; + tab.TabWidth = tab.MaxWidth; + totalAllocatedWidth += tab.TabWidth; + anyWidthWithinAverage = true; + remainedTabs--; + } + + if (remainedTabs != 0) + averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; + } + + // 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) + { + var tab = (MremoteNGTab)tab1; + if (tab.Flag) + continue; + + tab.Flag = true; + if (roundUpWidth > 0) + { + tab.TabWidth = averageWidth + 1; + roundUpWidth--; + } + else + tab.TabWidth = averageWidth; + } + } + + // Set the X position of the tabs + var x = rectTabStrip.X + ToolWindowStripGapLeft; + foreach (var tab1 in Tabs) + { + var tab = (MremoteNGTab)tab1; + tab.TabX = x; + x += tab.TabWidth; + } + } + + private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) + { + var overflow = false; + + if (!(Tabs[index] is MremoteNGTab tab)) return false; + tab.MaxWidth = GetMaxTabWidth(index); + var width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); + if (x + width < rectTabStrip.Right || index == StartDisplayingTab) + { + tab.TabX = x; + tab.TabWidth = width; + EndDisplayingTab = index; + } + else + { + tab.TabX = 0; + tab.TabWidth = 0; + overflow = true; + } + + x += width; + + return overflow; + } + + /// + /// Calculate which tabs are displayed and in what order. + /// + private void CalculateTabs_Document() + { + if (m_startDisplayingTab >= Tabs.Count) + m_startDisplayingTab = 0; + + var rectTabStrip = TabsRectangle; + + var x = rectTabStrip.X; //+ rectTabStrip.Height / 2; + var overflow = false; + + // Originally all new documents that were considered overflow + // (not enough pane strip space to show all tabs) were added to + // the far left (assuming not right to left) and the tabs on the + // right were dropped from view. If StartDisplayingTab is not 0 + // then we are dealing with making sure a specific tab is kept in focus. + if (m_startDisplayingTab > 0) + { + var 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--) + CalculateDocumentTab(rectTabStrip, ref tempX, i); + + // Store which tab is the first one displayed so that it + // will be drawn correctly (without part of the tab cut off) + FirstDisplayingTab = EndDisplayingTab; + + tempX = x; // Reset X location because we are starting over + + // 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++) + overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); + + // If not all tabs are shown then we have an overflow. + if (FirstDisplayingTab != 0) + overflow = true; + } + else + { + for (var i = StartDisplayingTab; i < Tabs.Count; i++) + overflow = CalculateDocumentTab(rectTabStrip, ref x, i); + for (var i = 0; i < StartDisplayingTab; i++) + overflow = CalculateDocumentTab(rectTabStrip, ref x, i); + + FirstDisplayingTab = StartDisplayingTab; + } + + if (!overflow) + { + m_startDisplayingTab = 0; + FirstDisplayingTab = 0; + x = rectTabStrip.X; + foreach (var tab1 in Tabs) + { + var tab = (MremoteNGTab)tab1; + tab.TabX = x; + x += tab.TabWidth; + } + } + + DocumentTabsOverflow = overflow; + } + + protected override void EnsureTabVisible(IDockContent content) + { + if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) + return; + + CalculateTabs(); + EnsureDocumentTabVisible(content, true); + } + + private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) + { + var index = Tabs.IndexOf(content); + if (index == -1) // TODO: should prevent it from being -1; + return false; + + if (Tabs[index] is MremoteNGTab tab && tab.TabWidth != 0) + return false; + + StartDisplayingTab = index; + if (repaint) + Invalidate(); + + return true; + } + + private int GetMaxTabWidth(int index) + { + if (Appearance == DockPane.AppearanceStyle.ToolWindow) + return GetMaxTabWidth_ToolWindow(index); + return GetMaxTabWidth_Document(index); + } + + private int GetMaxTabWidth_ToolWindow(int index) + { + var content = Tabs[index].Content; + var sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); + return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + + ToolWindowImageGapRight + ToolWindowTextGapRight; + } + + private const int TAB_CLOSE_BUTTON_WIDTH = 30; + + 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, + new Size(DocumentTabMaxWidth, height), DocumentTextFormat); + + int width; + if (DockPane.DockPanel.ShowDocumentIcon) + width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + + DocumentTextGapRight; + else + width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; + + width += TAB_CLOSE_BUTTON_WIDTH; + return width; + } + + private void DrawTabStrip(Graphics g) + { + // IMPORTANT: fill background. + var rectTabStrip = TabStripRectangle; + g.FillRectangle( + DockPane.DockPanel.Theme.PaintingService.GetBrush(DockPane.DockPanel.Theme.ColorPalette + .MainWindowActive + .Background), rectTabStrip); + + if (Appearance == DockPane.AppearanceStyle.Document) + DrawTabStrip_Document(g); + else + DrawTabStrip_ToolWindow(g); + } + + private void DrawTabStrip_Document(Graphics g) + { + var count = Tabs.Count; + if (count == 0) + return; + + var rectTabStrip = new Rectangle(TabStripRectangle.Location, TabStripRectangle.Size); + rectTabStrip.Height += 1; + + // Draw the tabs + var rectTabOnly = TabsRectangle; + Rectangle rectTab; + MremoteNGTab tabActive = null; + g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); + for (var i = 0; i < count; i++) + { + rectTab = GetTabRectangle(i); + if (Tabs[i].Content == DockPane.ActiveContent) + { + tabActive = Tabs[i] as MremoteNGTab; + if (tabActive != null) tabActive.Rectangle = rectTab; + continue; + } + + if (!rectTab.IntersectsWith(rectTabOnly)) continue; + if (!(Tabs[i] is MremoteNGTab tab)) continue; + tab.Rectangle = rectTab; + DrawTab(g, tab); + } + + g.SetClip(rectTabStrip); + + if (DockPane.DockPanel.DocumentTabStripLocation != DocumentTabStripLocation.Bottom) + { + Color tabUnderLineColor; + if (tabActive != null && DockPane.IsActiveDocumentPane) + tabUnderLineColor = DockPane.DockPanel.Theme.ColorPalette.TabSelectedActive.Background; + else + tabUnderLineColor = DockPane.DockPanel.Theme.ColorPalette.TabSelectedInactive.Background; + + g.DrawLine(DockPane.DockPanel.Theme.PaintingService.GetPen(tabUnderLineColor, 4), rectTabStrip.Left, + rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); + } + + g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); + if (tabActive == null) return; + rectTab = tabActive.Rectangle.Value; + if (!rectTab.IntersectsWith(rectTabOnly)) return; + rectTab.Intersect(rectTabOnly); + tabActive.Rectangle = rectTab; + DrawTab(g, tabActive); + } + + private void DrawTabStrip_ToolWindow(Graphics g) + { + var rect = TabStripRectangle_ToolWindow; + var 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++) + { + if (!(Tabs[i] is MremoteNGTab tab)) continue; + tab.Rectangle = GetTabRectangle(i); + DrawTab(g, tab); + } + } + + private Rectangle GetTabRectangle(int index) + { + return Appearance == DockPane.AppearanceStyle.ToolWindow + ? GetTabRectangle_ToolWindow(index) + : GetTabRectangle_Document(index); + } + + private Rectangle GetTabRectangle_ToolWindow(int index) + { + var rectTabStrip = TabStripRectangle; + + var 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]; + + var rect = new Rectangle + { + X = tab.TabX, Width = tab.TabWidth, Height = rectTabStrip.Height - DocumentTabGapTop + }; + + if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) + rect.Y = rectTabStrip.Y + DocumentStripGapBottom; + else + rect.Y = rectTabStrip.Y + DocumentTabGapTop; + + return rect; + } + + private void DrawTab(Graphics g, MremoteNGTab tab) + { + if (Appearance == DockPane.AppearanceStyle.ToolWindow) + DrawTab_ToolWindow(g, tab); + else + DrawTab_Document(g, tab); + } + + private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) + { + return Appearance == DockPane.AppearanceStyle.ToolWindow + ? GetTabOutline_ToolWindow(tab, rtlTransform, toScreen) + : GetTabOutline_Document(tab, rtlTransform, toScreen, false); + } + + private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) + { + var rect = GetTabRectangle(Tabs.IndexOf(tab)); + if (rtlTransform) + rect = DrawHelper.RtlTransform(this, rect); + if (toScreen) + rect = RectangleToScreen(rect); + + DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); + return GraphicsPath; + } + + private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) + { + GraphicsPath.Reset(); + var rect = GetTabRectangle(Tabs.IndexOf(tab)); + + // Shorten TabOutline so it doesn't get overdrawn by icons next to it + rect.Intersect(TabsRectangle); + rect.Width--; + + if (rtlTransform) + rect = DrawHelper.RtlTransform(this, rect); + if (toScreen) + rect = RectangleToScreen(rect); + + GraphicsPath.AddRectangle(rect); + return GraphicsPath; + } + + private void DrawTab_ToolWindow(Graphics g, MremoteNGTab tab) + { + if (tab.Rectangle == null) return; + var rect = tab.Rectangle.Value; + var rectIcon = new Rectangle( + rect.X + ToolWindowImageGapLeft, + rect.Y + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, + ToolWindowImageWidth, ToolWindowImageHeight); + var rectText = PatchController.EnableHighDpi == true + ? new Rectangle( + rect.X + ToolWindowImageGapLeft, + rect.Y + rect.Height - ToolWindowImageGapBottom - TextFont.Height, + ToolWindowImageWidth, TextFont.Height) + : rectIcon; + rectText.X += rectIcon.Width + ToolWindowImageGapRight; + rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - + ToolWindowImageGapRight - ToolWindowTextGapRight; + + var rectTab = DrawHelper.RtlTransform(this, rect); + rectText = DrawHelper.RtlTransform(this, rectText); + rectIcon = DrawHelper.RtlTransform(this, rectIcon); + var borderColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowBorder; + + var separatorColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowSeparator; + if (DockPane.ActiveContent == tab.Content) + { + Color textColor; + Color backgroundColor; + if (DockPane.IsActiveDocumentPane) + { + textColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabSelectedActive.Text; + backgroundColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabSelectedActive.Background; + } + else + { + textColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabSelectedInactive.Text; + backgroundColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabSelectedInactive.Background; + } + + g.FillRectangle(DockPane.DockPanel.Theme.PaintingService.GetBrush(backgroundColor), rect); + g.DrawLine(DockPane.DockPanel.Theme.PaintingService.GetPen(borderColor), rect.Left, rect.Top, + rect.Left, rect.Bottom); + g.DrawLine(DockPane.DockPanel.Theme.PaintingService.GetPen(borderColor), rect.Left, rect.Bottom - 1, + rect.Right, rect.Bottom - 1); + g.DrawLine(DockPane.DockPanel.Theme.PaintingService.GetPen(borderColor), rect.Right - 1, rect.Top, + rect.Right - 1, rect.Bottom); + TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, + ToolWindowTextFormat); + } + else + { + Color textColor; + Color backgroundColor; + if (tab.Content == DockPane.MouseOverTab) + { + textColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabUnselectedHovered.Text; + backgroundColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabUnselectedHovered.Background; + } + else + { + textColor = DockPane.DockPanel.Theme.ColorPalette.ToolWindowTabUnselected.Text; + backgroundColor = DockPane.DockPanel.Theme.ColorPalette.MainWindowActive.Background; + } + + g.FillRectangle(DockPane.DockPanel.Theme.PaintingService.GetBrush(backgroundColor), rect); + g.DrawLine(DockPane.DockPanel.Theme.PaintingService.GetPen(borderColor), rect.Left, rect.Top, + rect.Right, rect.Top); + TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, + ToolWindowTextFormat); + } + + if (rectTab.Contains(rectIcon)) + g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); + } + + private void DrawTab_Document(Graphics g, MremoteNGTab tab) + { + if (tab.Rectangle == null) return; + var rect = tab.Rectangle.Value; + if (tab.TabWidth == 0) + return; + + var rectCloseButton = GetCloseButtonRect(rect); + var rectIcon = new Rectangle( + rect.X + DocumentIconGapLeft, + rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, + DocumentIconWidth, DocumentIconHeight); + var rectText = PatchController.EnableHighDpi == true + ? new Rectangle( + rect.X + DocumentIconGapLeft, + rect.Y + rect.Height - DocumentIconGapBottom - TextFont.Height, + DocumentIconWidth, TextFont.Height) + : rectIcon; + if (DockPane.DockPanel.ShowDocumentIcon) + { + rectText.X += rectIcon.Width + DocumentIconGapRight; + rectText.Y = rect.Y; + rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - + DocumentTextGapRight - rectCloseButton.Width; + rectText.Height = rect.Height; + } + else + rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; + + var rectTab = DrawHelper.RtlTransform(this, rect); + var 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; + + 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 text; + Image image = null; + Color paint; + var imageService = DockPane.DockPanel.Theme.ImageService; + if (DockPane.ActiveContent == tab.Content) + { + if (DockPane.IsActiveDocumentPane) + { + paint = activeColor; + text = activeText; + image = IsMouseDown + ? imageService.TabPressActive_Close + : rectCloseButton == ActiveClose + ? imageService.TabHoverActive_Close + : imageService.TabActive_Close; + } + else + { + paint = lostFocusColor; + text = lostFocusText; + image = IsMouseDown + ? imageService.TabPressLostFocus_Close + : rectCloseButton == ActiveClose + ? imageService.TabHoverLostFocus_Close + : imageService.TabLostFocus_Close; + } + } + else + { + if (tab.Content == DockPane.MouseOverTab) + { + paint = mouseHoverColor; + text = mouseHoverText; + image = IsMouseDown + ? imageService.TabPressInactive_Close + : rectCloseButton == ActiveClose + ? imageService.TabHoverInactive_Close + : imageService.TabInactive_Close; + } + else + { + paint = inactiveColor; + text = inactiveText; + } + } + + g.FillRectangle(DockPane.DockPanel.Theme.PaintingService.GetBrush(paint), rect); + TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, text, DocumentTextFormat); + if (image != null) + g.DrawImage(image, rectCloseButton); + + if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) + g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); + } + + private bool m_isMouseDown; + + protected bool IsMouseDown + { + get => m_isMouseDown; + private set + { + if (m_isMouseDown == value) + return; + + m_isMouseDown = value; + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (IsMouseDown) + IsMouseDown = false; + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + // suspend drag if mouse is down on active close button. + m_suspendDrag = ActiveCloseHitTest(e.Location); + if (!IsMouseDown) + IsMouseDown = true; + } + + protected override void OnMouseMove(MouseEventArgs e) + { + if (!m_suspendDrag) + base.OnMouseMove(e); + + var index = HitTest(PointToClient(MousePosition)); + var toolTip = string.Empty; + + var tabUpdate = false; + var buttonUpdate = false; + if (index != -1) + { + if (Tabs[index] is MremoteNGTab tab) + { + if (Appearance == DockPane.AppearanceStyle.ToolWindow || + Appearance == DockPane.AppearanceStyle.Document) + { + tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); + } + + if (!string.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) + toolTip = tab.Content.DockHandler.ToolTipText; + else if (tab.MaxWidth > tab.TabWidth) + toolTip = tab.Content.DockHandler.TabText; + + var 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)); + buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) + ? closeButtonRect + : Rectangle.Empty); + } + } + } + else + { + tabUpdate = SetMouseOverTab(null); + buttonUpdate = SetActiveClose(Rectangle.Empty); + } + + if (tabUpdate || buttonUpdate) + Invalidate(); + + if (m_toolTip.GetToolTip(this) == toolTip) return; + m_toolTip.Active = false; + m_toolTip.SetToolTip(this, toolTip); + m_toolTip.Active = true; + } + + protected override void OnMouseClick(MouseEventArgs e) + { + base.OnMouseClick(e); + if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) + return; + + var indexHit = HitTest(); + if (indexHit > -1) + TabCloseButtonHit(indexHit); + } + + private void TabCloseButtonHit(int index) + { + var mousePos = PointToClient(MousePosition); + var tabRect = GetTabBounds(Tabs[index]); + if (tabRect.Contains(ActiveClose) && ActiveCloseHitTest(mousePos)) + TryCloseTab(index); + } + + private Rectangle GetCloseButtonRect(Rectangle rectTab) + { + if (Appearance != DockPane.AppearanceStyle.Document) + { + return Rectangle.Empty; + } + + const int gap = 3; + var imageSize = PatchController.EnableHighDpi == true ? rectTab.Height - gap * 2 : 15; + return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, + imageSize); + } + + private void WindowList_Click(object sender, EventArgs e) + { + SelectMenu.Items.Clear(); + foreach (var tab1 in Tabs) + { + var tab = (MremoteNGTab)tab1; + var content = tab.Content; + var item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); + item.Tag = tab.Content; + item.Click += ContextMenuItem_Click; + } + + var workingArea = + Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, + ButtonWindowList.Height / 2))); + var menu = new Rectangle( + ButtonWindowList.PointToScreen(new Point(0, + ButtonWindowList.Location.Y + + ButtonWindowList.Height)), + SelectMenu.Size); + var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, + menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); + if (workingArea.Contains(menuMargined)) + { + SelectMenu.Show(menu.Location); + } + else + { + var 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)); + if (newPoint.Y < button.Y) + { + // flip the menu up to be above the button. + newPoint.Y = button.Y - ButtonWindowList.Height; + SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); + } + else + { + SelectMenu.Show(newPoint); + } + } + } + + private void ContextMenuItem_Click(object sender, EventArgs e) + { + if (!(sender is ToolStripMenuItem item)) return; + var content = (IDockContent)item.Tag; + DockPane.ActiveContent = content; + } + + private void SetInertButtons() + { + if (Appearance == DockPane.AppearanceStyle.ToolWindow) + { + if (m_buttonOverflow != null) + m_buttonOverflow.Left = -m_buttonOverflow.Width; + + if (m_buttonWindowList != null) + m_buttonWindowList.Left = -m_buttonWindowList.Width; + } + else + { + ButtonOverflow.Visible = m_documentTabsOverflow; + ButtonOverflow.RefreshChanges(); + + ButtonWindowList.Visible = !m_documentTabsOverflow; + ButtonWindowList.RefreshChanges(); + } + } + + protected override void OnLayout(LayoutEventArgs levent) + { + if (Appearance == DockPane.AppearanceStyle.Document) + { + LayoutButtons(); + OnRefreshChanges(); + } + + base.OnLayout(levent); + } + + private void LayoutButtons() + { + var 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; + if (buttonHeight < height) + { + buttonWidth = buttonWidth * height / buttonHeight; + buttonHeight = height; + } + + var buttonSize = new Size(buttonWidth, buttonHeight); + + var x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft + - DocumentButtonGapRight - buttonWidth; + var y = rectTabStrip.Y + DocumentButtonGapTop; + var point = new Point(x, y); + ButtonOverflow.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); + + // If the close button is not visible draw the window list button overtop. + // Otherwise it is drawn to the left of the close button. + ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); + } + + private void Close_Click(object sender, EventArgs e) + { + CloseProtocol(); + + if (PatchController.EnableMemoryLeakFix == true) + { + ContentClosed(); + } + } + + protected override int HitTest(Point point) + { + if (!TabsRectangle.Contains(point)) + return -1; + + foreach (var tab in Tabs) + { + var path = GetTabOutline(tab, true, false); + if (path.IsVisible(point)) + return Tabs.IndexOf(tab); + } + + return -1; + } + + protected override bool MouseDownActivateTest(MouseEventArgs e) + { + var 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 + result = !ActiveCloseHitTest(e.Location); + } + + return result; + } + + private bool ActiveCloseHitTest(Point ptMouse) + { + if (ActiveClose.IsEmpty) return false; + var mouseRect = new Rectangle(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(); + return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height); + } + + private Rectangle ActiveClose { get; set; } + + private bool SetActiveClose(Rectangle rectangle) + { + if (ActiveClose == rectangle) + return false; + + ActiveClose = rectangle; + return true; + } + + private bool SetMouseOverTab(IDockContent content) + { + if (DockPane.MouseOverTab == content) + return false; + + DockPane.MouseOverTab = content; + return true; + } + + protected override void OnMouseLeave(EventArgs e) + { + var tabUpdate = SetMouseOverTab(null); + var buttonUpdate = SetActiveClose(Rectangle.Empty); + if (tabUpdate || buttonUpdate) + Invalidate(); + + base.OnMouseLeave(e); + } + + protected override void OnRightToLeftChanged(EventArgs e) + { + base.OnRightToLeftChanged(e); + PerformLayout(); + } + + private void CloseProtocol() + { + var ic = InterfaceControl.FindInterfaceControl(DockPane.DockPanel); + ic?.Protocol.Close(); + } + + #region Native Methods + + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + protected override void WndProc(ref Message m) + { + if (m.Msg == (int)Msgs.WM_LBUTTONDBLCLK) + { + // If the option is not set, do nothing. Do not send the message to base. + if (!Settings.Default.DoubleClickOnTabClosesIt) return; + + // Option is set, close the tab, then send to base. + //DockPane.CloseActiveContent(); + CloseProtocol(); + + if (PatchController.EnableMemoryLeakFix == true) + { + ContentClosed(); + } + + return; + } + + base.WndProc(ref m); + } + + #endregion + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/Enums.cs b/mRemoteV1/UI/Tabs/Enums.cs new file mode 100644 index 00000000..601f30d1 --- /dev/null +++ b/mRemoteV1/UI/Tabs/Enums.cs @@ -0,0 +1,375 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mRemoteNG.UI.Tabs +{ + [Flags] + internal enum FlagsSetWindowPos : uint + { + SWP_NOSIZE = 0x0001, + SWP_NOMOVE = 0x0002, + SWP_NOZORDER = 0x0004, + SWP_NOREDRAW = 0x0008, + SWP_NOACTIVATE = 0x0010, + SWP_FRAMECHANGED = 0x0020, + SWP_SHOWWINDOW = 0x0040, + SWP_HIDEWINDOW = 0x0080, + SWP_NOCOPYBITS = 0x0100, + SWP_NOOWNERZORDER = 0x0200, + SWP_NOSENDCHANGING = 0x0400, + SWP_DRAWFRAME = 0x0020, + SWP_NOREPOSITION = 0x0200, + SWP_DEFERERASE = 0x2000, + SWP_ASYNCWINDOWPOS = 0x4000 + } + + internal enum ShowWindowStyles : short + { + SW_HIDE = 0, + SW_SHOWNORMAL = 1, + SW_NORMAL = 1, + SW_SHOWMINIMIZED = 2, + SW_SHOWMAXIMIZED = 3, + SW_MAXIMIZE = 3, + SW_SHOWNOACTIVATE = 4, + SW_SHOW = 5, + SW_MINIMIZE = 6, + SW_SHOWMINNOACTIVE = 7, + SW_SHOWNA = 8, + SW_RESTORE = 9, + SW_SHOWDEFAULT = 10, + SW_FORCEMINIMIZE = 11, + SW_MAX = 11 + } + + internal enum WindowStyles : uint + { + WS_OVERLAPPED = 0x00000000, + WS_POPUP = 0x80000000, + WS_CHILD = 0x40000000, + WS_MINIMIZE = 0x20000000, + WS_VISIBLE = 0x10000000, + WS_DISABLED = 0x08000000, + WS_CLIPSIBLINGS = 0x04000000, + WS_CLIPCHILDREN = 0x02000000, + WS_MAXIMIZE = 0x01000000, + WS_CAPTION = 0x00C00000, + WS_BORDER = 0x00800000, + WS_DLGFRAME = 0x00400000, + WS_VSCROLL = 0x00200000, + WS_HSCROLL = 0x00100000, + WS_SYSMENU = 0x00080000, + WS_THICKFRAME = 0x00040000, + WS_GROUP = 0x00020000, + WS_TABSTOP = 0x00010000, + WS_MINIMIZEBOX = 0x00020000, + WS_MAXIMIZEBOX = 0x00010000, + WS_TILED = 0x00000000, + WS_ICONIC = 0x20000000, + WS_SIZEBOX = 0x00040000, + WS_POPUPWINDOW = 0x80880000, + WS_OVERLAPPEDWINDOW = 0x00CF0000, + WS_TILEDWINDOW = 0x00CF0000, + WS_CHILDWINDOW = 0x40000000 + } + + [Flags] + internal enum WindowExStyles + { + WS_EX_DLGMODALFRAME = 0x00000001, + WS_EX_NOPARENTNOTIFY = 0x00000004, + WS_EX_TOPMOST = 0x00000008, + WS_EX_ACCEPTFILES = 0x00000010, + WS_EX_TRANSPARENT = 0x00000020, + WS_EX_MDICHILD = 0x00000040, + WS_EX_TOOLWINDOW = 0x00000080, + WS_EX_WINDOWEDGE = 0x00000100, + WS_EX_CLIENTEDGE = 0x00000200, + WS_EX_CONTEXTHELP = 0x00000400, + WS_EX_RIGHT = 0x00001000, + WS_EX_LEFT = 0x00000000, + WS_EX_RTLREADING = 0x00002000, + WS_EX_LTRREADING = 0x00000000, + WS_EX_LEFTSCROLLBAR = 0x00004000, + WS_EX_RIGHTSCROLLBAR = 0x00000000, + WS_EX_CONTROLPARENT = 0x00010000, + WS_EX_STATICEDGE = 0x00020000, + WS_EX_APPWINDOW = 0x00040000, + WS_EX_OVERLAPPEDWINDOW = 0x00000300, + WS_EX_PALETTEWINDOW = 0x00000188, + WS_EX_LAYERED = 0x00080000, + WS_EX_NOACTIVATE = 0x08000000 + } + + internal enum Msgs + { + WM_NULL = 0x0000, + WM_CREATE = 0x0001, + WM_DESTROY = 0x0002, + WM_MOVE = 0x0003, + WM_SIZE = 0x0005, + WM_ACTIVATE = 0x0006, + WM_SETFOCUS = 0x0007, + WM_KILLFOCUS = 0x0008, + WM_ENABLE = 0x000A, + WM_SETREDRAW = 0x000B, + WM_SETTEXT = 0x000C, + WM_GETTEXT = 0x000D, + WM_GETTEXTLENGTH = 0x000E, + WM_PAINT = 0x000F, + WM_CLOSE = 0x0010, + WM_QUERYENDSESSION = 0x0011, + WM_QUIT = 0x0012, + WM_QUERYOPEN = 0x0013, + WM_ERASEBKGND = 0x0014, + WM_SYSCOLORCHANGE = 0x0015, + WM_ENDSESSION = 0x0016, + WM_SHOWWINDOW = 0x0018, + WM_WININICHANGE = 0x001A, + WM_SETTINGCHANGE = 0x001A, + WM_DEVMODECHANGE = 0x001B, + WM_ACTIVATEAPP = 0x001C, + WM_FONTCHANGE = 0x001D, + WM_TIMECHANGE = 0x001E, + WM_CANCELMODE = 0x001F, + WM_SETCURSOR = 0x0020, + WM_MOUSEACTIVATE = 0x0021, + WM_CHILDACTIVATE = 0x0022, + WM_QUEUESYNC = 0x0023, + WM_GETMINMAXINFO = 0x0024, + WM_PAINTICON = 0x0026, + WM_ICONERASEBKGND = 0x0027, + WM_NEXTDLGCTL = 0x0028, + WM_SPOOLERSTATUS = 0x002A, + WM_DRAWITEM = 0x002B, + WM_MEASUREITEM = 0x002C, + WM_DELETEITEM = 0x002D, + WM_VKEYTOITEM = 0x002E, + WM_CHARTOITEM = 0x002F, + WM_SETFONT = 0x0030, + WM_GETFONT = 0x0031, + WM_SETHOTKEY = 0x0032, + WM_GETHOTKEY = 0x0033, + WM_QUERYDRAGICON = 0x0037, + WM_COMPAREITEM = 0x0039, + WM_GETOBJECT = 0x003D, + WM_COMPACTING = 0x0041, + WM_COMMNOTIFY = 0x0044, + WM_WINDOWPOSCHANGING = 0x0046, + WM_WINDOWPOSCHANGED = 0x0047, + WM_POWER = 0x0048, + WM_COPYDATA = 0x004A, + WM_CANCELJOURNAL = 0x004B, + WM_NOTIFY = 0x004E, + WM_INPUTLANGCHANGEREQUEST = 0x0050, + WM_INPUTLANGCHANGE = 0x0051, + WM_TCARD = 0x0052, + WM_HELP = 0x0053, + WM_USERCHANGED = 0x0054, + WM_NOTIFYFORMAT = 0x0055, + WM_CONTEXTMENU = 0x007B, + WM_STYLECHANGING = 0x007C, + WM_STYLECHANGED = 0x007D, + WM_DISPLAYCHANGE = 0x007E, + WM_GETICON = 0x007F, + WM_SETICON = 0x0080, + WM_NCCREATE = 0x0081, + WM_NCDESTROY = 0x0082, + WM_NCCALCSIZE = 0x0083, + WM_NCHITTEST = 0x0084, + WM_NCPAINT = 0x0085, + WM_NCACTIVATE = 0x0086, + WM_GETDLGCODE = 0x0087, + WM_SYNCPAINT = 0x0088, + WM_NCMOUSEMOVE = 0x00A0, + WM_NCLBUTTONDOWN = 0x00A1, + WM_NCLBUTTONUP = 0x00A2, + WM_NCLBUTTONDBLCLK = 0x00A3, + WM_NCRBUTTONDOWN = 0x00A4, + WM_NCRBUTTONUP = 0x00A5, + WM_NCRBUTTONDBLCLK = 0x00A6, + WM_NCMBUTTONDOWN = 0x00A7, + WM_NCMBUTTONUP = 0x00A8, + WM_NCMBUTTONDBLCLK = 0x00A9, + WM_KEYDOWN = 0x0100, + WM_KEYUP = 0x0101, + WM_CHAR = 0x0102, + WM_DEADCHAR = 0x0103, + WM_SYSKEYDOWN = 0x0104, + WM_SYSKEYUP = 0x0105, + WM_SYSCHAR = 0x0106, + WM_SYSDEADCHAR = 0x0107, + WM_KEYLAST = 0x0108, + WM_IME_STARTCOMPOSITION = 0x010D, + WM_IME_ENDCOMPOSITION = 0x010E, + WM_IME_COMPOSITION = 0x010F, + WM_IME_KEYLAST = 0x010F, + WM_INITDIALOG = 0x0110, + WM_COMMAND = 0x0111, + WM_SYSCOMMAND = 0x0112, + WM_TIMER = 0x0113, + WM_HSCROLL = 0x0114, + WM_VSCROLL = 0x0115, + WM_INITMENU = 0x0116, + WM_INITMENUPOPUP = 0x0117, + WM_MENUSELECT = 0x011F, + WM_MENUCHAR = 0x0120, + WM_ENTERIDLE = 0x0121, + WM_MENURBUTTONUP = 0x0122, + WM_MENUDRAG = 0x0123, + WM_MENUGETOBJECT = 0x0124, + WM_UNINITMENUPOPUP = 0x0125, + WM_MENUCOMMAND = 0x0126, + WM_CTLCOLORMSGBOX = 0x0132, + WM_CTLCOLOREDIT = 0x0133, + WM_CTLCOLORLISTBOX = 0x0134, + WM_CTLCOLORBTN = 0x0135, + WM_CTLCOLORDLG = 0x0136, + WM_CTLCOLORSCROLLBAR = 0x0137, + WM_CTLCOLORSTATIC = 0x0138, + WM_MOUSEMOVE = 0x0200, + WM_LBUTTONDOWN = 0x0201, + WM_LBUTTONUP = 0x0202, + WM_LBUTTONDBLCLK = 0x0203, + WM_RBUTTONDOWN = 0x0204, + WM_RBUTTONUP = 0x0205, + WM_RBUTTONDBLCLK = 0x0206, + WM_MBUTTONDOWN = 0x0207, + WM_MBUTTONUP = 0x0208, + WM_MBUTTONDBLCLK = 0x0209, + WM_MOUSEWHEEL = 0x020A, + WM_PARENTNOTIFY = 0x0210, + WM_ENTERMENULOOP = 0x0211, + WM_EXITMENULOOP = 0x0212, + WM_NEXTMENU = 0x0213, + WM_SIZING = 0x0214, + WM_CAPTURECHANGED = 0x0215, + WM_MOVING = 0x0216, + WM_DEVICECHANGE = 0x0219, + WM_MDICREATE = 0x0220, + WM_MDIDESTROY = 0x0221, + WM_MDIACTIVATE = 0x0222, + WM_MDIRESTORE = 0x0223, + WM_MDINEXT = 0x0224, + WM_MDIMAXIMIZE = 0x0225, + WM_MDITILE = 0x0226, + WM_MDICASCADE = 0x0227, + WM_MDIICONARRANGE = 0x0228, + WM_MDIGETACTIVE = 0x0229, + WM_MDISETMENU = 0x0230, + WM_ENTERSIZEMOVE = 0x0231, + WM_EXITSIZEMOVE = 0x0232, + WM_DROPFILES = 0x0233, + WM_MDIREFRESHMENU = 0x0234, + WM_IME_SETCONTEXT = 0x0281, + WM_IME_NOTIFY = 0x0282, + WM_IME_CONTROL = 0x0283, + WM_IME_COMPOSITIONFULL = 0x0284, + WM_IME_SELECT = 0x0285, + WM_IME_CHAR = 0x0286, + WM_IME_REQUEST = 0x0288, + WM_IME_KEYDOWN = 0x0290, + WM_IME_KEYUP = 0x0291, + WM_MOUSEHOVER = 0x02A1, + WM_MOUSELEAVE = 0x02A3, + WM_CUT = 0x0300, + WM_COPY = 0x0301, + WM_PASTE = 0x0302, + WM_CLEAR = 0x0303, + WM_UNDO = 0x0304, + WM_RENDERFORMAT = 0x0305, + WM_RENDERALLFORMATS = 0x0306, + WM_DESTROYCLIPBOARD = 0x0307, + WM_DRAWCLIPBOARD = 0x0308, + WM_PAINTCLIPBOARD = 0x0309, + WM_VSCROLLCLIPBOARD = 0x030A, + WM_SIZECLIPBOARD = 0x030B, + WM_ASKCBFORMATNAME = 0x030C, + WM_CHANGECBCHAIN = 0x030D, + WM_HSCROLLCLIPBOARD = 0x030E, + WM_QUERYNEWPALETTE = 0x030F, + WM_PALETTEISCHANGING = 0x0310, + WM_PALETTECHANGED = 0x0311, + WM_HOTKEY = 0x0312, + WM_PRINT = 0x0317, + WM_PRINTCLIENT = 0x0318, + WM_HANDHELDFIRST = 0x0358, + WM_HANDHELDLAST = 0x035F, + WM_AFXFIRST = 0x0360, + WM_AFXLAST = 0x037F, + WM_PENWINFIRST = 0x0380, + WM_PENWINLAST = 0x038F, + WM_APP = 0x8000, + WM_USER = 0x0400 + } + + internal enum HitTest + { + HTERROR = -2, + HTTRANSPARENT = -1, + HTNOWHERE = 0, + HTCLIENT = 1, + HTCAPTION = 2, + HTSYSMENU = 3, + HTGROWBOX = 4, + HTSIZE = 4, + HTMENU = 5, + HTHSCROLL = 6, + HTVSCROLL = 7, + HTMINBUTTON = 8, + HTMAXBUTTON = 9, + HTLEFT = 10, + HTRIGHT = 11, + HTTOP = 12, + HTTOPLEFT = 13, + HTTOPRIGHT = 14, + HTBOTTOM = 15, + HTBOTTOMLEFT = 16, + HTBOTTOMRIGHT = 17, + HTBORDER = 18, + HTREDUCE = 8, + HTZOOM = 9, + HTSIZEFIRST = 10, + HTSIZELAST = 17, + HTOBJECT = 19, + HTCLOSE = 20, + HTHELP = 21 + } + + internal enum ScrollBars : uint + { + SB_HORZ = 0, + SB_VERT = 1, + SB_CTL = 2, + SB_BOTH = 3 + } + + internal enum GetWindowLongIndex + { + GWL_STYLE = -16, + GWL_EXSTYLE = -20 + } + + // Hook Types + internal enum HookType + { + WH_JOURNALRECORD = 0, + WH_JOURNALPLAYBACK = 1, + WH_KEYBOARD = 2, + WH_GETMESSAGE = 3, + WH_CALLWNDPROC = 4, + WH_CBT = 5, + WH_SYSMSGFILTER = 6, + WH_MOUSE = 7, + WH_HARDWARE = 8, + WH_DEBUG = 9, + WH_SHELL = 10, + WH_FOREGROUNDIDLE = 11, + WH_CALLWNDPROCRET = 12, + WH_KEYBOARD_LL = 13, + WH_MOUSE_LL = 14 + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/FloatWindowNG.cs b/mRemoteV1/UI/Tabs/FloatWindowNG.cs new file mode 100644 index 00000000..770474da --- /dev/null +++ b/mRemoteV1/UI/Tabs/FloatWindowNG.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeifenLuo.WinFormsUI.Docking; + +namespace mRemoteNG.UI.Tabs +{ + class FloatWindowNG : FloatWindow + { + public FloatWindowNG(DockPanel dockPanel, DockPane pane) + : base(dockPanel, pane) + { + } + + public FloatWindowNG(DockPanel dockPanel, DockPane pane, Rectangle bounds) + : base(dockPanel, pane, bounds) + { + } + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/MremoteNGAutoHideStrip.cs b/mRemoteV1/UI/Tabs/MremoteNGAutoHideStrip.cs new file mode 100644 index 00000000..38088ad3 --- /dev/null +++ b/mRemoteV1/UI/Tabs/MremoteNGAutoHideStrip.cs @@ -0,0 +1,501 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using WeifenLuo.WinFormsUI.Docking; + +namespace mRemoteNG.UI.Tabs +{ + internal sealed class MremoteNGAutoHideStrip : AutoHideStripBase + { + private class TabNG : Tab + { + internal TabNG(IDockContent content) + : base(content) + { + } + + public int TabX { get; set; } + + public int TabWidth { get; set; } + } + + private const int _ImageHeight = 16; + private const int _ImageWidth = 16; + private const int _ImageGapTop = 2; + private const int _ImageGapLeft = 4; + private const int _ImageGapRight = 2; + private const int _ImageGapBottom = 2; + private const int _TextGapLeft = 0; + private const int _TextGapRight = 0; + private const int _TabGapTop = 3; + private const int _TabGapLeft = 4; + private const int _TabGapBetween = 10; + + #region Customizable Properties + + public Font TextFont => DockPanel.Theme.Skin.AutoHideStripSkin.TextFont; + + private static StringFormat _stringFormatTabHorizontal; + + private StringFormat StringFormatTabHorizontal + { + get + { + if (_stringFormatTabHorizontal == null) + { + _stringFormatTabHorizontal = new StringFormat + { + Alignment = StringAlignment.Near, + LineAlignment = StringAlignment.Center, + FormatFlags = StringFormatFlags.NoWrap, + Trimming = StringTrimming.None + }; + } + + if (RightToLeft == RightToLeft.Yes) + _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; + else + _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; + + return _stringFormatTabHorizontal; + } + } + + private static StringFormat _stringFormatTabVertical; + + private StringFormat StringFormatTabVertical + { + get + { + if (_stringFormatTabVertical == null) + { + _stringFormatTabVertical = new StringFormat(); + _stringFormatTabVertical.Alignment = StringAlignment.Near; + _stringFormatTabVertical.LineAlignment = StringAlignment.Center; + _stringFormatTabVertical.FormatFlags = + StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; + _stringFormatTabVertical.Trimming = StringTrimming.None; + } + + if (RightToLeft == RightToLeft.Yes) + _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; + else + _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; + + return _stringFormatTabVertical; + } + } + + private static int ImageHeight => _ImageHeight; + + private static int ImageWidth => _ImageWidth; + + private static int ImageGapTop => _ImageGapTop; + + private static int ImageGapLeft => _ImageGapLeft; + + private static int ImageGapRight => _ImageGapRight; + + private static int ImageGapBottom => _ImageGapBottom; + + private static int TextGapLeft => _TextGapLeft; + + private static int TextGapRight => _TextGapRight; + + private static int TabGapTop => _TabGapTop; + + private static int TabGapLeft => _TabGapLeft; + + private static int TabGapBetween => _TabGapBetween; + + private static Pen PenTabBorder => SystemPens.GrayText; + + #endregion + + private static Matrix MatrixIdentity { get; } = new Matrix(); + + private static DockState[] _dockStates; + + private static DockState[] DockStates + { + get + { + if (_dockStates == null) + { + _dockStates = new DockState[4]; + _dockStates[0] = DockState.DockLeftAutoHide; + _dockStates[1] = DockState.DockRightAutoHide; + _dockStates[2] = DockState.DockTopAutoHide; + _dockStates[3] = DockState.DockBottomAutoHide; + } + + return _dockStates; + } + } + + private static GraphicsPath _graphicsPath; + + internal static GraphicsPath GraphicsPath + { + get + { + if (_graphicsPath == null) + _graphicsPath = new GraphicsPath(); + + return _graphicsPath; + } + } + + public MremoteNGAutoHideStrip(DockPanel panel) + : base(panel) + { + SetStyle(ControlStyles.ResizeRedraw | + ControlStyles.UserPaint | + ControlStyles.AllPaintingInWmPaint | + ControlStyles.OptimizedDoubleBuffer, true); + BackColor = SystemColors.ControlLight; + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + var 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)) + { + g.FillRectangle(brush, ClientRectangle); + } + + DrawTabStrip(g); + } + + protected override void OnLayout(LayoutEventArgs levent) + { + CalculateTabs(); + base.OnLayout(levent); + } + + private void DrawTabStrip(Graphics g) + { + DrawTabStrip(g, DockState.DockTopAutoHide); + DrawTabStrip(g, DockState.DockBottomAutoHide); + DrawTabStrip(g, DockState.DockLeftAutoHide); + DrawTabStrip(g, DockState.DockRightAutoHide); + } + + private void DrawTabStrip(Graphics g, DockState dockState) + { + var rectTabStrip = GetLogicalTabStripRectangle(dockState); + + if (rectTabStrip.IsEmpty) + return; + + var matrixIdentity = g.Transform; + if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) + { + var matrixRotated = new Matrix(); + 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 (TabNG tab in pane.AutoHideTabs) + DrawTab(g, tab); + } + + g.Transform = matrixIdentity; + } + + private void CalculateTabs() + { + CalculateTabs(DockState.DockTopAutoHide); + CalculateTabs(DockState.DockBottomAutoHide); + CalculateTabs(DockState.DockLeftAutoHide); + CalculateTabs(DockState.DockRightAutoHide); + } + + private void CalculateTabs(DockState dockState) + { + var rectTabStrip = GetLogicalTabStripRectangle(dockState); + + var imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; + var imageWidth = ImageWidth; + if (imageHeight > ImageHeight) + imageWidth = ImageWidth * (imageHeight / ImageHeight); + + var x = TabGapLeft + rectTabStrip.X; + foreach (var pane in GetPanes(dockState)) + { + foreach (TabNG tab in pane.AutoHideTabs) + { + var width = imageWidth + ImageGapLeft + ImageGapRight + + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + + TextGapLeft + TextGapRight; + tab.TabX = x; + tab.TabWidth = width; + x += width; + } + + x += TabGapBetween; + } + } + + private Rectangle RtlTransform(Rectangle rect, DockState dockState) + { + Rectangle rectTransformed; + if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) + rectTransformed = rect; + else + rectTransformed = DrawHelper.RtlTransform(this, rect); + + return rectTransformed; + } + + private GraphicsPath GetTabOutline(TabNG tab, bool transformed, bool rtlTransform) + { + var dockState = tab.Content.DockHandler.DockState; + var rectTab = GetTabRectangle(tab, transformed); + if (rtlTransform) + rectTab = RtlTransform(rectTab, dockState); + var upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); + DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); + + return GraphicsPath; + } + + private void DrawTab(Graphics g, TabNG tab) + { + var rectTabOrigin = GetTabRectangle(tab); + if (rectTabOrigin.IsEmpty) + return; + + var dockState = tab.Content.DockHandler.DockState; + var 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; + 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) + { + g.Transform = MatrixIdentity; + + // Draw the icon + var rectImage = rectTabOrigin; + rectImage.X += ImageGapLeft; + rectImage.Y += ImageGapTop; + var imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; + var imageWidth = ImageWidth; + if (imageHeight > ImageHeight) + imageWidth = ImageWidth * (imageHeight / ImageHeight); + rectImage.Height = imageHeight; + rectImage.Width = imageWidth; + rectImage = GetTransformedRectangle(dockState, rectImage); + + 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); + 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) + }; + + using (var rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) + { + g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); + } + } + else + { + // Draw the icon normally without any rotation. + g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); + } + + // Draw the text + var 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; + + if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) + g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, + StringFormatTabVertical); + else + g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, + StringFormatTabHorizontal); + + // Set rotate back + g.Transform = matrixRotate; + } + } + + private Rectangle GetLogicalTabStripRectangle(DockState dockState) + { + return GetLogicalTabStripRectangle(dockState, false); + } + + private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) + { + 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 x, y, width, height; + + height = MeasureHeight(); + if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) + { + x = 0; + y = (topPanes == 0) ? 0 : height; + width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); + } + else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) + { + x = Width - height; + if (leftPanes != 0 && x < height) + x = height; + y = (topPanes == 0) ? 0 : height; + width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); + } + else if (dockState == DockState.DockTopAutoHide && topPanes > 0) + { + x = leftPanes == 0 ? 0 : height; + y = 0; + width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); + } + else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) + { + x = leftPanes == 0 ? 0 : height; + y = Height - height; + if (topPanes != 0 && y < height) + y = height; + width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); + } + else + return Rectangle.Empty; + + if (width == 0 || height == 0) + { + return Rectangle.Empty; + } + + var rect = new Rectangle(x, y, width, height); + return transformed ? GetTransformedRectangle(dockState, rect) : rect; + } + + private Rectangle GetTabRectangle(TabNG tab) + { + return GetTabRectangle(tab, false); + } + + private Rectangle GetTabRectangle(TabNG tab, bool transformed) + { + var dockState = tab.Content.DockHandler.DockState; + var rectTabStrip = GetLogicalTabStripRectangle(dockState); + + if (rectTabStrip.IsEmpty) + return Rectangle.Empty; + + var x = tab.TabX; + var y = rectTabStrip.Y + + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide + ? 0 + : TabGapTop); + var width = tab.TabWidth; + var height = rectTabStrip.Height - TabGapTop; + + if (!transformed) + return new Rectangle(x, y, width, height); + else + return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); + } + + private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) + { + if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) + return rect; + + var 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()) + { + matrix.RotateAt(90, new PointF(rectTabStrip.X + (float)rectTabStrip.Height / 2, + rectTabStrip.Y + (float)rectTabStrip.Height / 2)); + matrix.TransformPoints(pts); + } + + return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), + (int)(pts[0].Y - (float)rect.Width / 2 + .5F), + rect.Height, rect.Width); + } + + protected override IDockContent HitTest(Point point) + { + foreach (var state in DockStates) + { + var rectTabStrip = GetLogicalTabStripRectangle(state, true); + if (!rectTabStrip.Contains(point)) + continue; + + foreach (var pane in GetPanes(state)) + { + foreach (TabNG tab in pane.AutoHideTabs) + { + var path = GetTabOutline(tab, true, true); + if (path.IsVisible(point)) + return tab.Content; + } + } + } + + return null; + } + + protected override Rectangle GetTabBounds(Tab tab) + { + var path = GetTabOutline((TabNG)tab, true, true); + var bounds = path.GetBounds(); + return new Rectangle((int)bounds.Left, (int)bounds.Top, (int)bounds.Width, (int)bounds.Height); + } + + protected override int MeasureHeight() + { + return Math.Max(ImageGapBottom + + ImageGapTop + ImageHeight, + TextFont.Height) + TabGapTop; + } + + protected override void OnRefreshChanges() + { + CalculateTabs(); + Invalidate(); + } + + protected override Tab CreateTab(IDockContent content) + { + return new TabNG(content); + } + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Tabs/TabHelper.cs b/mRemoteV1/UI/Tabs/TabHelper.cs new file mode 100644 index 00000000..62e102d8 --- /dev/null +++ b/mRemoteV1/UI/Tabs/TabHelper.cs @@ -0,0 +1,56 @@ +using mRemoteNG.App; +using mRemoteNG.UI.Window; +using System; + +namespace mRemoteNG.UI.Tabs +{ + class TabHelper + { + private static readonly Lazy lazyHelper = new Lazy(() => new TabHelper()); + + public static TabHelper Instance => lazyHelper.Value; + + private TabHelper() + { + } + + private ConnectionTab currentTab; + + public ConnectionTab CurrentTab + { + get => currentTab; + set + { + currentTab = value; + findCurrentPanel(); + Runtime.MessageCollector.AddMessage(Messages.MessageClass.DebugMsg, + "Tab got focused: " + currentTab.TabText); + } + } + + private void findCurrentPanel() + { + var currentForm = currentTab.Parent; + while (currentForm != null && !(currentForm is ConnectionWindow)) + { + currentForm = currentForm.Parent; + } + + if (currentForm != null) + CurrentPanel = (ConnectionWindow)currentForm; + } + + private ConnectionWindow currentPanel; + + public ConnectionWindow CurrentPanel + { + get => currentPanel; + set + { + currentPanel = value; + Runtime.MessageCollector.AddMessage(Messages.MessageClass.DebugMsg, + "Panel got focused: " + currentPanel.TabText); + } + } + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/TaskDialog/CommandButton.cs b/mRemoteV1/UI/TaskDialog/CommandButton.cs index 6c9fc574..1cd0cea6 100644 --- a/mRemoteV1/UI/TaskDialog/CommandButton.cs +++ b/mRemoteV1/UI/TaskDialog/CommandButton.cs @@ -10,22 +10,32 @@ namespace mRemoteNG.UI.TaskDialog public sealed partial class CommandButton : Button { //-------------------------------------------------------------------------------- - #region PRIVATE MEMBERS - //-------------------------------------------------------------------------------- - Image imgArrow1; - Image imgArrow2; - private ThemeManager _themeManager; - const int LEFT_MARGIN = 10; - const int TOP_MARGIN = 10; - const int ARROW_WIDTH = 19; - enum eButtonState { Normal, MouseOver, Down } + #region PRIVATE MEMBERS + + //-------------------------------------------------------------------------------- + private Image imgArrow1; + private Image imgArrow2; + private readonly ThemeManager _themeManager; + private const int LEFT_MARGIN = 10; + private const int TOP_MARGIN = 10; + private const int ARROW_WIDTH = 19; + + enum eButtonState + { + Normal, + MouseOver, + Down + } + eButtonState m_State = eButtonState.Normal; #endregion //-------------------------------------------------------------------------------- + #region PUBLIC PROPERTIES + //-------------------------------------------------------------------------------- // Override this to make sure the control is invalidated (repainted) when 'Text' is changed public override string Text @@ -45,15 +55,26 @@ namespace mRemoteNG.UI.TaskDialog // AutoHeight determines whether the button automatically resizes itself to fit the Text bool m_autoHeight = true; + [Browsable(true)] [Category("Behavior")] [DefaultValue(true)] - public bool AutoHeight { get { return m_autoHeight; } set { m_autoHeight = value; if (m_autoHeight) Invalidate(); } } + public bool AutoHeight + { + get { return m_autoHeight; } + set + { + m_autoHeight = value; + if (m_autoHeight) Invalidate(); + } + } #endregion //-------------------------------------------------------------------------------- + #region CONSTRUCTOR + //-------------------------------------------------------------------------------- public CommandButton() { @@ -66,20 +87,25 @@ namespace mRemoteNG.UI.TaskDialog #endregion //-------------------------------------------------------------------------------- + #region PUBLIC ROUTINES + //-------------------------------------------------------------------------------- public int GetBestHeight() { return (TOP_MARGIN * 2) + (int)GetSmallTextSizeF().Height + (int)GetLargeTextSizeF().Height; } + #endregion //-------------------------------------------------------------------------------- + #region PRIVATE ROUTINES + //-------------------------------------------------------------------------------- string GetLargeText() { - string[] lines = Text.Split('\n'); + var lines = Text.Split('\n'); return lines[0]; } @@ -88,37 +114,40 @@ namespace mRemoteNG.UI.TaskDialog if (Text.IndexOf('\n') < 0) return ""; - string s = Text; - string[] lines = s.Split('\n'); + var s = Text; + var lines = s.Split('\n'); s = ""; - for (int i = 1; i < lines.Length; i++) + for (var i = 1; i < lines.Length; i++) s += lines[i] + "\n"; return s.Trim('\n'); } SizeF GetLargeTextSizeF() { - int x = LEFT_MARGIN + ARROW_WIDTH + 5; - SizeF mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN - Graphics g = Graphics.FromHwnd(Handle); - SizeF textSize = g.MeasureString(GetLargeText(), Font, mzSize); + 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); return textSize; } SizeF GetSmallTextSizeF() { - string s = GetSmallText(); + var s = GetSmallText(); if (s == "") return new SizeF(0, 0); - int x = LEFT_MARGIN + ARROW_WIDTH + 8; // <- indent small text slightly more - SizeF mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN - Graphics g = Graphics.FromHwnd(Handle); - SizeF textSize = g.MeasureString(s, SmallFont, mzSize); + 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); return textSize; } + #endregion //-------------------------------------------------------------------------------- - #region OVERRIDEs + + #region OVERRIDES + //-------------------------------------------------------------------------------- protected override void OnCreateControl() { @@ -130,20 +159,21 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- protected override void OnPaint(PaintEventArgs e) { - if ( !_themeManager.ThemingActive) + if (!_themeManager.ActiveAndExtended) { base.OnPaint(e); return; } + e.Graphics.SmoothingMode = SmoothingMode.HighQuality; e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; - LinearGradientBrush brush; - LinearGradientMode mode = LinearGradientMode.Vertical; + const LinearGradientMode mode = LinearGradientMode.Vertical; - Rectangle newRect = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1); + var newRect = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, + ClientRectangle.Height - 1); - Image img = imgArrow1; + var img = imgArrow1; Color back; @@ -151,7 +181,6 @@ namespace mRemoteNG.UI.TaskDialog Color border; if (Enabled) { - switch (m_State) { case eButtonState.MouseOver: @@ -185,22 +214,28 @@ namespace mRemoteNG.UI.TaskDialog } else { - brush = new LinearGradientBrush(newRect, back, back, mode); + var brush = new LinearGradientBrush(newRect, back, back, mode); e.Graphics.FillRectangle(brush, newRect); e.Graphics.DrawRectangle(new Pen(border, 1), newRect); } - string largetext = GetLargeText(); - string smalltext = GetSmallText(); + var largetext = GetLargeText(); + var smalltext = GetSmallText(); - SizeF szL = GetLargeTextSizeF(); + var 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, (int)szL.Height), fore, TextFormatFlags.Default); + TextRenderer.DrawText(e.Graphics, largetext, Font, + new Rectangle(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN, (int)szL.Width, + (int)szL.Height), fore, + TextFormatFlags.Default); if (smalltext != "") { - 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), szS)); + var szS = GetSmallTextSizeF(); + e.Graphics.DrawString(smalltext, SmallFont, new SolidBrush(fore), + new + RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 8, TOP_MARGIN + (int)szL.Height), + szS)); } e.Graphics.DrawImage(img, new Point(LEFT_MARGIN, TOP_MARGIN + (int)(szL.Height / 2) - img.Height / 2)); @@ -243,17 +278,19 @@ namespace mRemoteNG.UI.TaskDialog { if (m_autoHeight) { - int h = GetBestHeight(); + var h = GetBestHeight(); if (Height != h) { Height = h; return; } } + base.OnSizeChanged(e); } + #endregion //-------------------------------------------------------------------------------- } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/TaskDialog/cTaskDialog.cs b/mRemoteV1/UI/TaskDialog/cTaskDialog.cs index ef3f70d7..24143088 100644 --- a/mRemoteV1/UI/TaskDialog/cTaskDialog.cs +++ b/mRemoteV1/UI/TaskDialog/cTaskDialog.cs @@ -51,18 +51,18 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- public static DialogResult ShowTaskDialogBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - string radioButtons, - string commandButtons, - ETaskDialogButtons buttons, - ESysIcons mainIcon, - ESysIcons footerIcon, - int defaultIndex) + string title, + string mainInstruction, + string content, + string expandedInfo, + string footer, + string verificationText, + string radioButtons, + string commandButtons, + ETaskDialogButtons buttons, + ESysIcons mainIcon, + ESysIcons footerIcon, + int defaultIndex) { DialogResult result; @@ -100,36 +100,36 @@ namespace mRemoteNG.UI.TaskDialog // Overloaded versions... //-------------------------------------------------------------------------------- public static DialogResult ShowTaskDialogBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - string radioButtons, - string commandButtons, - ETaskDialogButtons buttons, - ESysIcons mainIcon, - ESysIcons footerIcon) + string title, + string mainInstruction, + string content, + string expandedInfo, + string footer, + string verificationText, + string radioButtons, + string commandButtons, + ETaskDialogButtons buttons, + ESysIcons mainIcon, + ESysIcons footerIcon) { return ShowTaskDialogBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, - radioButtons, commandButtons, buttons, mainIcon, footerIcon, 0); + radioButtons, commandButtons, buttons, mainIcon, footerIcon, 0); } public static DialogResult ShowTaskDialogBox(string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - string radioButtons, - string commandButtons, - ETaskDialogButtons buttons, - ESysIcons mainIcon, - ESysIcons footerIcon) + string mainInstruction, + string content, + string expandedInfo, + string footer, + string verificationText, + string radioButtons, + string commandButtons, + ETaskDialogButtons buttons, + ESysIcons mainIcon, + ESysIcons footerIcon) { return ShowTaskDialogBox(null, title, mainInstruction, content, expandedInfo, footer, verificationText, - radioButtons, commandButtons, buttons, mainIcon, footerIcon, 0); + radioButtons, commandButtons, buttons, mainIcon, footerIcon, 0); } #endregion @@ -140,56 +140,56 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- public static DialogResult MessageBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - ETaskDialogButtons buttons, - ESysIcons mainIcon, - ESysIcons footerIcon) + string title, + string mainInstruction, + string content, + string expandedInfo, + string footer, + string verificationText, + ETaskDialogButtons buttons, + ESysIcons mainIcon, + ESysIcons footerIcon) { return ShowTaskDialogBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, "", - "", buttons, mainIcon, footerIcon); + "", buttons, mainIcon, footerIcon); } //-------------------------------------------------------------------------------- // Overloaded versions... //-------------------------------------------------------------------------------- public static DialogResult MessageBox(string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - ETaskDialogButtons buttons, - ESysIcons mainIcon, - ESysIcons footerIcon) + string mainInstruction, + string content, + string expandedInfo, + string footer, + string verificationText, + ETaskDialogButtons buttons, + ESysIcons mainIcon, + ESysIcons footerIcon) { return ShowTaskDialogBox(null, title, mainInstruction, content, expandedInfo, footer, verificationText, "", - "", buttons, mainIcon, footerIcon); + "", buttons, mainIcon, footerIcon); } public static DialogResult MessageBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - ETaskDialogButtons buttons, - ESysIcons mainIcon) + string title, + string mainInstruction, + string content, + ETaskDialogButtons buttons, + ESysIcons mainIcon) { return MessageBox(owner, title, mainInstruction, content, "", "", "", buttons, mainIcon, - ESysIcons.Information); + ESysIcons.Information); } public static DialogResult MessageBox(string title, - string mainInstruction, - string content, - ETaskDialogButtons buttons, - ESysIcons mainIcon) + string mainInstruction, + string content, + ETaskDialogButtons buttons, + ESysIcons mainIcon) { return MessageBox(null, title, mainInstruction, content, "", "", "", buttons, mainIcon, - ESysIcons.Information); + ESysIcons.Information); } //-------------------------------------------------------------------------------- @@ -202,19 +202,20 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- 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) + 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); + radioButtons, "", ETaskDialogButtons.OkCancel, mainIcon, footerIcon, + defaultIndex); if (res == DialogResult.OK) return RadioButtonResult; return -1; @@ -224,66 +225,67 @@ namespace mRemoteNG.UI.TaskDialog // Overloaded versions... //-------------------------------------------------------------------------------- public static int ShowRadioBox(string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - string radioButtons, - ESysIcons mainIcon, - ESysIcons footerIcon, - int defaultIndex) + 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); + radioButtons, "", ETaskDialogButtons.OkCancel, mainIcon, footerIcon, + defaultIndex); if (res == DialogResult.OK) return RadioButtonResult; return -1; } public static int ShowRadioBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - string radioButtons, - ESysIcons mainIcon, - ESysIcons footerIcon) + string title, + string mainInstruction, + string content, + string expandedInfo, + string footer, + string verificationText, + string radioButtons, + ESysIcons mainIcon, + ESysIcons footerIcon) { return ShowRadioBox(owner, title, mainInstruction, content, expandedInfo, footer, verificationText, - radioButtons, ESysIcons.Question, ESysIcons.Information, 0); + radioButtons, ESysIcons.Question, ESysIcons.Information, 0); } public static int ShowRadioBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - string radioButtons, - int defaultIndex) + string title, + string mainInstruction, + string content, + string radioButtons, + int defaultIndex) { return ShowRadioBox(owner, title, mainInstruction, content, "", "", "", radioButtons, ESysIcons.Question, - ESysIcons.Information, defaultIndex); + ESysIcons.Information, defaultIndex); } public static int ShowRadioBox(IWin32Window owner, - string title, - string mainInstruction, - string content, - string radioButtons) + string title, + string mainInstruction, + string content, + string radioButtons) { return ShowRadioBox(owner, title, mainInstruction, content, "", "", "", radioButtons, ESysIcons.Question, - ESysIcons.Information, 0); + ESysIcons.Information, 0); } public static int ShowRadioBox(string title, - string mainInstruction, - string content, - string radioButtons) + string mainInstruction, + string content, + string radioButtons) { return ShowRadioBox(null, title, mainInstruction, content, "", "", "", radioButtons, ESysIcons.Question, - ESysIcons.Information, 0); + ESysIcons.Information, 0); } #endregion @@ -294,20 +296,21 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- 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) + 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); + "", commandButtons, + showCancelButton ? ETaskDialogButtons.Cancel : ETaskDialogButtons.None, + mainIcon, footerIcon); if (res == DialogResult.OK) return CommandButtonResult; return -1; @@ -317,36 +320,44 @@ namespace mRemoteNG.UI.TaskDialog // Overloaded versions... //-------------------------------------------------------------------------------- public static int ShowCommandBox(string title, - string mainInstruction, - string content, - string expandedInfo, - string footer, - string verificationText, - string commandButtons, - bool showCancelButton, - ESysIcons mainIcon, - ESysIcons footerIcon) + 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); + "", commandButtons, + showCancelButton ? ETaskDialogButtons.Cancel : ETaskDialogButtons.None, + mainIcon, footerIcon); if (res == DialogResult.OK) return CommandButtonResult; return -1; } - public static int ShowCommandBox(IWin32Window owner, string title, string mainInstruction, string content, - string commandButtons, bool showCancelButton) + public static int ShowCommandBox(IWin32Window owner, + string title, + string mainInstruction, + string content, + string commandButtons, + bool showCancelButton) { return ShowCommandBox(owner, title, mainInstruction, content, "", "", "", commandButtons, showCancelButton, - ESysIcons.Question, ESysIcons.Information); + ESysIcons.Question, ESysIcons.Information); } - public static int ShowCommandBox(string title, string mainInstruction, string content, string commandButtons, - bool showCancelButton) + public static int ShowCommandBox(string title, + string mainInstruction, + string content, + string commandButtons, + bool showCancelButton) { return ShowCommandBox(null, title, mainInstruction, content, "", "", "", commandButtons, showCancelButton, - ESysIcons.Question, ESysIcons.Information); + ESysIcons.Question, ESysIcons.Information); } #endregion diff --git a/mRemoteV1/UI/TaskDialog/frmTaskDialog.cs b/mRemoteV1/UI/TaskDialog/frmTaskDialog.cs index 65096087..6e91dd76 100644 --- a/mRemoteV1/UI/TaskDialog/frmTaskDialog.cs +++ b/mRemoteV1/UI/TaskDialog/frmTaskDialog.cs @@ -10,11 +10,15 @@ namespace mRemoteNG.UI.TaskDialog public partial class frmTaskDialog : Form { //-------------------------------------------------------------------------------- + #region PRIVATE members + //-------------------------------------------------------------------------------- private string _mainInstruction = "Main Instruction Text"; - private readonly Font _mainInstructionFont = new Font("Segoe UI", 11.75F, FontStyle.Regular, GraphicsUnit.Point, 0); + + private readonly Font _mainInstructionFont = + new Font("Segoe UI", 11.75F, FontStyle.Regular, GraphicsUnit.Point, 0); private readonly List _radioButtonCtrls = new List(); private readonly DisplayProperties _display = new DisplayProperties(); @@ -24,28 +28,51 @@ namespace mRemoteNG.UI.TaskDialog private int _mainInstructionLeftMargin; private int _mainInstructionRightMargin; + #endregion //-------------------------------------------------------------------------------- + #region PROPERTIES + //-------------------------------------------------------------------------------- public ESysIcons MainIcon { get; set; } = ESysIcons.Question; public ESysIcons FooterIcon { get; set; } = ESysIcons.Warning; - public string Title { get => Text; + public string Title + { + get => Text; set => Text = value; } - public string MainInstruction { get => _mainInstruction; - set { _mainInstruction = value; Invalidate(); } } - public string Content { get => lbContent.Text; + + public string MainInstruction + { + get => _mainInstruction; + set + { + _mainInstruction = value; + Invalidate(); + } + } + + public string Content + { + get => lbContent.Text; set => lbContent.Text = value; } - public string ExpandedInfo { get => lbExpandedInfo.Text; + + public string ExpandedInfo + { + get => lbExpandedInfo.Text; set => lbExpandedInfo.Text = value; } - public string Footer { get => lbFooter.Text; + + public string Footer + { + get => lbFooter.Text; set => lbFooter.Text = value; } + public int DefaultButtonIndex { get; set; } public string RadioButtons { get; set; } = ""; @@ -66,10 +93,15 @@ namespace mRemoteNG.UI.TaskDialog public ETaskDialogButtons Buttons { get; set; } = ETaskDialogButtons.YesNoCancel; - public string VerificationText { get => cbVerify.Text; + public string VerificationText + { + get => cbVerify.Text; set => cbVerify.Text = value; } - public bool VerificationCheckBoxChecked { get => cbVerify.Checked; + + public bool VerificationCheckBoxChecked + { + get => cbVerify.Checked; set => cbVerify.Checked = value; } @@ -78,7 +110,9 @@ namespace mRemoteNG.UI.TaskDialog #endregion //-------------------------------------------------------------------------------- + #region CONSTRUCTOR + //-------------------------------------------------------------------------------- public frmTaskDialog() { @@ -94,13 +128,17 @@ namespace mRemoteNG.UI.TaskDialog Footer = ""; VerificationText = ""; } + #endregion //-------------------------------------------------------------------------------- + #region BuildForm + // This is the main routine that should be called before .ShowDialog() //-------------------------------------------------------------------------------- private bool _formBuilt; + public void BuildForm() { var formHeight = 0; @@ -185,6 +223,7 @@ namespace mRemoteNG.UI.TaskDialog pnlHeight += rb.Height; _radioButtonCtrls.Add(rb); } + pnlRadioButtons.Height = pnlHeight; formHeight += pnlRadioButtons.Height; } @@ -202,7 +241,7 @@ namespace mRemoteNG.UI.TaskDialog { Parent = pnlCommandButtons, Location = new Point(_display.ScaleWidth(50), t) }; - if (_isVista) // <- tweak font if vista + if (_isVista) // <- tweak font if vista btn.Font = new Font(btn.Font, FontStyle.Regular); btn.Text = arr[i]; btn.Size = new Size(Width - btn.Left - _display.ScaleWidth(15), btn.GetBestHeight()); @@ -213,6 +252,7 @@ namespace mRemoteNG.UI.TaskDialog if (i == DefaultButtonIndex) _focusControl = btn; } + pnlCommandButtons.Height = pnlHeight; formHeight += pnlCommandButtons.Height; } @@ -311,6 +351,7 @@ namespace mRemoteNG.UI.TaskDialog default: throw new ArgumentOutOfRangeException(); } + formHeight += pnlFooter.Height; } @@ -323,8 +364,7 @@ namespace mRemoteNG.UI.TaskDialog private void ApplyTheme() { - if (!ThemeManager.getInstance().ThemingActive) - return; + if (!ThemeManager.getInstance().ActiveAndExtended) return; pnlButtons.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); pnlButtons.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); @@ -336,16 +376,24 @@ namespace mRemoteNG.UI.TaskDialog panel5.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); panel3.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); panel3.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlCommandButtons.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlCommandButtons.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlMainInstruction.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlMainInstruction.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlCommandButtons.BackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlCommandButtons.ForeColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlMainInstruction.BackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlMainInstruction.ForeColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); pnlContent.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); pnlContent.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlExpandedInfo.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlExpandedInfo.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlRadioButtons.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlRadioButtons.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlExpandedInfo.BackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlExpandedInfo.ForeColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlRadioButtons.BackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlRadioButtons.ForeColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } //-------------------------------------------------------------------------------- @@ -365,6 +413,7 @@ namespace mRemoteNG.UI.TaskDialog g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(srcImg, 0, 0, w, h); } + return b; } @@ -382,10 +431,13 @@ namespace mRemoteNG.UI.TaskDialog lb.Height = (int)stringSize.Height + 4; } } + #endregion //-------------------------------------------------------------------------------- + #region EVENTS + //-------------------------------------------------------------------------------- private void CommandButton_Click(object sender, EventArgs e) { @@ -445,14 +497,23 @@ namespace mRemoteNG.UI.TaskDialog { switch (MainIcon) { - case ESysIcons.Error: System.Media.SystemSounds.Hand.Play(); break; - case ESysIcons.Information: System.Media.SystemSounds.Asterisk.Play(); break; - case ESysIcons.Question: System.Media.SystemSounds.Asterisk.Play(); break; - case ESysIcons.Warning: System.Media.SystemSounds.Exclamation.Play(); break; + case ESysIcons.Error: + System.Media.SystemSounds.Hand.Play(); + break; + case ESysIcons.Information: + System.Media.SystemSounds.Asterisk.Play(); + break; + case ESysIcons.Question: + System.Media.SystemSounds.Asterisk.Play(); + break; + case ESysIcons.Warning: + System.Media.SystemSounds.Exclamation.Play(); + break; default: throw new ArgumentOutOfRangeException(); } } + _focusControl?.Focus(); } @@ -460,4 +521,4 @@ namespace mRemoteNG.UI.TaskDialog //-------------------------------------------------------------------------------- } -} +} \ No newline at end of file diff --git a/mRemoteV1/UI/Window/AboutWindow.cs b/mRemoteV1/UI/Window/AboutWindow.cs index 9f381e96..e00289e1 100644 --- a/mRemoteV1/UI/Window/AboutWindow.cs +++ b/mRemoteV1/UI/Window/AboutWindow.cs @@ -3,31 +3,32 @@ using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using System.IO; using System.Text; -using System.Text.RegularExpressions; using mRemoteNG.App; using mRemoteNG.App.Info; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Window { - public class AboutWindow : BaseWindow - { + public class AboutWindow : BaseWindow + { #region Form Init - internal Controls.Base.NGLabel lblCopyright; - internal Controls.Base.NGLabel lblTitle; - internal Controls.Base.NGLabel lblVersion; - internal Controls.Base.NGLabel lblLicense; - internal Controls.Base.NGTextBox txtChangeLog; - internal Controls.Base.NGLabel lblChangeLog; - internal Panel pnlBottom; - internal PictureBox pbLogo; + internal Controls.Base.NGLabel lblCopyright; + internal Controls.Base.NGLabel lblTitle; + internal Controls.Base.NGLabel lblVersion; + internal Controls.Base.NGLabel lblLicense; + internal Controls.Base.NGTextBox txtChangeLog; + internal Controls.Base.NGLabel lblChangeLog; + internal Panel pnlBottom; + internal PictureBox pbLogo; internal Controls.Base.NGLabel lblCredits; internal Controls.Base.NGTextBox txtCredits; internal Panel pnlTop; private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutWindow)); + { + System.ComponentModel.ComponentResourceManager resources = + new System.ComponentModel.ComponentResourceManager(typeof(AboutWindow)); this.pnlTop = new System.Windows.Forms.Panel(); this.pbLogo = new System.Windows.Forms.PictureBox(); this.pnlBottom = new System.Windows.Forms.Panel(); @@ -46,7 +47,8 @@ namespace mRemoteNG.UI.Window // // pnlTop // - this.pnlTop.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(58)))), ((int)(((byte)(64))))); + this.pnlTop.BackColor = + System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(58)))), ((int)(((byte)(64))))); this.pnlTop.Controls.Add(this.pbLogo); this.pnlTop.Dock = System.Windows.Forms.DockStyle.Top; this.pnlTop.ForeColor = System.Drawing.Color.White; @@ -97,12 +99,15 @@ namespace mRemoteNG.UI.Window // // txtCredits // - this.txtCredits.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left))); + this.txtCredits.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); this.txtCredits.BackColor = System.Drawing.SystemColors.Control; this.txtCredits.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCredits.Cursor = System.Windows.Forms.Cursors.Default; - this.txtCredits.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtCredits.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtCredits.ForeColor = System.Drawing.SystemColors.ControlText; this.txtCredits.Location = new System.Drawing.Point(8, 156); this.txtCredits.MinimumSize = new System.Drawing.Size(370, 260); @@ -116,13 +121,16 @@ namespace mRemoteNG.UI.Window // // txtChangeLog // - this.txtChangeLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.txtChangeLog.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.txtChangeLog.BackColor = System.Drawing.SystemColors.Control; this.txtChangeLog.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtChangeLog.Cursor = System.Windows.Forms.Cursors.Default; - this.txtChangeLog.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.txtChangeLog.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtChangeLog.ForeColor = System.Drawing.SystemColors.ControlText; this.txtChangeLog.Location = new System.Drawing.Point(414, 156); this.txtChangeLog.MinimumSize = new System.Drawing.Size(370, 260); @@ -137,7 +145,8 @@ namespace mRemoteNG.UI.Window // lblTitle // this.lblTitle.AutoSize = true; - this.lblTitle.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblTitle.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblTitle.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTitle.Location = new System.Drawing.Point(3, 3); this.lblTitle.Name = "lblTitle"; @@ -202,7 +211,8 @@ namespace mRemoteNG.UI.Window this.ClientSize = new System.Drawing.Size(1117, 705); this.Controls.Add(this.pnlBottom); this.Controls.Add(this.pnlTop); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ForeColor = System.Drawing.SystemColors.ControlText; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximumSize = new System.Drawing.Size(20000, 10000); @@ -216,55 +226,59 @@ namespace mRemoteNG.UI.Window this.pnlBottom.ResumeLayout(false); this.pnlBottom.PerformLayout(); this.ResumeLayout(false); + } - } #endregion - + #region Public Methods - public AboutWindow() - { - WindowType = WindowType.About; - DockPnl = new DockContent(); - InitializeComponent(); + + public AboutWindow() + { + WindowType = WindowType.About; + DockPnl = new DockContent(); + InitializeComponent(); FontOverrider.FontOverride(this); - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + ThemeManager.getInstance().ThemeChanged += ApplyTheme; ApplyLanguage(); } + #endregion - + #region Private Methods - private void ApplyLanguage() - { - lblLicense.Text = Language.strLabelReleasedUnderGPL; - lblChangeLog.Text = Language.strLabelChangeLog; - TabText = Language.strAbout; - Text = Language.strAbout; - } + + private void ApplyLanguage() + { + lblLicense.Text = Language.strLabelReleasedUnderGPL; + lblChangeLog.Text = Language.strLabelChangeLog; + TabText = Language.strAbout; + Text = Language.strAbout; + } private new void ApplyTheme() { - if (!Themes.ThemeManager.getInstance().ThemingActive) return; + if (!ThemeManager.getInstance().ThemingActive) return; base.ApplyTheme(); - BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlBottom.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlBottom.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlTop.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlTop.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + if (!ThemeManager.getInstance().ActiveAndExtended) return; + BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlBottom.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlBottom.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlTop.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlTop.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } private void ApplyEditions() - { - #if PORTABLE - lblTitle.Text += " " + Language.strLabelPortableEdition; - #endif - } + { +#if PORTABLE + lblTitle.Text += " " + Language.strLabelPortableEdition; +#endif + } - #if false +#if false private void FillLinkLabel(LinkLabel llbl, string txt, string URL) { llbl.Links.Clear(); - + int Open = txt.IndexOf("["); while (Open != -1) { @@ -278,24 +292,25 @@ namespace mRemoteNG.UI.Window llbl.Links.Add(Open, Close - Open, URL); Open = txt.IndexOf("[", Open); } - + llbl.Text = txt; } - #endif +#endif + #endregion - -#region Form Stuff - private void About_Load(object sender, EventArgs e) - { + #region Form Stuff + + private void About_Load(object sender, EventArgs e) + { ApplyTheme(); - ApplyEditions(); + ApplyEditions(); - try - { - lblCopyright.Text = GeneralAppInfo.Copyright; + try + { + lblCopyright.Text = GeneralAppInfo.Copyright; - lblVersion.Text = $@"Version {GeneralAppInfo.ApplicationVersion}"; + lblVersion.Text = $@"Version {GeneralAppInfo.ApplicationVersion}"; // AppVeyor seems to pull text files in UNIX format... This messes up the display on the about screen... // @@ -309,8 +324,9 @@ namespace mRemoteNG.UI.Window // The Changelog is a bit long anyways... Limit the number of lines to something reasonable. if (File.Exists(GeneralAppInfo.HomePath + "\\CHANGELOG.TXT")) - { - using (var sR = new StreamReader(GeneralAppInfo.HomePath + "\\CHANGELOG.TXT", Encoding.Default, true)) + { + using (var sR = new StreamReader(GeneralAppInfo.HomePath + "\\CHANGELOG.TXT", Encoding.Default, + true)) { string line; var i = 0; @@ -328,8 +344,8 @@ namespace mRemoteNG.UI.Window } } - if (File.Exists(GeneralAppInfo.HomePath + "\\CREDITS.TXT")) - { + if (File.Exists(GeneralAppInfo.HomePath + "\\CREDITS.TXT")) + { using (var sR = new StreamReader(GeneralAppInfo.HomePath + "\\CREDITS.TXT", Encoding.Default, true)) { string line; @@ -337,30 +353,31 @@ namespace mRemoteNG.UI.Window txtCredits.Text += line + Environment.NewLine; } } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, - "Loading About failed" + Environment.NewLine + ex.Message, true); - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "Loading About failed" + Environment.NewLine + ex.Message, true); + } + } #if false private void llblFAMFAMFAM_LinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) { Runtime.GoToURL(Language.strFAMFAMFAMAttributionURL); } - + private void llblMagicLibrary_LinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) { Runtime.GoToURL(Language.strMagicLibraryAttributionURL); } - + private void llblWeifenLuo_LinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) { Runtime.GoToURL(Language.strWeifenLuoAttributionURL); } #endif -#endregion - } -} + + #endregion + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.Designer.cs b/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.Designer.cs index 5761dc31..d9ec226a 100644 --- a/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.Designer.cs +++ b/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.Designer.cs @@ -22,7 +22,7 @@ namespace mRemoteNG.UI.Window // this.btnImport._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.HOVER; this.btnImport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.btnImport.Location = new System.Drawing.Point(12, 346); + this.btnImport.Location = new System.Drawing.Point(126, 345); this.btnImport.Name = "btnImport"; this.btnImport.Size = new System.Drawing.Size(75, 23); this.btnImport.TabIndex = 4; @@ -34,6 +34,7 @@ namespace mRemoteNG.UI.Window // this.txtDomain.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); + this.txtDomain.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtDomain.Location = new System.Drawing.Point(12, 25); this.txtDomain.Name = "txtDomain"; this.txtDomain.Size = new System.Drawing.Size(406, 22); @@ -53,9 +54,9 @@ namespace mRemoteNG.UI.Window // this.btnChangeDomain._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.HOVER; this.btnChangeDomain.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.btnChangeDomain.Location = new System.Drawing.Point(424, 25); + this.btnChangeDomain.Location = new System.Drawing.Point(422, 23); this.btnChangeDomain.Name = "btnChangeDomain"; - this.btnChangeDomain.Size = new System.Drawing.Size(99, 23); + this.btnChangeDomain.Size = new System.Drawing.Size(100, 24); this.btnChangeDomain.TabIndex = 2; this.btnChangeDomain.Text = "Change"; this.btnChangeDomain.UseVisualStyleBackColor = true; @@ -68,12 +69,12 @@ namespace mRemoteNG.UI.Window | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ActiveDirectoryTree.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.ActiveDirectoryTree.Domain = "DOMAIN"; + this.ActiveDirectoryTree.Domain = ""; this.ActiveDirectoryTree.Location = new System.Drawing.Point(12, 52); this.ActiveDirectoryTree.Margin = new System.Windows.Forms.Padding(4); this.ActiveDirectoryTree.Name = "ActiveDirectoryTree"; this.ActiveDirectoryTree.SelectedNode = null; - this.ActiveDirectoryTree.Size = new System.Drawing.Size(510, 271); + this.ActiveDirectoryTree.Size = new System.Drawing.Size(510, 285); this.ActiveDirectoryTree.TabIndex = 3; this.ActiveDirectoryTree.ADPathChanged += new ADTree.ADtree.ADPathChangedEventHandler(this.ActiveDirectoryTree_ADPathChanged); // @@ -81,9 +82,9 @@ namespace mRemoteNG.UI.Window // this.btnClose._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.HOVER; this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.btnClose.Location = new System.Drawing.Point(447, 330); + this.btnClose.Location = new System.Drawing.Point(422, 344); this.btnClose.Name = "btnClose"; - this.btnClose.Size = new System.Drawing.Size(75, 39); + this.btnClose.Size = new System.Drawing.Size(100, 24); this.btnClose.TabIndex = 5; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; @@ -94,7 +95,8 @@ namespace mRemoteNG.UI.Window this.chkSubOU._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; this.chkSubOU.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.chkSubOU.AutoSize = true; - this.chkSubOU.Location = new System.Drawing.Point(12, 330); + this.chkSubOU.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.chkSubOU.Location = new System.Drawing.Point(12, 349); this.chkSubOU.Name = "chkSubOU"; this.chkSubOU.Size = new System.Drawing.Size(108, 17); this.chkSubOU.TabIndex = 6; diff --git a/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.cs b/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.cs index df27f667..07e0d9fe 100644 --- a/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.cs +++ b/mRemoteV1/UI/Window/ActiveDirectoryImportWindow.cs @@ -4,6 +4,7 @@ using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using mRemoteNG.App; using mRemoteNG.Container; +using mRemoteNG.Themes; namespace mRemoteNG.UI.Window { @@ -24,10 +25,15 @@ namespace mRemoteNG.UI.Window private new void ApplyTheme() { base.ApplyTheme(); + if (ActiveDirectoryTree.Controls.Count < 1) return; + if (!(ActiveDirectoryTree.Controls[0] is TreeView tv)) return; + var tm = ThemeManager.getInstance(); + if (!tm.ActiveAndExtended) return; + tv.BackColor = tm.ActiveTheme.ExtendedPalette.getColor("List_Background"); + tv.ForeColor = tm.ActiveTheme.ExtendedPalette.getColor("List_Item_Foreground"); } #region Private Methods - #region Event Handlers @@ -37,7 +43,7 @@ namespace mRemoteNG.UI.Window txtDomain.Text = _currentDomain; ActiveDirectoryTree.Domain = _currentDomain; EnableDisableImportButton(); - + // Domain doesn't refresh on load, so it defaults to DOMAIN without this... ChangeDomain(); } diff --git a/mRemoteV1/UI/Window/BaseWindow.cs b/mRemoteV1/UI/Window/BaseWindow.cs index 877456eb..993c2c0c 100644 --- a/mRemoteV1/UI/Window/BaseWindow.cs +++ b/mRemoteV1/UI/Window/BaseWindow.cs @@ -1,16 +1,19 @@ using mRemoteNG.Themes; using WeifenLuo.WinFormsUI.Docking; + // ReSharper disable UnusedAutoPropertyAccessor.Global namespace mRemoteNG.UI.Window { - public class BaseWindow : DockContent + public class BaseWindow : DockContent { #region Private Variables + //private WindowType _WindowType; //private DockContent _DockPnl; private ThemeManager _themeManager; + #endregion #region Public Properties @@ -20,25 +23,28 @@ namespace mRemoteNG.UI.Window protected DockContent DockPnl { get; set; } #endregion - + #region Public Methods - public void SetFormText(string t) - { - Text = t; - TabText = t; - } + + public void SetFormText(string t) + { + Text = t; + TabText = t; + } + #endregion internal void ApplyTheme() - { + { _themeManager = ThemeManager.getInstance(); - if (!_themeManager.ThemingActive) return; + if (!_themeManager.ActiveAndExtended) return; BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } #region Private Methods + /* private void Base_Load(object sender, EventArgs e) { @@ -52,6 +58,7 @@ namespace mRemoteNG.UI.Window FrmMain.Default.ShowHidePanelTabs(this); } */ + #endregion private void InitializeComponent() @@ -61,10 +68,10 @@ namespace mRemoteNG.UI.Window // BaseWindow // this.ClientSize = new System.Drawing.Size(284, 261); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "BaseWindow"; this.ResumeLayout(false); - } } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ComponentsCheckWindow.cs b/mRemoteV1/UI/Window/ComponentsCheckWindow.cs index 9e70cde8..9b978864 100644 --- a/mRemoteV1/UI/Window/ComponentsCheckWindow.cs +++ b/mRemoteV1/UI/Window/ComponentsCheckWindow.cs @@ -10,16 +10,18 @@ using mRemoteNG.App; using mRemoteNG.App.Info; using mRemoteNG.Connection.Protocol.RDP; using mRemoteNG.Messages; +using mRemoteNG.Themes; using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.UI.Window { - public class ComponentsCheckWindow : BaseWindow - { - private readonly Image _successImage; - private readonly Image _failureImage; + public class ComponentsCheckWindow : BaseWindow + { + private readonly Image _successImage; + private readonly Image _failureImage; #region Form Stuff + private System.Windows.Forms.PictureBox pbCheck1; private Controls.Base.NGLabel lblCheck1; private System.Windows.Forms.Panel pnlCheck2; @@ -84,8 +86,10 @@ namespace mRemoteNG.UI.Window // // pnlCheck1 // - this.pnlCheck1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlCheck1.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlCheck1.Controls.Add(this.txtCheck1); this.pnlCheck1.Controls.Add(this.lblCheck1); this.pnlCheck1.Controls.Add(this.pbCheck1); @@ -97,9 +101,11 @@ namespace mRemoteNG.UI.Window // // txtCheck1 // - this.txtCheck1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.txtCheck1.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.txtCheck1.BackColor = System.Drawing.SystemColors.Control; this.txtCheck1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCheck1.Location = new System.Drawing.Point(129, 29); @@ -111,9 +117,12 @@ namespace mRemoteNG.UI.Window // // lblCheck1 // - this.lblCheck1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.lblCheck1.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblCheck1.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblCheck1.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCheck1.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCheck1.Location = new System.Drawing.Point(108, 3); this.lblCheck1.Name = "lblCheck1"; @@ -123,8 +132,10 @@ namespace mRemoteNG.UI.Window // // pbCheck1 // - this.pbCheck1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left))); + this.pbCheck1.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); this.pbCheck1.Location = new System.Drawing.Point(3, 3); this.pbCheck1.Name = "pbCheck1"; this.pbCheck1.Size = new System.Drawing.Size(72, 123); @@ -133,8 +144,10 @@ namespace mRemoteNG.UI.Window // // pnlCheck2 // - this.pnlCheck2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlCheck2.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlCheck2.Controls.Add(this.txtCheck2); this.pnlCheck2.Controls.Add(this.lblCheck2); this.pnlCheck2.Controls.Add(this.pbCheck2); @@ -146,9 +159,11 @@ namespace mRemoteNG.UI.Window // // txtCheck2 // - this.txtCheck2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.txtCheck2.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.txtCheck2.BackColor = System.Drawing.SystemColors.Control; this.txtCheck2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCheck2.Location = new System.Drawing.Point(129, 29); @@ -160,9 +175,12 @@ namespace mRemoteNG.UI.Window // // lblCheck2 // - this.lblCheck2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.lblCheck2.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblCheck2.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblCheck2.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCheck2.Location = new System.Drawing.Point(112, 3); this.lblCheck2.Name = "lblCheck2"; this.lblCheck2.Size = new System.Drawing.Size(447, 23); @@ -171,8 +189,10 @@ namespace mRemoteNG.UI.Window // // pbCheck2 // - this.pbCheck2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left))); + this.pbCheck2.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); this.pbCheck2.Location = new System.Drawing.Point(3, 3); this.pbCheck2.Name = "pbCheck2"; this.pbCheck2.Size = new System.Drawing.Size(72, 123); @@ -181,8 +201,10 @@ namespace mRemoteNG.UI.Window // // pnlCheck3 // - this.pnlCheck3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlCheck3.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlCheck3.Controls.Add(this.txtCheck3); this.pnlCheck3.Controls.Add(this.lblCheck3); this.pnlCheck3.Controls.Add(this.pbCheck3); @@ -194,9 +216,11 @@ namespace mRemoteNG.UI.Window // // txtCheck3 // - this.txtCheck3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.txtCheck3.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.txtCheck3.BackColor = System.Drawing.SystemColors.Control; this.txtCheck3.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCheck3.Location = new System.Drawing.Point(129, 29); @@ -208,9 +232,12 @@ namespace mRemoteNG.UI.Window // // lblCheck3 // - this.lblCheck3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.lblCheck3.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblCheck3.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblCheck3.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCheck3.Location = new System.Drawing.Point(112, 3); this.lblCheck3.Name = "lblCheck3"; this.lblCheck3.Size = new System.Drawing.Size(447, 23); @@ -219,8 +246,10 @@ namespace mRemoteNG.UI.Window // // pbCheck3 // - this.pbCheck3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left))); + this.pbCheck3.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); this.pbCheck3.Location = new System.Drawing.Point(3, 3); this.pbCheck3.Name = "pbCheck3"; this.pbCheck3.Size = new System.Drawing.Size(72, 123); @@ -229,8 +258,10 @@ namespace mRemoteNG.UI.Window // // pnlCheck4 // - this.pnlCheck4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlCheck4.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlCheck4.Controls.Add(this.txtCheck4); this.pnlCheck4.Controls.Add(this.lblCheck4); this.pnlCheck4.Controls.Add(this.pbCheck4); @@ -242,9 +273,11 @@ namespace mRemoteNG.UI.Window // // txtCheck4 // - this.txtCheck4.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.txtCheck4.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.txtCheck4.BackColor = System.Drawing.SystemColors.Control; this.txtCheck4.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCheck4.Location = new System.Drawing.Point(129, 30); @@ -256,9 +289,12 @@ namespace mRemoteNG.UI.Window // // lblCheck4 // - this.lblCheck4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.lblCheck4.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblCheck4.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblCheck4.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCheck4.Location = new System.Drawing.Point(112, 3); this.lblCheck4.Name = "lblCheck4"; this.lblCheck4.Size = new System.Drawing.Size(447, 23); @@ -267,8 +303,10 @@ namespace mRemoteNG.UI.Window // // pbCheck4 // - this.pbCheck4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left))); + this.pbCheck4.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); this.pbCheck4.Location = new System.Drawing.Point(3, 3); this.pbCheck4.Name = "pbCheck4"; this.pbCheck4.Size = new System.Drawing.Size(72, 123); @@ -277,8 +315,10 @@ namespace mRemoteNG.UI.Window // // pnlCheck5 // - this.pnlCheck5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlCheck5.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlCheck5.Controls.Add(this.txtCheck5); this.pnlCheck5.Controls.Add(this.lblCheck5); this.pnlCheck5.Controls.Add(this.pbCheck5); @@ -290,9 +330,11 @@ namespace mRemoteNG.UI.Window // // txtCheck5 // - this.txtCheck5.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.txtCheck5.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.txtCheck5.BackColor = System.Drawing.SystemColors.Control; this.txtCheck5.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCheck5.Location = new System.Drawing.Point(129, 29); @@ -304,9 +346,12 @@ namespace mRemoteNG.UI.Window // // lblCheck5 // - this.lblCheck5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.lblCheck5.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblCheck5.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblCheck5.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCheck5.Location = new System.Drawing.Point(112, 3); this.lblCheck5.Name = "lblCheck5"; this.lblCheck5.Size = new System.Drawing.Size(447, 23); @@ -315,8 +360,10 @@ namespace mRemoteNG.UI.Window // // pbCheck5 // - this.pbCheck5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left))); + this.pbCheck5.Anchor = + ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); this.pbCheck5.Location = new System.Drawing.Point(3, 3); this.pbCheck5.Name = "pbCheck5"; this.pbCheck5.Size = new System.Drawing.Size(72, 123); @@ -326,7 +373,9 @@ namespace mRemoteNG.UI.Window // btnCheckAgain // this.btnCheckAgain._mice = mRemoteNG.UI.Controls.Base.NGButton.MouseState.HOVER; - this.btnCheckAgain.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.btnCheckAgain.Anchor = + ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | + System.Windows.Forms.AnchorStyles.Right))); this.btnCheckAgain.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCheckAgain.Location = new System.Drawing.Point(476, 810); this.btnCheckAgain.Name = "btnCheckAgain"; @@ -339,7 +388,9 @@ namespace mRemoteNG.UI.Window // chkAlwaysShow // this.chkAlwaysShow._mice = mRemoteNG.UI.Controls.Base.NGCheckBox.MouseState.HOVER; - this.chkAlwaysShow.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.chkAlwaysShow.Anchor = + ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | + System.Windows.Forms.AnchorStyles.Left))); this.chkAlwaysShow.AutoSize = true; this.chkAlwaysShow.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkAlwaysShow.Location = new System.Drawing.Point(12, 814); @@ -352,9 +403,11 @@ namespace mRemoteNG.UI.Window // // pnlChecks // - this.pnlChecks.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlChecks.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlChecks.AutoScroll = true; this.pnlChecks.Controls.Add(this.pnlCheck1); this.pnlChecks.Controls.Add(this.pnlCheck2); @@ -374,7 +427,8 @@ namespace mRemoteNG.UI.Window this.Controls.Add(this.pnlChecks); this.Controls.Add(this.chkAlwaysShow); this.Controls.Add(this.btnCheckAgain); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = global::mRemoteNG.Resources.ComponentsCheck_Icon; this.Name = "ComponentsCheckWindow"; this.TabText = "Components Check"; @@ -398,11 +452,12 @@ namespace mRemoteNG.UI.Window this.pnlChecks.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); - } + #endregion #region Public Methods + public ComponentsCheckWindow() { WindowType = WindowType.ComponentsCheck; @@ -412,11 +467,13 @@ namespace mRemoteNG.UI.Window _successImage = display.ScaleImage(Resources.Good_Symbol); _failureImage = display.ScaleImage(Resources.Bad_Symbol); FontOverrider.FontOverride(this); - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + ThemeManager.getInstance().ThemeChanged += ApplyTheme; } + #endregion #region Form Stuff + private void ComponentsCheck_Load(object sender, EventArgs e) { ApplyLanguage(); @@ -435,20 +492,22 @@ namespace mRemoteNG.UI.Window private new void ApplyTheme() { - if (!Themes.ThemeManager.getInstance().ThemingActive) return; + if (!ThemeManager.getInstance().ThemingActive) return; base.ApplyTheme(); - pnlCheck1.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlCheck1.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlCheck2.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlCheck2.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlCheck3.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlCheck3.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlCheck4.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlCheck4.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlCheck5.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlCheck5.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); - pnlChecks.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - pnlChecks.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + + if (!ThemeManager.getInstance().ActiveAndExtended) return; + pnlCheck1.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlCheck1.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlCheck2.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlCheck2.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlCheck3.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlCheck3.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlCheck4.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlCheck4.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlCheck5.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlCheck5.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + pnlChecks.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlChecks.ForeColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } private void btnCheckAgain_Click(object sender, EventArgs e) @@ -459,14 +518,14 @@ namespace mRemoteNG.UI.Window private void chkAlwaysShow_CheckedChanged(object sender, EventArgs e) { Settings.Default.StartupComponentsCheck = chkAlwaysShow.Checked; - Settings.Default.Save(); } public new void Show(DockPanel panel) { try { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Trying to show the components window", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Trying to show the components window", + true); base.Show(panel); } catch (Exception ex) @@ -474,6 +533,7 @@ namespace mRemoteNG.UI.Window Runtime.MessageCollector.AddExceptionMessage("Failed to properly show the ComponentsWindow", ex); } } + #endregion private void CheckComponents() @@ -490,7 +550,7 @@ namespace mRemoteNG.UI.Window private void CheckRdp() { pnlCheck1.Visible = true; - + try { using (var rdpClient = new AxMsRdpClient8NotSafeForScripting()) @@ -506,7 +566,7 @@ namespace mRemoteNG.UI.Window if (!(new Version(rdpClient.Version) >= RdpProtocol.Versions.RDC80)) { throw new Exception( - $"Found RDC Client version {rdpClient.Version} but version {RdpProtocol.Versions.RDC80} or higher is required."); + $"Found RDC Client version {rdpClient.Version} but version {RdpProtocol.Versions.RDC80} or higher is required."); } pbCheck1.Image = _successImage; @@ -524,7 +584,7 @@ namespace mRemoteNG.UI.Window txtCheck1.Text = string.Format(Language.strCcRDPFailed, GeneralAppInfo.UrlForum); Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, - "RDP " + Language.strCcNotInstalledProperly, true); + "RDP " + Language.strCcNotInstalledProperly, true); Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, ex.Message, true); } } @@ -532,7 +592,7 @@ namespace mRemoteNG.UI.Window private void CheckVnc() { pnlCheck2.Visible = true; - + try { using (var vnc = new VncSharp.RemoteDesktop()) @@ -560,7 +620,7 @@ namespace mRemoteNG.UI.Window txtCheck2.Text = string.Format(Language.strCcVNCFailed, GeneralAppInfo.UrlForum); Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, - "VNC " + Language.strCcNotInstalledProperly, true); + "VNC " + Language.strCcNotInstalledProperly, true); } } @@ -596,16 +656,16 @@ namespace mRemoteNG.UI.Window txtCheck3.Text = Language.strCcPuttyFailed; Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, - "PuTTY " + Language.strCcNotInstalledProperly, true); + "PuTTY " + Language.strCcNotInstalledProperly, true); Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "File " + pPath + " does not exist.", - true); + true); } } private void CheckIca() { pnlCheck4.Visible = true; - + try { using (var ica = new AxICAClient()) @@ -626,7 +686,8 @@ namespace mRemoteNG.UI.Window lblCheck4.Text = @"ICA (Citrix ICA) " + Language.strCcCheckFailed; txtCheck4.Text = string.Format(Language.strCcICAFailed, GeneralAppInfo.UrlForum); - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "ICA " + Language.strCcNotInstalledProperly, true); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "ICA " + Language.strCcNotInstalledProperly, true); Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, ex.Message, true); } } @@ -670,9 +731,9 @@ namespace mRemoteNG.UI.Window txtCheck5.Text = string.Format(Language.strCcGeckoFailed, GeneralAppInfo.UrlForum); Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, - "Gecko " + Language.strCcNotInstalledProperly, true); + "Gecko " + Language.strCcNotInstalledProperly, true); Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, - "GeckoFx was not found in " + geckoFxPath, true); + "GeckoFx was not found in " + geckoFxPath, true); } } } diff --git a/mRemoteV1/UI/Window/ConfigWindow.cs b/mRemoteV1/UI/Window/ConfigWindow.cs index 34f84a5a..74762036 100644 --- a/mRemoteV1/UI/Window/ConfigWindow.cs +++ b/mRemoteV1/UI/Window/ConfigWindow.cs @@ -25,7 +25,7 @@ using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.UI.Window { public class ConfigWindow : BaseWindow - { + { private bool _originalPropertyGridToolStripItemCountValid; private int _originalPropertyGridToolStripItemCount; private System.ComponentModel.Container _components; @@ -44,6 +44,7 @@ namespace mRemoteNG.UI.Window private ThemeManager _themeManager; private AbstractConnectionRecord _selectedTreeNode; + public AbstractConnectionRecord SelectedTreeNode { get => _selectedTreeNode; @@ -55,7 +56,7 @@ namespace mRemoteNG.UI.Window } private void InitializeComponent() - { + { _components = new System.ComponentModel.Container(); Load += Config_Load; SystemColorsChanged += Config_SystemColorsChanged; @@ -89,8 +90,8 @@ namespace mRemoteNG.UI.Window //pGrid // _pGrid.Anchor = ((AnchorStyles.Top | AnchorStyles.Bottom) - | AnchorStyles.Left) - | AnchorStyles.Right; + | AnchorStyles.Left) + | AnchorStyles.Right; _pGrid.BrowsableProperties = null; _pGrid.ContextMenuStrip = PropertyGridContextMenu; _pGrid.Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, Convert.ToByte(0)); @@ -105,7 +106,10 @@ namespace mRemoteNG.UI.Window // //propertyGridContextMenu // - PropertyGridContextMenu.Items.AddRange(new ToolStripItem[] { _propertyGridContextMenuReset, _toolStripSeparator1, _propertyGridContextMenuShowHelpText }); + PropertyGridContextMenu.Items.AddRange(new ToolStripItem[] + { + _propertyGridContextMenuReset, _toolStripSeparator1, _propertyGridContextMenuShowHelpText + }); PropertyGridContextMenu.Name = "PropertyGridContextMenu"; PropertyGridContextMenu.Size = new Size(157, 76); // @@ -201,66 +205,67 @@ namespace mRemoteNG.UI.Window Text = @"Config"; PropertyGridContextMenu.ResumeLayout(false); ResumeLayout(false); - - } - + } + #region Public Properties + public bool PropertiesVisible - { - get => _btnShowProperties.Checked; + { + get => _btnShowProperties.Checked; set - { + { _btnShowProperties.Checked = value; - if (!value) return; - _btnShowInheritance.Checked = false; - _btnShowDefaultInheritance.Checked = false; - _btnShowDefaultProperties.Checked = false; - } - } - + if (!value) return; + _btnShowInheritance.Checked = false; + _btnShowDefaultInheritance.Checked = false; + _btnShowDefaultProperties.Checked = false; + } + } + public bool InheritanceVisible - { - get => _btnShowInheritance.Checked; + { + get => _btnShowInheritance.Checked; set - { + { _btnShowInheritance.Checked = value; - if (!value) return; - _btnShowProperties.Checked = false; - _btnShowDefaultInheritance.Checked = false; - _btnShowDefaultProperties.Checked = false; - } - } - + if (!value) return; + _btnShowProperties.Checked = false; + _btnShowDefaultInheritance.Checked = false; + _btnShowDefaultProperties.Checked = false; + } + } + public bool DefaultPropertiesVisible - { - get => _btnShowDefaultProperties.Checked; + { + get => _btnShowDefaultProperties.Checked; set - { + { _btnShowDefaultProperties.Checked = value; - if (!value) return; - _btnShowProperties.Checked = false; - _btnShowDefaultInheritance.Checked = false; - _btnShowInheritance.Checked = false; - } - } - + if (!value) return; + _btnShowProperties.Checked = false; + _btnShowDefaultInheritance.Checked = false; + _btnShowInheritance.Checked = false; + } + } + public bool DefaultInheritanceVisible - { - get => _btnShowDefaultInheritance.Checked; + { + get => _btnShowDefaultInheritance.Checked; set - { + { _btnShowDefaultInheritance.Checked = value; - if (!value) return; - _btnShowProperties.Checked = false; - _btnShowDefaultProperties.Checked = false; - _btnShowInheritance.Checked = false; - } - } + if (!value) return; + _btnShowProperties.Checked = false; + _btnShowDefaultProperties.Checked = false; + _btnShowInheritance.Checked = false; + } + } /// /// A list of properties being shown for the current object. /// - public IEnumerable VisibleObjectProperties => _pGrid.VisibleProperties; + public IEnumerable VisibleObjectProperties => _pGrid.VisibleProperties; + #endregion #region Constructors @@ -276,144 +281,145 @@ namespace mRemoteNG.UI.Window InitializeComponent(); ApplyLanguage(); } + #endregion #region Public Methods - - protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, Keys keyData) - { - // Main form handle command key events - // Adapted from http://kiwigis.blogspot.com/2009/05/adding-tab-key-support-to-propertygrid.html - if ((keyData & Keys.KeyCode) != Keys.Tab) return base.ProcessCmdKey(ref msg, keyData); - var selectedItem = _pGrid.SelectedGridItem; - var gridRoot = selectedItem; - while (gridRoot.GridItemType != GridItemType.Root) - { - gridRoot = gridRoot.Parent; - } - - var gridItems = new List(); - FindChildGridItems(gridRoot, ref gridItems); - - if (!ContainsGridItemProperty(gridItems)) - return true; - - var newItem = selectedItem; - - // ReSharper disable once SwitchStatementMissingSomeCases - switch (keyData) - { - case (Keys.Tab | Keys.Shift): - newItem = FindPreviousGridItemProperty(gridItems, selectedItem); - break; - case Keys.Tab: - newItem = FindNextGridItemProperty(gridItems, selectedItem); - break; - } - - _pGrid.SelectedGridItem = newItem; - - return true; // Handled - } - - private void FindChildGridItems(GridItem item, ref List gridItems) - { - gridItems.Add(item); - if (item.Expandable && !item.Expanded) return; - foreach (GridItem child in item.GridItems) - { - FindChildGridItems(child, ref gridItems); - } - } - - private bool ContainsGridItemProperty(IEnumerable gridItems) - { - return gridItems.Any(item => item.GridItemType == GridItemType.Property); - } + protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, Keys keyData) + { + // Main form handle command key events + // Adapted from http://kiwigis.blogspot.com/2009/05/adding-tab-key-support-to-propertygrid.html + if ((keyData & Keys.KeyCode) != Keys.Tab) return base.ProcessCmdKey(ref msg, keyData); + var selectedItem = _pGrid.SelectedGridItem; + var gridRoot = selectedItem; + while (gridRoot.GridItemType != GridItemType.Root) + { + gridRoot = gridRoot.Parent; + } + + var gridItems = new List(); + FindChildGridItems(gridRoot, ref gridItems); + + if (!ContainsGridItemProperty(gridItems)) + return true; + + var newItem = selectedItem; + + // ReSharper disable once SwitchStatementMissingSomeCases + switch (keyData) + { + case (Keys.Tab | Keys.Shift): + newItem = FindPreviousGridItemProperty(gridItems, selectedItem); + break; + case Keys.Tab: + newItem = FindNextGridItemProperty(gridItems, selectedItem); + break; + } + + _pGrid.SelectedGridItem = newItem; + + return true; // Handled + } + + private void FindChildGridItems(GridItem item, ref List gridItems) + { + gridItems.Add(item); + + if (item.Expandable && !item.Expanded) return; + foreach (GridItem child in item.GridItems) + { + FindChildGridItems(child, ref gridItems); + } + } + + private bool ContainsGridItemProperty(IEnumerable gridItems) + { + return gridItems.Any(item => item.GridItemType == GridItemType.Property); + } private GridItem FindPreviousGridItemProperty(IList gridItems, GridItem startItem) - { - if (gridItems.Count == 0 || startItem == null) - return null; - - var startIndex = gridItems.IndexOf(startItem); - if (startItem.GridItemType == GridItemType.Property) - { - startIndex--; - if (startIndex < 0) - { - startIndex = gridItems.Count - 1; - } - } - - var previousIndex = 0; - var previousIndexValid = false; - for (var index = startIndex; index >= 0; index--) - { - if (gridItems[index].GridItemType != GridItemType.Property) continue; - previousIndex = index; - previousIndexValid = true; - break; - } - - if (previousIndexValid) - return gridItems[previousIndex]; - - for (var index = gridItems.Count - 1; index >= startIndex + 1; index--) - { - if (gridItems[index].GridItemType != GridItemType.Property) continue; - previousIndex = index; - previousIndexValid = true; - break; - } - - return !previousIndexValid ? null : gridItems[previousIndex]; - } - - private GridItem FindNextGridItemProperty(IList gridItems, GridItem startItem) - { - if (gridItems.Count == 0 || startItem == null) - return null; - - var startIndex = gridItems.IndexOf(startItem); - if (startItem.GridItemType == GridItemType.Property) - { - startIndex++; - if (startIndex >= gridItems.Count) - { - startIndex = 0; - } - } - - var nextIndex = 0; - var nextIndexValid = false; - for (var index = startIndex; index <= gridItems.Count - 1; index++) - { - if (gridItems[index].GridItemType != GridItemType.Property) continue; - nextIndex = index; - nextIndexValid = true; - break; - } - - if (nextIndexValid) - return gridItems[nextIndex]; - - for (var index = 0; index <= startIndex - 1; index++) - { - if (gridItems[index].GridItemType != GridItemType.Property) continue; - nextIndex = index; - nextIndexValid = true; - break; - } - - return !nextIndexValid ? null : gridItems[nextIndex]; - } + { + if (gridItems.Count == 0 || startItem == null) + return null; - private void SetPropertyGridObject(object propertyGridObject) - { - try - { + var startIndex = gridItems.IndexOf(startItem); + if (startItem.GridItemType == GridItemType.Property) + { + startIndex--; + if (startIndex < 0) + { + startIndex = gridItems.Count - 1; + } + } + + var previousIndex = 0; + var previousIndexValid = false; + for (var index = startIndex; index >= 0; index--) + { + if (gridItems[index].GridItemType != GridItemType.Property) continue; + previousIndex = index; + previousIndexValid = true; + break; + } + + if (previousIndexValid) + return gridItems[previousIndex]; + + for (var index = gridItems.Count - 1; index >= startIndex + 1; index--) + { + if (gridItems[index].GridItemType != GridItemType.Property) continue; + previousIndex = index; + previousIndexValid = true; + break; + } + + return !previousIndexValid ? null : gridItems[previousIndex]; + } + + private GridItem FindNextGridItemProperty(IList gridItems, GridItem startItem) + { + if (gridItems.Count == 0 || startItem == null) + return null; + + var startIndex = gridItems.IndexOf(startItem); + if (startItem.GridItemType == GridItemType.Property) + { + startIndex++; + if (startIndex >= gridItems.Count) + { + startIndex = 0; + } + } + + var nextIndex = 0; + var nextIndexValid = false; + for (var index = startIndex; index <= gridItems.Count - 1; index++) + { + if (gridItems[index].GridItemType != GridItemType.Property) continue; + nextIndex = index; + nextIndexValid = true; + break; + } + + if (nextIndexValid) + return gridItems[nextIndex]; + + for (var index = 0; index <= startIndex - 1; index++) + { + if (gridItems[index].GridItemType != GridItemType.Property) continue; + nextIndex = index; + nextIndexValid = true; + break; + } + + return !nextIndexValid ? null : gridItems[nextIndex]; + } + + private void SetPropertyGridObject(object propertyGridObject) + { + try + { _btnShowProperties.Enabled = false; _btnShowInheritance.Enabled = false; _btnShowDefaultProperties.Enabled = false; @@ -424,62 +430,62 @@ namespace mRemoteNG.UI.Window _btnIcon.Image = null; if (propertyGridObject is ConnectionInfo gridObjectAsConnectionInfo) //CONNECTION INFO - { + { if (propertyGridObject is ContainerInfo gridObjectAsContainerInfo) //CONTAINER { if (propertyGridObject is RootNodeInfo gridObjectAsRootNodeInfo) // ROOT - { - // ReSharper disable once SwitchStatementMissingSomeCases - switch (gridObjectAsRootNodeInfo.Type) - { - case RootNodeType.Connection: - PropertiesVisible = true; - DefaultPropertiesVisible = false; - _btnShowProperties.Enabled = true; - _btnShowInheritance.Enabled = false; - _btnShowDefaultProperties.Enabled = true; - _btnShowDefaultInheritance.Enabled = true; - _btnIcon.Enabled = false; - _btnHostStatus.Enabled = false; - break; - case RootNodeType.PuttySessions: - PropertiesVisible = true; - DefaultPropertiesVisible = false; - _btnShowProperties.Enabled = true; - _btnShowInheritance.Enabled = false; - _btnShowDefaultProperties.Enabled = false; - _btnShowDefaultInheritance.Enabled = false; - _btnIcon.Enabled = false; - _btnHostStatus.Enabled = false; - break; - } - - _pGrid.SelectedObject = propertyGridObject; - } - else { - _pGrid.SelectedObject = propertyGridObject; + // ReSharper disable once SwitchStatementMissingSomeCases + switch (gridObjectAsRootNodeInfo.Type) + { + case RootNodeType.Connection: + PropertiesVisible = true; + DefaultPropertiesVisible = false; + _btnShowProperties.Enabled = true; + _btnShowInheritance.Enabled = false; + _btnShowDefaultProperties.Enabled = true; + _btnShowDefaultInheritance.Enabled = true; + _btnIcon.Enabled = false; + _btnHostStatus.Enabled = false; + break; + case RootNodeType.PuttySessions: + PropertiesVisible = true; + DefaultPropertiesVisible = false; + _btnShowProperties.Enabled = true; + _btnShowInheritance.Enabled = false; + _btnShowDefaultProperties.Enabled = false; + _btnShowDefaultInheritance.Enabled = false; + _btnIcon.Enabled = false; + _btnHostStatus.Enabled = false; + break; + } - _btnShowProperties.Enabled = true; - _btnShowInheritance.Enabled = + _pGrid.SelectedObject = propertyGridObject; + } + else + { + _pGrid.SelectedObject = propertyGridObject; + + _btnShowProperties.Enabled = true; + _btnShowInheritance.Enabled = gridObjectAsContainerInfo.Parent != null && !(gridObjectAsContainerInfo.Parent is RootNodeInfo); - _btnShowDefaultProperties.Enabled = false; - _btnShowDefaultInheritance.Enabled = false; - _btnIcon.Enabled = true; - _btnHostStatus.Enabled = false; + _btnShowDefaultProperties.Enabled = false; + _btnShowDefaultInheritance.Enabled = false; + _btnIcon.Enabled = true; + _btnHostStatus.Enabled = false; - PropertiesVisible = true; - } + PropertiesVisible = true; + } } else //NO CONTAINER - { + { if (PropertiesVisible) //Properties selected { _pGrid.SelectedObject = propertyGridObject; _btnShowProperties.Enabled = true; - _btnShowInheritance.Enabled = + _btnShowInheritance.Enabled = !(gridObjectAsConnectionInfo is PuttySessionInfo) && gridObjectAsConnectionInfo.Parent != null && !(gridObjectAsConnectionInfo.Parent is RootNodeInfo); @@ -540,33 +546,38 @@ namespace mRemoteNG.UI.Window } var conIcon = ConnectionIcon.FromString(Convert.ToString(gridObjectAsConnectionInfo.Icon)); - if (conIcon != null) - { + if (conIcon != null) + { _btnIcon.Image = conIcon.ToBitmap(); - } - } - else if (propertyGridObject is ConnectionInfoInheritance) //INHERITANCE - { + } + } + else if (propertyGridObject is ConnectionInfoInheritance) //INHERITANCE + { _pGrid.SelectedObject = propertyGridObject; - - if (InheritanceVisible) - { + + if (InheritanceVisible) + { InheritanceVisible = true; _btnShowProperties.Enabled = true; _btnShowInheritance.Enabled = true; _btnShowDefaultProperties.Enabled = false; _btnShowDefaultInheritance.Enabled = false; _btnIcon.Enabled = true; - _btnHostStatus.Enabled = !((ConnectionInfo)((ConnectionInfoInheritance)propertyGridObject).Parent).IsContainer; + _btnHostStatus.Enabled = + !((ConnectionInfo)((ConnectionInfoInheritance)propertyGridObject).Parent).IsContainer; InheritanceVisible = true; - var conIcon = ConnectionIcon.FromString(Convert.ToString(((ConnectionInfo)((ConnectionInfoInheritance)propertyGridObject).Parent).Icon)); - if (conIcon != null) - { + var conIcon = ConnectionIcon.FromString(Convert.ToString( + ((ConnectionInfo) + ((ConnectionInfoInheritance) + propertyGridObject).Parent) + .Icon)); + if (conIcon != null) + { _btnIcon.Image = conIcon.ToBitmap(); - } - } - else if (DefaultInheritanceVisible) - { + } + } + else if (DefaultInheritanceVisible) + { _btnShowProperties.Enabled = true; _btnShowInheritance.Enabled = false; _btnShowDefaultProperties.Enabled = true; @@ -575,37 +586,40 @@ namespace mRemoteNG.UI.Window _btnHostStatus.Enabled = false; DefaultInheritanceVisible = true; - } - - } + } + } ShowHideGridItems(); SetHostStatus(propertyGridObject); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConfigPropertyGridObjectFailed + Environment.NewLine + ex.Message, true); - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strConfigPropertyGridObjectFailed + Environment.NewLine + + ex.Message, true); + } + } + #endregion - + #region Private Methods - private void ApplyLanguage() - { - _btnShowInheritance.Text = Language.strButtonInheritance; - _btnShowDefaultInheritance.Text = Language.strButtonDefaultInheritance; - _btnShowProperties.Text = Language.strButtonProperties; - _btnShowDefaultProperties.Text = Language.strButtonDefaultProperties; - _btnIcon.Text = Language.strButtonIcon; - _btnHostStatus.Text = Language.strStatus; - Text = Language.strMenuConfig; - TabText = Language.strMenuConfig; - _propertyGridContextMenuShowHelpText.Text = Language.strMenuShowHelpText; - } - - private new void ApplyTheme() - { - if (!ThemeManager.getInstance().ThemingActive) return; + + private void ApplyLanguage() + { + _btnShowInheritance.Text = Language.strButtonInheritance; + _btnShowDefaultInheritance.Text = Language.strButtonDefaultInheritance; + _btnShowProperties.Text = Language.strButtonProperties; + _btnShowDefaultProperties.Text = Language.strButtonDefaultProperties; + _btnIcon.Text = Language.strButtonIcon; + _btnHostStatus.Text = Language.strStatus; + Text = Language.strMenuConfig; + TabText = Language.strMenuConfig; + _propertyGridContextMenuShowHelpText.Text = Language.strMenuShowHelpText; + } + + private new void ApplyTheme() + { + if (!ThemeManager.getInstance().ActiveAndExtended) return; _pGrid.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); _pGrid.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); _pGrid.ViewBackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Background"); @@ -613,80 +627,87 @@ namespace mRemoteNG.UI.Window _pGrid.LineColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Border"); _pGrid.HelpBackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); _pGrid.HelpForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); - _pGrid.CategoryForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Header_Foreground"); - _pGrid.CommandsDisabledLinkColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Disabled_Foreground"); - _pGrid.CommandsBackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Disabled_Background"); - _pGrid.CommandsForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Disabled_Foreground"); + _pGrid.CategoryForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Header_Foreground"); + _pGrid.CommandsDisabledLinkColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Disabled_Foreground"); + _pGrid.CommandsBackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Disabled_Background"); + _pGrid.CommandsForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("List_Item_Disabled_Foreground"); } private void AddToolStripItems() - { - try - { - var customToolStrip = new ToolStrip(); - customToolStrip.Items.Add(_btnShowProperties); - customToolStrip.Items.Add(_btnShowInheritance); - customToolStrip.Items.Add(_btnShowDefaultProperties); - customToolStrip.Items.Add(_btnShowDefaultInheritance); - customToolStrip.Items.Add(_btnHostStatus); - customToolStrip.Items.Add(_btnIcon); - customToolStrip.Show(); - - var propertyGridToolStrip = new ToolStrip(); - - ToolStrip toolStrip = null; - foreach (Control control in _pGrid.Controls) - { + { + try + { + var customToolStrip = new ToolStrip(); + customToolStrip.Items.Add(_btnShowProperties); + customToolStrip.Items.Add(_btnShowInheritance); + customToolStrip.Items.Add(_btnShowDefaultProperties); + customToolStrip.Items.Add(_btnShowDefaultInheritance); + customToolStrip.Items.Add(_btnHostStatus); + customToolStrip.Items.Add(_btnIcon); + customToolStrip.Show(); + + var propertyGridToolStrip = new ToolStrip(); + + ToolStrip toolStrip = null; + foreach (Control control in _pGrid.Controls) + { toolStrip = control as ToolStrip; - if (toolStrip == null) continue; - propertyGridToolStrip = toolStrip; - break; - } - - if (toolStrip == null) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strCouldNotFindToolStripInFilteredPropertyGrid, true); - return; - } - - if (!_originalPropertyGridToolStripItemCountValid) - { - _originalPropertyGridToolStripItemCount = propertyGridToolStrip.Items.Count; - _originalPropertyGridToolStripItemCountValid = true; - } - Debug.Assert(_originalPropertyGridToolStripItemCount == 5); - - // Hide the "Property Pages" button - propertyGridToolStrip.Items[_originalPropertyGridToolStripItemCount - 1].Visible = false; - - var expectedToolStripItemCount = _originalPropertyGridToolStripItemCount + customToolStrip.Items.Count; - if (propertyGridToolStrip.Items.Count == expectedToolStripItemCount) return; - propertyGridToolStrip.AllowMerge = true; - ToolStripManager.Merge(customToolStrip, propertyGridToolStrip); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConfigUiLoadFailed + Environment.NewLine + ex.Message, true); - } - } - - private void Config_Load(object sender, EventArgs e) - { + if (toolStrip == null) continue; + propertyGridToolStrip = toolStrip; + break; + } + + if (toolStrip == null) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strCouldNotFindToolStripInFilteredPropertyGrid, true); + return; + } + + if (!_originalPropertyGridToolStripItemCountValid) + { + _originalPropertyGridToolStripItemCount = propertyGridToolStrip.Items.Count; + _originalPropertyGridToolStripItemCountValid = true; + } + + Debug.Assert(_originalPropertyGridToolStripItemCount == 5); + + // Hide the "Property Pages" button + propertyGridToolStrip.Items[_originalPropertyGridToolStripItemCount - 1].Visible = false; + + var expectedToolStripItemCount = _originalPropertyGridToolStripItemCount + customToolStrip.Items.Count; + if (propertyGridToolStrip.Items.Count == expectedToolStripItemCount) return; + propertyGridToolStrip.AllowMerge = true; + ToolStripManager.Merge(customToolStrip, propertyGridToolStrip); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strConfigUiLoadFailed + Environment.NewLine + ex.Message, + true); + } + } + + private void Config_Load(object sender, EventArgs e) + { _themeManager = ThemeManager.getInstance(); _themeManager.ThemeChanged += ApplyTheme; ApplyTheme(); - AddToolStripItems(); - _pGrid.HelpVisible = Settings.Default.ShowConfigHelpText; - } - - private void Config_SystemColorsChanged(object sender, EventArgs e) - { - AddToolStripItems(); - } - - private void pGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) - { - try + AddToolStripItems(); + _pGrid.HelpVisible = Settings.Default.ShowConfigHelpText; + } + + private void Config_SystemColorsChanged(object sender, EventArgs e) + { + AddToolStripItems(); + } + + private void pGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) + { + try { UpdateConnectionInfoNode(e); UpdateRootInfoNode(e); @@ -694,10 +715,12 @@ namespace mRemoteNG.UI.Window ShowHideGridItems(); } catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConfigPropertyGridValueFailed + Environment.NewLine + ex.Message, true); - } - } + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strConfigPropertyGridValueFailed + Environment.NewLine + + ex.Message, true); + } + } private void UpdateConnectionInfoNode(PropertyValueChangedEventArgs e) { @@ -728,7 +751,7 @@ namespace mRemoteNG.UI.Window } if (selectedGridObject is DefaultConnectionInfo) - DefaultConnectionInfo.Instance.SaveTo(Settings.Default, a=>"ConDefault"+a); + DefaultConnectionInfo.Instance.SaveTo(Settings.Default, a => "ConDefault" + a); } private void UpdateRootInfoNode(PropertyValueChangedEventArgs e) @@ -741,8 +764,8 @@ namespace mRemoteNG.UI.Window if (rootInfo.Password) { - var passwordName = Settings.Default.UseSQLServer - ? Language.strSQLServer.TrimEnd(':') + var passwordName = Settings.Default.UseSQLServer + ? Language.strSQLServer.TrimEnd(':') : Path.GetFileName(Runtime.ConnectionsService.GetStartupConnectionFileName()); var password = MiscTools.PasswordDialog(passwordName); @@ -765,19 +788,19 @@ namespace mRemoteNG.UI.Window private void UpdateInheritanceNode() { if (!(_pGrid.SelectedObject is DefaultConnectionInheritance)) return; - DefaultConnectionInheritance.Instance.SaveTo(Settings.Default, a=>"InhDefault"+a); + DefaultConnectionInheritance.Instance.SaveTo(Settings.Default, a => "InhDefault" + a); } private void pGrid_PropertySortChanged(object sender, EventArgs e) - { - if (_pGrid.PropertySort == PropertySort.CategorizedAlphabetical) - _pGrid.PropertySort = PropertySort.Categorized; - } - - private void ShowHideGridItems() - { - try - { + { + if (_pGrid.PropertySort == PropertySort.CategorizedAlphabetical) + _pGrid.PropertySort = PropertySort.Categorized; + } + + private void ShowHideGridItems() + { + try + { var strHide = new List(); if (_pGrid.SelectedObject is RootNodeInfo o) { @@ -786,6 +809,7 @@ namespace mRemoteNG.UI.Window { strHide.Add("Password"); } + strHide.Add("CacheBitmaps"); strHide.Add("Colors"); strHide.Add("DisplayThemes"); @@ -841,488 +865,495 @@ namespace mRemoteNG.UI.Window strHide.Add("SoundQuality"); strHide.Add(nameof(AbstractConnectionRecord.CredentialRecord)); } - else if (_pGrid.SelectedObject is ConnectionInfo) - { - var conI = (ConnectionInfo)_pGrid.SelectedObject; - // ReSharper disable once SwitchStatementMissingSomeCases - switch (conI.Protocol) - { - case ProtocolType.RDP: - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("PuttySession"); - strHide.Add("RenderingEngine"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + else if (_pGrid.SelectedObject is ConnectionInfo conI) + { + // ReSharper disable once SwitchStatementMissingSomeCases + switch (conI.Protocol) + { + case ProtocolType.RDP: + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("PuttySession"); + strHide.Add("RenderingEngine"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); if (conI.RDPMinutesToIdleTimeout <= 0) { strHide.Add("RDPAlertIdleTimeout"); } - if (conI.RDGatewayUsageMethod == RdpProtocol.RDGatewayUsageMethod.Never) - { - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - } - else if (conI.RDGatewayUseConnectionCredentials == RdpProtocol.RDGatewayUseConnectionCredentials.Yes) - { - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsername"); - } - if (!(conI.Resolution == RdpProtocol.RDPResolutions.FitToWindow || conI.Resolution == RdpProtocol.RDPResolutions.Fullscreen)) - { - strHide.Add("AutomaticResize"); - } - if (conI.RedirectSound != RdpProtocol.RDPSounds.BringToThisComputer) - { + + if (conI.RDGatewayUsageMethod == RdpProtocol.RDGatewayUsageMethod.Never) + { + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + } + else if (conI.RDGatewayUseConnectionCredentials == + RdpProtocol.RDGatewayUseConnectionCredentials.Yes) + { + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsername"); + } + + if (!(conI.Resolution == RdpProtocol.RDPResolutions.FitToWindow || + conI.Resolution == RdpProtocol.RDPResolutions.Fullscreen)) + { + strHide.Add("AutomaticResize"); + } + + if (conI.RedirectSound != RdpProtocol.RDPSounds.BringToThisComputer) + { strHide.Add("SoundQuality"); } - break; - case ProtocolType.VNC: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("PuttySession"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + + break; + case ProtocolType.VNC: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("PuttySession"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - if (conI.VNCAuthMode == ProtocolVNC.AuthMode.AuthVNC) - { - strHide.Add("Username"); - strHide.Add("Domain"); - } - if (conI.VNCProxyType == ProtocolVNC.ProxyType.ProxyNone) - { - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyUsername"); - } + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + if (conI.VNCAuthMode == ProtocolVNC.AuthMode.AuthVNC) + { + strHide.Add("Username"); + strHide.Add("Domain"); + } + + if (conI.VNCProxyType == ProtocolVNC.ProxyType.ProxyNone) + { + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyUsername"); + } + strHide.Add("SoundQuality"); break; - case ProtocolType.SSH1: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.SSH1: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); break; - case ProtocolType.SSH2: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.SSH2: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); break; - case ProtocolType.Telnet: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.Telnet: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); strHide.Add(nameof(AbstractConnectionRecord.CredentialRecord)); break; - case ProtocolType.Rlogin: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.Rlogin: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); strHide.Add(nameof(AbstractConnectionRecord.CredentialRecord)); break; - case ProtocolType.RAW: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.RAW: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); strHide.Add(nameof(AbstractConnectionRecord.CredentialRecord)); break; - case ProtocolType.HTTP: - case ProtocolType.HTTPS: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("Domain"); - strHide.Add("ExtApp"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("PuttySession"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.HTTP: + case ProtocolType.HTTPS: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("Domain"); + strHide.Add("ExtApp"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("PuttySession"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); break; - case ProtocolType.ICA: - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ExtApp"); - strHide.Add("Port"); - strHide.Add("PuttySession"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.ICA: + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ExtApp"); + strHide.Add("Port"); + strHide.Add("PuttySession"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); break; - case ProtocolType.IntApp: - strHide.Add("CacheBitmaps"); - strHide.Add("Colors"); - strHide.Add("DisplayThemes"); - strHide.Add("DisplayWallpaper"); - strHide.Add("EnableFontSmoothing"); - strHide.Add("EnableDesktopComposition"); - strHide.Add("ICAEncryptionStrength"); - strHide.Add("PuttySession"); - strHide.Add("RDGatewayDomain"); - strHide.Add("RDGatewayHostname"); - strHide.Add("RDGatewayPassword"); - strHide.Add("RDGatewayUsageMethod"); - strHide.Add("RDGatewayUseConnectionCredentials"); - strHide.Add("RDGatewayUsername"); - strHide.Add("RDPAuthenticationLevel"); + case ProtocolType.IntApp: + strHide.Add("CacheBitmaps"); + strHide.Add("Colors"); + strHide.Add("DisplayThemes"); + strHide.Add("DisplayWallpaper"); + strHide.Add("EnableFontSmoothing"); + strHide.Add("EnableDesktopComposition"); + strHide.Add("ICAEncryptionStrength"); + strHide.Add("PuttySession"); + strHide.Add("RDGatewayDomain"); + strHide.Add("RDGatewayHostname"); + strHide.Add("RDGatewayPassword"); + strHide.Add("RDGatewayUsageMethod"); + strHide.Add("RDGatewayUseConnectionCredentials"); + strHide.Add("RDGatewayUsername"); + strHide.Add("RDPAuthenticationLevel"); strHide.Add("RDPMinutesToIdleTimeout"); strHide.Add("RDPAlertIdleTimeout"); strHide.Add("LoadBalanceInfo"); - strHide.Add("RedirectDiskDrives"); - strHide.Add("RedirectKeys"); - strHide.Add("RedirectPorts"); - strHide.Add("RedirectPrinters"); + strHide.Add("RedirectDiskDrives"); + strHide.Add("RedirectKeys"); + strHide.Add("RedirectPorts"); + strHide.Add("RedirectPrinters"); strHide.Add("RedirectClipboard"); strHide.Add("RedirectSmartCards"); - strHide.Add("RedirectSound"); - strHide.Add("RenderingEngine"); - strHide.Add("Resolution"); - strHide.Add("AutomaticResize"); - strHide.Add("UseConsoleSession"); - strHide.Add("UseCredSsp"); - strHide.Add("VNCAuthMode"); - strHide.Add("VNCColors"); - strHide.Add("VNCCompression"); - strHide.Add("VNCEncoding"); - strHide.Add("VNCProxyIP"); - strHide.Add("VNCProxyPassword"); - strHide.Add("VNCProxyPort"); - strHide.Add("VNCProxyType"); - strHide.Add("VNCProxyUsername"); - strHide.Add("VNCSmartSizeMode"); - strHide.Add("VNCViewOnly"); + strHide.Add("RedirectSound"); + strHide.Add("RenderingEngine"); + strHide.Add("Resolution"); + strHide.Add("AutomaticResize"); + strHide.Add("UseConsoleSession"); + strHide.Add("UseCredSsp"); + strHide.Add("VNCAuthMode"); + strHide.Add("VNCColors"); + strHide.Add("VNCCompression"); + strHide.Add("VNCEncoding"); + strHide.Add("VNCProxyIP"); + strHide.Add("VNCProxyPassword"); + strHide.Add("VNCProxyPort"); + strHide.Add("VNCProxyType"); + strHide.Add("VNCProxyUsername"); + strHide.Add("VNCSmartSizeMode"); + strHide.Add("VNCViewOnly"); strHide.Add("SoundQuality"); break; - } - - if (!(conI is DefaultConnectionInfo)) - { - if (conI.Inheritance.CacheBitmaps) - strHide.Add("CacheBitmaps"); - if (conI.Inheritance.Colors) - strHide.Add("Colors"); - if (conI.Inheritance.Description) - strHide.Add("Description"); - if (conI.Inheritance.DisplayThemes) - strHide.Add("DisplayThemes"); - if (conI.Inheritance.DisplayWallpaper) - strHide.Add("DisplayWallpaper"); - if (conI.Inheritance.EnableFontSmoothing) - strHide.Add("EnableFontSmoothing"); - if (conI.Inheritance.EnableDesktopComposition) - strHide.Add("EnableDesktopComposition"); - if (conI.Inheritance.Domain) - strHide.Add("Domain"); - if (conI.Inheritance.Icon) - strHide.Add("Icon"); - if (conI.Inheritance.Password) - strHide.Add("Password"); - if (conI.Inheritance.Port) - strHide.Add("Port"); - if (conI.Inheritance.Protocol) - strHide.Add("Protocol"); - if (conI.Inheritance.PuttySession) - strHide.Add("PuttySession"); - if (conI.Inheritance.RedirectDiskDrives) + } + + if (!(conI is DefaultConnectionInfo)) + { + if (conI.Inheritance.CacheBitmaps) + strHide.Add("CacheBitmaps"); + if (conI.Inheritance.Colors) + strHide.Add("Colors"); + if (conI.Inheritance.Description) + strHide.Add("Description"); + if (conI.Inheritance.DisplayThemes) + strHide.Add("DisplayThemes"); + if (conI.Inheritance.DisplayWallpaper) + strHide.Add("DisplayWallpaper"); + if (conI.Inheritance.EnableFontSmoothing) + strHide.Add("EnableFontSmoothing"); + if (conI.Inheritance.EnableDesktopComposition) + strHide.Add("EnableDesktopComposition"); + if (conI.Inheritance.Domain) + strHide.Add("Domain"); + if (conI.Inheritance.Icon) + strHide.Add("Icon"); + if (conI.Inheritance.Password) + strHide.Add("Password"); + if (conI.Inheritance.Port) + strHide.Add("Port"); + if (conI.Inheritance.Protocol) + strHide.Add("Protocol"); + if (conI.Inheritance.PuttySession) + strHide.Add("PuttySession"); + if (conI.Inheritance.RedirectDiskDrives) strHide.Add("RedirectDiskDrives"); if (conI.Inheritance.RedirectKeys) strHide.Add("RedirectKeys"); @@ -1408,260 +1439,288 @@ namespace mRemoteNG.UI.Window strHide.Add("RDGatewayUseConnectionCredentials"); if (conI.Inheritance.RDGatewayHostname) strHide.Add("RDGatewayHostname"); - if(conI.Inheritance.SoundQuality) + if (conI.Inheritance.SoundQuality) strHide.Add("SoundQuality"); } - else - { - strHide.Add("Hostname"); - strHide.Add("Name"); - } - } + else + { + strHide.Add("Hostname"); + strHide.Add("Name"); + } + } _pGrid.HiddenProperties = strHide.ToArray(); _pGrid.Refresh(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConfigPropertyGridHideItemsFailed + Environment.NewLine + ex.Message, true); - } - } - - private void btnShowProperties_Click(object sender, EventArgs e) - { + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strConfigPropertyGridHideItemsFailed + + Environment.NewLine + ex.Message, true); + } + } + + private void btnShowProperties_Click(object sender, EventArgs e) + { if (_pGrid.SelectedObject is ConnectionInfoInheritance o) - { - if (_pGrid.SelectedObject is DefaultConnectionInheritance) - { + { + if (_pGrid.SelectedObject is DefaultConnectionInheritance) + { PropertiesVisible = true; InheritanceVisible = false; DefaultPropertiesVisible = false; DefaultInheritanceVisible = false; SetPropertyGridObject((RootNodeInfo)_selectedTreeNode); - } - else - { + } + else + { PropertiesVisible = true; InheritanceVisible = false; DefaultPropertiesVisible = false; DefaultInheritanceVisible = false; SetPropertyGridObject(o.Parent); - } - } - else if (_pGrid.SelectedObject is ConnectionInfo) - { - if (!((ConnectionInfo) _pGrid.SelectedObject).IsDefault) return; - PropertiesVisible = true; - InheritanceVisible = false; - DefaultPropertiesVisible = false; - DefaultInheritanceVisible = false; - SetPropertyGridObject((RootNodeInfo)_selectedTreeNode); - } - } - - private void btnShowDefaultProperties_Click(object sender, EventArgs e) - { - if (!(_pGrid.SelectedObject is RootNodeInfo) && !(_pGrid.SelectedObject is ConnectionInfoInheritance)) return; - PropertiesVisible = false; - InheritanceVisible = false; - DefaultPropertiesVisible = true; - DefaultInheritanceVisible = false; - SetPropertyGridObject(DefaultConnectionInfo.Instance); - } - - private void btnShowInheritance_Click(object sender, EventArgs e) - { - if (!(_pGrid.SelectedObject is ConnectionInfo)) return; - PropertiesVisible = false; - InheritanceVisible = true; - DefaultPropertiesVisible = false; - DefaultInheritanceVisible = false; - SetPropertyGridObject(((ConnectionInfo)_pGrid.SelectedObject).Inheritance); - } - - private void btnShowDefaultInheritance_Click(object sender, EventArgs e) - { - if (!(_pGrid.SelectedObject is RootNodeInfo) && !(_pGrid.SelectedObject is ConnectionInfo)) return; - PropertiesVisible = false; - InheritanceVisible = false; - DefaultPropertiesVisible = false; - DefaultInheritanceVisible = true; - SetPropertyGridObject(DefaultConnectionInheritance.Instance); - } - - private void btnHostStatus_Click(object sender, EventArgs e) - { - SetHostStatus(_pGrid.SelectedObject); - } - - private void btnIcon_Click(object sender, MouseEventArgs e) - { - try - { - if (!(_pGrid.SelectedObject is ConnectionInfo) || _pGrid.SelectedObject is PuttySessionInfo) return; - CMenIcons.Items.Clear(); - - foreach (var iStr in ConnectionIcon.Icons) - { - var tI = new ToolStripMenuItem - { - Text = iStr, - Image = ConnectionIcon.FromString(iStr).ToBitmap() - }; - tI.Click += IconMenu_Click; + } + } + else if (_pGrid.SelectedObject is ConnectionInfo) + { + if (!((ConnectionInfo)_pGrid.SelectedObject).IsDefault) return; + PropertiesVisible = true; + InheritanceVisible = false; + DefaultPropertiesVisible = false; + DefaultInheritanceVisible = false; + SetPropertyGridObject((RootNodeInfo)_selectedTreeNode); + } + } - CMenIcons.Items.Add(tI); - } - var mPos = new Point(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.strConfigPropertyGridButtonIconClickFailed + Environment.NewLine + ex.Message, true); - } - } - - private void IconMenu_Click(object sender, EventArgs e) - { - try - { - var connectionInfo = (ConnectionInfo)_pGrid.SelectedObject; - if (connectionInfo == null) return; - - var selectedMenuItem = (ToolStripMenuItem)sender; + private void btnShowDefaultProperties_Click(object sender, EventArgs e) + { + if (!(_pGrid.SelectedObject is RootNodeInfo) && + !(_pGrid.SelectedObject is ConnectionInfoInheritance)) return; + PropertiesVisible = false; + InheritanceVisible = false; + DefaultPropertiesVisible = true; + DefaultInheritanceVisible = false; + SetPropertyGridObject(DefaultConnectionInfo.Instance); + } + + private void btnShowInheritance_Click(object sender, EventArgs e) + { + if (!(_pGrid.SelectedObject is ConnectionInfo)) return; + PropertiesVisible = false; + InheritanceVisible = true; + DefaultPropertiesVisible = false; + DefaultInheritanceVisible = false; + SetPropertyGridObject(((ConnectionInfo)_pGrid.SelectedObject).Inheritance); + } + + private void btnShowDefaultInheritance_Click(object sender, EventArgs e) + { + if (!(_pGrid.SelectedObject is RootNodeInfo) && !(_pGrid.SelectedObject is ConnectionInfo)) return; + PropertiesVisible = false; + InheritanceVisible = false; + DefaultPropertiesVisible = false; + DefaultInheritanceVisible = true; + SetPropertyGridObject(DefaultConnectionInheritance.Instance); + } + + private void btnHostStatus_Click(object sender, EventArgs e) + { + SetHostStatus(_pGrid.SelectedObject); + } + + private void btnIcon_Click(object sender, MouseEventArgs e) + { + try + { + if (!(_pGrid.SelectedObject is ConnectionInfo) || _pGrid.SelectedObject is PuttySessionInfo) return; + CMenIcons.Items.Clear(); + + foreach (var iStr in ConnectionIcon.Icons) + { + var tI = new ToolStripMenuItem + { + Text = iStr, + Image = ConnectionIcon.FromString(iStr).ToBitmap() + }; + tI.Click += IconMenu_Click; + + CMenIcons.Items.Add(tI); + } + + var mPos = new Point( + 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.strConfigPropertyGridButtonIconClickFailed + + Environment.NewLine + ex.Message, true); + } + } + + private void IconMenu_Click(object sender, EventArgs e) + { + try + { + var connectionInfo = (ConnectionInfo)_pGrid.SelectedObject; + if (connectionInfo == null) return; + + var selectedMenuItem = (ToolStripMenuItem)sender; + + var iconName = selectedMenuItem?.Text; + if (string.IsNullOrEmpty(iconName)) return; + + var connectionIcon = ConnectionIcon.FromString(iconName); + if (connectionIcon == null) return; + + _btnIcon.Image = connectionIcon.ToBitmap(); + + connectionInfo.Icon = iconName; + _pGrid.Refresh(); + + Runtime.ConnectionsService.SaveConnectionsAsync(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strConfigPropertyGridMenuClickFailed + + Environment.NewLine + ex.Message, true); + } + } - var iconName = selectedMenuItem?.Text; - if (string.IsNullOrEmpty(iconName)) return; - - var connectionIcon = ConnectionIcon.FromString(iconName); - if (connectionIcon == null) return; - - _btnIcon.Image = connectionIcon.ToBitmap(); - - connectionInfo.Icon = iconName; - _pGrid.Refresh(); - - Runtime.ConnectionsService.SaveConnectionsAsync(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConfigPropertyGridMenuClickFailed + Environment.NewLine + ex.Message, true); - } - } #endregion - + #region Host Status (Ping) - private Thread _pThread; - - private void CheckHostAlive(object hostName) - { - if (string.IsNullOrEmpty(hostName as string)) - { - ShowStatusImage(Resources.HostStatus_Off); + + private Thread _pThread; + + private void CheckHostAlive(object hostName) + { + if (string.IsNullOrEmpty(hostName as string)) + { + ShowStatusImage(Resources.HostStatus_Off); return; - } + } - var pingSender = new Ping(); + var pingSender = new Ping(); - try - { - var pReply = pingSender.Send((string)hostName); - if (pReply?.Status == IPStatus.Success) - { - if ((string)_btnHostStatus.Tag == "checking") - ShowStatusImage(Resources.HostStatus_On); - } - else - { - if ((string)_btnHostStatus.Tag == "checking") - ShowStatusImage(Resources.HostStatus_Off); - } - } - catch (Exception) - { - if ((string)_btnHostStatus.Tag == "checking") - ShowStatusImage(Resources.HostStatus_Off); - } - } + try + { + var pReply = pingSender.Send((string)hostName); + if (pReply?.Status == IPStatus.Success) + { + if ((string)_btnHostStatus.Tag == "checking") + ShowStatusImage(Resources.HostStatus_On); + } + else + { + if ((string)_btnHostStatus.Tag == "checking") + ShowStatusImage(Resources.HostStatus_Off); + } + } + catch (Exception) + { + if ((string)_btnHostStatus.Tag == "checking") + ShowStatusImage(Resources.HostStatus_Off); + } + } private delegate void ShowStatusImageCb(Image image); - private void ShowStatusImage(Image image) - { - if (_pGrid.InvokeRequired) - { - ShowStatusImageCb d = ShowStatusImage; + + private void ShowStatusImage(Image image) + { + if (_pGrid.InvokeRequired) + { + ShowStatusImageCb d = ShowStatusImage; _pGrid.Invoke(d, image); - } - else - { + } + else + { _btnHostStatus.Image = image; _btnHostStatus.Tag = "checkfinished"; - } - } + } + } - private void SetHostStatus(object connectionInfo) - { - try - { + private void SetHostStatus(object connectionInfo) + { + try + { _btnHostStatus.Image = Resources.HostStatus_Check; - // To check status, ConnectionInfo must be an mRemoteNG.Connection.Info that is not a container + // To check status, ConnectionInfo must be an mRemoteNG.Connection.Info that is not a container if (!(connectionInfo is ConnectionInfo info)) return; if (info.IsContainer) return; _btnHostStatus.Tag = "checking"; - _pThread = new Thread(CheckHostAlive); - _pThread.SetApartmentState(ApartmentState.STA); - _pThread.IsBackground = true; - _pThread.Start(((ConnectionInfo)connectionInfo).Hostname); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConfigPropertyGridSetHostStatusFailed + Environment.NewLine + ex.Message, true); - } - } + _pThread = new Thread(CheckHostAlive); + _pThread.SetApartmentState(ApartmentState.STA); + _pThread.IsBackground = true; + _pThread.Start(((ConnectionInfo)connectionInfo).Hostname); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + Language.strConfigPropertyGridSetHostStatusFailed + + Environment.NewLine + ex.Message, true); + } + } + #endregion #region Event Handlers + private void propertyGridContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) - { - try - { - _propertyGridContextMenuShowHelpText.Checked = Settings.Default.ShowConfigHelpText; - var gridItem = _pGrid.SelectedGridItem; - _propertyGridContextMenuReset.Enabled = Convert.ToBoolean(_pGrid.SelectedObject != null && gridItem?.PropertyDescriptor != null && gridItem.PropertyDescriptor.CanResetValue(_pGrid.SelectedObject)); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.Config.propertyGridContextMenu_Opening() failed.", ex); - } - } - - private void propertyGridContextMenuReset_Click(object sender, EventArgs e) - { - try - { - var gridItem = _pGrid.SelectedGridItem; - if (_pGrid.SelectedObject != null && gridItem?.PropertyDescriptor != null && gridItem.PropertyDescriptor.CanResetValue(_pGrid.SelectedObject)) - { - _pGrid.ResetSelectedProperty(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.Config.propertyGridContextMenuReset_Click() failed.", ex); - } - } - - private void propertyGridContextMenuShowHelpText_Click(object sender, EventArgs e) - { - _propertyGridContextMenuShowHelpText.Checked = !_propertyGridContextMenuShowHelpText.Checked; - } - - private void propertyGridContextMenuShowHelpText_CheckedChanged(object sender, EventArgs e) - { - Settings.Default.ShowConfigHelpText = _propertyGridContextMenuShowHelpText.Checked; - _pGrid.HelpVisible = _propertyGridContextMenuShowHelpText.Checked; + { + try + { + _propertyGridContextMenuShowHelpText.Checked = Settings.Default.ShowConfigHelpText; + var gridItem = _pGrid.SelectedGridItem; + _propertyGridContextMenuReset.Enabled = Convert.ToBoolean( + _pGrid.SelectedObject != null && + gridItem?.PropertyDescriptor != null && + gridItem.PropertyDescriptor + .CanResetValue(_pGrid + .SelectedObject)); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + "UI.Window.Config.propertyGridContextMenu_Opening() failed.", + ex); + } } + + private void propertyGridContextMenuReset_Click(object sender, EventArgs e) + { + try + { + var gridItem = _pGrid.SelectedGridItem; + if (_pGrid.SelectedObject != null && gridItem?.PropertyDescriptor != null && + gridItem.PropertyDescriptor.CanResetValue(_pGrid.SelectedObject)) + { + _pGrid.ResetSelectedProperty(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + "UI.Window.Config.propertyGridContextMenuReset_Click() failed.", + ex); + } + } + + private void propertyGridContextMenuShowHelpText_Click(object sender, EventArgs e) + { + _propertyGridContextMenuShowHelpText.Checked = !_propertyGridContextMenuShowHelpText.Checked; + } + + private void propertyGridContextMenuShowHelpText_CheckedChanged(object sender, EventArgs e) + { + Settings.Default.ShowConfigHelpText = _propertyGridContextMenuShowHelpText.Checked; + _pGrid.HelpVisible = _propertyGridContextMenuShowHelpText.Checked; + } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ConnectionTreeWindow.Designer.cs b/mRemoteV1/UI/Window/ConnectionTreeWindow.Designer.cs index 555cca06..09c05c9f 100644 --- a/mRemoteV1/UI/Window/ConnectionTreeWindow.Designer.cs +++ b/mRemoteV1/UI/Window/ConnectionTreeWindow.Designer.cs @@ -4,7 +4,6 @@ namespace mRemoteNG.UI.Window { #region Windows Form Designer generated code internal System.Windows.Forms.MenuStrip msMain; - internal System.Windows.Forms.ToolStripMenuItem mMenView; internal System.Windows.Forms.ToolStripMenuItem mMenViewExpandAllFolders; internal System.Windows.Forms.ToolStripMenuItem mMenViewCollapseAllFolders; internal System.Windows.Forms.ToolStripMenuItem mMenSortAscending; @@ -18,12 +17,11 @@ namespace mRemoteNG.UI.Window this.msMain = new System.Windows.Forms.MenuStrip(); this.mMenAddConnection = new System.Windows.Forms.ToolStripMenuItem(); this.mMenAddFolder = new System.Windows.Forms.ToolStripMenuItem(); - this.mMenView = new System.Windows.Forms.ToolStripMenuItem(); this.mMenViewExpandAllFolders = new System.Windows.Forms.ToolStripMenuItem(); this.mMenViewCollapseAllFolders = new System.Windows.Forms.ToolStripMenuItem(); this.mMenSortAscending = new System.Windows.Forms.ToolStripMenuItem(); this.vsToolStripExtender = new WeifenLuo.WinFormsUI.Docking.VisualStudioToolStripExtender(this.components); - this.PictureBoxSearch = new Controls.Base.NGPictureBox(); + this.PictureBoxSearch = new mRemoteNG.UI.Controls.Base.NGPictureBox(this.components); this.txtSearch = new mRemoteNG.UI.Controls.Base.NGTextBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); ((System.ComponentModel.ISupportInitialize)(this.olvConnections)).BeginInit(); @@ -39,10 +37,10 @@ namespace mRemoteNG.UI.Window this.olvConnections.CellEditUseWholeCell = false; this.olvConnections.Cursor = System.Windows.Forms.Cursors.Default; this.olvConnections.Dock = System.Windows.Forms.DockStyle.Fill; + this.olvConnections.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.olvConnections.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.olvConnections.HideSelection = false; this.olvConnections.IsSimpleDragSource = true; - this.olvConnections.IsSimpleDropSink = true; this.olvConnections.LabelEdit = true; this.olvConnections.Location = new System.Drawing.Point(0, 24); this.olvConnections.MultiSelect = false; @@ -66,7 +64,8 @@ namespace mRemoteNG.UI.Window this.msMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mMenAddConnection, this.mMenAddFolder, - this.mMenView, + this.mMenViewExpandAllFolders, + this.mMenViewCollapseAllFolders, this.mMenSortAscending}); this.msMain.Location = new System.Drawing.Point(0, 0); this.msMain.Name = "msMain"; @@ -93,29 +92,20 @@ namespace mRemoteNG.UI.Window this.mMenAddFolder.Size = new System.Drawing.Size(28, 20); this.mMenAddFolder.Click += new System.EventHandler(this.cMenTreeAddFolder_Click); // - // mMenView - // - this.mMenView.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.mMenView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.mMenViewExpandAllFolders, - this.mMenViewCollapseAllFolders}); - this.mMenView.Image = global::mRemoteNG.Resources.View; - this.mMenView.Name = "mMenView"; - this.mMenView.Size = new System.Drawing.Size(28, 20); - this.mMenView.Text = "&View"; - // // mMenViewExpandAllFolders // + this.mMenViewExpandAllFolders.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mMenViewExpandAllFolders.Image = global::mRemoteNG.Resources.Expand; this.mMenViewExpandAllFolders.Name = "mMenViewExpandAllFolders"; - this.mMenViewExpandAllFolders.Size = new System.Drawing.Size(172, 22); + this.mMenViewExpandAllFolders.Size = new System.Drawing.Size(28, 20); this.mMenViewExpandAllFolders.Text = "Expand all folders"; // // mMenViewCollapseAllFolders // + this.mMenViewCollapseAllFolders.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mMenViewCollapseAllFolders.Image = global::mRemoteNG.Resources.Collapse; this.mMenViewCollapseAllFolders.Name = "mMenViewCollapseAllFolders"; - this.mMenViewCollapseAllFolders.Size = new System.Drawing.Size(172, 22); + this.mMenViewCollapseAllFolders.Size = new System.Drawing.Size(133, 20); this.mMenViewCollapseAllFolders.Text = "Collapse all folders"; // // mMenSortAscending @@ -145,6 +135,7 @@ namespace mRemoteNG.UI.Window // this.txtSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.None; + this.txtSearch.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtSearch.ForeColor = System.Drawing.SystemColors.GrayText; this.txtSearch.Location = new System.Drawing.Point(26, 3); this.txtSearch.Margin = new System.Windows.Forms.Padding(0); diff --git a/mRemoteV1/UI/Window/ConnectionTreeWindow.cs b/mRemoteV1/UI/Window/ConnectionTreeWindow.cs index c77b032f..e5f64cd0 100644 --- a/mRemoteV1/UI/Window/ConnectionTreeWindow.cs +++ b/mRemoteV1/UI/Window/ConnectionTreeWindow.cs @@ -13,46 +13,48 @@ using System.Drawing; using System.Linq; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; + // ReSharper disable ArrangeAccessorOwnerBody namespace mRemoteNG.UI.Window { public partial class ConnectionTreeWindow - { + { private readonly IConnectionInitiator _connectionInitiator = new ConnectionInitiator(Runtime.CredentialService); - private ThemeManager _themeManager; + private ThemeManager _themeManager; - public ConnectionInfo SelectedNode => olvConnections.SelectedNode; + public ConnectionInfo SelectedNode => olvConnections.SelectedNode; - public ConnectionTree ConnectionTree - { - get { return olvConnections; } - } - - public ConnectionTreeWindow() : this(new DockContent()) - { - } - - public ConnectionTreeWindow(DockContent panel) - { - WindowType = WindowType.Tree; - DockPnl = panel; - InitializeComponent(); - SetMenuEventHandlers(); - SetConnectionTreeEventHandlers(); - Settings.Default.PropertyChanged += OnAppSettingsChanged; - ApplyLanguage(); + public ConnectionTree ConnectionTree + { + get { return olvConnections; } } - private void OnAppSettingsChanged(object o, PropertyChangedEventArgs propertyChangedEventArgs) - { - if (propertyChangedEventArgs.PropertyName == nameof(Settings.UseFilterSearch)) - { - ConnectionTree.UseFiltering = Settings.Default.UseFilterSearch; - ApplyFiltering(); + public ConnectionTreeWindow() : this(new DockContent()) + { + } + + public ConnectionTreeWindow(DockContent panel) + { + WindowType = WindowType.Tree; + DockPnl = panel; + InitializeComponent(); + SetMenuEventHandlers(); + SetConnectionTreeEventHandlers(); + Settings.Default.PropertyChanged += OnAppSettingsChanged; + ApplyLanguage(); + } + + private void OnAppSettingsChanged(object o, PropertyChangedEventArgs propertyChangedEventArgs) + { + if (propertyChangedEventArgs.PropertyName == nameof(Settings.UseFilterSearch)) + { + ConnectionTree.UseFiltering = Settings.Default.UseFilterSearch; + ApplyFiltering(); } PlaceSearchBar(Settings.Default.PlaceSearchBarAboveConnectionTree); + SetConnectionTreeClickHandlers(); } private void PlaceSearchBar(bool placeSearchBarAboveConnectionTree) @@ -61,7 +63,8 @@ namespace mRemoteNG.UI.Window } - #region Form Stuff + #region Form Stuff + private void Tree_Load(object sender, EventArgs e) { //work on the theme change @@ -82,7 +85,6 @@ namespace mRemoteNG.UI.Window mMenAddConnection.ToolTipText = Language.strAddConnection; mMenAddFolder.ToolTipText = Language.strAddFolder; - mMenView.ToolTipText = Language.strMenuView.Replace("&", ""); mMenViewExpandAllFolders.Text = Language.strExpandAllFolders; mMenViewCollapseAllFolders.Text = Language.strCollapseAllFolders; mMenSortAscending.ToolTipText = Language.strSortAsc; @@ -94,86 +96,100 @@ namespace mRemoteNG.UI.Window { if (!_themeManager.ThemingActive) return; vsToolStripExtender.SetStyle(msMain, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - vsToolStripExtender.SetStyle(olvConnections.ContextMenuStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(olvConnections.ContextMenuStrip, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + + if (!_themeManager.ActiveAndExtended) return; //Treelistview need to be manually themed olvConnections.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TreeView_Background"); olvConnections.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TreeView_Foreground"); - olvConnections.SelectedBackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Active_Background"); - olvConnections.SelectedForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Active_Foreground"); - olvConnections.UnfocusedSelectedBackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Inactive_Background"); - olvConnections.UnfocusedSelectedForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Inactive_Foreground"); + olvConnections.SelectedBackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Active_Background"); + olvConnections.SelectedForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Active_Foreground"); + olvConnections.UnfocusedSelectedBackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Inactive_Background"); + olvConnections.UnfocusedSelectedForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("Treeview_SelectedItem_Inactive_Foreground"); //There is a border around txtSearch that dont theme well txtSearch.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); txtSearch.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); } + #endregion #region ConnectionTree - private void SetConnectionTreeEventHandlers() - { - olvConnections.NodeDeletionConfirmer = new SelectedConnectionDeletionConfirmer(prompt => - CTaskDialog.MessageBox(Application.ProductName, prompt, "", ETaskDialogButtons.YesNo, ESysIcons.Question)); + + private void SetConnectionTreeEventHandlers() + { + olvConnections.NodeDeletionConfirmer = new SelectedConnectionDeletionConfirmer(prompt => + CTaskDialog + .MessageBox(Application.ProductName, + prompt, + "", + ETaskDialogButtons + .YesNo, + ESysIcons + .Question)); olvConnections.KeyDown += tvConnections_KeyDown; olvConnections.KeyPress += tvConnections_KeyPress; SetTreePostSetupActions(); - SetConnectionTreeDoubleClickHandlers(); - SetConnectionTreeSingleClickHandlers(); - Runtime.ConnectionsService.ConnectionsLoaded += ConnectionsServiceOnConnectionsLoaded; + SetConnectionTreeClickHandlers(); + Runtime.ConnectionsService.ConnectionsLoaded += ConnectionsServiceOnConnectionsLoaded; } - private void SetTreePostSetupActions() - { - var actions = new List - { - new PreviouslyOpenedFolderExpander(), - new RootNodeExpander() - }; + private void SetTreePostSetupActions() + { + var actions = new List + { + new PreviouslyOpenedFolderExpander(), + new RootNodeExpander() + }; - if (Settings.Default.OpenConsFromLastSession && !Settings.Default.NoReconnect) + if (Settings.Default.OpenConsFromLastSession && !Settings.Default.NoReconnect) actions.Add(new PreviousSessionOpener(_connectionInitiator)); - olvConnections.PostSetupActions = actions; - } - - private void SetConnectionTreeDoubleClickHandlers() - { - var doubleClickHandler = new TreeNodeCompositeClickHandler - { - ClickHandlers = new ITreeNodeClickHandler[] - { - new ExpandNodeClickHandler(olvConnections), - new OpenConnectionClickHandler(_connectionInitiator) - } - }; - olvConnections.DoubleClickHandler = doubleClickHandler; - } - - private void SetConnectionTreeSingleClickHandlers() - { - var handlers = new List>(); - if (Settings.Default.SingleClickOnConnectionOpensIt) - handlers.Add(new OpenConnectionClickHandler(_connectionInitiator)); - if (Settings.Default.SingleClickSwitchesToOpenConnection) - handlers.Add(new SwitchToConnectionClickHandler(_connectionInitiator)); - var singleClickHandler = new TreeNodeCompositeClickHandler {ClickHandlers = handlers}; - olvConnections.SingleClickHandler = singleClickHandler; + olvConnections.PostSetupActions = actions; } - private void ConnectionsServiceOnConnectionsLoaded(object o, ConnectionsLoadedEventArgs connectionsLoadedEventArgs) - { - if (olvConnections.InvokeRequired) - { - olvConnections.Invoke(() => ConnectionsServiceOnConnectionsLoaded(o, connectionsLoadedEventArgs)); + private void SetConnectionTreeClickHandlers() + { + var singleClickHandlers = new List>(); + var doubleClickHandlers = new List> + { + new ExpandNodeClickHandler(olvConnections) + }; + + if (Settings.Default.SingleClickOnConnectionOpensIt) + singleClickHandlers.Add(new OpenConnectionClickHandler(_connectionInitiator)); + else + doubleClickHandlers.Add(new OpenConnectionClickHandler(_connectionInitiator)); + + if (Settings.Default.SingleClickSwitchesToOpenConnection) + singleClickHandlers.Add(new SwitchToConnectionClickHandler(_connectionInitiator)); + + olvConnections.SingleClickHandler = new TreeNodeCompositeClickHandler {ClickHandlers = singleClickHandlers}; + olvConnections.DoubleClickHandler = new TreeNodeCompositeClickHandler {ClickHandlers = doubleClickHandlers}; + } + + private void ConnectionsServiceOnConnectionsLoaded(object o, + ConnectionsLoadedEventArgs connectionsLoadedEventArgs) + { + if (olvConnections.InvokeRequired) + { + olvConnections.Invoke(() => ConnectionsServiceOnConnectionsLoaded(o, connectionsLoadedEventArgs)); return; - } + } // TODO: might not need this call anymore olvConnections.SelectedObject = ConnectionTree.ConnectionTreeModel?.RootNodes - .OfType().FirstOrDefault(); - } + .OfType().FirstOrDefault(); + } + #endregion #region Top Menu + private void SetMenuEventHandlers() { mMenViewExpandAllFolders.Click += (sender, args) => olvConnections.ExpandAll(); @@ -182,38 +198,43 @@ namespace mRemoteNG.UI.Window olvConnections.CollapseAll(); olvConnections.Expand(olvConnections.GetRootConnectionNode()); }; - mMenSortAscending.Click += (sender, args) => olvConnections.SortRecursive(olvConnections.GetRootConnectionNode(), ListSortDirection.Ascending); + mMenSortAscending.Click += (sender, args) => + olvConnections.SortRecursive(olvConnections.GetRootConnectionNode(), ListSortDirection.Ascending); } + #endregion #region Tree Context Menu + private void cMenTreeAddConnection_Click(object sender, EventArgs e) - { - olvConnections.AddConnection(); - } + { + olvConnections.AddConnection(); + } private void cMenTreeAddFolder_Click(object sender, EventArgs e) - { + { olvConnections.AddFolder(); - } + } + #endregion #region Search + private void txtSearch_GotFocus(object sender, EventArgs e) - { - if (txtSearch.Text == Language.strSearchPrompt) - txtSearch.Text = ""; - } + { + if (txtSearch.Text == Language.strSearchPrompt) + txtSearch.Text = ""; + } private void txtSearch_LostFocus(object sender, EventArgs e) - { + { if (txtSearch.Text != "") return; txtSearch.Text = Language.strSearchPrompt; - } + } private void txtSearch_KeyDown(object sender, KeyEventArgs e) - { - try + { + try { switch (e.KeyCode) { @@ -240,94 +261,103 @@ namespace mRemoteNG.UI.Window break; } } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("txtSearch_KeyDown (UI.Window.ConnectionTreeWindow) failed", ex); - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace( + "txtSearch_KeyDown (UI.Window.ConnectionTreeWindow) failed", + ex); + } + } private void txtSearch_TextChanged(object sender, EventArgs e) { ApplyFiltering(); } - private void ApplyFiltering() - { - if (Settings.Default.UseFilterSearch) - { - if (txtSearch.Text == "" || txtSearch.Text == Language.strSearchPrompt) - { - olvConnections.RemoveFilter(); - return; - } - olvConnections.ApplyFilter(txtSearch.Text); - } - else - { - if (txtSearch.Text == "") return; - olvConnections.NodeSearcher?.SearchByName(txtSearch.Text); - JumpToNode(olvConnections.NodeSearcher?.CurrentMatch); - } + private void ApplyFiltering() + { + if (Settings.Default.UseFilterSearch) + { + if (txtSearch.Text == "" || txtSearch.Text == Language.strSearchPrompt) + { + olvConnections.RemoveFilter(); + return; + } + + olvConnections.ApplyFilter(txtSearch.Text); + } + else + { + if (txtSearch.Text == "") return; + olvConnections.NodeSearcher?.SearchByName(txtSearch.Text); + JumpToNode(olvConnections.NodeSearcher?.CurrentMatch); + } } - public void JumpToNode(ConnectionInfo connectionInfo) - { - if (connectionInfo == null) - { - olvConnections.SelectedObject = null; + public void JumpToNode(ConnectionInfo connectionInfo) + { + if (connectionInfo == null) + { + olvConnections.SelectedObject = null; return; - } - ExpandParentsRecursive(connectionInfo); + } + + ExpandParentsRecursive(connectionInfo); olvConnections.SelectObject(connectionInfo); olvConnections.EnsureModelVisible(connectionInfo); } - private void ExpandParentsRecursive(ConnectionInfo connectionInfo) - { - while (true) - { - if (connectionInfo?.Parent == null) return; - olvConnections.Expand(connectionInfo.Parent); - connectionInfo = connectionInfo.Parent; - } - } + private void ExpandParentsRecursive(ConnectionInfo connectionInfo) + { + while (true) + { + if (connectionInfo?.Parent == null) return; + olvConnections.Expand(connectionInfo.Parent); + connectionInfo = connectionInfo.Parent; + } + } - private void tvConnections_KeyPress(object sender, KeyPressEventArgs e) - { - try - { - if (!char.IsLetterOrDigit(e.KeyChar)) return; - txtSearch.Text = e.KeyChar.ToString(); - txtSearch.Focus(); - txtSearch.SelectionStart = txtSearch.TextLength; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("tvConnections_KeyPress (UI.Window.ConnectionTreeWindow) failed", ex); - } - } + private void tvConnections_KeyPress(object sender, KeyPressEventArgs e) + { + try + { + if (!char.IsLetterOrDigit(e.KeyChar)) return; + txtSearch.Text = e.KeyChar.ToString(); + txtSearch.Focus(); + txtSearch.SelectionStart = txtSearch.TextLength; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace( + "tvConnections_KeyPress (UI.Window.ConnectionTreeWindow) failed", + ex); + } + } private void tvConnections_KeyDown(object sender, KeyEventArgs e) - { - try - { - if (e.KeyCode == Keys.Enter) - { - e.Handled = true; + { + try + { + if (e.KeyCode == Keys.Enter) + { + e.Handled = true; _connectionInitiator.OpenConnection(SelectedNode); - } - else if (e.Control && e.KeyCode == Keys.F) - { - txtSearch.Focus(); + } + else if (e.Control && e.KeyCode == Keys.F) + { + txtSearch.Focus(); txtSearch.SelectAll(); - e.Handled = true; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionStackTrace("tvConnections_KeyDown (UI.Window.ConnectionTreeWindow) failed", ex); - } - } + e.Handled = true; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionStackTrace( + "tvConnections_KeyDown (UI.Window.ConnectionTreeWindow) failed", + ex); + } + } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ConnectionWindow.Designer.cs b/mRemoteV1/UI/Window/ConnectionWindow.Designer.cs index 5b4a9732..ab2c4121 100644 --- a/mRemoteV1/UI/Window/ConnectionWindow.Designer.cs +++ b/mRemoteV1/UI/Window/ConnectionWindow.Designer.cs @@ -1,7 +1,6 @@ using System; using System.Drawing; using System.Windows.Forms; -using TabControl = Crownwood.Magic.Controls.TabControl; namespace mRemoteNG.UI.Window @@ -9,12 +8,12 @@ namespace mRemoteNG.UI.Window public partial class ConnectionWindow { internal ContextMenuStrip cmenTab; - private System.ComponentModel.Container components; private ToolStripMenuItem cmenTabFullscreen; private ToolStripMenuItem cmenTabScreenshot; private ToolStripMenuItem cmenTabTransferFile; private ToolStripMenuItem cmenTabSendSpecialKeys; private ToolStripSeparator cmenTabSep1; + private ToolStripSeparator cmenTabSep2; private ToolStripMenuItem cmenTabRenameTab; private ToolStripMenuItem cmenTabDuplicateTab; private ToolStripMenuItem cmenTabDisconnect; @@ -28,229 +27,229 @@ namespace mRemoteNG.UI.Window internal ToolStripMenuItem cmenTabExternalApps; private ToolStripMenuItem cmenTabStartChat; private ToolStripMenuItem cmenTabRefreshScreen; - private ToolStripSeparator ToolStripSeparator1; private ToolStripMenuItem cmenTabPuttySettings; private void InitializeComponent() { - components = new System.ComponentModel.Container(); + this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConnectionWindow)); - TabController = new TabControl(); - cmenTab = new ContextMenuStrip(components); - cmenTabFullscreen = new ToolStripMenuItem(); - cmenTabSmartSize = new ToolStripMenuItem(); - cmenTabViewOnly = new ToolStripMenuItem(); - ToolStripSeparator1 = new ToolStripSeparator(); - cmenTabScreenshot = new ToolStripMenuItem(); - cmenTabStartChat = new ToolStripMenuItem(); - cmenTabTransferFile = new ToolStripMenuItem(); - cmenTabRefreshScreen = new ToolStripMenuItem(); - cmenTabSendSpecialKeys = new ToolStripMenuItem(); - cmenTabSendSpecialKeysCtrlAltDel = new ToolStripMenuItem(); - cmenTabSendSpecialKeysCtrlEsc = new ToolStripMenuItem(); - cmenTabExternalApps = new ToolStripMenuItem(); - cmenTabSep1 = new ToolStripSeparator(); - cmenTabRenameTab = new ToolStripMenuItem(); - cmenTabDuplicateTab = new ToolStripMenuItem(); - cmenTabReconnect = new ToolStripMenuItem(); - cmenTabDisconnect = new ToolStripMenuItem(); - cmenTabDisconnectOthers = new ToolStripMenuItem(); - cmenTabDisconnectOthersRight = new ToolStripMenuItem(); - cmenTabPuttySettings = new ToolStripMenuItem(); - cmenTab.SuspendLayout(); - SuspendLayout(); - // - //TabController - // - TabController.Anchor = ((AnchorStyles.Top | AnchorStyles.Bottom) - | AnchorStyles.Left) - | AnchorStyles.Right; - TabController.Appearance = TabControl.VisualAppearance.MultiDocument; - TabController.Cursor = Cursors.Hand; - TabController.DragFromControl = false; - TabController.IDEPixelArea = true; - TabController.IDEPixelBorder = false; - TabController.Location = new Point(0, -1); - TabController.Name = "TabController"; - TabController.Size = new Size(632, 454); - TabController.TabIndex = 0; - // - //cmenTab - // - cmenTab.Items.AddRange(new ToolStripItem[] - { - cmenTabFullscreen, - cmenTabSmartSize, - cmenTabViewOnly, - ToolStripSeparator1, - cmenTabScreenshot, - cmenTabStartChat, - cmenTabTransferFile, - cmenTabRefreshScreen, - cmenTabSendSpecialKeys, - cmenTabPuttySettings, - cmenTabExternalApps, - cmenTabSep1, - cmenTabRenameTab, - cmenTabDuplicateTab, - cmenTabReconnect, - cmenTabDisconnect, - cmenTabDisconnectOthers, - cmenTabDisconnectOthersRight - }); - cmenTab.Name = "cmenTab"; - cmenTab.RenderMode = ToolStripRenderMode.Professional; - cmenTab.Size = new Size(202, 346); - // - //cmenTabFullscreen - // - cmenTabFullscreen.Image = Resources.arrow_out; - cmenTabFullscreen.Name = "cmenTabFullscreen"; - cmenTabFullscreen.Size = new Size(201, 22); - cmenTabFullscreen.Text = @"Fullscreen (RDP)"; - // - //cmenTabSmartSize - // - cmenTabSmartSize.Image = Resources.SmartSize; - cmenTabSmartSize.Name = "cmenTabSmartSize"; - cmenTabSmartSize.Size = new Size(201, 22); - cmenTabSmartSize.Text = @"SmartSize (RDP/VNC)"; - // - //cmenTabViewOnly - // - cmenTabViewOnly.Name = "cmenTabViewOnly"; - cmenTabViewOnly.Size = new Size(201, 22); - cmenTabViewOnly.Text = @"View Only (VNC)"; - // - //ToolStripSeparator1 - // - ToolStripSeparator1.Name = "ToolStripSeparator1"; - ToolStripSeparator1.Size = new Size(198, 6); - // - //cmenTabScreenshot - // - cmenTabScreenshot.Image = Resources.Screenshot_Add; - cmenTabScreenshot.Name = "cmenTabScreenshot"; - cmenTabScreenshot.Size = new Size(201, 22); - cmenTabScreenshot.Text = @"Screenshot"; - // - //cmenTabStartChat - // - cmenTabStartChat.Image = Resources.Chat; - cmenTabStartChat.Name = "cmenTabStartChat"; - cmenTabStartChat.Size = new Size(201, 22); - cmenTabStartChat.Text = @"Start Chat (VNC)"; - cmenTabStartChat.Visible = false; - // - //cmenTabTransferFile - // - cmenTabTransferFile.Image = Resources.SSHTransfer; - cmenTabTransferFile.Name = "cmenTabTransferFile"; - cmenTabTransferFile.Size = new Size(201, 22); - cmenTabTransferFile.Text = @"Transfer File (SSH)"; - // - //cmenTabRefreshScreen - // - cmenTabRefreshScreen.Image = Resources.Refresh; - cmenTabRefreshScreen.Name = "cmenTabRefreshScreen"; - cmenTabRefreshScreen.Size = new Size(201, 22); - cmenTabRefreshScreen.Text = @"Refresh Screen (VNC)"; - // - //cmenTabSendSpecialKeys - // - cmenTabSendSpecialKeys.DropDownItems.AddRange(new ToolStripItem[] - { - cmenTabSendSpecialKeysCtrlAltDel, - cmenTabSendSpecialKeysCtrlEsc - }); - cmenTabSendSpecialKeys.Image = Resources.Keyboard; - cmenTabSendSpecialKeys.Name = "cmenTabSendSpecialKeys"; - cmenTabSendSpecialKeys.Size = new Size(201, 22); - cmenTabSendSpecialKeys.Text = @"Send special Keys (VNC)"; - // - //cmenTabSendSpecialKeysCtrlAltDel - // - cmenTabSendSpecialKeysCtrlAltDel.Name = "cmenTabSendSpecialKeysCtrlAltDel"; - cmenTabSendSpecialKeysCtrlAltDel.Size = new Size(141, 22); - cmenTabSendSpecialKeysCtrlAltDel.Text = @"Ctrl+Alt+Del"; - // - //cmenTabSendSpecialKeysCtrlEsc - // - cmenTabSendSpecialKeysCtrlEsc.Name = "cmenTabSendSpecialKeysCtrlEsc"; - cmenTabSendSpecialKeysCtrlEsc.Size = new Size(141, 22); - cmenTabSendSpecialKeysCtrlEsc.Text = @"Ctrl+Esc"; - // - //cmenTabExternalApps - // - cmenTabExternalApps.Image = (Image)(resources.GetObject("cmenTabExternalApps.Image")); - cmenTabExternalApps.Name = "cmenTabExternalApps"; - cmenTabExternalApps.Size = new Size(201, 22); - cmenTabExternalApps.Text = @"External Applications"; - // - //cmenTabSep1 - // - cmenTabSep1.Name = "cmenTabSep1"; - cmenTabSep1.Size = new Size(198, 6); - // - //cmenTabRenameTab - // - cmenTabRenameTab.Image = Resources.Rename; - cmenTabRenameTab.Name = "cmenTabRenameTab"; - cmenTabRenameTab.Size = new Size(201, 22); - cmenTabRenameTab.Text = @"Rename Tab"; - // - //cmenTabDuplicateTab - // - cmenTabDuplicateTab.Name = "cmenTabDuplicateTab"; - cmenTabDuplicateTab.Size = new Size(201, 22); - cmenTabDuplicateTab.Text = @"Duplicate Tab"; - // - //cmenTabReconnect - // - cmenTabReconnect.Image = (Image)(resources.GetObject("cmenTabReconnect.Image")); - cmenTabReconnect.Name = "cmenTabReconnect"; - cmenTabReconnect.Size = new Size(201, 22); - cmenTabReconnect.Text = @"Reconnect"; - // - //cmenTabDisconnect - // - cmenTabDisconnect.Image = Resources.Pause; - cmenTabDisconnect.Name = "cmenTabDisconnect"; - cmenTabDisconnect.Size = new Size(201, 22); - cmenTabDisconnect.Text = @"Disconnect"; - // - //cmenTabDisconnectOthers - // - cmenTabDisconnectOthers.Image = Resources.Pause; - cmenTabDisconnectOthers.Name = "cmenTabDisconnectOthers"; - cmenTabDisconnectOthers.Size = new Size(201, 22); - cmenTabDisconnectOthers.Text = @"Disconnect Other Tabs"; - // - //cmenTabDisconnectOthersRight - // - cmenTabDisconnectOthersRight.Image = Resources.Pause; - cmenTabDisconnectOthersRight.Name = "cmenTabDisconnectOthersRight"; - cmenTabDisconnectOthersRight.Size = new Size(201, 22); - cmenTabDisconnectOthersRight.Text = @"Disconnect Tabs To The Right"; - // - //cmenTabPuttySettings - // - cmenTabPuttySettings.Name = "cmenTabPuttySettings"; - cmenTabPuttySettings.Size = new Size(201, 22); - cmenTabPuttySettings.Text = @"PuTTY Settings"; - // - //Connection - // - ClientSize = new Size(632, 453); - Controls.Add(TabController); - Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, Convert.ToByte(0)); - Icon = Resources.mRemoteNG_Icon; - Name = "Connection"; - TabText = @"UI.Window.Connection"; - Text = @"UI.Window.Connection"; - cmenTab.ResumeLayout(false); - ResumeLayout(false); + this.connDock = new WeifenLuo.WinFormsUI.Docking.DockPanel(); + this.cmenTab = new System.Windows.Forms.ContextMenuStrip(this.components); + this.cmenTabReconnect = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabDisconnect = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabDisconnectOthers = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabDisconnectOthersRight = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabRenameTab = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabDuplicateTab = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabSep1 = new System.Windows.Forms.ToolStripSeparator(); + this.cmenTabFullscreen = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabSmartSize = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabViewOnly = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabStartChat = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabRefreshScreen = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabTransferFile = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabSendSpecialKeys = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabSendSpecialKeysCtrlAltDel = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabSendSpecialKeysCtrlEsc = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabSep2 = new System.Windows.Forms.ToolStripSeparator(); + this.cmenTabScreenshot = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabPuttySettings = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTabExternalApps = new System.Windows.Forms.ToolStripMenuItem(); + this.cmenTab.SuspendLayout(); + this.SuspendLayout(); + // + // connDock + // + this.connDock.Dock = System.Windows.Forms.DockStyle.Fill; + this.connDock.DockBackColor = System.Drawing.SystemColors.Control; + this.connDock.DockLeftPortion = 230D; + this.connDock.DockRightPortion = 230D; + this.connDock.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.DockingSdi; + this.connDock.Location = new System.Drawing.Point(0, 0); + this.connDock.Margin = new System.Windows.Forms.Padding(4); + this.connDock.Name = "connDock"; + this.connDock.Size = new System.Drawing.Size(632, 453); + this.connDock.TabIndex = 13; + // + // cmenTab + // + this.cmenTab.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.cmenTabReconnect, + this.cmenTabDisconnect, + this.cmenTabDisconnectOthers, + this.cmenTabDisconnectOthersRight, + this.cmenTabRenameTab, + this.cmenTabDuplicateTab, + this.cmenTabSep1, + this.cmenTabFullscreen, + this.cmenTabSmartSize, + this.cmenTabViewOnly, + this.cmenTabStartChat, + this.cmenTabRefreshScreen, + this.cmenTabTransferFile, + this.cmenTabSendSpecialKeys, + this.cmenTabSep2, + this.cmenTabScreenshot, + this.cmenTabPuttySettings, + this.cmenTabExternalApps}); + this.cmenTab.Name = "cmenTab"; + this.cmenTab.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; + this.cmenTab.Size = new System.Drawing.Size(231, 390); + // + // cmenTabReconnect + // + this.cmenTabReconnect.Image = ((System.Drawing.Image)(resources.GetObject("cmenTabReconnect.Image"))); + this.cmenTabReconnect.Name = "cmenTabReconnect"; + this.cmenTabReconnect.Size = new System.Drawing.Size(230, 22); + this.cmenTabReconnect.Text = "Reconnect"; + // + // cmenTabDisconnect + // + this.cmenTabDisconnect.Image = global::mRemoteNG.Resources.tab_delete; + this.cmenTabDisconnect.Name = "cmenTabDisconnect"; + this.cmenTabDisconnect.Size = new System.Drawing.Size(230, 22); + this.cmenTabDisconnect.Text = "Disconnect"; + // + // cmenTabDisconnectOthers + // + this.cmenTabDisconnectOthers.Image = global::mRemoteNG.Resources.tab_delete; + this.cmenTabDisconnectOthers.Name = "cmenTabDisconnectOthers"; + this.cmenTabDisconnectOthers.Size = new System.Drawing.Size(230, 22); + this.cmenTabDisconnectOthers.Text = "Disconnect Other Tabs"; + // + // cmenTabDisconnectOthersRight + // + this.cmenTabDisconnectOthersRight.Image = global::mRemoteNG.Resources.tab_delete; + this.cmenTabDisconnectOthersRight.Name = "cmenTabDisconnectOthersRight"; + this.cmenTabDisconnectOthersRight.Size = new System.Drawing.Size(230, 22); + this.cmenTabDisconnectOthersRight.Text = "Disconnect Tabs To The Right"; + // + // cmenTabRenameTab + // + this.cmenTabRenameTab.Image = global::mRemoteNG.Resources.tab_edit; + this.cmenTabRenameTab.Name = "cmenTabRenameTab"; + this.cmenTabRenameTab.Size = new System.Drawing.Size(230, 22); + this.cmenTabRenameTab.Text = "Rename Tab"; + // + // cmenTabDuplicateTab + // + this.cmenTabDuplicateTab.Image = global::mRemoteNG.Resources.tab_add; + this.cmenTabDuplicateTab.Name = "cmenTabDuplicateTab"; + this.cmenTabDuplicateTab.Size = new System.Drawing.Size(230, 22); + this.cmenTabDuplicateTab.Text = "Duplicate Tab"; + // + // cmenTabSep1 + // + this.cmenTabSep1.Name = "cmenTabSep1"; + this.cmenTabSep1.Size = new System.Drawing.Size(227, 6); + // + // cmenTabFullscreen + // + this.cmenTabFullscreen.Image = global::mRemoteNG.Resources.arrow_out; + this.cmenTabFullscreen.Name = "cmenTabFullscreen"; + this.cmenTabFullscreen.Size = new System.Drawing.Size(230, 22); + this.cmenTabFullscreen.Text = "Fullscreen (RDP)"; + // + // cmenTabSmartSize + // + this.cmenTabSmartSize.Image = global::mRemoteNG.Resources.SmartSize; + this.cmenTabSmartSize.Name = "cmenTabSmartSize"; + this.cmenTabSmartSize.Size = new System.Drawing.Size(230, 22); + this.cmenTabSmartSize.Text = "SmartSize (RDP/VNC)"; + // + // cmenTabViewOnly + // + this.cmenTabViewOnly.Image = global::mRemoteNG.Resources.View; + this.cmenTabViewOnly.Name = "cmenTabViewOnly"; + this.cmenTabViewOnly.Size = new System.Drawing.Size(230, 22); + this.cmenTabViewOnly.Text = "View Only (VNC)"; + // + // cmenTabStartChat + // + this.cmenTabStartChat.Image = global::mRemoteNG.Resources.Chat; + this.cmenTabStartChat.Name = "cmenTabStartChat"; + this.cmenTabStartChat.Size = new System.Drawing.Size(230, 22); + this.cmenTabStartChat.Text = "Start Chat (VNC)"; + this.cmenTabStartChat.Visible = false; + // + // cmenTabRefreshScreen + // + this.cmenTabRefreshScreen.Image = global::mRemoteNG.Resources.Refresh; + this.cmenTabRefreshScreen.Name = "cmenTabRefreshScreen"; + this.cmenTabRefreshScreen.Size = new System.Drawing.Size(230, 22); + this.cmenTabRefreshScreen.Text = "Refresh Screen (VNC)"; + // + // cmenTabTransferFile + // + this.cmenTabTransferFile.Image = global::mRemoteNG.Resources.SSHTransfer; + this.cmenTabTransferFile.Name = "cmenTabTransferFile"; + this.cmenTabTransferFile.Size = new System.Drawing.Size(230, 22); + this.cmenTabTransferFile.Text = "Transfer File (SSH)"; + // + // cmenTabSendSpecialKeys + // + this.cmenTabSendSpecialKeys.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.cmenTabSendSpecialKeysCtrlAltDel, + this.cmenTabSendSpecialKeysCtrlEsc}); + this.cmenTabSendSpecialKeys.Image = global::mRemoteNG.Resources.Keyboard; + this.cmenTabSendSpecialKeys.Name = "cmenTabSendSpecialKeys"; + this.cmenTabSendSpecialKeys.Size = new System.Drawing.Size(230, 22); + this.cmenTabSendSpecialKeys.Text = "Send special Keys (VNC)"; + // + // cmenTabSendSpecialKeysCtrlAltDel + // + this.cmenTabSendSpecialKeysCtrlAltDel.Name = "cmenTabSendSpecialKeysCtrlAltDel"; + this.cmenTabSendSpecialKeysCtrlAltDel.Size = new System.Drawing.Size(141, 22); + this.cmenTabSendSpecialKeysCtrlAltDel.Text = "Ctrl+Alt+Del"; + // + // cmenTabSendSpecialKeysCtrlEsc + // + this.cmenTabSendSpecialKeysCtrlEsc.Name = "cmenTabSendSpecialKeysCtrlEsc"; + this.cmenTabSendSpecialKeysCtrlEsc.Size = new System.Drawing.Size(141, 22); + this.cmenTabSendSpecialKeysCtrlEsc.Text = "Ctrl+Esc"; + // + // cmenTabSep2 + // + this.cmenTabSep2.Name = "cmenTabSep2"; + this.cmenTabSep2.Size = new System.Drawing.Size(227, 6); + // + // cmenTabScreenshot + // + this.cmenTabScreenshot.Image = global::mRemoteNG.Resources.Screenshot_Add; + this.cmenTabScreenshot.Name = "cmenTabScreenshot"; + this.cmenTabScreenshot.Size = new System.Drawing.Size(230, 22); + this.cmenTabScreenshot.Text = "Screenshot"; + // + // cmenTabPuttySettings + // + this.cmenTabPuttySettings.Image = global::mRemoteNG.Resources.PuttyConfig; + this.cmenTabPuttySettings.Name = "cmenTabPuttySettings"; + this.cmenTabPuttySettings.Size = new System.Drawing.Size(230, 22); + this.cmenTabPuttySettings.Text = "PuTTY Settings"; + // + // cmenTabExternalApps + // + this.cmenTabExternalApps.Image = ((System.Drawing.Image)(resources.GetObject("cmenTabExternalApps.Image"))); + this.cmenTabExternalApps.Name = "cmenTabExternalApps"; + this.cmenTabExternalApps.Size = new System.Drawing.Size(230, 22); + this.cmenTabExternalApps.Text = "External Applications"; + // + // ConnectionWindow + // + this.ClientSize = new System.Drawing.Size(632, 453); + this.Controls.Add(this.connDock); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Icon = global::mRemoteNG.Resources.mRemoteNG_Icon; + this.Name = "ConnectionWindow"; + this.TabText = "UI.Window.Connection"; + this.Text = "UI.Window.Connection"; + this.cmenTab.ResumeLayout(false); + this.ResumeLayout(false); + } + + internal WeifenLuo.WinFormsUI.Docking.DockPanel connDock; + private System.ComponentModel.IContainer components; } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ConnectionWindow.cs b/mRemoteV1/UI/Window/ConnectionWindow.cs index 668969dd..a28fe3cd 100644 --- a/mRemoteV1/UI/Window/ConnectionWindow.cs +++ b/mRemoteV1/UI/Window/ConnectionWindow.cs @@ -1,9 +1,8 @@ using System; -using System.Drawing; +using System.Collections.Generic; +using System.ComponentModel; using System.Linq; -using System.Runtime.InteropServices; using System.Windows.Forms; -using BrightIdeasSoftware; using mRemoteNG.App; using mRemoteNG.App.Info; using mRemoteNG.Config; @@ -11,7 +10,7 @@ using mRemoteNG.Connection; using mRemoteNG.Connection.Protocol; using mRemoteNG.Connection.Protocol.RDP; using mRemoteNG.Connection.Protocol.VNC; -using mRemoteNG.Container; +using mRemoteNG.Messages; using mRemoteNG.Security; using mRemoteNG.Themes; using mRemoteNG.Tools; @@ -19,19 +18,18 @@ using mRemoteNG.UI.Forms; using mRemoteNG.UI.Forms.Input; using mRemoteNG.UI.TaskDialog; using WeifenLuo.WinFormsUI.Docking; -using TabControl = Crownwood.Magic.Controls.TabControl; -using TabPage = Crownwood.Magic.Controls.TabPage; +using mRemoteNG.UI.Tabs; namespace mRemoteNG.UI.Window { - public partial class ConnectionWindow : BaseWindow + public partial class ConnectionWindow : BaseWindow { - public TabControl TabController; private readonly IConnectionInitiator _connectionInitiator = new ConnectionInitiator(Runtime.CredentialService); private VisualStudioToolStripExtender vsToolStripExtender; private readonly ToolStripRenderer _toolStripProfessionalRenderer = new ToolStripProfessionalRenderer(); #region Public Methods + public ConnectionWindow(DockContent panel, string formText = "") { if (formText == "") @@ -46,12 +44,20 @@ namespace mRemoteNG.UI.Window // ReSharper disable once VirtualMemberCallInConstructor Text = formText; TabText = formText; + connDock.DocumentStyle = DocumentStyle.DockingWindow; + connDock.ShowDocumentIcon = true; + + connDock.ActiveContentChanged += ConnDockOnActiveContentChanged; + } + + private InterfaceControl GetInterfaceControl() + { + return InterfaceControl.FindInterfaceControl(connDock); } private void SetEventHandlers() { SetFormEventHandlers(); - SetTabControllerEventHandlers(); SetContextMenuEventHandlers(); } @@ -62,23 +68,12 @@ namespace mRemoteNG.UI.Window FormClosing += Connection_FormClosing; } - private void SetTabControllerEventHandlers() - { - TabController.ClosePressed += TabController_ClosePressed; - TabController.DoubleClickTab += TabController_DoubleClickTab; - TabController.DragDrop += TabController_DragDrop; - TabController.DragOver += TabController_DragOver; - TabController.SelectionChanged += TabController_SelectionChanged; - TabController.MouseUp += TabController_MouseUp; - TabController.PageDragEnd += TabController_PageDragStart; - TabController.PageDragStart += TabController_PageDragStart; - TabController.PageDragMove += TabController_PageDragMove; - TabController.PageDragEnd += TabController_PageDragEnd; - TabController.PageDragQuit += TabController_PageDragEnd; - } - private void SetContextMenuEventHandlers() { + // event handler to adjust the items within the context menu + cmenTab.Opening += ShowHideMenuButtons; + + // event handlers for all context menu items... cmenTabFullscreen.Click += (sender, args) => ToggleFullscreen(); cmenTabSmartSize.Click += (sender, args) => ToggleSmartSize(); cmenTabViewOnly.Click += (sender, args) => ToggleViewOnly(); @@ -86,7 +81,8 @@ namespace mRemoteNG.UI.Window cmenTabStartChat.Click += (sender, args) => StartChat(); cmenTabTransferFile.Click += (sender, args) => TransferFile(); cmenTabRefreshScreen.Click += (sender, args) => RefreshScreen(); - cmenTabSendSpecialKeysCtrlAltDel.Click += (sender, args) => SendSpecialKeys(ProtocolVNC.SpecialKeys.CtrlAltDel); + cmenTabSendSpecialKeysCtrlAltDel.Click += + (sender, args) => SendSpecialKeys(ProtocolVNC.SpecialKeys.CtrlAltDel); cmenTabSendSpecialKeysCtrlEsc.Click += (sender, args) => SendSpecialKeys(ProtocolVNC.SpecialKeys.CtrlEsc); cmenTabRenameTab.Click += (sender, args) => RenameTab(); cmenTabDuplicateTab.Click += (sender, args) => DuplicateTab(); @@ -95,85 +91,106 @@ namespace mRemoteNG.UI.Window cmenTabDisconnectOthers.Click += (sender, args) => CloseOtherTabs(); cmenTabDisconnectOthersRight.Click += (sender, args) => CloseOtherTabsToTheRight(); cmenTabPuttySettings.Click += (sender, args) => ShowPuttySettingsDialog(); + GotFocus += ConnectionWindow_GotFocus; } - public TabPage AddConnectionTab(ConnectionInfo connectionInfo) + private void ConnectionWindow_GotFocus(object sender, EventArgs e) + { + TabHelper.Instance.CurrentPanel = this; + } + + public ConnectionTab AddConnectionTab(ConnectionInfo connectionInfo) { try { - var nTab = new TabPage - { - Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top - }; - + //Set the connection text based on name and preferences + string titleText; if (Settings.Default.ShowProtocolOnTabs) - nTab.Title = connectionInfo.Protocol + @": "; + titleText = connectionInfo.Protocol + @": "; else - nTab.Title = ""; + titleText = ""; - nTab.Title += connectionInfo.Name; + titleText += connectionInfo.Name; if (Settings.Default.ShowLogonInfoOnTabs) { var cred = Runtime.CredentialService.GetEffectiveCredentialRecord(connectionInfo.CredentialRecordId .FirstOrDefault()).FirstOrDefault(); - nTab.Title += @" ("; + titleText += @" ("; if (!string.IsNullOrEmpty(cred.Domain)) - nTab.Title += cred.Domain; + titleText += cred.Domain; if (!string.IsNullOrEmpty(cred.Username)) { if (!string.IsNullOrEmpty(cred.Domain)) - nTab.Title += @"\"; - nTab.Title += cred.Username; + titleText += @"\"; + titleText += cred.Username; } - nTab.Title += @")"; + titleText += @")"; } - nTab.Title = nTab.Title.Replace("&", "&&"); + titleText = titleText.Replace("&", "&&"); - var conIcon = ConnectionIcon.FromString(connectionInfo.Icon); - if (conIcon != null) - nTab.Icon = conIcon; + var conTab = new ConnectionTab + { + Tag = connectionInfo, + DockAreas = DockAreas.Document | DockAreas.Float, + Icon = ConnectionIcon.FromString(connectionInfo.Icon), + TabText = titleText, + TabPageContextMenuStrip = cmenTab + }; - if (Settings.Default.OpenTabsRightOfSelected) - TabController.TabPages.Insert(TabController.SelectedIndex + 1, nTab); - else - TabController.TabPages.Add(nTab); + //if (Settings.Default.AlwaysShowConnectionTabs == false) + // TODO: See if we can make this work with DPS... + //TabController.HideTabsMode = TabControl.HideTabsModes.HideAlways; - if (Settings.Default.AlwaysShowConnectionTabs == false) - TabController.HideTabsMode = TabControl.HideTabsModes.HideAlways; - nTab.Selected = true; - _ignoreChangeSelectedTabClick = false; - - return nTab; + //Show the tab + conTab.Show(connDock, DockState.Document); + conTab.Focus(); + return conTab; } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("AddConnectionTab (UI.Window.ConnectionWindow) failed", ex); + Runtime.MessageCollector.AddExceptionMessage("AddConnectionTab (UI.Window.ConnectionWindow) failed", + ex); } return null; } - public void UpdateSelectedConnection() - { - if (TabController.SelectedTab == null) - { - FrmMain.Default.SelectedConnection = null; - } - else - { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; - FrmMain.Default.SelectedConnection = interfaceControl?.Info; - } - } #endregion + public void reconnectAll(IConnectionInitiator initiator) + { + var controlList = new List(); + try + { + foreach (var dockContent in connDock.DocumentsToArray()) + { + var tab = (ConnectionTab)dockContent; + controlList.Add((InterfaceControl)tab.Tag); + } + + foreach (var iControl in controlList) + { + iControl.Protocol.Close(); + initiator.OpenConnection(iControl.Info, ConnectionInfo.Force.DoNotJump); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("reconnectAll (UI.Window.ConnectionWindow) failed", ex); + } + + // ReSharper disable once RedundantAssignment + controlList = null; + } + #region Form + private void Connection_Load(object sender, EventArgs e) { ApplyTheme(); @@ -183,45 +200,69 @@ namespace mRemoteNG.UI.Window private new void ApplyTheme() { - if (!ThemeManager.getInstance().ThemingActive) return; + if (!ThemeManager.getInstance().ThemingActive) + { + connDock.Theme = ThemeManager.getInstance().DefaultTheme.Theme; + return; + } + base.ApplyTheme(); + try + { + connDock.Theme = ThemeManager.getInstance().ActiveTheme.Theme; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ConnectionWindow.ApplyTheme() failed", ex); + } + vsToolStripExtender = new VisualStudioToolStripExtender(components) { DefaultRenderer = _toolStripProfessionalRenderer }; - vsToolStripExtender.SetStyle(cmenTab, ThemeManager.getInstance().ActiveTheme.Version, ThemeManager.getInstance().ActiveTheme.Theme); - TabController.BackColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Tab_Item_Background"); - TabController.TextColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Tab_Item_Foreground"); - TabController.TextInactiveColor = ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Tab_Item_Disabled_Foreground"); + vsToolStripExtender.SetStyle(cmenTab, ThemeManager.getInstance().ActiveTheme.Version, + ThemeManager.getInstance().ActiveTheme.Theme); + + if (!ThemeManager.getInstance().ActiveAndExtended) return; + connDock.DockBackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Tab_Item_Background"); } private bool _documentHandlersAdded; private bool _floatHandlersAdded; + private void Connection_DockStateChanged(object sender, EventArgs e) { - if (DockState == DockState.Float) + switch (DockState) { - if (_documentHandlersAdded) + case DockState.Float: { - FrmMain.Default.ResizeBegin -= Connection_ResizeBegin; - FrmMain.Default.ResizeEnd -= Connection_ResizeEnd; - _documentHandlersAdded = false; + if (_documentHandlersAdded) + { + FrmMain.Default.ResizeBegin -= Connection_ResizeBegin; + FrmMain.Default.ResizeEnd -= Connection_ResizeEnd; + _documentHandlersAdded = false; + } + + DockHandler.FloatPane.FloatWindow.ResizeBegin += Connection_ResizeBegin; + DockHandler.FloatPane.FloatWindow.ResizeEnd += Connection_ResizeEnd; + _floatHandlersAdded = true; + break; } - DockHandler.FloatPane.FloatWindow.ResizeBegin += Connection_ResizeBegin; - DockHandler.FloatPane.FloatWindow.ResizeEnd += Connection_ResizeEnd; - _floatHandlersAdded = true; - } - else if (DockState == DockState.Document) - { - if (_floatHandlersAdded) + case DockState.Document: { - DockHandler.FloatPane.FloatWindow.ResizeBegin -= Connection_ResizeBegin; - DockHandler.FloatPane.FloatWindow.ResizeEnd -= Connection_ResizeEnd; - _floatHandlersAdded = false; + if (_floatHandlersAdded) + { + DockHandler.FloatPane.FloatWindow.ResizeBegin -= Connection_ResizeBegin; + DockHandler.FloatPane.FloatWindow.ResizeEnd -= Connection_ResizeEnd; + _floatHandlersAdded = false; + } + + FrmMain.Default.ResizeBegin += Connection_ResizeBegin; + FrmMain.Default.ResizeEnd += Connection_ResizeEnd; + _documentHandlersAdded = true; + break; } - FrmMain.Default.ResizeBegin += Connection_ResizeBegin; - FrmMain.Default.ResizeEnd += Connection_ResizeEnd; - _documentHandlersAdded = true; } } @@ -250,14 +291,22 @@ namespace mRemoteNG.UI.Window private void Connection_FormClosing(object sender, FormClosingEventArgs e) { if (!FrmMain.Default.IsClosing && - (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All & TabController.TabPages.Count > 0 || - Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple & TabController.TabPages.Count > 1)) + (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All & connDock.Documents.Any() || + Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple & + connDock.Documents.Count() > 1)) { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.strConfirmCloseConnectionPanelMainInstruction, Text), "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); + var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, + string + .Format(Language.strConfirmCloseConnectionPanelMainInstruction, + Text), "", "", "", + Language.strCheckboxDoNotShowThisMessageAgain, + ETaskDialogButtons.YesNo, ESysIcons.Question, + ESysIcons.Question); if (CTaskDialog.VerificationChecked) { Settings.Default.ConfirmCloseConnection--; } + if (result == DialogResult.No) { e.Cancel = true; @@ -267,124 +316,55 @@ namespace mRemoteNG.UI.Window try { - foreach (TabPage tabP in TabController.TabPages) + foreach (var dockContent in connDock.Documents.ToArray()) { + var tabP = (ConnectionTab)dockContent; if (tabP.Tag == null) continue; - var interfaceControl = (InterfaceControl)tabP.Tag; - interfaceControl.Protocol.Close(); + tabP.silentClose = true; + tabP.Close(); } } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.Connection.Connection_FormClosing() failed", ex); + Runtime.MessageCollector.AddExceptionMessage("UI.Window.Connection.Connection_FormClosing() failed", + ex); } } public new event EventHandler ResizeBegin; + private void Connection_ResizeBegin(object sender, EventArgs e) { ResizeBegin?.Invoke(this, e); } public new event EventHandler ResizeEnd; + private void Connection_ResizeEnd(object sender, EventArgs e) { ResizeEnd?.Invoke(sender, e); } + #endregion - #region TabController - private void TabController_ClosePressed(object sender, EventArgs e) - { - if (TabController.SelectedTab == null) - { - return; - } + #region Events - CloseConnectionTab(); + private void ConnDockOnActiveContentChanged(object sender, EventArgs e) + { + var ic = GetInterfaceControl(); + if (ic?.Info == null) return; + FrmMain.Default.SelectedConnection = ic.Info; } - private void CloseConnectionTab() - { - try - { - var selectedTab = TabController.SelectedTab; - if (selectedTab == null) return; - if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All) - { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.strConfirmCloseConnectionMainInstruction, selectedTab.Title), "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); - if (CTaskDialog.VerificationChecked) - { - Settings.Default.ConfirmCloseConnection--; - } - if (result == DialogResult.No) - { - return; - } - } - - if (selectedTab.Tag != null) - { - var interfaceControl = (InterfaceControl)selectedTab.Tag; - interfaceControl.Protocol.Close(); - } - else - { - CloseTab(selectedTab); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.Connection.CloseConnectionTab() failed", ex); - } - - UpdateSelectedConnection(); - } - - private void TabController_DoubleClickTab(TabControl sender, TabPage page) - { - _firstClickTicks = 0; - if (Settings.Default.DoubleClickOnTabClosesIt) - { - CloseConnectionTab(); - } - } - - #region Drag and Drop - private void TabController_DragDrop(object sender, DragEventArgs e) - { - var dropDataAsOlvDataObject = e.Data as OLVDataObject; - if (dropDataAsOlvDataObject == null) return; - var modelObjects = dropDataAsOlvDataObject.ModelObjects; - foreach (var model in modelObjects) - { - var modelAsContainer = model as ContainerInfo; - var modelAsConnection = model as ConnectionInfo; - if (modelAsContainer != null) - _connectionInitiator.OpenConnection(modelAsContainer); - else if (modelAsConnection != null) - _connectionInitiator.OpenConnection(modelAsConnection); - } - } - - private void TabController_DragOver(object sender, DragEventArgs e) - { - e.Effect = DragDropEffects.None; - var dropDataAsOlvDataObject = e.Data as OLVDataObject; - var modelObjects = dropDataAsOlvDataObject?.ModelObjects; - if (modelObjects == null) return; - if (!modelObjects.OfType().Any()) return; - e.Effect = DragDropEffects.Move; - } - #endregion #endregion #region Tab Menu - private void ShowHideMenuButtons() + + private void ShowHideMenuButtons(object sender, CancelEventArgs e) { try { - var interfaceControl = (InterfaceControl)TabController.SelectedTab?.Tag; + var interfaceControl = GetInterfaceControl(); if (interfaceControl == null) return; if (interfaceControl.Info.Protocol == ProtocolType.RDP) @@ -422,7 +402,8 @@ namespace mRemoteNG.UI.Window cmenTabTransferFile.Visible = false; } - if (interfaceControl.Info.Protocol == ProtocolType.SSH1 | interfaceControl.Info.Protocol == ProtocolType.SSH2) + if (interfaceControl.Info.Protocol == ProtocolType.SSH1 | + interfaceControl.Info.Protocol == ProtocolType.SSH2) { cmenTabTransferFile.Visible = true; } @@ -433,28 +414,29 @@ namespace mRemoteNG.UI.Window } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("ShowHideMenuButtons (UI.Window.ConnectionWindow) failed", ex); + Runtime.MessageCollector.AddExceptionMessage("ShowHideMenuButtons (UI.Window.ConnectionWindow) failed", + ex); } } + #endregion #region Tab Actions + private void ToggleSmartSize() { try { - if (!(TabController.SelectedTab?.Tag is InterfaceControl)) return; - var interfaceControl = (InterfaceControl)TabController.SelectedTab?.Tag; + var interfaceControl = GetInterfaceControl(); - if (interfaceControl.Protocol is RdpProtocol protocol) + switch (interfaceControl.Protocol) { - var rdp = protocol; - rdp.ToggleSmartSize(); - } - else if (interfaceControl.Protocol is ProtocolVNC) - { - var vnc = (ProtocolVNC)interfaceControl.Protocol; - vnc.ToggleSmartSize(); + case RdpProtocol rdp: + rdp.ToggleSmartSize(); + break; + case ProtocolVNC vnc: + vnc.ToggleSmartSize(); + break; } } catch (Exception ex) @@ -467,9 +449,11 @@ namespace mRemoteNG.UI.Window { try { - if (!(TabController.SelectedTab?.Tag is InterfaceControl interfaceControl)) return; + var interfaceControl = GetInterfaceControl(); + if (interfaceControl == null) return; - if (interfaceControl.Info.Protocol == ProtocolType.SSH1 | interfaceControl.Info.Protocol == ProtocolType.SSH2) + if (interfaceControl.Info.Protocol == ProtocolType.SSH1 | + interfaceControl.Info.Protocol == ProtocolType.SSH2) SshTransferFile(); else if (interfaceControl.Info.Protocol == ProtocolType.VNC) VncTransferFile(); @@ -484,8 +468,8 @@ namespace mRemoteNG.UI.Window { try { - if (!(TabController.SelectedTab?.Tag is InterfaceControl interfaceControl)) - return; + var interfaceControl = GetInterfaceControl(); + if (interfaceControl == null) return; Windows.Show(WindowType.SSHTransfer); var connectionInfo = interfaceControl.Info; @@ -505,7 +489,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); var vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.StartFileTransfer(); } @@ -519,7 +503,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); if (!(interfaceControl?.Protocol is ProtocolVNC vnc)) return; cmenTabViewOnly.Checked = !cmenTabViewOnly.Checked; vnc.ToggleViewOnly(); @@ -534,7 +518,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); var vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.StartChat(); } @@ -548,7 +532,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); var vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.RefreshScreen(); } @@ -562,7 +546,7 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); var vnc = interfaceControl?.Protocol as ProtocolVNC; vnc?.SendSpecialKeys(keys); } @@ -576,13 +560,14 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); var rdp = interfaceControl?.Protocol as RdpProtocol; rdp?.ToggleFullscreen(); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("ToggleFullscreen (UI.Window.ConnectionWindow) failed", ex); + Runtime.MessageCollector.AddExceptionMessage("ToggleFullscreen (UI.Window.ConnectionWindow) failed", + ex); } } @@ -590,13 +575,15 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); var puttyBase = interfaceControl?.Protocol as PuttyBase; puttyBase?.ShowSettingsDialog(); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("ShowPuttySettingsDialog (UI.Window.ConnectionWindow) failed", ex); + Runtime.MessageCollector.AddExceptionMessage( + "ShowPuttySettingsDialog (UI.Window.ConnectionWindow) failed", + ex); } } @@ -631,7 +618,9 @@ namespace mRemoteNG.UI.Window } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace("cMenTreeTools_DropDownOpening failed (UI.Window.ConnectionWindow)", ex); + Runtime.MessageCollector.AddExceptionStackTrace( + "cMenTreeTools_DropDownOpening failed (UI.Window.ConnectionWindow)", + ex); } } @@ -639,21 +628,26 @@ namespace mRemoteNG.UI.Window { try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; + var interfaceControl = GetInterfaceControl(); externalTool.Start(interfaceControl?.Info); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("cmenTabExternalAppsEntry_Click failed (UI.Window.ConnectionWindow)", ex); + Runtime.MessageCollector.AddExceptionMessage( + "cmenTabExternalAppsEntry_Click failed (UI.Window.ConnectionWindow)", + ex); } } + private void CloseTabMenu() { + var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + if (selectedTab == null) return; + try { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; - interfaceControl?.Protocol.Close(); + selectedTab.Close(); } catch (Exception ex) { @@ -663,44 +657,34 @@ namespace mRemoteNG.UI.Window private void CloseOtherTabs() { - try + var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + if (selectedTab == null) return; + if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple) { - if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple) + var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, + string.Format(Language.strConfirmCloseConnectionOthersInstruction, + selectedTab.TabText), "", "", "", + Language.strCheckboxDoNotShowThisMessageAgain, + ETaskDialogButtons.YesNo, ESysIcons.Question, + ESysIcons.Question); + if (CTaskDialog.VerificationChecked) { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.strConfirmCloseConnectionOthersInstruction, TabController.SelectedTab.Title), "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); - if (CTaskDialog.VerificationChecked) - { - Settings.Default.ConfirmCloseConnection--; - } - if (result == DialogResult.No) - { - return; - } + Settings.Default.ConfirmCloseConnection--; } - foreach (TabPage tab in TabController.TabPages) + + if (result == DialogResult.No) { - if (TabController.TabPages.IndexOf(tab) != TabController.TabPages.IndexOf(TabController.SelectedTab)) - { - if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All) - { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.strConfirmCloseConnectionMainInstruction, tab.Title), "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); - if (CTaskDialog.VerificationChecked) - { - Settings.Default.ConfirmCloseConnection--; - } - if (result == DialogResult.No) - { - continue; - } - } - var interfaceControl = tab.Tag as InterfaceControl; - interfaceControl?.Protocol.Close(); - } + return; } } - catch (Exception ex) + + foreach (var dockContent in connDock.DocumentsToArray()) { - Runtime.MessageCollector.AddExceptionMessage("CloseTabMenu (UI.Window.ConnectionWindow) failed", ex); + var tab = (ConnectionTab)dockContent; + if (selectedTab != tab) + { + tab.Close(); + } } } @@ -708,37 +692,25 @@ namespace mRemoteNG.UI.Window { try { - if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.Multiple) + var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + if (selectedTab == null) return; + var dockPane = selectedTab.Pane; + + var pastTabToKeepAlive = false; + var connectionsToClose = new List(); + foreach (var dockContent in dockPane.Contents) { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.strConfirmCloseConnectionRightInstruction, TabController.SelectedTab.Title), "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); - if (CTaskDialog.VerificationChecked) - { - Settings.Default.ConfirmCloseConnection--; - } - if (result == DialogResult.No) - { - return; - } + var tab = (ConnectionTab)dockContent; + if (pastTabToKeepAlive) + connectionsToClose.Add(tab); + + if (selectedTab == tab) + pastTabToKeepAlive = true; } - foreach (TabPage tab in TabController.TabPages) + + foreach (var tab in connectionsToClose) { - if (TabController.TabPages.IndexOf(tab) > TabController.TabPages.IndexOf(TabController.SelectedTab)) - { - if (Settings.Default.ConfirmCloseConnection == (int)ConfirmCloseEnum.All) - { - var result = CTaskDialog.MessageBox(this, GeneralAppInfo.ProductName, string.Format(Language.strConfirmCloseConnectionMainInstruction, tab.Title), "", "", "", Language.strCheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.YesNo, ESysIcons.Question, ESysIcons.Question); - if (CTaskDialog.VerificationChecked) - { - Settings.Default.ConfirmCloseConnection--; - } - if (result == DialogResult.No) - { - continue; - } - } - var interfaceControl = tab.Tag as InterfaceControl; - interfaceControl?.Protocol.Close(); - } + tab.Close(); } } catch (Exception ex) @@ -751,9 +723,9 @@ namespace mRemoteNG.UI.Window { try { - if (!(TabController.SelectedTab?.Tag is InterfaceControl interfaceControl)) return; + var interfaceControl = GetInterfaceControl(); + if (interfaceControl == null) return; _connectionInitiator.OpenConnection(interfaceControl.Info, ConnectionInfo.Force.DoNotJump); - _ignoreChangeSelectedTabClick = false; } catch (Exception ex) { @@ -765,8 +737,15 @@ namespace mRemoteNG.UI.Window { try { - if (!(TabController.SelectedTab?.Tag is InterfaceControl interfaceControl)) return; - interfaceControl.Protocol.Close(); + var interfaceControl = GetInterfaceControl(); + if (interfaceControl == null) + { + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "Reconnect (UI.Window.ConnectionWindow) failed. Could not find InterfaceControl."); + return; + } + + Invoke(new Action(() => Prot_Event_Closed(interfaceControl.Protocol))); _connectionInitiator.OpenConnection(interfaceControl.Info, ConnectionInfo.Force.DoNotJump); } catch (Exception ex) @@ -779,12 +758,15 @@ namespace mRemoteNG.UI.Window { try { - var title = TabController.SelectedTab.Title; - using (var frmInputBox = new FrmInputBox(Language.strNewTitle, Language.strNewTitle + ":", ref title)) + var interfaceControl = GetInterfaceControl(); + if (interfaceControl == null) return; + using (var frmInputBox = new FrmInputBox(Language.strNewTitle, Language.strNewTitle, + ((ConnectionTab)interfaceControl.Parent).TabText)) { var dr = frmInputBox.ShowDialog(); - if (dr == DialogResult.OK && !string.IsNullOrEmpty(frmInputBox.returnValue)) - TabController.SelectedTab.Title = frmInputBox.returnValue;// newTitle.Replace("&", "&&"); + if (dr != DialogResult.OK) return; + if (!string.IsNullOrEmpty(frmInputBox.returnValue)) + ((ConnectionTab)interfaceControl.Parent).TabText = frmInputBox.returnValue.Replace("&", "&&"); } } catch (Exception ex) @@ -797,219 +779,24 @@ namespace mRemoteNG.UI.Window { cmenTab.Close(); Application.DoEvents(); - Windows.ScreenshotForm.AddScreenshot(MiscTools.TakeScreenshot(this)); + //var selectedTab = (ConnectionTab)GetInterfaceControl()?.Parent; + if (TabHelper.Instance.CurrentTab == null) return; + Windows.ScreenshotForm.AddScreenshot(MiscTools.TakeScreenshot(TabHelper.Instance.CurrentTab)); } + #endregion #region Protocols + public void Prot_Event_Closed(object sender) { var protocolBase = sender as ProtocolBase; - if (protocolBase?.InterfaceControl.Parent is TabPage tabPage) - CloseTab(tabPage); - } - #endregion - - #region Tabs - private delegate void CloseTabDelegate(TabPage tabToBeClosed); - private void CloseTab(TabPage tabToBeClosed) - { - if (tabToBeClosed.Disposing || tabToBeClosed.IsDisposed) - return; - - if (TabController.InvokeRequired) - { - CloseTabDelegate s = CloseTab; - - try - { - TabController.Invoke(s, tabToBeClosed); - } - catch (COMException) - { - TabController.Invoke(s, tabToBeClosed); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("Couldn't close tab", ex); - } - } - else - { - try - { - TabController.TabPages.Remove(tabToBeClosed); - _ignoreChangeSelectedTabClick = false; - } - catch (COMException) - { - CloseTab(tabToBeClosed); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("Couldn't close tab", ex); - } - - if (TabController.TabPages.Count == 0) - { - Close(); - } - } + if (!(protocolBase?.InterfaceControl.Parent is ConnectionTab tabPage)) return; + if (tabPage.Disposing) return; + tabPage.protocolClose = true; + Invoke(new Action(() => tabPage.Close())); } - private bool _ignoreChangeSelectedTabClick; - private void TabController_SelectionChanged(object sender, EventArgs e) - { - _ignoreChangeSelectedTabClick = true; - UpdateSelectedConnection(); - FocusInterfaceController(); - RefreshInterfaceController(); - } - - private int _firstClickTicks; - private Rectangle _doubleClickRectangle; - private void TabController_MouseUp(object sender, MouseEventArgs e) - { - try - { - if (!(NativeMethods.GetForegroundWindow() == FrmMain.Default.Handle) && !_ignoreChangeSelectedTabClick) - { - var clickedTab = TabController.TabPageFromPoint(e.Location); - if (clickedTab != null && TabController.SelectedTab != clickedTab) - { - NativeMethods.SetForegroundWindow(Handle); - TabController.SelectedTab = clickedTab; - } - } - _ignoreChangeSelectedTabClick = false; - - switch (e.Button) - { - case MouseButtons.Left: - var currentTicks = Environment.TickCount; - var elapsedTicks = currentTicks - _firstClickTicks; - if (elapsedTicks > SystemInformation.DoubleClickTime || !_doubleClickRectangle.Contains(MousePosition)) - { - _firstClickTicks = currentTicks; - _doubleClickRectangle = new Rectangle(MousePosition.X - SystemInformation.DoubleClickSize.Width / 2, MousePosition.Y - SystemInformation.DoubleClickSize.Height / 2, SystemInformation.DoubleClickSize.Width, SystemInformation.DoubleClickSize.Height); - FocusInterfaceController(); - } - else - { - TabController.OnDoubleClickTab(TabController.SelectedTab); - } - break; - case MouseButtons.Middle: - CloseConnectionTab(); - break; - case MouseButtons.Right: - if (TabController.SelectedTab?.Tag == null) return; - ShowHideMenuButtons(); - NativeMethods.SetForegroundWindow(Handle); - cmenTab.Show(TabController, e.Location); - break; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("TabController_MouseUp (UI.Window.ConnectionWindow) failed", ex); - } - } - - private void FocusInterfaceController() - { - try - { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; - interfaceControl?.Protocol?.Focus(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("FocusIC (UI.Window.ConnectionWindow) failed", ex); - } - } - - public void RefreshInterfaceController() - { - try - { - var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; - if (interfaceControl?.Info.Protocol == ProtocolType.VNC) - ((ProtocolVNC)interfaceControl.Protocol).RefreshScreen(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("RefreshIC (UI.Window.Connection) failed", ex); - } - } - #endregion - - #region Window Overrides - protected override void WndProc(ref Message m) - { - try - { - if (m.Msg == NativeMethods.WM_MOUSEACTIVATE) - { - var selectedTab = TabController.SelectedTab; - if (selectedTab == null) return; - { - var tabClientRectangle = selectedTab.RectangleToScreen(selectedTab.ClientRectangle); - if (tabClientRectangle.Contains(MousePosition)) - { - var interfaceControl = selectedTab.Tag as InterfaceControl; - if (interfaceControl?.Info?.Protocol == ProtocolType.RDP) - { - interfaceControl.Protocol.Focus(); - return; // Do not pass to base class - } - } - } - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.Connection.WndProc() failed.", ex); - } - - base.WndProc(ref m); - } - #endregion - - #region Tab drag and drop - public bool InTabDrag { get; set; } - - private void TabController_PageDragStart(object sender, MouseEventArgs e) - { - Cursor = Cursors.SizeWE; - } - - private void TabController_PageDragMove(object sender, MouseEventArgs e) - { - InTabDrag = true; // For some reason PageDragStart gets raised again after PageDragEnd so set this here instead - - var sourceTab = TabController.SelectedTab; - var destinationTab = TabController.TabPageFromPoint(e.Location); - - if (!TabController.TabPages.Contains(destinationTab) || sourceTab == destinationTab) - return; - - var targetIndex = TabController.TabPages.IndexOf(destinationTab); - - TabController.TabPages.SuspendEvents(); - TabController.TabPages.Remove(sourceTab); - TabController.TabPages.Insert(targetIndex, sourceTab); - TabController.SelectedTab = sourceTab; - TabController.TabPages.ResumeEvents(); - } - - private void TabController_PageDragEnd(object sender, MouseEventArgs e) - { - Cursor = Cursors.Default; - InTabDrag = false; - var interfaceControl = TabController?.SelectedTab?.Tag as InterfaceControl; - interfaceControl?.Protocol.Focus(); - } #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ConnectionWindow.resx b/mRemoteV1/UI/Window/ConnectionWindow.resx index 940a426c..2285f203 100644 --- a/mRemoteV1/UI/Window/ConnectionWindow.resx +++ b/mRemoteV1/UI/Window/ConnectionWindow.resx @@ -112,49 +112,49 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + 17, 17 - - - - iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAmlJREFUOE+lVN1L - k1EcPv9Ft06mzOF0m27qdHOb040cRpubc3PEyKQhTktbVuJAWkUKUr5FkWXSh5pObKTmJK1WYFdjBnVR - 7MXogwIvkurCi552DpwoCBK8eC6f3/PFOQQA2Q3IjVv3ri6vJrdXn61h5ekaEo+fYz7xBPcXHmE6voQ7 - M/MYm5jDlZvTuHjtLgYvjSM6PIq+s8J2e3d/iGTJP1/u24t3sT0wzxnw6s3Gf/H67QY+fdlE6NTgCFlN - vsDX5Yf48V7Agw9xfPy8uSNsffuO4PEzAqGWVSoV1Go1SkpKUFpaCo1GA61Wi7KyMlRUVKCyshJVVVXQ - 6/Worq6GyWRCTU0NWrsiAllaSTJSTk4OJBIJcnNzIZVKkZeXh/z8fMhkMsjlchQWFkKhUKC4uJgJ1tXV - oTsyLBBaGD+QSqUwOTm54wPZDgQSX1xhNrliJpNBT0/PP1VpTB6xvr4eh8NRgczEEyxbQUEB0uk0YrEY - ioqKflvlJN5JeXk5dDodGhoacLCzXyATswswm82MoFQqWT5eJiVRcBItk4pROBwOHGjvFcj4VBxWq/Uv - Em+fKvEFDAYDW8BoNLIVXC4XfG3dAhm9PQuah6rQLijpz8n4bNQlhcViQW1tLZqamuAOhARyeWyK5eHW - uBJVoQS6NyfR6ShsNhu8Xi+c/qBAzo9c36J5nE4nGhsbmTW3280UKDweD5qbmxnB5/OhpaWFwe/3w+4O - DJHO3oHOvuiF9b7oiBgeGBaP9g+JHSfOicFjp8VDXREx0HFS9AfDorf1iJi1LGZVxf3eNtHuCqxb7C7j - rp4y/QZ+AXhAQe1Sf9VzAAAAAElFTkSuQmCC - - + - iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAkpJREFUOE+Fk9tL - k3Ecxgf7M2J20JJCurBC1vlkspYnMoNWmz/XdOShgWXOxZq+bu7QDu6k5tiwJKMSBkYjKqttbLgOyxF0 - 7Z0I3oZ3T9/3pWCn2sV79f5+z/N8n8/vKwIgqvRdfdIy0j4nE5c7V/Eyf6l1tiknmzoT+q/A4Ee15NZb - lU7zShFTLXVuXnvahsthOZqDjdA+60L3YwWOGg97ikWEBAMr3VLtG2WUS+jhzdgQ+u5HeC2A2awH/s8P - 4V6dxGTShI5AC+oGaifyRUT977okva+vR12rZiz8mMPMNzceZb0IfHHCk7HCkeJgThrx4JMel5xN2KvZ - Yy8QoMg644e7mM/NIJT1w5m2QLOoxGmLlI+MQ8MH0eqR4aKjETXqXb6SEZQvOmK2hElwtCc5nHecWD/J - NTjzD9b2VOeq2c5I2RKvzDdvUMvb1PKvs9ZjW8dNR7jig7tVVYYqxQ4xmTFCyggpk/vOMTJjImqZXXCd - YhSZUWRGkdlQqlesi980FAuRGUdmW3/Mtslso+w7IKQRQprLFyCkTjJbd6UsRMWK4eXbfD+xEgFC6jOn - DRiL3wNFBkUGRUbfSzUcCU5AakuNo3O6jUeqKxAgpHYuqcfiz7CANJKbLkA6Hh8VkKoXbuBA374oIZUU - CBDSifvvhxBZCwpIg1/dmMrY4UibMbYyiv4lDdq9cuzX1kQJqZQfsWQEiuwZjPZA+5zxSEFI0WCoR/2d - uk2KHCOkOkIq+dtP2RL5xSGkBSX+a2PLChBSMSEdqbTm/P/fhKyImURcon4AAAAASUVORK5CYII= + iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6 + JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACUUlEQVQ4T4WT60uTcRTHB/szYnbRkkJ6 + YYWs+81kLW9kBq02f67pyEsDy5yLNX3c3KVd3E3NsWFJRiUMjEZUVtvYcF2WI+i170Twbfju23keWuzR + RS++D+P8zjnfL+fDJAD+q6tPmoZaZxTScm/bCuXUPN1QUEyciZR7+/uj/6NWduutxqB7pUpoFtrXrz1t + weWoEo3heuifdaDzsQpHzYd9pcO8hE/fUqdc/0Yd51JG+HMORL4HEV0JYTrvQ/DzQ3iXxzGetqAt1ISa + vuox0YLedx2y7tfX455lK+Z+zGDqmxeP8n6Evrjhy9nhynCwps148MmIS+4G7NXtcYoWUGSD+cNdzBam + EMkH4c7aoJtX47RNzkfGocGDaPYpcNFVjyrtrkDpsLBA/aIt4UhZBEdnmsN514nVk1ydu7SpuquyUMl2 + xkprRUmuzDau0ZU36cq/ztqPbRy3HOG2Nu3WVJgqVDukZMYIKSOkTBk4x8iMSejK7ILnFKPIjCIziswG + Mt1SQ/KmaesiMuPIbOOP2SaZrYkaiiKkMUJaKK0RUjeZrXoyNqJix+Dibf4+CdEgL0IasGZNGEneA0UG + RQZFRs9LLVwpTkDqyIyifbKFR2oQDRNSJ5c2Yv5nVEAaK0yKkI4mhwWk2rkbONCzL05IZaIFhHTs/vsB + xFbCAtLwVy8mck64slaMLA2jd0GHVr8S+/VVcUIq52dEC3hRZF9/vAv654xHCkKKOlMtau/UrFPkBCE1 + EFJZsX/bAl78H4euLDriv1S2SEilhHSo3JtYkPwGhKyImaaNa1UAAAAASUVORK5CYII= - + + + iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6 + JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACYUlEQVQ4T6WT3UvTURzGz3/R7RQVN5xT + p/Nlunc3ybHIuc1tjhiZNMSX2jIrUZBWkYKUpyiyTHpR04mN1Jyk1QrsSmZQF4U/jF4o8CKpLrzoaefA + gSIhoYvn8nOely+HAPgvkRu37l1dXE5uLz9bwdLTFSQeP8ds4gnuzz3CZHwBd6ZmMTI2gys3J3Hx2l30 + XxpFdHAY3Wfpdku4p42k4Z8v9+3Fu9gemGZ0ePVm4596/XYDn75sou1U/xBZTr7A18WH+PGe4sGHOD5+ + 3tyVtr59R+j4GUpY5MLCQhQVFUGtVqO4uBglJSXQaDQoLS1FeXk5tFotKisrUVVVBb1eD6PRCLPZjKaO + XkoWlpIckslkyMjIQGZmJrKyspCdnY2cnBzk5uZCoVAgLy8PSqUSKpWKG1qtVoR7Bylhg4kHVldXMT4+ + vusH0htQEp9f4jEFsL6+jkgksiPEaoqKtbW1ONwZpWQqnuDd5HI5UqkUYrEY8vPz/4LEJmVlZaioqIDD + 4cDB9h5KxqbnYDKZOFBQUMAhMSaDmATExmRmTHV1dTjQ0kXJ6EQcNpvtD0isLyB2AZ1Oxy9gMBj4FVwu + F/zNYUqGb0/zPsxFQL+fTJyNpWSyWCyorq6Gx+OBO9hGyeWRCd5HRBNOAmL3FhBbnqmmpgY+nw/OQIiS + 80PXt1gfp9OJ+vp6Hs3tdnMHpoaGBni9Xg74/X40NjZyBQIB2N3BAdLe1dfeHb2w1h0dkjr7BqWjPQNS + 64lzUujYaelQR68UbD0pBUKdkq/piJSOLKVdpf2+ZsnuCq5Z7C7Djl909wL5BXhAQe3YxLjpAAAAAElF + TkSuQmCC + + + 59 \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ErrorAndInfoWindow.cs b/mRemoteV1/UI/Window/ErrorAndInfoWindow.cs index 4b7c2f3d..0e7ec216 100644 --- a/mRemoteV1/UI/Window/ErrorAndInfoWindow.cs +++ b/mRemoteV1/UI/Window/ErrorAndInfoWindow.cs @@ -13,17 +13,17 @@ using Message = mRemoteNG.Messages.Message; namespace mRemoteNG.UI.Window { - public partial class ErrorAndInfoWindow : BaseWindow - { + public partial class ErrorAndInfoWindow : BaseWindow + { private ControlLayout _layout = ControlLayout.Vertical; private readonly ThemeManager _themeManager; - private readonly DisplayProperties _display; + private readonly DisplayProperties _display; public DockContent PreviousActiveForm { get; set; } - public ErrorAndInfoWindow() : this(new DockContent()) - { - } + public ErrorAndInfoWindow() : this(new DockContent()) + { + } public ErrorAndInfoWindow(DockContent panel) { @@ -41,24 +41,27 @@ namespace mRemoteNG.UI.Window } #region Form Stuff + private void ErrorsAndInfos_Load(object sender, EventArgs e) - { - } - - private void ApplyLanguage() - { - clmMessage.Text = Language.strColumnMessage; - cMenMCCopy.Text = Language.strMenuNotificationsCopyAll; - cMenMCDelete.Text = Language.strMenuNotificationsDeleteAll; - TabText = Language.strMenuNotifications; - Text = Language.strMenuNotifications; - } - #endregion - - #region Private Methods - private new void ApplyTheme() { - if (!_themeManager.ThemingActive) return; + } + + private void ApplyLanguage() + { + clmMessage.Text = Language.strColumnMessage; + cMenMCCopy.Text = Language.strMenuNotificationsCopyAll; + cMenMCDelete.Text = Language.strMenuNotificationsDeleteAll; + TabText = Language.strMenuNotifications; + Text = Language.strMenuNotifications; + } + + #endregion + + #region Private Methods + + private new void ApplyTheme() + { + if (!_themeManager.ActiveAndExtended) return; lvErrorCollector.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); lvErrorCollector.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Foreground"); @@ -74,297 +77,335 @@ namespace mRemoteNG.UI.Window { imgListMC.ImageSize = _display.ScaleSize(imgListMC.ImageSize); imgListMC.Images.Add(_display.ScaleImage(Resources.brick)); - imgListMC.Images.Add(_display.ScaleImage(Resources.InformationSmall)); - imgListMC.Images.Add(_display.ScaleImage(Resources.WarningSmall)); - imgListMC.Images.Add(_display.ScaleImage(Resources.ErrorSmall)); - } - - private void LayoutVertical() - { - try - { - pnlErrorMsg.Location = new Point(0, Height - _display.ScaleHeight(200)); - pnlErrorMsg.Size = new Size(Width, Height - pnlErrorMsg.Top); - pnlErrorMsg.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - txtMsgText.Size = new Size( - pnlErrorMsg.Width - pbError.Width - _display.ScaleWidth(8), - pnlErrorMsg.Height - _display.ScaleHeight(20)); - lvErrorCollector.Location = new Point(0, 0); - lvErrorCollector.Size = new Size(Width, Height - pnlErrorMsg.Height - _display.ScaleHeight(5)); - lvErrorCollector.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; - - _layout = ControlLayout.Vertical; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "LayoutVertical (UI.Window.ErrorsAndInfos) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void LayoutHorizontal() - { - try - { - pnlErrorMsg.Location = new Point(0, 0); - pnlErrorMsg.Size = new Size(_display.ScaleWidth(200), Height); - pnlErrorMsg.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top; + imgListMC.Images.Add(_display.ScaleImage(Resources.InformationSmall)); + imgListMC.Images.Add(_display.ScaleImage(Resources.WarningSmall)); + imgListMC.Images.Add(_display.ScaleImage(Resources.ErrorSmall)); + } + + private void LayoutVertical() + { + try + { + pnlErrorMsg.Location = new Point(0, Height - _display.ScaleHeight(200)); + pnlErrorMsg.Size = new Size(Width, Height - pnlErrorMsg.Top); + pnlErrorMsg.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + txtMsgText.Size = new Size( + pnlErrorMsg.Width - pbError.Width - _display.ScaleWidth(8), + pnlErrorMsg.Height - _display.ScaleHeight(20)); + lvErrorCollector.Location = new Point(0, 0); + lvErrorCollector.Size = new Size(Width, Height - pnlErrorMsg.Height - _display.ScaleHeight(5)); + lvErrorCollector.Anchor = + AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + + _layout = ControlLayout.Vertical; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "LayoutVertical (UI.Window.ErrorsAndInfos) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void LayoutHorizontal() + { + try + { + pnlErrorMsg.Location = new Point(0, 0); + pnlErrorMsg.Size = new Size(_display.ScaleWidth(200), Height); + pnlErrorMsg.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top; txtMsgText.Size = new Size( - pnlErrorMsg.Width - pbError.Width - _display.ScaleWidth(8), - pnlErrorMsg.Height - _display.ScaleHeight(20)); - lvErrorCollector.Location = new Point(pnlErrorMsg.Width + _display.ScaleWidth(5), 0); - lvErrorCollector.Size = new Size(Width - pnlErrorMsg.Width - _display.ScaleWidth(5), Height); - lvErrorCollector.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; - - _layout = ControlLayout.Horizontal; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "LayoutHorizontal (UI.Window.ErrorsAndInfos) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void ErrorsAndInfos_Resize(object sender, EventArgs e) - { - try - { - if (Width > Height) - { - if (_layout == ControlLayout.Vertical) - LayoutHorizontal(); - } - else - { - if (_layout == ControlLayout.Horizontal) - LayoutVertical(); - } - - lvErrorCollector.Columns[0].Width = lvErrorCollector.Width - 20; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "ErrorsAndInfos_Resize (UI.Window.ErrorsAndInfos) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void SetStyleWhenNoMessageSelected() - { - try - { - pnlErrorMsg.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + pnlErrorMsg.Width - pbError.Width - _display.ScaleWidth(8), + pnlErrorMsg.Height - _display.ScaleHeight(20)); + lvErrorCollector.Location = new Point(pnlErrorMsg.Width + _display.ScaleWidth(5), 0); + lvErrorCollector.Size = new Size(Width - pnlErrorMsg.Width - _display.ScaleWidth(5), Height); + lvErrorCollector.Anchor = + AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + + _layout = ControlLayout.Horizontal; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "LayoutHorizontal (UI.Window.ErrorsAndInfos) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void ErrorsAndInfos_Resize(object sender, EventArgs e) + { + try + { + if (Width > Height) + { + if (_layout == ControlLayout.Vertical) + LayoutHorizontal(); + } + else + { + if (_layout == ControlLayout.Horizontal) + LayoutVertical(); + } + + lvErrorCollector.Columns[0].Width = lvErrorCollector.Width - 20; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "ErrorsAndInfos_Resize (UI.Window.ErrorsAndInfos) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void SetStyleWhenNoMessageSelected() + { + try + { + pnlErrorMsg.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); pbError.Image = null; - txtMsgText.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); + txtMsgText.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("TextBox_Background"); txtMsgText.Text = ""; lblMsgDate.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); lblMsgDate.Text = ""; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "pnlErrorMsg_ResetDefaultStyle (UI.Window.ErrorsAndInfos) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void MC_KeyDown(object sender, KeyEventArgs e) - { - try - { - if (e.KeyCode != Keys.Escape) return; - try - { - if (PreviousActiveForm != null) - PreviousActiveForm.Show(FrmMain.Default.pnlDock); - else - Windows.TreeForm.Show(FrmMain.Default.pnlDock); - } - catch (Exception) - { - // ignored - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "MC_KeyDown (UI.Window.ErrorsAndInfos) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void lvErrorCollector_SelectedIndexChanged(object sender, EventArgs e) - { - try - { - if (lvErrorCollector.SelectedItems.Count == 0 | lvErrorCollector.SelectedItems.Count > 1) - { - SetStyleWhenNoMessageSelected(); - return; - } - - var sItem = lvErrorCollector.SelectedItems[0]; - var eMsg = (Messages.Message)sItem.Tag; - switch (eMsg.Class) - { + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "pnlErrorMsg_ResetDefaultStyle (UI.Window.ErrorsAndInfos) failed" + + Environment.NewLine + + ex.Message, true); + } + } + + private void MC_KeyDown(object sender, KeyEventArgs e) + { + try + { + if (e.KeyCode != Keys.Escape) return; + try + { + if (PreviousActiveForm != null) + PreviousActiveForm.Show(FrmMain.Default.pnlDock); + else + Windows.TreeForm.Show(FrmMain.Default.pnlDock); + } + catch (Exception) + { + // ignored + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "MC_KeyDown (UI.Window.ErrorsAndInfos) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void lvErrorCollector_SelectedIndexChanged(object sender, EventArgs e) + { + try + { + if (lvErrorCollector.SelectedItems.Count == 0 | lvErrorCollector.SelectedItems.Count > 1) + { + SetStyleWhenNoMessageSelected(); + return; + } + + var sItem = lvErrorCollector.SelectedItems[0]; + var eMsg = (Message)sItem.Tag; + switch (eMsg.Class) + { case MessageClass.DebugMsg: - pbError.Image = _display.ScaleImage(Resources.brick); - if(_themeManager.ThemingActive) + pbError.Image = _display.ScaleImage(Resources.brick); + if (_themeManager.ThemingActive) { pnlErrorMsg.BackColor = Color.LightSteelBlue; txtMsgText.BackColor = Color.LightSteelBlue; lblMsgDate.BackColor = Color.LightSteelBlue; } + break; - case MessageClass.InformationMsg: - pbError.Image = _display.ScaleImage(Resources.Information); + case MessageClass.InformationMsg: + pbError.Image = _display.ScaleImage(Resources.Information); if (_themeManager.ThemingActive) { pnlErrorMsg.BackColor = Color.LightSteelBlue; - txtMsgText.BackColor = Color.LightSteelBlue; + txtMsgText.BackColor = Color.LightSteelBlue; lblMsgDate.BackColor = Color.LightSteelBlue; } + break; - case MessageClass.WarningMsg: - pbError.Image = _display.ScaleImage(Resources.Warning); - if (_themeManager.ThemingActive) + case MessageClass.WarningMsg: + pbError.Image = _display.ScaleImage(Resources.Warning); + if (_themeManager.ActiveAndExtended) { //Inverse colors for dramatic effect - pnlErrorMsg.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Foreground"); - pnlErrorMsg.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor ("WarningText_Background"); - txtMsgText.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Foreground"); - txtMsgText.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Background"); - lblMsgDate.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Foreground"); - lblMsgDate.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Background"); + pnlErrorMsg.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Foreground"); + pnlErrorMsg.ForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Background"); + txtMsgText.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Foreground"); + txtMsgText.ForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Background"); + lblMsgDate.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Foreground"); + lblMsgDate.ForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("WarningText_Background"); } - break; - case MessageClass.ErrorMsg: - pbError.Image = _display.ScaleImage(Resources._Error); - if (_themeManager.ThemingActive) - { - pnlErrorMsg.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Foreground"); - pnlErrorMsg.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Background"); - txtMsgText.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Foreground"); - txtMsgText.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Background"); - lblMsgDate.BackColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Foreground"); - lblMsgDate.ForeColor = _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Background"); - } - break; - } - - lblMsgDate.Text = eMsg.Date.ToString(CultureInfo.InvariantCulture); - txtMsgText.Text = eMsg.Text; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "lvErrorCollector_SelectedIndexChanged (UI.Window.ErrorsAndInfos) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void cMenMC_Opening(object sender, System.ComponentModel.CancelEventArgs e) - { - if (lvErrorCollector.Items.Count > 0) - { - cMenMCCopy.Enabled = true; - cMenMCDelete.Enabled = true; - } - else - { - cMenMCCopy.Enabled = false; - cMenMCDelete.Enabled = false; - } - - if (lvErrorCollector.SelectedItems.Count > 0) - { - cMenMCCopy.Text = Language.strMenuCopy; - cMenMCDelete.Text = Language.strMenuNotificationsDelete; - } - else - { - cMenMCCopy.Text = Language.strMenuNotificationsCopyAll; - cMenMCDelete.Text = Language.strMenuNotificationsDeleteAll; - } - } - - private void cMenMCCopy_Click(object sender, EventArgs e) - { - CopyMessagesToClipboard(); - } - - private void CopyMessagesToClipboard() - { - try - { - IEnumerable items; - if (lvErrorCollector.SelectedItems.Count > 0) - { - items = lvErrorCollector.SelectedItems; - } - else - { - items = lvErrorCollector.Items; - } - - var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("----------"); - - lvErrorCollector.BeginUpdate(); - foreach (ListViewItem item in items) - { + break; + case MessageClass.ErrorMsg: + pbError.Image = _display.ScaleImage(Resources._Error); + if (_themeManager.ActiveAndExtended) + { + pnlErrorMsg.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Foreground"); + pnlErrorMsg.ForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Background"); + txtMsgText.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Foreground"); + txtMsgText.ForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Background"); + lblMsgDate.BackColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Foreground"); + lblMsgDate.ForeColor = + _themeManager.ActiveTheme.ExtendedPalette.getColor("ErrorText_Background"); + } + + break; + } + + lblMsgDate.Text = eMsg.Date.ToString(CultureInfo.InvariantCulture); + txtMsgText.Text = eMsg.Text; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "lvErrorCollector_SelectedIndexChanged (UI.Window.ErrorsAndInfos) failed" + + Environment.NewLine + + ex.Message, true); + } + } + + private void cMenMC_Opening(object sender, System.ComponentModel.CancelEventArgs e) + { + if (lvErrorCollector.Items.Count > 0) + { + cMenMCCopy.Enabled = true; + cMenMCDelete.Enabled = true; + } + else + { + cMenMCCopy.Enabled = false; + cMenMCDelete.Enabled = false; + } + + if (lvErrorCollector.SelectedItems.Count > 0) + { + cMenMCCopy.Text = Language.strMenuCopy; + cMenMCDelete.Text = Language.strMenuNotificationsDelete; + } + else + { + cMenMCCopy.Text = Language.strMenuNotificationsCopyAll; + cMenMCDelete.Text = Language.strMenuNotificationsDeleteAll; + } + } + + private void cMenMCCopy_Click(object sender, EventArgs e) + { + CopyMessagesToClipboard(); + } + + private void CopyMessagesToClipboard() + { + try + { + IEnumerable items; + if (lvErrorCollector.SelectedItems.Count > 0) + { + items = lvErrorCollector.SelectedItems; + } + else + { + items = lvErrorCollector.Items; + } + + var stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("----------"); + + lvErrorCollector.BeginUpdate(); + + foreach (ListViewItem item in items) + { if (!(item.Tag is Message message)) - { - continue; - } - - stringBuilder.AppendLine(message.Class.ToString()); - stringBuilder.AppendLine(message.Date.ToString(CultureInfo.InvariantCulture)); - stringBuilder.AppendLine(message.Text); - stringBuilder.AppendLine("----------"); - } - - Clipboard.SetText(stringBuilder.ToString()); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "UI.Window.ErrorsAndInfos.CopyMessagesToClipboard() failed." + Environment.NewLine + ex.Message, true); - } - finally - { - lvErrorCollector.EndUpdate(); - } - } - - private void cMenMCDelete_Click(object sender, EventArgs e) - { - DeleteMessages(); - } - - private void DeleteMessages() - { - try - { - lvErrorCollector.BeginUpdate(); - - if (lvErrorCollector.SelectedItems.Count > 0) - { - foreach (ListViewItem item in lvErrorCollector.SelectedItems) - item.Remove(); - } - else - { - lvErrorCollector.Items.Clear(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "UI.Window.ErrorsAndInfos.DeleteMessages() failed" + Environment.NewLine + ex.Message, true); - } - finally - { - lvErrorCollector.EndUpdate(); - } - } + { + continue; + } + + stringBuilder.AppendLine(message.Class.ToString()); + stringBuilder.AppendLine(message.Date.ToString(CultureInfo.InvariantCulture)); + stringBuilder.AppendLine(message.Text); + stringBuilder.AppendLine("----------"); + } + + Clipboard.SetText(stringBuilder.ToString()); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "UI.Window.ErrorsAndInfos.CopyMessagesToClipboard() failed." + + Environment.NewLine + ex.Message, + true); + } + finally + { + lvErrorCollector.EndUpdate(); + } + } + + private void cMenMCDelete_Click(object sender, EventArgs e) + { + DeleteMessages(); + } + + private void DeleteMessages() + { + try + { + lvErrorCollector.BeginUpdate(); + + if (lvErrorCollector.SelectedItems.Count > 0) + { + foreach (ListViewItem item in lvErrorCollector.SelectedItems) + item.Remove(); + } + else + { + lvErrorCollector.Items.Clear(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, + "UI.Window.ErrorsAndInfos.DeleteMessages() failed" + + Environment.NewLine + ex.Message, true); + } + finally + { + lvErrorCollector.EndUpdate(); + } + } + #endregion - private enum ControlLayout - { - Vertical = 0, - Horizontal = 1 - } - } -} + private enum ControlLayout + { + Vertical = 0, + Horizontal = 1 + } + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ExternalToolsWindow.cs b/mRemoteV1/UI/Window/ExternalToolsWindow.cs index 3c96cd4a..efd96757 100644 --- a/mRemoteV1/UI/Window/ExternalToolsWindow.cs +++ b/mRemoteV1/UI/Window/ExternalToolsWindow.cs @@ -12,119 +12,124 @@ using mRemoteNG.Tools.CustomCollections; namespace mRemoteNG.UI.Window { - public partial class ExternalToolsWindow - { + public partial class ExternalToolsWindow + { private readonly ExternalAppsSaver _externalAppsSaver; private readonly ThemeManager _themeManager; - private readonly FullyObservableCollection _currentlySelectedExternalTools; + private readonly FullyObservableCollection _currentlySelectedExternalTools; public ExternalToolsWindow() - { - InitializeComponent(); - WindowType = WindowType.ExternalApps; - DockPnl = new DockContent(); + { + InitializeComponent(); + WindowType = WindowType.ExternalApps; + DockPnl = new DockContent(); _themeManager = ThemeManager.getInstance(); _themeManager.ThemeChanged += ApplyTheme; _externalAppsSaver = new ExternalAppsSaver(); _currentlySelectedExternalTools = new FullyObservableCollection(); _currentlySelectedExternalTools.CollectionUpdated += CurrentlySelectedExternalToolsOnCollectionUpdated; - BrowseButton.Height = FilenameTextBox.Height; - BrowseWorkingDir.Height = WorkingDirTextBox.Height; - } + BrowseButton.Height = FilenameTextBox.Height; + BrowseWorkingDir.Height = WorkingDirTextBox.Height; + } - #region Private Methods - private void ExternalTools_Load(object sender, EventArgs e) - { - ApplyLanguage(); - ApplyTheme(); - UpdateToolsListObjView(); - } + #region Private Methods + + private void ExternalTools_Load(object sender, EventArgs e) + { + ApplyLanguage(); + ApplyTheme(); + UpdateToolsListObjView(); + } private void ApplyLanguage() - { - Text = Language.strMenuExternalTools; - TabText = Language.strMenuExternalTools; + { + Text = Language.strMenuExternalTools; + TabText = Language.strMenuExternalTools; - NewToolToolstripButton.Text = Language.strButtonNew; - DeleteToolToolstripButton.Text = Language.strOptionsThemeButtonDelete; - LaunchToolToolstripButton.Text = Language.strButtonLaunch; + NewToolToolstripButton.Text = Language.strButtonNew; + DeleteToolToolstripButton.Text = Language.strOptionsThemeButtonDelete; + LaunchToolToolstripButton.Text = Language.strButtonLaunch; - DisplayNameColumnHeader.Text = Language.strColumnDisplayName; - FilenameColumnHeader.Text = Language.strColumnFilename; - ArgumentsColumnHeader.Text = Language.strColumnArguments; + DisplayNameColumnHeader.Text = Language.strColumnDisplayName; + FilenameColumnHeader.Text = Language.strColumnFilename; + ArgumentsColumnHeader.Text = Language.strColumnArguments; WorkingDirColumnHeader.Text = Language.strWorkingDirColumnHeader; WaitForExitColumnHeader.Text = Language.strColumnWaitForExit; TryToIntegrateColumnHeader.Text = Language.strTryToIntegrateColumnHeader; RunElevateHeader.Text = Language.strRunElevateHeader; ShowOnToolbarColumnHeader.Text = Language.strShowOnToolbarColumnHeader; - + TryToIntegrateCheckBox.Text = Language.strTryIntegrate; - ShowOnToolbarCheckBox.Text = Language.strShowOnToolbar; + ShowOnToolbarCheckBox.Text = Language.strShowOnToolbar; RunElevatedCheckBox.Text = Language.strRunElevated; PropertiesGroupBox.Text = Language.strGroupboxExternalToolProperties; - DisplayNameLabel.Text = Language.strLabelDisplayName; - FilenameLabel.Text = Language.strLabelFilename; - ArgumentsLabel.Text = Language.strLabelArguments; + DisplayNameLabel.Text = Language.strLabelDisplayName; + FilenameLabel.Text = Language.strLabelFilename; + ArgumentsLabel.Text = Language.strLabelArguments; WorkingDirLabel.Text = Language.srtWorkingDirectory; OptionsLabel.Text = Language.strLabelOptions; - - WaitForExitCheckBox.Text = Language.strCheckboxWaitForExit; - BrowseButton.Text = Language.strButtonBrowse; + + WaitForExitCheckBox.Text = Language.strCheckboxWaitForExit; + BrowseButton.Text = Language.strButtonBrowse; BrowseWorkingDir.Text = Language.strButtonBrowse; NewToolMenuItem.Text = Language.strMenuNewExternalTool; - DeleteToolMenuItem.Text = Language.strMenuDeleteExternalTool; - LaunchToolMenuItem.Text = Language.strMenuLaunchExternalTool; - } + DeleteToolMenuItem.Text = Language.strMenuDeleteExternalTool; + LaunchToolMenuItem.Text = Language.strMenuLaunchExternalTool; + } - private new void ApplyTheme() - { - if (!_themeManager.ThemingActive) return; - vsToolStripExtender.SetStyle(ToolStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - vsToolStripExtender.SetStyle(ToolsContextMenuStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); - //Apply the extended palette + private new void ApplyTheme() + { + if (!_themeManager.ThemingActive) return; + vsToolStripExtender.SetStyle(ToolStrip, _themeManager.ActiveTheme.Version, _themeManager.ActiveTheme.Theme); + vsToolStripExtender.SetStyle(ToolsContextMenuStrip, _themeManager.ActiveTheme.Version, + _themeManager.ActiveTheme.Theme); + //Apply the extended palette - ToolStripContainer.TopToolStripPanel.BackColor = _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Background; - ToolStripContainer.TopToolStripPanel.ForeColor = _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Text; - PropertiesGroupBox.BackColor = _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Background; - PropertiesGroupBox.ForeColor = _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Text; - } + ToolStripContainer.TopToolStripPanel.BackColor = + _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Background; + ToolStripContainer.TopToolStripPanel.ForeColor = + _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Text; + PropertiesGroupBox.BackColor = + _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Background; + PropertiesGroupBox.ForeColor = _themeManager.ActiveTheme.Theme.ColorPalette.CommandBarMenuDefault.Text; + } - private void UpdateToolsListObjView() - { - try - { - ToolsListObjView.BeginUpdate(); - ToolsListObjView.SetObjects(Runtime.ExternalToolsService.ExternalTools, true); - ToolsListObjView.AutoResizeColumns(); - ToolsListObjView.EndUpdate(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.PopulateToolsListObjView()", ex); - } - } + private void UpdateToolsListObjView() + { + try + { + ToolsListObjView.BeginUpdate(); + ToolsListObjView.SetObjects(Runtime.ExternalToolsService.ExternalTools, true); + ToolsListObjView.AutoResizeColumns(); + ToolsListObjView.EndUpdate(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.PopulateToolsListObjView()", ex); + } + } - private void LaunchTool() - { - try - { - foreach (var externalTool in _currentlySelectedExternalTools) - { - externalTool.Start(); - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.LaunchTool() failed.", ex); - } - } + private void LaunchTool() + { + try + { + foreach (var externalTool in _currentlySelectedExternalTools) + { + externalTool.Start(); + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.LaunchTool() failed.", ex); + } + } - private void UpdateEditorControls() - { - var selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); + private void UpdateEditorControls() + { + var selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); DisplayNameTextBox.Text = selectedTool?.DisplayName; FilenameTextBox.Text = selectedTool?.FileName; @@ -134,122 +139,132 @@ namespace mRemoteNG.UI.Window TryToIntegrateCheckBox.Checked = selectedTool?.TryIntegrate ?? false; ShowOnToolbarCheckBox.Checked = selectedTool?.ShowOnToolbar ?? false; RunElevatedCheckBox.Checked = selectedTool?.RunElevated ?? false; - WaitForExitCheckBox.Enabled = !TryToIntegrateCheckBox.Checked; + WaitForExitCheckBox.Enabled = !TryToIntegrateCheckBox.Checked; } - private void UpdateToolstipControls() - { - _currentlySelectedExternalTools.Clear(); - _currentlySelectedExternalTools.AddRange(ToolsListObjView.SelectedObjects.OfType()); - PropertiesGroupBox.Enabled = _currentlySelectedExternalTools.Count == 1; + private void UpdateToolstipControls() + { + _currentlySelectedExternalTools.Clear(); + _currentlySelectedExternalTools.AddRange(ToolsListObjView.SelectedObjects.OfType()); + PropertiesGroupBox.Enabled = _currentlySelectedExternalTools.Count == 1; - var atleastOneToolSelected = _currentlySelectedExternalTools.Count > 0; - DeleteToolMenuItem.Enabled = atleastOneToolSelected; - DeleteToolToolstripButton.Enabled = atleastOneToolSelected; - LaunchToolMenuItem.Enabled = atleastOneToolSelected; - LaunchToolToolstripButton.Enabled = atleastOneToolSelected; + var atleastOneToolSelected = _currentlySelectedExternalTools.Count > 0; + DeleteToolMenuItem.Enabled = atleastOneToolSelected; + DeleteToolToolstripButton.Enabled = atleastOneToolSelected; + LaunchToolMenuItem.Enabled = atleastOneToolSelected; + LaunchToolToolstripButton.Enabled = atleastOneToolSelected; } - #endregion + + #endregion #region Event Handlers - private void CurrentlySelectedExternalToolsOnCollectionUpdated(object sender, CollectionUpdatedEventArgs collectionUpdatedEventArgs) - { - UpdateEditorControls(); - } + + private void CurrentlySelectedExternalToolsOnCollectionUpdated(object sender, + CollectionUpdatedEventArgs + collectionUpdatedEventArgs) + { + UpdateEditorControls(); + } private void ExternalTools_FormClosed(object sender, FormClosedEventArgs e) - { + { _externalAppsSaver.Save(Runtime.ExternalToolsService.ExternalTools); - _themeManager.ThemeChanged -= ApplyTheme; - _currentlySelectedExternalTools.CollectionUpdated -= CurrentlySelectedExternalToolsOnCollectionUpdated; + _themeManager.ThemeChanged -= ApplyTheme; + _currentlySelectedExternalTools.CollectionUpdated -= CurrentlySelectedExternalToolsOnCollectionUpdated; } private void NewTool_Click(object sender, EventArgs e) - { - try - { - var externalTool = new ExternalTool(Language.strExternalToolDefaultName); - Runtime.ExternalToolsService.ExternalTools.Add(externalTool); - UpdateToolsListObjView(); - ToolsListObjView.SelectedObject = externalTool; - DisplayNameTextBox.Focus(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.NewTool_Click() failed.", ex); - } - } + { + try + { + var externalTool = new ExternalTool(Language.strExternalToolDefaultName); + Runtime.ExternalToolsService.ExternalTools.Add(externalTool); + UpdateToolsListObjView(); + ToolsListObjView.SelectedObject = externalTool; + DisplayNameTextBox.Focus(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.NewTool_Click() failed.", ex); + } + } private void DeleteTool_Click(object sender, EventArgs e) - { - try - { - string message; - if (_currentlySelectedExternalTools.Count == 1) - message = string.Format(Language.strConfirmDeleteExternalTool, _currentlySelectedExternalTools[0].DisplayName); - else if (_currentlySelectedExternalTools.Count > 1) - message = string.Format(Language.strConfirmDeleteExternalToolMultiple, _currentlySelectedExternalTools.Count); - else - return; - - if (MessageBox.Show(FrmMain.Default, message, "Question?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - return; - - foreach (var externalTool in _currentlySelectedExternalTools) - { - Runtime.ExternalToolsService.ExternalTools.Remove(externalTool); - } - var firstDeletedNode = _currentlySelectedExternalTools.FirstOrDefault(); - var oldSelectedIndex = ToolsListObjView.IndexOf(firstDeletedNode); + { + try + { + string message; + if (_currentlySelectedExternalTools.Count == 1) + message = string.Format(Language.strConfirmDeleteExternalTool, + _currentlySelectedExternalTools[0].DisplayName); + else if (_currentlySelectedExternalTools.Count > 1) + message = string.Format(Language.strConfirmDeleteExternalToolMultiple, + _currentlySelectedExternalTools.Count); + else + return; + + if (MessageBox.Show(FrmMain.Default, message, "Question?", MessageBoxButtons.YesNo, + MessageBoxIcon.Question) != DialogResult.Yes) + return; + + foreach (var externalTool in _currentlySelectedExternalTools) + { + Runtime.ExternalToolsService.ExternalTools.Remove(externalTool); + } + + var firstDeletedNode = _currentlySelectedExternalTools.FirstOrDefault(); + var oldSelectedIndex = ToolsListObjView.IndexOf(firstDeletedNode); _currentlySelectedExternalTools.Clear(); UpdateToolsListObjView(); var maxIndex = ToolsListObjView.GetItemCount() - 1; - ToolsListObjView.SelectedIndex = oldSelectedIndex <= maxIndex - ? oldSelectedIndex - : maxIndex; + ToolsListObjView.SelectedIndex = oldSelectedIndex <= maxIndex + ? oldSelectedIndex + : maxIndex; - UpdateToolstipControls(); + UpdateToolstipControls(); } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.DeleteTool_Click() failed.", ex); - } - } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.DeleteTool_Click() failed.", ex); + } + } private void LaunchTool_Click(object sender, EventArgs e) - { - LaunchTool(); - } + { + LaunchTool(); + } private void ToolsListObjView_SelectedIndexChanged(object sender, EventArgs e) - { - try - { - UpdateToolstipControls(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.ToolsListObjView_SelectedIndexChanged() failed.", ex); - } - } + { + try + { + UpdateToolstipControls(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + "UI.Window.ExternalTools.ToolsListObjView_SelectedIndexChanged() failed.", + ex); + } + } private void ToolsListObjView_DoubleClick(object sender, EventArgs e) - { - if (ToolsListObjView.SelectedItems.Count > 0) - { - LaunchTool(); - } - } + { + if (ToolsListObjView.SelectedItems.Count > 0) + { + LaunchTool(); + } + } private void PropertyControl_ChangedOrLostFocus(object sender, EventArgs e) - { - var selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); + { + var selectedTool = _currentlySelectedExternalTools.FirstOrDefault(); if (selectedTool == null) - return; - - try - { + return; + + try + { selectedTool.DisplayName = DisplayNameTextBox.Text; selectedTool.FileName = FilenameTextBox.Text; selectedTool.Arguments = ArgumentsCheckBox.Text; @@ -260,32 +275,36 @@ namespace mRemoteNG.UI.Window selectedTool.RunElevated = RunElevatedCheckBox.Checked; UpdateToolsListObjView(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.PropertyControl_ChangedOrLostFocus() failed.", ex); - } - } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage( + "UI.Window.ExternalTools.PropertyControl_ChangedOrLostFocus() failed.", + ex); + } + } private void BrowseButton_Click(object sender, EventArgs e) - { - try - { - using (var browseDialog = new OpenFileDialog()) - { - browseDialog.Filter = string.Join("|", Language.strFilterApplication, "*.exe", Language.strFilterAll, "*.*"); - if (browseDialog.ShowDialog() != DialogResult.OK) + { + try + { + using (var browseDialog = new OpenFileDialog()) + { + browseDialog.Filter = string.Join("|", Language.strFilterApplication, "*.exe", + Language.strFilterAll, "*.*"); + if (browseDialog.ShowDialog() != DialogResult.OK) return; - var selectedItem = _currentlySelectedExternalTools.FirstOrDefault(); - if (selectedItem == null) - return; - selectedItem.FileName = browseDialog.FileName; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.BrowseButton_Click() failed.", ex); - } + var selectedItem = _currentlySelectedExternalTools.FirstOrDefault(); + if (selectedItem == null) + return; + selectedItem.FileName = browseDialog.FileName; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.BrowseButton_Click() failed.", + ex); + } } private void BrowseWorkingDir_Click(object sender, EventArgs e) @@ -301,11 +320,11 @@ namespace mRemoteNG.UI.Window return; selectedItem.WorkingDir = browseDialog.SelectedPath; } - } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.BrowseButton_Click() failed.", ex); + Runtime.MessageCollector.AddExceptionMessage("UI.Window.ExternalTools.BrowseButton_Click() failed.", + ex); } } @@ -317,8 +336,10 @@ namespace mRemoteNG.UI.Window if (!(e.Model is ExternalTool rowItemAsExternalTool) || !rowItemAsExternalTool.TryIntegrate) return; - e.Text = $"'{Language.strCheckboxWaitForExit}' cannot be enabled if '{Language.strTryIntegrate}' is enabled"; + e.Text = + $"'{Language.strCheckboxWaitForExit}' cannot be enabled if '{Language.strTryIntegrate}' is enabled"; } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/HelpWindow.cs b/mRemoteV1/UI/Window/HelpWindow.cs index 6396330b..ef93ccb7 100644 --- a/mRemoteV1/UI/Window/HelpWindow.cs +++ b/mRemoteV1/UI/Window/HelpWindow.cs @@ -7,28 +7,27 @@ using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.UI.Window { public class HelpWindow : BaseWindow - { - + { #region Form Init - private TreeView tvIndex; + private TreeView tvIndex; private ImageList imgListHelp; - private System.ComponentModel.Container components; - private SplitContainer pnlSplitter; - private Label lblDocName; - private WebBrowser wbHelp; - - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - Load += Help_Load; - Shown += Help_Shown; + private System.ComponentModel.Container components; + private SplitContainer pnlSplitter; + private Label lblDocName; + private WebBrowser wbHelp; + + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + Load += Help_Load; + Shown += Help_Shown; var TreeNode1 = new TreeNode("Introduction"); var TreeNode2 = new TreeNode("Prerequisites"); var TreeNode3 = new TreeNode("Installation/Update"); var TreeNode4 = new TreeNode("Running mRemoteNG"); var TreeNode5 = new TreeNode("Command-Line Switches"); - var TreeNode6 = new TreeNode("Getting Started", new[] { TreeNode2, TreeNode3, TreeNode4, TreeNode5 }); + var TreeNode6 = new TreeNode("Getting Started", new[] {TreeNode2, TreeNode3, TreeNode4, TreeNode5}); var TreeNode7 = new TreeNode("Menus"); var TreeNode8 = new TreeNode("Connections"); var TreeNode9 = new TreeNode("Config"); @@ -43,58 +42,60 @@ namespace mRemoteNG.UI.Window var TreeNode18 = new TreeNode("External Tools"); var TreeNode19 = new TreeNode("Import/Export"); var TreeNode20 = new TreeNode("Keyboard Shortcuts"); - var TreeNode21 = new TreeNode("User Interface", new[] { + var TreeNode21 = new TreeNode("User Interface", new[] + { TreeNode7, TreeNode8, TreeNode9, TreeNode10, TreeNode11, TreeNode12, TreeNode13, TreeNode14, TreeNode15, TreeNode16, TreeNode17, TreeNode18, TreeNode19, TreeNode20 }); var TreeNode22 = new TreeNode("Common Problems (RDP)"); - var TreeNode23 = new TreeNode("Special Topics", new[] { + var TreeNode23 = new TreeNode("Special Topics", new[] + { TreeNode22 }); - var TreeNode99 = new TreeNode("Help", new[] { TreeNode1, TreeNode6, TreeNode21, TreeNode23 }); + var TreeNode99 = new TreeNode("Help", new[] {TreeNode1, TreeNode6, TreeNode21, TreeNode23}); wbHelp = new WebBrowser(); - wbHelp.DocumentTitleChanged += wbHelp_DocumentTitleChanged; - tvIndex = new TreeView(); - tvIndex.NodeMouseClick += tvIndex_NodeMouseClick; - tvIndex.AfterSelect += tvIndex_AfterSelect; - imgListHelp = new ImageList(components); - pnlSplitter = new SplitContainer(); - lblDocName = new Label(); - pnlSplitter.Panel1.SuspendLayout(); - pnlSplitter.Panel2.SuspendLayout(); - pnlSplitter.SuspendLayout(); - SuspendLayout(); - // - //wbHelp - // - wbHelp.Anchor = AnchorStyles.Top | AnchorStyles.Bottom - | AnchorStyles.Left - | AnchorStyles.Right; - wbHelp.Location = new System.Drawing.Point(1, 36); - wbHelp.MinimumSize = new System.Drawing.Size(20, 20); - wbHelp.Name = "wbHelp"; - wbHelp.ScriptErrorsSuppressed = true; - wbHelp.Size = new System.Drawing.Size(327, 286); - wbHelp.TabIndex = 1; - // - //tvIndex - // - tvIndex.Anchor = AnchorStyles.Top | AnchorStyles.Bottom - | AnchorStyles.Left - | AnchorStyles.Right; - tvIndex.BorderStyle = BorderStyle.None; - tvIndex.HideSelection = false; - tvIndex.Location = new System.Drawing.Point(1, 1); + wbHelp.DocumentTitleChanged += wbHelp_DocumentTitleChanged; + tvIndex = new TreeView(); + tvIndex.NodeMouseClick += tvIndex_NodeMouseClick; + tvIndex.AfterSelect += tvIndex_AfterSelect; + imgListHelp = new ImageList(components); + pnlSplitter = new SplitContainer(); + lblDocName = new Label(); + pnlSplitter.Panel1.SuspendLayout(); + pnlSplitter.Panel2.SuspendLayout(); + pnlSplitter.SuspendLayout(); + SuspendLayout(); + // + //wbHelp + // + wbHelp.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + | AnchorStyles.Left + | AnchorStyles.Right; + wbHelp.Location = new System.Drawing.Point(1, 36); + wbHelp.MinimumSize = new System.Drawing.Size(20, 20); + wbHelp.Name = "wbHelp"; + wbHelp.ScriptErrorsSuppressed = true; + wbHelp.Size = new System.Drawing.Size(327, 286); + wbHelp.TabIndex = 1; + // + //tvIndex + // + tvIndex.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + | AnchorStyles.Left + | AnchorStyles.Right; + tvIndex.BorderStyle = BorderStyle.None; + tvIndex.HideSelection = false; + tvIndex.Location = new System.Drawing.Point(1, 1); tvIndex.Name = "tvIndex"; - TreeNode1.Tag = "Introduction"; - TreeNode2.Tag = "gs_prerequisites"; - TreeNode3.Tag = "gs_installation"; + TreeNode1.Tag = "Introduction"; + TreeNode2.Tag = "gs_prerequisites"; + TreeNode3.Tag = "gs_installation"; TreeNode4.Tag = "gs_running_mremoteng"; TreeNode5.Tag = "gs_command_line_switches"; TreeNode7.Tag = "ui_menus"; - TreeNode8.Tag = "ui_connections"; - TreeNode9.Tag = "ui_config"; - TreeNode10.Tag = "ui_options"; + TreeNode8.Tag = "ui_connections"; + TreeNode9.Tag = "ui_config"; + TreeNode10.Tag = "ui_options"; TreeNode11.Tag = "ui_navigation"; TreeNode12.Tag = "ui_notifications"; TreeNode13.Tag = "ui_sql_configuration"; @@ -109,135 +110,140 @@ namespace mRemoteNG.UI.Window TreeNode99.Tag = "Index"; tvIndex.Nodes.AddRange(new[] {TreeNode99}); tvIndex.ShowRootLines = false; - tvIndex.Size = new System.Drawing.Size(207, 321); - tvIndex.TabIndex = 0; - // - //imgListHelp - // - imgListHelp.ColorDepth = ColorDepth.Depth32Bit; - imgListHelp.ImageSize = new System.Drawing.Size(16, 16); - imgListHelp.TransparentColor = System.Drawing.Color.Transparent; - // - //pnlSplitter - // - pnlSplitter.Anchor = AnchorStyles.Top | AnchorStyles.Bottom - | AnchorStyles.Left - | AnchorStyles.Right; - pnlSplitter.FixedPanel = FixedPanel.Panel1; - pnlSplitter.Location = new System.Drawing.Point(0, 0); - pnlSplitter.Name = "pnlSplitter"; - // - //pnlSplitter.Panel1 - // - pnlSplitter.Panel1.Controls.Add(tvIndex); - // - //pnlSplitter.Panel2 - // - pnlSplitter.Panel2.Controls.Add(lblDocName); - pnlSplitter.Panel2.Controls.Add(wbHelp); - pnlSplitter.Size = new System.Drawing.Size(542, 323); - pnlSplitter.SplitterDistance = 209; - pnlSplitter.TabIndex = 2; - // - //lblDocName - // - lblDocName.Anchor = AnchorStyles.Top | AnchorStyles.Left - | AnchorStyles.Right; - lblDocName.BackColor = System.Drawing.Color.DimGray; - lblDocName.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0)); - lblDocName.ForeColor = System.Drawing.Color.White; - lblDocName.Location = new System.Drawing.Point(1, 1); - lblDocName.Name = "lblDocName"; - lblDocName.Size = new System.Drawing.Size(327, 35); - lblDocName.TabIndex = 2; - lblDocName.Text = @"Introduction"; - lblDocName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - //Help - // - ClientSize = new System.Drawing.Size(542, 323); - Controls.Add(pnlSplitter); - Icon = Resources.Help_Icon; - TabText = @"Help"; - Text = @"Help"; - pnlSplitter.Panel1.ResumeLayout(false); - pnlSplitter.Panel2.ResumeLayout(false); - pnlSplitter.ResumeLayout(false); - ResumeLayout(false); - - } + tvIndex.Size = new System.Drawing.Size(207, 321); + tvIndex.TabIndex = 0; + // + //imgListHelp + // + imgListHelp.ColorDepth = ColorDepth.Depth32Bit; + imgListHelp.ImageSize = new System.Drawing.Size(16, 16); + imgListHelp.TransparentColor = System.Drawing.Color.Transparent; + // + //pnlSplitter + // + pnlSplitter.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + | AnchorStyles.Left + | AnchorStyles.Right; + pnlSplitter.FixedPanel = FixedPanel.Panel1; + pnlSplitter.Location = new System.Drawing.Point(0, 0); + pnlSplitter.Name = "pnlSplitter"; + // + //pnlSplitter.Panel1 + // + pnlSplitter.Panel1.Controls.Add(tvIndex); + // + //pnlSplitter.Panel2 + // + pnlSplitter.Panel2.Controls.Add(lblDocName); + pnlSplitter.Panel2.Controls.Add(wbHelp); + pnlSplitter.Size = new System.Drawing.Size(542, 323); + pnlSplitter.SplitterDistance = 209; + pnlSplitter.TabIndex = 2; + // + //lblDocName + // + lblDocName.Anchor = AnchorStyles.Top | AnchorStyles.Left + | AnchorStyles.Right; + lblDocName.BackColor = System.Drawing.Color.DimGray; + lblDocName.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Bold, + System.Drawing.GraphicsUnit.Point, Convert.ToByte(0)); + lblDocName.ForeColor = System.Drawing.Color.White; + lblDocName.Location = new System.Drawing.Point(1, 1); + lblDocName.Name = "lblDocName"; + lblDocName.Size = new System.Drawing.Size(327, 35); + lblDocName.TabIndex = 2; + lblDocName.Text = @"Introduction"; + lblDocName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + //Help + // + ClientSize = new System.Drawing.Size(542, 323); + Controls.Add(pnlSplitter); + Icon = Resources.Help_Icon; + TabText = @"Help"; + Text = @"Help"; + pnlSplitter.Panel1.ResumeLayout(false); + pnlSplitter.Panel2.ResumeLayout(false); + pnlSplitter.ResumeLayout(false); + ResumeLayout(false); + } + #endregion - + #region Public Methods - public HelpWindow() - { - WindowType = WindowType.Help; - DockPnl = new DockContent(); - InitializeComponent(); - - FillImageList(); - tvIndex.ImageList = imgListHelp; - SetImages(tvIndex.Nodes[0]); - } + + public HelpWindow() + { + WindowType = WindowType.Help; + DockPnl = new DockContent(); + InitializeComponent(); + + FillImageList(); + tvIndex.ImageList = imgListHelp; + SetImages(tvIndex.Nodes[0]); + } + #endregion - + #region Private Methods - private void Help_Load(object sender, EventArgs e) - { - tvIndex.Nodes[0].ExpandAll(); - tvIndex.SelectedNode = tvIndex.Nodes[0].Nodes[0]; - } - - private void Help_Shown(object sender, EventArgs e) - { - // This can only be set once the WebBrowser control is shown, it will throw a COM exception otherwise. - wbHelp.AllowWebBrowserDrop = false; - } - - private void tvIndex_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) - { - tvIndex.SelectedNode = e.Node; - } - - private void tvIndex_AfterSelect(object sender, TreeViewEventArgs e) - { - if (!string.IsNullOrEmpty((string)e.Node.Tag)) - { - wbHelp.Navigate(GeneralAppInfo.HomePath + "\\Help\\" + Convert.ToString(e.Node.Tag) +".htm"); - } - } - - private void wbHelp_DocumentTitleChanged(object sender, EventArgs e) - { - lblDocName.Text = wbHelp.DocumentTitle; - } - - private void FillImageList() - { - imgListHelp.Images.Add("File", Resources.Page); - imgListHelp.Images.Add("Folder", Resources.Folder); - imgListHelp.Images.Add("Help", Resources.Help); - } - - private static void SetImages(TreeNode node) - { - node.ImageIndex = 2; - node.SelectedImageIndex = 2; - - foreach (TreeNode n in node.Nodes) - { - if (n.Nodes.Count > 0) - { - n.ImageIndex = 1; - n.SelectedImageIndex = 1; - } - else - { - n.ImageIndex = 0; - n.SelectedImageIndex = 0; - } - } - } + + private void Help_Load(object sender, EventArgs e) + { + tvIndex.Nodes[0].ExpandAll(); + tvIndex.SelectedNode = tvIndex.Nodes[0].Nodes[0]; + } + + private void Help_Shown(object sender, EventArgs e) + { + // This can only be set once the WebBrowser control is shown, it will throw a COM exception otherwise. + wbHelp.AllowWebBrowserDrop = false; + } + + private void tvIndex_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) + { + tvIndex.SelectedNode = e.Node; + } + + private void tvIndex_AfterSelect(object sender, TreeViewEventArgs e) + { + if (!string.IsNullOrEmpty((string)e.Node.Tag)) + { + wbHelp.Navigate(GeneralAppInfo.HomePath + "\\Help\\" + Convert.ToString(e.Node.Tag) + ".htm"); + } + } + + private void wbHelp_DocumentTitleChanged(object sender, EventArgs e) + { + lblDocName.Text = wbHelp.DocumentTitle; + } + + private void FillImageList() + { + imgListHelp.Images.Add("File", Resources.Page); + imgListHelp.Images.Add("Folder", Resources.Folder); + imgListHelp.Images.Add("Help", Resources.Help); + } + + private static void SetImages(TreeNode node) + { + node.ImageIndex = 2; + node.SelectedImageIndex = 2; + + foreach (TreeNode n in node.Nodes) + { + if (n.Nodes.Count > 0) + { + n.ImageIndex = 1; + n.SelectedImageIndex = 1; + } + else + { + n.ImageIndex = 0; + n.SelectedImageIndex = 0; + } + } + } + #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Window/PortScanWindow.cs b/mRemoteV1/UI/Window/PortScanWindow.cs index 615755ba..190cb0fb 100644 --- a/mRemoteV1/UI/Window/PortScanWindow.cs +++ b/mRemoteV1/UI/Window/PortScanWindow.cs @@ -15,238 +15,263 @@ using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.UI.Window { public partial class PortScanWindow - { + { #region Constructors - public PortScanWindow() - { - InitializeComponent(); - - WindowType = WindowType.PortScan; - DockPnl = new DockContent(); + + public PortScanWindow() + { + InitializeComponent(); + + WindowType = WindowType.PortScan; + DockPnl = new DockContent(); ApplyTheme(); var display = new DisplayProperties(); - btnScan.Image = display.ScaleImage(btnScan.Image); - } + btnScan.Image = display.ScaleImage(btnScan.Image); + } + #endregion - private new void ApplyTheme() + private new void ApplyTheme() { - base.ApplyTheme(); + base.ApplyTheme(); } #region Private Properties + private bool IpsValid - { - get - { - if (string.IsNullOrEmpty(ipStart.Octet1.Text)) - { - return false; - } - if (string.IsNullOrEmpty(ipStart.Octet2.Text)) - { - return false; - } - if (string.IsNullOrEmpty(ipStart.Octet3.Text)) - { - return false; - } - if (string.IsNullOrEmpty(ipStart.Octet4.Text)) - { - return false; - } - - if (string.IsNullOrEmpty(ipEnd.Octet1.Text)) - { - return false; - } - if (string.IsNullOrEmpty(ipEnd.Octet2.Text)) - { - return false; - } - if (string.IsNullOrEmpty(ipEnd.Octet3.Text)) - { - return false; - } - if (string.IsNullOrEmpty(ipEnd.Octet4.Text)) - { - return false; - } - - return true; - } - } + { + get + { + if (string.IsNullOrEmpty(ipStart.Octet1.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipStart.Octet2.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipStart.Octet3.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipStart.Octet4.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipEnd.Octet1.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipEnd.Octet2.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipEnd.Octet3.Text)) + { + return false; + } + + if (string.IsNullOrEmpty(ipEnd.Octet4.Text)) + { + return false; + } + + return true; + } + } + #endregion - + #region Private Fields - private PortScanner _portScanner; - private bool _scanning; + + private PortScanner _portScanner; + private bool _scanning; + #endregion - + #region Private Methods + #region Event Handlers - private void PortScan_Load(object sender, EventArgs e) - { - ApplyLanguage(); + private void PortScan_Load(object sender, EventArgs e) + { + ApplyLanguage(); - try - { - olvHosts.Columns.AddRange(new ColumnHeader[]{clmHost, clmSSH, clmTelnet, clmHTTP, clmHTTPS, clmRlogin, clmRDP, clmVNC, clmOpenPorts, clmClosedPorts}); - ShowImportControls(true); - cbProtocol.SelectedIndex = 0; - numericSelectorTimeout.Value = 5; - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage(Language.strPortScanCouldNotLoadPanel, ex); - } - } + try + { + olvHosts.Columns.AddRange(new ColumnHeader[] + { + clmHost, clmSSH, clmTelnet, clmHTTP, clmHTTPS, clmRlogin, clmRDP, clmVNC, clmOpenPorts, + clmClosedPorts + }); + ShowImportControls(true); + cbProtocol.SelectedIndex = 0; + numericSelectorTimeout.Value = 5; + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage(Language.strPortScanCouldNotLoadPanel, ex); + } + } - private void portStart_Enter(object sender, EventArgs e) - { - portStart.Select(0, portStart.Text.Length); - } + private void portStart_Enter(object sender, EventArgs e) + { + portStart.Select(0, portStart.Text.Length); + } - private void portEnd_Enter(object sender, EventArgs e) - { - portEnd.Select(0, portEnd.Text.Length); - } + private void portEnd_Enter(object sender, EventArgs e) + { + portEnd.Select(0, portEnd.Text.Length); + } - private void btnScan_Click(object sender, EventArgs e) - { - if (_scanning) - { - StopScan(); - } - else - { - if (IpsValid) - { - StartScan(); - } - else - { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, Language.strCannotStartPortScan); + private void btnScan_Click(object sender, EventArgs e) + { + if (_scanning) + { + StopScan(); + } + else + { + if (IpsValid) + { + StartScan(); } - } - } + else + { + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, Language.strCannotStartPortScan); + } + } + } + + private void btnImport_Click(object sender, EventArgs e) + { + var protocol = + (ProtocolType)Enum.Parse(typeof(ProtocolType), Convert.ToString(cbProtocol.SelectedItem), true); + importSelectedHosts(protocol); + } - private void btnImport_Click(object sender, EventArgs e) - { - var protocol = (ProtocolType)Enum.Parse(typeof(ProtocolType), Convert.ToString(cbProtocol.SelectedItem), true); - importSelectedHosts(protocol); - } #endregion - - private void ApplyLanguage() - { - lblStartIP.Text = Language.strStartIP; - lblEndIP.Text = Language.strEndIP; - btnScan.Text = Language.strButtonScan; - btnImport.Text = Language.strButtonImport; - lblOnlyImport.Text = Language.strProtocolToImport; - clmHost.Text = Language.strColumnHostnameIP; - clmOpenPorts.Text = Language.strOpenPorts; - clmClosedPorts.Text = Language.strClosedPorts; + + private void ApplyLanguage() + { + lblStartIP.Text = Language.strStartIP; + lblEndIP.Text = Language.strEndIP; + btnScan.Text = Language.strButtonScan; + btnImport.Text = Language.strButtonImport; + lblOnlyImport.Text = Language.strProtocolToImport; + clmHost.Text = Language.strColumnHostnameIP; + clmOpenPorts.Text = Language.strOpenPorts; + clmClosedPorts.Text = Language.strClosedPorts; ngCheckFirstPort.Text = Language.strStartPort; ngCheckLastPort.Text = Language.strEndPort; - lblTimeout.Text = Language.strTimeoutInSeconds; - TabText = Language.strMenuPortScan; - Text = Language.strMenuPortScan; - } - - private void ShowImportControls(bool controlsVisible) - { - pnlImport.Visible = controlsVisible; - if (controlsVisible) - olvHosts.Height = pnlImport.Top - olvHosts.Top; - else - olvHosts.Height = pnlImport.Bottom - olvHosts.Top; - } - - private void StartScan() - { - try - { - _scanning = true; - SwitchButtonText(); - olvHosts.Items.Clear(); - - var ipAddressStart = IPAddress.Parse(ipStart.Text); - var ipAddressEnd = IPAddress.Parse(ipEnd.Text); + lblTimeout.Text = Language.strTimeoutInSeconds; + TabText = Language.strMenuPortScan; + Text = Language.strMenuPortScan; + } + + private void ShowImportControls(bool controlsVisible) + { + pnlImport.Visible = controlsVisible; + if (controlsVisible) + olvHosts.Height = pnlImport.Top - olvHosts.Top; + else + olvHosts.Height = pnlImport.Bottom - olvHosts.Top; + } + + private void StartScan() + { + try + { + _scanning = true; + SwitchButtonText(); + olvHosts.Items.Clear(); + + var ipAddressStart = IPAddress.Parse(ipStart.Text); + var ipAddressEnd = IPAddress.Parse(ipEnd.Text); if (!ngCheckFirstPort.Checked && !ngCheckLastPort.Checked) - _portScanner = new PortScanner(ipAddressStart, ipAddressEnd, (int)portStart.Value, (int)portEnd.Value, (int)numericSelectorTimeout.Value * 1000, true); + _portScanner = new PortScanner(ipAddressStart, ipAddressEnd, (int)portStart.Value, + (int)portEnd.Value, (int)numericSelectorTimeout.Value * 1000, true); else - _portScanner = new PortScanner(ipAddressStart, ipAddressEnd, (int)portStart.Value, (int)portEnd.Value, (int)numericSelectorTimeout.Value*1000); - - _portScanner.BeginHostScan += PortScanner_BeginHostScan; - _portScanner.HostScanned += PortScanner_HostScanned; - _portScanner.ScanComplete += PortScanner_ScanComplete; - - _portScanner.StartScan(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddExceptionMessage("StartScan failed (UI.Window.PortScan)", ex); - } - } - - private void StopScan() + _portScanner = new PortScanner(ipAddressStart, ipAddressEnd, (int)portStart.Value, + (int)portEnd.Value, (int)numericSelectorTimeout.Value * 1000); + + _portScanner.BeginHostScan += PortScanner_BeginHostScan; + _portScanner.HostScanned += PortScanner_HostScanned; + _portScanner.ScanComplete += PortScanner_ScanComplete; + + _portScanner.StartScan(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddExceptionMessage("StartScan failed (UI.Window.PortScan)", ex); + } + } + + private void StopScan() { _portScanner.BeginHostScan -= PortScanner_BeginHostScan; _portScanner.HostScanned -= PortScanner_HostScanned; _portScanner.ScanComplete -= PortScanner_ScanComplete; _portScanner?.StopScan(); - _scanning = false; - SwitchButtonText(); - } - - private void SwitchButtonText() - { - btnScan.Text = _scanning ? Language.strButtonStop : Language.strButtonScan; - - prgBar.Maximum = 100; - prgBar.Value = 0; - } - - private static void PortScanner_BeginHostScan(string host) - { - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Scanning " + host, true); - } - - private delegate void PortScannerHostScannedDelegate(ScanHost host, int scannedCount, int totalCount); - private void PortScanner_HostScanned(ScanHost host, int scannedCount, int totalCount) - { - if (InvokeRequired) - { - Invoke(new PortScannerHostScannedDelegate(PortScanner_HostScanned), new object[] {host, scannedCount, totalCount}); - return; - } - - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Host scanned " + host.HostIp, true); + _scanning = false; + SwitchButtonText(); + } + + private void SwitchButtonText() + { + btnScan.Text = _scanning ? Language.strButtonStop : Language.strButtonScan; + + prgBar.Maximum = 100; + prgBar.Value = 0; + } + + private static void PortScanner_BeginHostScan(string host) + { + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Scanning " + host, true); + } + + private delegate void PortScannerHostScannedDelegate(ScanHost host, int scannedCount, int totalCount); + + private void PortScanner_HostScanned(ScanHost host, int scannedCount, int totalCount) + { + if (InvokeRequired) + { + Invoke(new PortScannerHostScannedDelegate(PortScanner_HostScanned), + new object[] {host, scannedCount, totalCount}); + return; + } + + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Host scanned " + host.HostIp, true); olvHosts.AddObject(host); prgBar.Maximum = totalCount; - prgBar.Value = scannedCount; - } - - private delegate void PortScannerScanComplete(List hosts); - private void PortScanner_ScanComplete(List hosts) - { - if (InvokeRequired) - { - Invoke(new PortScannerScanComplete(PortScanner_ScanComplete), new object[] {hosts}); - return; - } - - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strPortScanComplete); - - _scanning = false; - SwitchButtonText(); - } + prgBar.Value = scannedCount; + } + + private delegate void PortScannerScanComplete(List hosts); + + private void PortScanner_ScanComplete(List hosts) + { + if (InvokeRequired) + { + Invoke(new PortScannerScanComplete(PortScanner_ScanComplete), new object[] {hosts}); + return; + } + + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strPortScanComplete); + + _scanning = false; + SwitchButtonText(); + } + #endregion private void importSelectedHosts(ProtocolType protocol) @@ -254,12 +279,13 @@ namespace mRemoteNG.UI.Window var hosts = new List(); foreach (ScanHost host in olvHosts.SelectedObjects) { - hosts.Add(host); + hosts.Add(host); } if (hosts.Count < 1) { - Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "Could not import host(s) from port scan context menu"); + Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, + "Could not import host(s) from port scan context menu"); return; } @@ -271,20 +297,22 @@ namespace mRemoteNG.UI.Window /// Determines where the imported hosts will be placed /// in the connection tree. /// - private ContainerInfo GetDestinationContainerForImportedHosts() - { - var selectedNode = Windows.TreeForm.SelectedNode - ?? Windows.TreeForm.ConnectionTree.ConnectionTreeModel.RootNodes.OfType().First(); + private ContainerInfo GetDestinationContainerForImportedHosts() + { + var selectedNode = Windows.TreeForm.SelectedNode + ?? Windows.TreeForm.ConnectionTree.ConnectionTreeModel.RootNodes.OfType() + .First(); // if a putty node is selected, place imported connections in the root connection node if (selectedNode is RootPuttySessionsNodeInfo || selectedNode is PuttySessionInfo) - selectedNode = Windows.TreeForm.ConnectionTree.ConnectionTreeModel.RootNodes.OfType().First(); + selectedNode = Windows.TreeForm.ConnectionTree.ConnectionTreeModel.RootNodes.OfType() + .First(); // if the selected node is a connection, use its parent container var selectedTreeNodeAsContainer = selectedNode as ContainerInfo ?? selectedNode.Parent; - return selectedTreeNodeAsContainer; - } + return selectedTreeNodeAsContainer; + } private void importVNCToolStripMenuItem_Click(object sender, EventArgs e) { diff --git a/mRemoteV1/UI/Window/SSHTransferWindow.cs b/mRemoteV1/UI/Window/SSHTransferWindow.cs index e19457a1..9a1d2452 100644 --- a/mRemoteV1/UI/Window/SSHTransferWindow.cs +++ b/mRemoteV1/UI/Window/SSHTransferWindow.cs @@ -1,8 +1,8 @@ using mRemoteNG.App; using System; using System.IO; -using System.Threading; -using mRemoteNG.Tools; +using System.Threading; +using mRemoteNG.Tools; using WeifenLuo.WinFormsUI.Docking; using System.Windows.Forms; using mRemoteNG.Messages; @@ -13,6 +13,7 @@ namespace mRemoteNG.UI.Window public class SSHTransferWindow : BaseWindow { #region Form Init + private Controls.Base.NGProgressBar pbStatus; private Controls.Base.NGButton btnTransfer; private Controls.Base.NGTextBox txtUser; @@ -36,7 +37,8 @@ namespace mRemoteNG.UI.Window private void InitializeComponent() { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SSHTransferWindow)); + System.ComponentModel.ComponentResourceManager resources = + new System.ComponentModel.ComponentResourceManager(typeof(SSHTransferWindow)); this.grpFiles = new mRemoteNG.UI.Controls.Base.NGGroupBox(); this.lblLocalFile = new mRemoteNG.UI.Controls.Base.NGLabel(); this.txtLocalFile = new mRemoteNG.UI.Controls.Base.NGTextBox(); @@ -89,6 +91,8 @@ namespace mRemoteNG.UI.Window // txtLocalFile // this.txtLocalFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtLocalFile.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtLocalFile.Location = new System.Drawing.Point(105, 28); this.txtLocalFile.Name = "txtLocalFile"; this.txtLocalFile.Size = new System.Drawing.Size(455, 22); @@ -100,18 +104,19 @@ namespace mRemoteNG.UI.Window this.btnTransfer.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnTransfer.Image = global::mRemoteNG.Resources.SSHTransfer; this.btnTransfer.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; - this.btnTransfer.Location = new System.Drawing.Point(566, 140); + this.btnTransfer.Location = new System.Drawing.Point(562, 145); this.btnTransfer.Name = "btnTransfer"; - this.btnTransfer.Size = new System.Drawing.Size(96, 29); + this.btnTransfer.Size = new System.Drawing.Size(100, 24); this.btnTransfer.TabIndex = 10000; this.btnTransfer.Text = "Transfer"; - this.btnTransfer.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnTransfer.UseVisualStyleBackColor = true; this.btnTransfer.Click += new System.EventHandler(this.btnTransfer_Click); // // txtRemoteFile // this.txtRemoteFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtRemoteFile.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtRemoteFile.Location = new System.Drawing.Point(105, 60); this.txtRemoteFile.Name = "txtRemoteFile"; this.txtRemoteFile.Size = new System.Drawing.Size(542, 22); @@ -132,7 +137,7 @@ namespace mRemoteNG.UI.Window this.btnBrowse.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnBrowse.Location = new System.Drawing.Point(566, 28); this.btnBrowse.Name = "btnBrowse"; - this.btnBrowse.Size = new System.Drawing.Size(81, 26); + this.btnBrowse.Size = new System.Drawing.Size(81, 22); this.btnBrowse.TabIndex = 30; this.btnBrowse.Text = "Browse"; this.btnBrowse.UseVisualStyleBackColor = true; @@ -231,6 +236,8 @@ namespace mRemoteNG.UI.Window // txtPort // this.txtPort.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtPort.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtPort.Location = new System.Drawing.Point(271, 110); this.txtPort.Name = "txtPort"; this.txtPort.Size = new System.Drawing.Size(30, 22); @@ -241,6 +248,8 @@ namespace mRemoteNG.UI.Window // txtHost // this.txtHost.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtHost.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtHost.Location = new System.Drawing.Point(105, 19); this.txtHost.Name = "txtHost"; this.txtHost.Size = new System.Drawing.Size(471, 22); @@ -249,6 +258,8 @@ namespace mRemoteNG.UI.Window // txtPassword // this.txtPassword.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtPassword.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtPassword.Location = new System.Drawing.Point(105, 81); this.txtPassword.Name = "txtPassword"; this.txtPassword.Size = new System.Drawing.Size(471, 22); @@ -258,6 +269,8 @@ namespace mRemoteNG.UI.Window // txtUser // this.txtUser.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtUser.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtUser.Location = new System.Drawing.Point(105, 51); this.txtUser.Name = "txtUser"; this.txtUser.Size = new System.Drawing.Size(471, 22); @@ -279,7 +292,8 @@ namespace mRemoteNG.UI.Window this.Controls.Add(this.grpFiles); this.Controls.Add(this.grpConnection); this.Controls.Add(this.pbStatus); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "SSHTransferWindow"; this.TabText = "SSH File Transfer"; @@ -290,15 +304,18 @@ namespace mRemoteNG.UI.Window this.grpConnection.ResumeLayout(false); this.grpConnection.PerformLayout(); this.ResumeLayout(false); - } + #endregion #region Private Properties + private readonly OpenFileDialog oDlg; + #endregion #region Public Properties + public string Hostname { get => txtHost.Text; @@ -322,12 +339,14 @@ namespace mRemoteNG.UI.Window get => txtPassword.Text; set => txtPassword.Text = value; } + #endregion #region Form Stuff + private void SSHTransfer_Load(object sender, EventArgs e) { - ApplyTheme(); + ApplyTheme(); ApplyLanguage(); var display = new DisplayProperties(); btnTransfer.Image = display.ScaleImage(btnTransfer.Image); @@ -349,10 +368,13 @@ namespace mRemoteNG.UI.Window TabText = Language.strMenuSSHFileTransfer; Text = Language.strMenuSSHFileTransfer; } + #endregion #region Private Methods + private SecureTransfer st; + private void StartTransfer(SecureTransfer.SSHTransferProtocol Protocol) { if (AllFieldsSet() == false) @@ -369,7 +391,8 @@ namespace mRemoteNG.UI.Window try { - st = new SecureTransfer(txtHost.Text, txtUser.Text, txtPassword.Text, int.Parse(txtPort.Text), Protocol, txtLocalFile.Text, txtRemoteFile.Text); + st = new SecureTransfer(txtHost.Text, txtUser.Text, txtPassword.Text, int.Parse(txtPort.Text), Protocol, + txtLocalFile.Text, txtRemoteFile.Text); // Connect creates the protocol objects and makes the initial connection. st.Connect(); @@ -418,7 +441,8 @@ namespace mRemoteNG.UI.Window try { DisableButtons(); - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Transfer of {Path.GetFileName(st.SrcFile)} started.", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Transfer of {Path.GetFileName(st.SrcFile)} started.", true); st.Upload(); // SftpClient is Asynchronous, so we need to wait here after the upload and handle the status directly since no status events are raised. @@ -427,22 +451,28 @@ namespace mRemoteNG.UI.Window var fi = new FileInfo(st.SrcFile); while (!st.asyncResult.IsCompleted) { - var max = fi.Length > int.MaxValue ? Convert.ToInt32(fi.Length / 1024) : Convert.ToInt32(fi.Length); + var max = fi.Length > int.MaxValue + ? Convert.ToInt32(fi.Length / 1024) + : Convert.ToInt32(fi.Length); - var cur = fi.Length > int.MaxValue ? Convert.ToInt32(st.asyncResult.UploadedBytes / 1024) : Convert.ToInt32(st.asyncResult.UploadedBytes); + var cur = fi.Length > int.MaxValue + ? Convert.ToInt32(st.asyncResult.UploadedBytes / 1024) + : Convert.ToInt32(st.asyncResult.UploadedBytes); SshTransfer_Progress(cur, max); Thread.Sleep(50); } } - Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, $"Transfer of {Path.GetFileName(st.SrcFile)} completed.", true); + Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, + $"Transfer of {Path.GetFileName(st.SrcFile)} completed.", true); st.Disconnect(); st.Dispose(); EnableButtons(); } catch (Exception ex) { - Runtime.MessageCollector.AddExceptionStackTrace(Language.strSSHStartTransferBG, ex, MessageClass.ErrorMsg, false); + Runtime.MessageCollector.AddExceptionStackTrace(Language.strSSHStartTransferBG, ex, + MessageClass.ErrorMsg, false); st?.Disconnect(); st?.Dispose(); } @@ -450,11 +480,13 @@ namespace mRemoteNG.UI.Window private bool AllFieldsSet() { - if (txtHost.Text != "" && txtPort.Text != "" && txtUser.Text != "" && txtLocalFile.Text != "" && txtRemoteFile.Text != "") + if (txtHost.Text != "" && txtPort.Text != "" && txtUser.Text != "" && txtLocalFile.Text != "" && + txtRemoteFile.Text != "") { if (txtPassword.Text == "") { - if (MessageBox.Show(FrmMain.Default, Language.strEmptyPasswordContinue, @"Question?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (MessageBox.Show(FrmMain.Default, Language.strEmptyPasswordContinue, @"Question?", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return false; } @@ -462,7 +494,8 @@ namespace mRemoteNG.UI.Window if (txtRemoteFile.Text.EndsWith("/") || txtRemoteFile.Text.EndsWith("\\")) { - txtRemoteFile.Text += txtLocalFile.Text.Substring(txtLocalFile.Text.LastIndexOf("\\", StringComparison.Ordinal) + 1); + txtRemoteFile.Text += + txtLocalFile.Text.Substring(txtLocalFile.Text.LastIndexOf("\\", StringComparison.Ordinal) + 1); } return true; @@ -478,6 +511,7 @@ namespace mRemoteNG.UI.Window private int curVal; private delegate void SetStatusCB(); + private void SetStatus() { if (pbStatus.InvokeRequired) @@ -493,6 +527,7 @@ namespace mRemoteNG.UI.Window } private delegate void EnableButtonsCB(); + private void EnableButtons() { if (btnTransfer.InvokeRequired) @@ -507,6 +542,7 @@ namespace mRemoteNG.UI.Window } private delegate void DisableButtonsCB(); + private void DisableButtons() { if (btnTransfer.InvokeRequired) @@ -531,6 +567,7 @@ namespace mRemoteNG.UI.Window #endregion #region Public Methods + public SSHTransferWindow() { WindowType = WindowType.SSHTransfer; @@ -543,9 +580,11 @@ namespace mRemoteNG.UI.Window CheckFileExists = true }; } + #endregion #region Form Stuff + private void btnBrowse_Click(object sender, EventArgs e) { if (oDlg.ShowDialog() != DialogResult.OK) return; @@ -566,6 +605,7 @@ namespace mRemoteNG.UI.Window StartTransfer(SecureTransfer.SSHTransferProtocol.SFTP); } } + #endregion } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/ScreenshotManagerWindow.cs b/mRemoteV1/UI/Window/ScreenshotManagerWindow.cs index eab5589d..17312526 100644 --- a/mRemoteV1/UI/Window/ScreenshotManagerWindow.cs +++ b/mRemoteV1/UI/Window/ScreenshotManagerWindow.cs @@ -9,26 +9,27 @@ using mRemoteNG.Themes; namespace mRemoteNG.UI.Window { - public class ScreenshotManagerWindow : BaseWindow - { + public class ScreenshotManagerWindow : BaseWindow + { #region Form Init - internal MenuStrip msMain; - private ToolStripMenuItem mMenFile; - private ToolStripMenuItem mMenFileSaveAll; - private ToolStripMenuItem mMenFileRemoveAll; - internal ContextMenuStrip cMenScreenshot; + + internal MenuStrip msMain; + private ToolStripMenuItem mMenFile; + private ToolStripMenuItem mMenFileSaveAll; + private ToolStripMenuItem mMenFileRemoveAll; + internal ContextMenuStrip cMenScreenshot; private System.ComponentModel.IContainer components; private ToolStripMenuItem cMenScreenshotCopy; - private ToolStripMenuItem cMenScreenshotSave; - internal SaveFileDialog dlgSaveSingleImage; - internal FolderBrowserDialog dlgSaveAllImages; + private ToolStripMenuItem cMenScreenshotSave; + internal SaveFileDialog dlgSaveSingleImage; + internal FolderBrowserDialog dlgSaveAllImages; private FlowLayoutPanel flpScreenshots; private VisualStudioToolStripExtender vsToolStripExtender; private readonly ToolStripRenderer _toolStripProfessionalRenderer = new ToolStripProfessionalRenderer(); private void InitializeComponent() - { + { components = new System.ComponentModel.Container(); flpScreenshots = new FlowLayoutPanel(); msMain = new MenuStrip(); @@ -46,8 +47,8 @@ namespace mRemoteNG.UI.Window // // flpScreenshots // - flpScreenshots.Anchor = AnchorStyles.Top | AnchorStyles.Bottom - | AnchorStyles.Left + flpScreenshots.Anchor = AnchorStyles.Top | AnchorStyles.Bottom + | AnchorStyles.Left | AnchorStyles.Right; flpScreenshots.AutoScroll = true; flpScreenshots.Location = new Point(0, 26); @@ -58,8 +59,10 @@ namespace mRemoteNG.UI.Window // msMain // msMain.Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - msMain.Items.AddRange(new ToolStripItem[] { - mMenFile}); + msMain.Items.AddRange(new ToolStripItem[] + { + mMenFile + }); msMain.Location = new Point(0, 0); msMain.Name = "msMain"; msMain.RenderMode = ToolStripRenderMode.Professional; @@ -69,9 +72,11 @@ namespace mRemoteNG.UI.Window // // mMenFile // - mMenFile.DropDownItems.AddRange(new ToolStripItem[] { - mMenFileSaveAll, - mMenFileRemoveAll}); + mMenFile.DropDownItems.AddRange(new ToolStripItem[] + { + mMenFileSaveAll, + mMenFileRemoveAll + }); mMenFile.Image = Resources.File; mMenFile.Name = "mMenFile"; mMenFile.Size = new Size(53, 20); @@ -96,9 +101,11 @@ namespace mRemoteNG.UI.Window // // cMenScreenshot // - cMenScreenshot.Items.AddRange(new ToolStripItem[] { - cMenScreenshotCopy, - cMenScreenshotSave}); + cMenScreenshot.Items.AddRange(new ToolStripItem[] + { + cMenScreenshotCopy, + cMenScreenshotSave + }); cMenScreenshot.Name = "cMenScreenshot"; cMenScreenshot.Size = new Size(103, 48); // @@ -120,9 +127,10 @@ namespace mRemoteNG.UI.Window // // dlgSaveSingleImage // - dlgSaveSingleImage.Filter = "Graphics Interchange Format File (.gif)|*.gif|Joint Photographic Experts Group Fi" + - "le (.jpeg)|*.jpeg|Joint Photographic Experts Group File (.jpg)|*.jpg|Portable Ne" + - "twork Graphics File (.png)|*.png"; + dlgSaveSingleImage.Filter = + "Graphics Interchange Format File (.gif)|*.gif|Joint Photographic Experts Group Fi" + + "le (.jpeg)|*.jpeg|Joint Photographic Experts Group File (.jpg)|*.jpg|Portable Ne" + + "twork Graphics File (.png)|*.png"; dlgSaveSingleImage.FilterIndex = 4; // // ScreenshotManagerWindow @@ -145,17 +153,18 @@ namespace mRemoteNG.UI.Window cMenScreenshot.ResumeLayout(false); ResumeLayout(false); PerformLayout(); + } - } #endregion - + #region Form Stuff - private void ScreenshotManager_Load(object sender, EventArgs e) - { + + private void ScreenshotManager_Load(object sender, EventArgs e) + { ApplyTheme(); ThemeManager.getInstance().ThemeChanged += ApplyTheme; ApplyLanguage(); - } + } private new void ApplyTheme() { @@ -165,253 +174,284 @@ namespace mRemoteNG.UI.Window { DefaultRenderer = _toolStripProfessionalRenderer }; - vsToolStripExtender.SetStyle(cMenScreenshot, ThemeManager.getInstance().ActiveTheme.Version, ThemeManager.getInstance().ActiveTheme.Theme); + vsToolStripExtender.SetStyle(cMenScreenshot, ThemeManager.getInstance().ActiveTheme.Version, + ThemeManager.getInstance().ActiveTheme.Theme); } + private void ApplyLanguage() - { - mMenFile.Text = Language.strMenuFile; - mMenFileSaveAll.Text = Language.strSaveAll; - mMenFileRemoveAll.Text = Language.strRemoveAll; - cMenScreenshotCopy.Text = Language.strMenuCopy; - cMenScreenshotSave.Text = Language.strSave; - dlgSaveSingleImage.Filter = Language.strSaveImageFilter; - TabText = Language.strScreenshots; - Text = Language.strScreenshots; - } + { + mMenFile.Text = Language.strMenuFile; + mMenFileSaveAll.Text = Language.strSaveAll; + mMenFileRemoveAll.Text = Language.strRemoveAll; + cMenScreenshotCopy.Text = Language.strMenuCopy; + cMenScreenshotSave.Text = Language.strSave; + dlgSaveSingleImage.Filter = Language.strSaveImageFilter; + TabText = Language.strScreenshots; + Text = Language.strScreenshots; + } + #endregion - + #region Public Methods - public ScreenshotManagerWindow() : this(new DockContent()) - { - } + public ScreenshotManagerWindow() : this(new DockContent()) + { + } + + internal ScreenshotManagerWindow(DockContent panel) + { + WindowType = WindowType.ScreenshotManager; + DockPnl = panel; + InitializeComponent(); + } + + public void AddScreenshot(Image Screenshot) + { + try + { + var nPB = new PictureBox(); + nPB.MouseDown += pbScreenshot_MouseDown; + + nPB.Parent = flpScreenshots; + nPB.SizeMode = PictureBoxSizeMode.StretchImage; + nPB.BorderStyle = BorderStyle.FixedSingle; + nPB.ContextMenuStrip = cMenScreenshot; + nPB.Image = Screenshot; + nPB.Size = new Size(100, 100); //New Size((Screenshot.Width / 100) * 20, (Screenshot.Height / 100) * 20) + nPB.Show(); + + var nBtn = new Button(); + nBtn.Click += btnCloseScreenshot_Click; + + nBtn.Parent = nPB; + nBtn.FlatStyle = FlatStyle.Flat; + nBtn.Text = "×"; + nBtn.Size = new Size(22, 22); + nBtn.Location = new Point(nPB.Width - nBtn.Width, -1); + nBtn.Show(); + + Show(FrmMain.Default.pnlDock); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "AddScreenshot (UI.Window.ScreenshotManager) failed" + + Environment.NewLine + ex.Message, true); + } + } - internal ScreenshotManagerWindow(DockContent panel) - { - WindowType = WindowType.ScreenshotManager; - DockPnl = panel; - InitializeComponent(); - } - - public void AddScreenshot(Image Screenshot) - { - try - { - var nPB = new PictureBox(); - nPB.MouseDown += pbScreenshot_MouseDown; - - nPB.Parent = flpScreenshots; - nPB.SizeMode = PictureBoxSizeMode.StretchImage; - nPB.BorderStyle = BorderStyle.FixedSingle; - nPB.ContextMenuStrip = cMenScreenshot; - nPB.Image = Screenshot; - nPB.Size = new Size(100, 100); //New Size((Screenshot.Width / 100) * 20, (Screenshot.Height / 100) * 20) - nPB.Show(); - - var nBtn = new Button(); - nBtn.Click += btnCloseScreenshot_Click; - - nBtn.Parent = nPB; - nBtn.FlatStyle = FlatStyle.Flat; - nBtn.Text = "×"; - nBtn.Size = new Size(22, 22); - nBtn.Location = new Point(nPB.Width - nBtn.Width, -1); - nBtn.Show(); - - Show(FrmMain.Default.pnlDock); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "AddScreenshot (UI.Window.ScreenshotManager) failed" + Environment.NewLine + ex.Message, true); - } - } #endregion - + #region Private Methods - private void pbScreenshot_MouseDown(object sender, MouseEventArgs e) - { - cMenScreenshot.Tag = sender; - - if (e.Button == MouseButtons.Left) - { - OpenScreenshot((PictureBox)sender); - } - } - - private void pbScreenshotOpen_MouseDown(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - CloseOpenedScreenshot((Form)((PictureBox)sender).Parent); - } - } - - private void CloseOpenedScreenshot(Form form) - { - form.Close(); - } - - private void OpenScreenshot(PictureBox sender) - { - try - { - var mImage = sender.Image; - var nForm = new Form - { - StartPosition = FormStartPosition.CenterParent, - ShowInTaskbar = false, - ShowIcon = false, - MaximizeBox = false, - MinimizeBox = false, - Width = mImage.Width + 2, - Height = mImage.Height + 2, - FormBorderStyle = FormBorderStyle.None - }; + private void pbScreenshot_MouseDown(object sender, MouseEventArgs e) + { + cMenScreenshot.Tag = sender; - var nPB = new PictureBox - { - Parent = nForm, - BorderStyle = BorderStyle.FixedSingle, - Location = new Point(0, 0), - SizeMode = PictureBoxSizeMode.AutoSize, - Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top, - Image = mImage, - ContextMenuStrip = cMenScreenshot - }; - nPB.Show(); - - nPB.MouseDown += pbScreenshotOpen_MouseDown; - - nForm.ShowDialog(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "OpenScreenshot (UI.Window.ScreenshotManager) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void btnCloseScreenshot_Click(object sender, EventArgs e) - { - try - { - ((PictureBox)sender).Parent.Dispose(); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "btnCloseScreenshot_Click (UI.Window.ScreenshotManager) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void mMenFileRemoveAll_Click(object sender, EventArgs e) - { - RemoveAllImages(); - } - - private void RemoveAllImages() - { - flpScreenshots.Controls.Clear(); - } - - private void mMenFileSaveAll_Click(object sender, EventArgs e) - { - SaveAllImages(); - } - - private void SaveAllImages() - { - try - { - var pCount = 1; + if (e.Button == MouseButtons.Left) + { + OpenScreenshot((PictureBox)sender); + } + } + + private void pbScreenshotOpen_MouseDown(object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { + CloseOpenedScreenshot((Form)((PictureBox)sender).Parent); + } + } + + private void CloseOpenedScreenshot(Form form) + { + form.Close(); + } + + private void OpenScreenshot(PictureBox sender) + { + try + { + var mImage = sender.Image; + + var nForm = new Form + { + StartPosition = FormStartPosition.CenterParent, + ShowInTaskbar = false, + ShowIcon = false, + MaximizeBox = false, + MinimizeBox = false, + Width = mImage.Width + 2, + Height = mImage.Height + 2, + FormBorderStyle = FormBorderStyle.None + }; + + var nPB = new PictureBox + { + Parent = nForm, + BorderStyle = BorderStyle.FixedSingle, + Location = new Point(0, 0), + SizeMode = PictureBoxSizeMode.AutoSize, + Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top, + Image = mImage, + ContextMenuStrip = cMenScreenshot + }; + nPB.Show(); + + nPB.MouseDown += pbScreenshotOpen_MouseDown; + + nForm.ShowDialog(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "OpenScreenshot (UI.Window.ScreenshotManager) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void btnCloseScreenshot_Click(object sender, EventArgs e) + { + try + { + ((PictureBox)((Button)sender).Parent).Dispose(); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "btnCloseScreenshot_Click (UI.Window.ScreenshotManager) failed" + + Environment.NewLine + ex.Message, + true); + } + } + + private void mMenFileRemoveAll_Click(object sender, EventArgs e) + { + RemoveAllImages(); + } + + private void RemoveAllImages() + { + flpScreenshots.Controls.Clear(); + } + + private void mMenFileSaveAll_Click(object sender, EventArgs e) + { + SaveAllImages(); + } + + private void SaveAllImages() + { + try + { + var pCount = 1; + + if (dlgSaveAllImages.ShowDialog() != DialogResult.OK) return; + foreach (var fPath in Directory.GetFiles(dlgSaveAllImages.SelectedPath, "Screenshot_*", + SearchOption.TopDirectoryOnly)) + { + var f = new FileInfo(fPath); + + var fCount = f.Name; + fCount = fCount.Replace(f.Extension, ""); + fCount = fCount.Replace("Screenshot_", ""); + + pCount = (int)(double.Parse(fCount) + 1); + } + + foreach (Control ctrl in flpScreenshots.Controls) + { + if (!(ctrl is PictureBox)) continue; + (ctrl as PictureBox).Image.Save( + dlgSaveAllImages.SelectedPath + "\\Screenshot_" + + Tools.MiscTools.LeadingZero(Convert.ToString(pCount)) + ".png", + System.Drawing.Imaging.ImageFormat.Png); + pCount++; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "SaveAllImages (UI.Window.ScreenshotManager) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void cMenScreenshotCopy_Click(object sender, EventArgs e) + { + CopyImageToClipboard(); + } + + private void CopyImageToClipboard() + { + try + { + Clipboard.SetImage(((PictureBox)cMenScreenshot.Tag).Image); + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "CopyImageToClipboard (UI.Window.ScreenshotManager) failed" + + Environment.NewLine + ex.Message, + true); + } + } + + private void cMenScreenshotSave_Click(object sender, EventArgs e) + { + SaveSingleImage(); + } + + private void SaveSingleImage() + { + try + { + if (dlgSaveSingleImage.ShowDialog() != DialogResult.OK) return; + // ReSharper disable once SwitchStatementMissingSomeCases + switch (dlgSaveSingleImage.FileName + .Substring(dlgSaveSingleImage + .FileName.LastIndexOf(".", StringComparison.Ordinal) + 1) + .ToLower()) + { + case "gif": + ((PictureBox)cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, + System.Drawing.Imaging.ImageFormat.Gif); + break; + case "jpeg": + ((PictureBox)cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, + System.Drawing.Imaging.ImageFormat.Jpeg); + break; + case "jpg": + ((PictureBox)cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, + System.Drawing.Imaging.ImageFormat.Jpeg); + break; + case "png": + ((PictureBox)cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, + System.Drawing.Imaging.ImageFormat.Png); + break; + } + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "SaveSingleImage (UI.Window.ScreenshotManager) failed" + + Environment.NewLine + ex.Message, true); + } + } + + private void mMenFile_DropDownOpening(object sender, EventArgs e) + { + if (flpScreenshots.Controls.Count < 1) + { + mMenFileSaveAll.Enabled = false; + mMenFileRemoveAll.Enabled = false; + } + else + { + mMenFileSaveAll.Enabled = true; + mMenFileRemoveAll.Enabled = true; + } + } - if (dlgSaveAllImages.ShowDialog() != DialogResult.OK) return; - foreach (var fPath in Directory.GetFiles(dlgSaveAllImages.SelectedPath, "Screenshot_*", SearchOption.TopDirectoryOnly)) - { - var f = new FileInfo(fPath); - - var fCount = f.Name; - fCount = fCount.Replace(f.Extension, ""); - fCount = fCount.Replace("Screenshot_", ""); - - pCount = (int) (double.Parse(fCount) + 1); - } - - foreach (Control ctrl in flpScreenshots.Controls) - { - if (!(ctrl is PictureBox)) continue; - (ctrl as PictureBox).Image.Save(dlgSaveAllImages.SelectedPath + "\\Screenshot_" + Tools.MiscTools.LeadingZero(Convert.ToString(pCount)) +".png", System.Drawing.Imaging.ImageFormat.Png); - pCount++; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "SaveAllImages (UI.Window.ScreenshotManager) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void cMenScreenshotCopy_Click(object sender, EventArgs e) - { - CopyImageToClipboard(); - } - - private void CopyImageToClipboard() - { - try - { - Clipboard.SetImage(((PictureBox) cMenScreenshot.Tag).Image); - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "CopyImageToClipboard (UI.Window.ScreenshotManager) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void cMenScreenshotSave_Click(object sender, EventArgs e) - { - SaveSingleImage(); - } - - private void SaveSingleImage() - { - try - { - if (dlgSaveSingleImage.ShowDialog() != DialogResult.OK) return; - // ReSharper disable once SwitchStatementMissingSomeCases - switch (dlgSaveSingleImage.FileName.Substring(dlgSaveSingleImage.FileName.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower()) - { - case "gif": - ((PictureBox) cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, System.Drawing.Imaging.ImageFormat.Gif); - break; - case "jpeg": - ((PictureBox) cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, System.Drawing.Imaging.ImageFormat.Jpeg); - break; - case "jpg": - ((PictureBox) cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, System.Drawing.Imaging.ImageFormat.Jpeg); - break; - case "png": - ((PictureBox) cMenScreenshot.Tag).Image.Save(dlgSaveSingleImage.FileName, System.Drawing.Imaging.ImageFormat.Png); - break; - } - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "SaveSingleImage (UI.Window.ScreenshotManager) failed" + Environment.NewLine + ex.Message, true); - } - } - - private void mMenFile_DropDownOpening(object sender, EventArgs e) - { - if (flpScreenshots.Controls.Count < 1) - { - mMenFileSaveAll.Enabled = false; - mMenFileRemoveAll.Enabled = false; - } - else - { - mMenFileSaveAll.Enabled = true; - mMenFileRemoveAll.Enabled = true; - } - } #endregion - } -} + } +} \ No newline at end of file diff --git a/mRemoteV1/UI/Window/UltraVNCWindow.cs b/mRemoteV1/UI/Window/UltraVNCWindow.cs index 571cdb8f..0b69042c 100644 --- a/mRemoteV1/UI/Window/UltraVNCWindow.cs +++ b/mRemoteV1/UI/Window/UltraVNCWindow.cs @@ -5,16 +5,18 @@ using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.UI.Window { - public class UltraVNCWindow : BaseWindow - { + public class UltraVNCWindow : BaseWindow + { #region Form Init - internal System.Windows.Forms.ToolStrip tsMain; - internal System.Windows.Forms.Panel pnlContainer; - internal System.Windows.Forms.ToolStripButton btnDisconnect; - - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UltraVNCWindow)); + + internal System.Windows.Forms.ToolStrip tsMain; + internal System.Windows.Forms.Panel pnlContainer; + internal System.Windows.Forms.ToolStripButton btnDisconnect; + + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = + new System.ComponentModel.ComponentResourceManager(typeof(UltraVNCWindow)); this.tsMain = new System.Windows.Forms.ToolStrip(); this.btnDisconnect = new System.Windows.Forms.ToolStripButton(); this.pnlContainer = new System.Windows.Forms.Panel(); @@ -24,8 +26,10 @@ namespace mRemoteNG.UI.Window // tsMain // this.tsMain.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; - this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.btnDisconnect}); + this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] + { + this.btnDisconnect + }); this.tsMain.Location = new System.Drawing.Point(0, 0); this.tsMain.Name = "tsMain"; this.tsMain.Size = new System.Drawing.Size(446, 25); @@ -44,9 +48,11 @@ namespace mRemoteNG.UI.Window // // pnlContainer // - this.pnlContainer.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); + this.pnlContainer.Anchor = + ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | + System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.pnlContainer.Location = new System.Drawing.Point(0, 27); this.pnlContainer.Name = "pnlContainer"; this.pnlContainer.Size = new System.Drawing.Size(446, 335); @@ -59,7 +65,8 @@ namespace mRemoteNG.UI.Window this.ClientSize = new System.Drawing.Size(446, 362); this.Controls.Add(this.pnlContainer); this.Controls.Add(this.tsMain); - this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, + System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = global::mRemoteNG.Resources.UVNC_SC_Icon; this.Name = "UltraVNCWindow"; this.TabText = "UltraVNC SC"; @@ -69,63 +76,70 @@ namespace mRemoteNG.UI.Window this.tsMain.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); + } - } #endregion - + #region Declarations - //Private WithEvents vnc As AxCSC_ViewerXControl + + //Private WithEvents vnc As AxCSC_ViewerXControl + #endregion - + #region Public Methods - public UltraVNCWindow() - { - this.WindowType = WindowType.UltraVNCSC; - this.DockPnl = new DockContent(); - this.InitializeComponent(); - } + + public UltraVNCWindow() + { + this.WindowType = WindowType.UltraVNCSC; + this.DockPnl = new DockContent(); + this.InitializeComponent(); + } + #endregion - + #region Private Methods - private void UltraVNCSC_Load(object sender, System.EventArgs e) - { - ApplyLanguage(); - - StartListening(); - } - - private void ApplyLanguage() - { - btnDisconnect.Text = Language.strButtonDisconnect; - } - - private void StartListening() - { - try - { - //If vnc IsNot Nothing Then - // vnc.Dispose() - // vnc = Nothing - //End If - - //vnc = New AxCSC_ViewerXControl() - //SetupLicense() - - //vnc.Parent = pnlContainer - //vnc.Dock = DockStyle.Fill - //vnc.Show() - - //vnc.StretchMode = ViewerX.ScreenStretchMode.SSM_ASPECT - //vnc.ListeningText = Language.strInheritListeningForIncomingVNCConnections & " " & Settings.UVNCSCPort - - //vnc.ListenEx(Settings.UVNCSCPort) - } - catch (Exception ex) - { - Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, "StartListening (UI.Window.UltraVNCSC) failed" + Environment.NewLine + ex.Message); - Close(); - } - } + + private void UltraVNCSC_Load(object sender, System.EventArgs e) + { + ApplyLanguage(); + + StartListening(); + } + + private void ApplyLanguage() + { + btnDisconnect.Text = Language.strButtonDisconnect; + } + + private void StartListening() + { + try + { + //If vnc IsNot Nothing Then + // vnc.Dispose() + // vnc = Nothing + //End If + + //vnc = New AxCSC_ViewerXControl() + //SetupLicense() + + //vnc.Parent = pnlContainer + //vnc.Dock = DockStyle.Fill + //vnc.Show() + + //vnc.StretchMode = ViewerX.ScreenStretchMode.SSM_ASPECT + //vnc.ListeningText = Language.strInheritListeningForIncomingVNCConnections & " " & Settings.UVNCSCPort + + //vnc.ListenEx(Settings.UVNCSCPort) + } + catch (Exception ex) + { + Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, + "StartListening (UI.Window.UltraVNCSC) failed" + + Environment.NewLine + ex.Message); + Close(); + } + } #if false private void SetupLicense() @@ -142,21 +156,22 @@ namespace mRemoteNG.UI.Window } } #endif - - //Private Sub vnc_ConnectionAccepted(ByVal sender As Object, ByVal e As AxViewerX._ISmartCodeVNCViewerEvents_ConnectionAcceptedEvent) Handles vnc.ConnectionAccepted - // mC.AddMessage(Messages.MessageClass.InformationMsg, e.bstrServerAddress & " is now connected to your UltraVNC SingleClick panel!") - //End Sub - - //Private Sub vnc_Disconnected(ByVal sender As Object, ByVal e As System.EventArgs) Handles vnc.Disconnected - // StartListening() - //End Sub - - private void btnDisconnect_Click(object sender, EventArgs e) - { - //vnc.Dispose() - Dispose(); - Windows.Show(WindowType.UltraVNCSC); - } -#endregion - } + + //Private Sub vnc_ConnectionAccepted(ByVal sender As Object, ByVal e As AxViewerX._ISmartCodeVNCViewerEvents_ConnectionAcceptedEvent) Handles vnc.ConnectionAccepted + // mC.AddMessage(Messages.MessageClass.InformationMsg, e.bstrServerAddress & " is now connected to your UltraVNC SingleClick panel!") + //End Sub + + //Private Sub vnc_Disconnected(ByVal sender As Object, ByVal e As System.EventArgs) Handles vnc.Disconnected + // StartListening() + //End Sub + + private void btnDisconnect_Click(object sender, EventArgs e) + { + //vnc.Dispose() + Dispose(); + Windows.Show(WindowType.UltraVNCSC); + } + + #endregion + } } \ No newline at end of file diff --git a/mRemoteV1/UI/Window/UpdateWindow.cs b/mRemoteV1/UI/Window/UpdateWindow.cs index b0e0a8b8..dc64f826 100644 --- a/mRemoteV1/UI/Window/UpdateWindow.cs +++ b/mRemoteV1/UI/Window/UpdateWindow.cs @@ -8,283 +8,298 @@ using System.Windows.Forms; using mRemoteNG.App; using mRemoteNG.App.Update; using mRemoteNG.Messages; +using mRemoteNG.Themes; using WeifenLuo.WinFormsUI.Docking; namespace mRemoteNG.UI.Window { - public partial class UpdateWindow : BaseWindow - { + public partial class UpdateWindow : BaseWindow + { private AppUpdater _appUpdate; private bool _isUpdateDownloadHandlerDeclared; #region Public Methods - public UpdateWindow() : this(new DockContent()) - { - } - public UpdateWindow(DockContent panel) - { - WindowType = WindowType.Update; - DockPnl = panel; - InitializeComponent(); + public UpdateWindow() : this(new DockContent()) + { + } + + public UpdateWindow(DockContent panel) + { + WindowType = WindowType.Update; + DockPnl = panel; + InitializeComponent(); FontOverrider.FontOverride(this); - } + } + #endregion - + #region Form Stuff - private void Update_Load(object sender, EventArgs e) - { + private void Update_Load(object sender, EventArgs e) + { ApplyTheme(); - Themes.ThemeManager.getInstance().ThemeChanged += ApplyTheme; + ThemeManager.getInstance().ThemeChanged += ApplyTheme; ApplyLanguage(); - CheckForUpdate(); - } + CheckForUpdate(); + } private new void ApplyTheme() { - if (!Themes.ThemeManager.getInstance().ThemingActive) - return; + if (!ThemeManager.getInstance().ActiveAndExtended) return; - base.ApplyTheme(); - txtChangeLog.BackColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); - txtChangeLog.ForeColor = Themes.ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); + base.ApplyTheme(); + txtChangeLog.BackColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Background"); + txtChangeLog.ForeColor = + ThemeManager.getInstance().ActiveTheme.ExtendedPalette.getColor("Dialog_Foreground"); } private void ApplyLanguage() - { - Text = Language.strMenuCheckForUpdates; - TabText = Language.strMenuCheckForUpdates; - btnCheckForUpdate.Text = Language.strCheckForUpdate; - btnDownload.Text = Runtime.IsPortableEdition ? Language.strDownloadPortable : Language.strDownloadAndInstall; + { + Text = Language.strMenuCheckForUpdates; + TabText = Language.strMenuCheckForUpdates; + btnCheckForUpdate.Text = Language.strCheckForUpdate; + btnDownload.Text = Runtime.IsPortableEdition + ? Language.strDownloadPortable + : Language.strDownloadAndInstall; lblChangeLogLabel.Text = Language.strLabelChangeLog; - lblInstalledVersion.Text = Language.strVersion; - lblInstalledVersionLabel.Text = $"{Language.strCurrentVersion}:"; - lblLatestVersion.Text = Language.strVersion; - lblLatestVersionLabel.Text = $"{Language.strAvailableVersion}:"; - } + lblInstalledVersion.Text = Language.strVersion; + lblInstalledVersionLabel.Text = $"{Language.strCurrentVersion}:"; + lblLatestVersion.Text = Language.strVersion; + lblLatestVersionLabel.Text = $"{Language.strAvailableVersion}:"; + } - private void btnCheckForUpdate_Click(object sender, EventArgs e) - { - CheckForUpdate(); - } + private void btnCheckForUpdate_Click(object sender, EventArgs e) + { + CheckForUpdate(); + } private void btnDownload_Click(object sender, EventArgs e) - { - DownloadUpdate(); - } + { + DownloadUpdate(); + } private void pbUpdateImage_Click(object sender, EventArgs e) - { - var linkUri = pbUpdateImage.Tag as Uri; - if (linkUri == null || linkUri.IsFile || linkUri.IsUnc || linkUri.IsLoopback) - { - return; - } - Process.Start(linkUri.ToString()); - } - #endregion - - #region Private Methods - private void CheckForUpdate() - { - if (_appUpdate == null) - { - _appUpdate = new AppUpdater(); - //_appUpdate.Load += _appUpdate.Update_Load; - } - else if (_appUpdate.IsGetUpdateInfoRunning) - { - return; - } - - lblStatus.Text = Language.strUpdateCheckingLabel; - lblStatus.ForeColor = SystemColors.WindowText; - lblLatestVersionLabel.Visible = false; - lblInstalledVersion.Visible = false; - lblInstalledVersionLabel.Visible = false; - lblLatestVersion.Visible = false; - btnCheckForUpdate.Visible = false; - - SetVisibilityOfUpdateControls(false); - - _appUpdate.GetUpdateInfoCompletedEvent += GetUpdateInfoCompleted; - - _appUpdate.GetUpdateInfoAsync(); - } - - private void GetUpdateInfoCompleted(object sender, AsyncCompletedEventArgs e) - { - if (InvokeRequired) - { - var myDelegate = new AsyncCompletedEventHandler(GetUpdateInfoCompleted); - Invoke(myDelegate, sender, e); - return; - } - - try - { - _appUpdate.GetUpdateInfoCompletedEvent -= GetUpdateInfoCompleted; - - lblInstalledVersion.Text = Application.ProductVersion; - lblInstalledVersion.Visible = true; - lblInstalledVersionLabel.Visible = true; - btnCheckForUpdate.Visible = true; - - if (e.Cancelled) - { - return; - } - if (e.Error != null) - { - throw e.Error; - } - - if (_appUpdate.IsUpdateAvailable()) - { - lblStatus.Text = Language.strUpdateAvailable; - lblStatus.ForeColor = Color.OrangeRed; - SetVisibilityOfUpdateControls(true); - - var updateInfo = _appUpdate.CurrentUpdateInfo; - lblLatestVersion.Text = updateInfo.Version.ToString(); - lblLatestVersionLabel.Visible = true; - lblLatestVersion.Visible = true; - - if (updateInfo.ImageAddress == null || string.IsNullOrEmpty(updateInfo.ImageAddress.ToString())) - { - pbUpdateImage.Visible = false; - } - else - { - pbUpdateImage.ImageLocation = updateInfo.ImageAddress.ToString(); - pbUpdateImage.Tag = updateInfo.ImageLinkAddress; - pbUpdateImage.Visible = true; - } - - _appUpdate.GetChangeLogCompletedEvent += GetChangeLogCompleted; - _appUpdate.GetChangeLogAsync(); - - btnDownload.Focus(); - } - else - { - lblStatus.Text = Language.strNoUpdateAvailable; - lblStatus.ForeColor = Color.ForestGreen; - - if (_appUpdate.CurrentUpdateInfo == null) return; - var updateInfo = _appUpdate.CurrentUpdateInfo; - if (!updateInfo.IsValid || updateInfo.Version == null) return; - lblLatestVersion.Text = updateInfo.Version.ToString(); - lblLatestVersionLabel.Visible = true; - lblLatestVersion.Visible = true; - } - } - catch (Exception ex) - { - lblStatus.Text = Language.strUpdateCheckFailedLabel; - lblStatus.ForeColor = Color.OrangeRed; - - Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateCheckCompleteFailed, ex); - } - } - - private void SetVisibilityOfUpdateControls(bool visible) - { - lblChangeLogLabel.Visible = visible; - txtChangeLog.Visible = visible; - btnDownload.Visible = visible; - prgbDownload.Visible = visible; - } - - private void GetChangeLogCompleted(object sender, AsyncCompletedEventArgs e) - { - if (InvokeRequired) - { - var myDelegate = new AsyncCompletedEventHandler(GetChangeLogCompleted); - Invoke(myDelegate, sender, e); - return; - } - - try - { - _appUpdate.GetChangeLogCompletedEvent -= GetChangeLogCompleted; - - if (e.Cancelled) - return; - if (e.Error != null) - throw e.Error; - - txtChangeLog.Text = _appUpdate.ChangeLog.Replace("\n", Environment.NewLine); + { + var linkUri = pbUpdateImage.Tag as Uri; + if (linkUri == null || linkUri.IsFile || linkUri.IsUnc || linkUri.IsLoopback) + { + return; } - catch (Exception ex) - { - Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateGetChangeLogFailed, ex); - } - } - - private void DownloadUpdate() - { - try - { - btnDownload.Enabled = false; - prgbDownload.Visible = true; - prgbDownload.Value = 0; - - if (_isUpdateDownloadHandlerDeclared == false) - { - _appUpdate.DownloadUpdateProgressChangedEvent += DownloadUpdateProgressChanged; - _appUpdate.DownloadUpdateCompletedEvent += DownloadUpdateCompleted; - _isUpdateDownloadHandlerDeclared = true; - } - - _appUpdate.DownloadUpdateAsync(); - } - catch (Exception ex) - { - Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateDownloadFailed, ex); - } - } - #endregion - - #region Events - private void DownloadUpdateProgressChanged(object sender, DownloadProgressChangedEventArgs e) - { - prgbDownload.Value = e.ProgressPercentage; - } - - private void DownloadUpdateCompleted(object sender, AsyncCompletedEventArgs e) - { - try - { - btnDownload.Enabled = true; - prgbDownload.Visible = false; - - if (e.Cancelled) - return; - if (e.Error != null) - throw e.Error; - if (Runtime.IsPortableEdition) - MessageBox.Show(Language.strUpdatePortableDownloadComplete, Language.strMenuCheckForUpdates, MessageBoxButtons.OK, MessageBoxIcon.Information); - else - { - if (MessageBox.Show(Language.strUpdateDownloadComplete, Language.strMenuCheckForUpdates, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) - { - Shutdown.Quit(_appUpdate.CurrentUpdateInfo.UpdateFilePath); - } - else - { - File.Delete(_appUpdate.CurrentUpdateInfo.UpdateFilePath); - } - } - } - catch (Exception ex) - { + Process.Start(linkUri.ToString()); + } + + #endregion + + #region Private Methods + + private void CheckForUpdate() + { + if (_appUpdate == null) + { + _appUpdate = new AppUpdater(); + //_appUpdate.Load += _appUpdate.Update_Load; + } + else if (_appUpdate.IsGetUpdateInfoRunning) + { + return; + } + + lblStatus.Text = Language.strUpdateCheckingLabel; + lblStatus.ForeColor = SystemColors.WindowText; + lblLatestVersionLabel.Visible = false; + lblInstalledVersion.Visible = false; + lblInstalledVersionLabel.Visible = false; + lblLatestVersion.Visible = false; + btnCheckForUpdate.Visible = false; + + SetVisibilityOfUpdateControls(false); + + _appUpdate.GetUpdateInfoCompletedEvent += GetUpdateInfoCompleted; + + _appUpdate.GetUpdateInfoAsync(); + } + + private void GetUpdateInfoCompleted(object sender, AsyncCompletedEventArgs e) + { + if (InvokeRequired) + { + var myDelegate = new AsyncCompletedEventHandler(GetUpdateInfoCompleted); + Invoke(myDelegate, sender, e); + return; + } + + try + { + _appUpdate.GetUpdateInfoCompletedEvent -= GetUpdateInfoCompleted; + + lblInstalledVersion.Text = Application.ProductVersion; + lblInstalledVersion.Visible = true; + lblInstalledVersionLabel.Visible = true; + btnCheckForUpdate.Visible = true; + + if (e.Cancelled) + { + return; + } + + if (e.Error != null) + { + throw e.Error; + } + + if (_appUpdate.IsUpdateAvailable()) + { + lblStatus.Text = Language.strUpdateAvailable; + lblStatus.ForeColor = Color.OrangeRed; + SetVisibilityOfUpdateControls(true); + + var updateInfo = _appUpdate.CurrentUpdateInfo; + lblLatestVersion.Text = updateInfo.Version.ToString(); + lblLatestVersionLabel.Visible = true; + lblLatestVersion.Visible = true; + + if (updateInfo.ImageAddress == null || string.IsNullOrEmpty(updateInfo.ImageAddress.ToString())) + { + pbUpdateImage.Visible = false; + } + else + { + pbUpdateImage.ImageLocation = updateInfo.ImageAddress.ToString(); + pbUpdateImage.Tag = updateInfo.ImageLinkAddress; + pbUpdateImage.Visible = true; + } + + _appUpdate.GetChangeLogCompletedEvent += GetChangeLogCompleted; + _appUpdate.GetChangeLogAsync(); + + btnDownload.Focus(); + } + else + { + lblStatus.Text = Language.strNoUpdateAvailable; + lblStatus.ForeColor = Color.ForestGreen; + + if (_appUpdate.CurrentUpdateInfo == null) return; + var updateInfo = _appUpdate.CurrentUpdateInfo; + if (!updateInfo.IsValid || updateInfo.Version == null) return; + lblLatestVersion.Text = updateInfo.Version.ToString(); + lblLatestVersionLabel.Visible = true; + lblLatestVersion.Visible = true; + } + } + catch (Exception ex) + { + lblStatus.Text = Language.strUpdateCheckFailedLabel; + lblStatus.ForeColor = Color.OrangeRed; + + Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateCheckCompleteFailed, ex); + } + } + + private void SetVisibilityOfUpdateControls(bool visible) + { + lblChangeLogLabel.Visible = visible; + txtChangeLog.Visible = visible; + btnDownload.Visible = visible; + prgbDownload.Visible = visible; + } + + private void GetChangeLogCompleted(object sender, AsyncCompletedEventArgs e) + { + if (InvokeRequired) + { + var myDelegate = new AsyncCompletedEventHandler(GetChangeLogCompleted); + Invoke(myDelegate, sender, e); + return; + } + + try + { + _appUpdate.GetChangeLogCompletedEvent -= GetChangeLogCompleted; + + if (e.Cancelled) + return; + if (e.Error != null) + throw e.Error; + + txtChangeLog.Text = _appUpdate.ChangeLog.Replace("\n", Environment.NewLine); + } + catch (Exception ex) + { + Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateGetChangeLogFailed, ex); + } + } + + private void DownloadUpdate() + { + try + { + btnDownload.Enabled = false; + prgbDownload.Visible = true; + prgbDownload.Value = 0; + + if (_isUpdateDownloadHandlerDeclared == false) + { + _appUpdate.DownloadUpdateProgressChangedEvent += DownloadUpdateProgressChanged; + _appUpdate.DownloadUpdateCompletedEvent += DownloadUpdateCompleted; + _isUpdateDownloadHandlerDeclared = true; + } + + _appUpdate.DownloadUpdateAsync(); + } + catch (Exception ex) + { + Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateDownloadFailed, ex); + } + } + + #endregion + + #region Events + + private void DownloadUpdateProgressChanged(object sender, DownloadProgressChangedEventArgs e) + { + prgbDownload.Value = e.ProgressPercentage; + } + + private void DownloadUpdateCompleted(object sender, AsyncCompletedEventArgs e) + { + try + { + btnDownload.Enabled = true; + prgbDownload.Visible = false; + + if (e.Cancelled) + return; + if (e.Error != null) + throw e.Error; + + if (Runtime.IsPortableEdition) + MessageBox.Show(Language.strUpdatePortableDownloadComplete, Language.strMenuCheckForUpdates, + MessageBoxButtons.OK, MessageBoxIcon.Information); + else + { + if (MessageBox.Show(Language.strUpdateDownloadComplete, Language.strMenuCheckForUpdates, + MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) + { + Shutdown.Quit(_appUpdate.CurrentUpdateInfo.UpdateFilePath); + } + else + { + File.Delete(_appUpdate.CurrentUpdateInfo.UpdateFilePath); + } + } + } + catch (Exception ex) + { Runtime.MessageCollector?.AddExceptionStackTrace(Language.strUpdateDownloadCompleteFailed, ex); Runtime.MessageCollector?.AddMessage(MessageClass.ErrorMsg, ex.Message); } - } + } + #endregion - } + } } \ No newline at end of file diff --git a/mRemoteV1/UI/WindowList.cs b/mRemoteV1/UI/WindowList.cs index 7f36cc1b..bf254c6b 100644 --- a/mRemoteV1/UI/WindowList.cs +++ b/mRemoteV1/UI/WindowList.cs @@ -4,85 +4,90 @@ using mRemoteNG.UI.Window; namespace mRemoteNG.UI { - public class WindowList : CollectionBase - { + public class WindowList : CollectionBase + { #region Public Properties + public BaseWindow this[object Index] - { - get - { - CleanUp(); - if (Index is BaseWindow) + { + get + { + CleanUp(); + if (Index is BaseWindow) return IndexByObject(Index); - if (Index is int) - return IndexByNumber(Convert.ToInt32(Index)); + if (Index is int) + return IndexByNumber(Convert.ToInt32(Index)); return null; - } - } - - public new int Count - { - get - { - CleanUp(); - return List.Count; - } - } - #endregion - - #region Public Methods - public void Add(BaseWindow uiWindow) - { - List.Add(uiWindow); - //AddHandler uiWindow.FormClosing, AddressOf uiFormClosing - } - - public void AddRange(BaseWindow[] uiWindow) - { - foreach (var uW in uiWindow) - { - List.Add(uW); - } - } - - public void Remove(BaseWindow uiWindow) - { - List.Remove(uiWindow); - } - - public BaseWindow FromString(string uiWindow) - { - CleanUp(); - for (var i = 0; i < List.Count; i++) - { - if (this[i].Text == uiWindow.Replace("&", "&&")) - { - return this[i]; - } - } - - return null; - } - #endregion - + } + } - private void CleanUp() - { - for (var i = 0; i <= List.Count - 1; i++) - { - if (i > List.Count - 1) - { - CleanUp(); - return; - } - var baseWindow = List[i] as BaseWindow; - if (baseWindow != null && !baseWindow.IsDisposed) continue; - List.RemoveAt(i); - CleanUp(); - return; - } - } + public new int Count + { + get + { + CleanUp(); + return List.Count; + } + } + + #endregion + + #region Public Methods + + public void Add(BaseWindow uiWindow) + { + List.Add(uiWindow); + //AddHandler uiWindow.FormClosing, AddressOf uiFormClosing + } + + public void AddRange(BaseWindow[] uiWindow) + { + foreach (var uW in uiWindow) + { + List.Add(uW); + } + } + + public void Remove(BaseWindow uiWindow) + { + List.Remove(uiWindow); + } + + public BaseWindow FromString(string uiWindow) + { + CleanUp(); + for (var i = 0; i < List.Count; i++) + { + if (this[i].Text == uiWindow.Replace("&", "&&")) + { + return this[i]; + } + } + + return null; + } + + #endregion + + + private void CleanUp() + { + for (var i = 0; i <= List.Count - 1; i++) + { + if (i > List.Count - 1) + { + CleanUp(); + return; + } + + var baseWindow = List[i] as BaseWindow; + if (baseWindow != null && !baseWindow.IsDisposed) continue; + List.RemoveAt(i); + CleanUp(); + return; + } + } private BaseWindow IndexByObject(object Index) { @@ -108,12 +113,12 @@ namespace mRemoteNG.UI throw new ArgumentOutOfRangeException(e.ParamName, e.ActualValue, "Index was out of bounds"); } } - + /* private void uiFormClosing(object sender, FormClosingEventArgs e) { List.Remove(sender); } */ - } + } } \ No newline at end of file diff --git a/mRemoteV1/UI/WindowType.cs b/mRemoteV1/UI/WindowType.cs index 3b320aaa..4921365d 100644 --- a/mRemoteV1/UI/WindowType.cs +++ b/mRemoteV1/UI/WindowType.cs @@ -1,21 +1,21 @@ namespace mRemoteNG.UI { - public enum WindowType - { - Tree = 0, - Connection = 1, - Config = 2, - ErrorsAndInfos = 4, - ScreenshotManager = 5, - Options = 6, - About = 8, - Update = 9, - SSHTransfer = 10, - ActiveDirectoryImport = 11, - Help = 12, - ExternalApps = 13, - PortScan = 14, - UltraVNCSC = 16, - ComponentsCheck = 17, - } + public enum WindowType + { + Tree = 0, + Connection = 1, + Config = 2, + ErrorsAndInfos = 4, + ScreenshotManager = 5, + Options = 6, + About = 8, + Update = 9, + SSHTransfer = 10, + ActiveDirectoryImport = 11, + Help = 12, + ExternalApps = 13, + PortScan = 14, + UltraVNCSC = 16, + ComponentsCheck = 17, + } } \ No newline at end of file diff --git a/mRemoteV1/app.config b/mRemoteV1/app.config index 4c635915..34002156 100644 --- a/mRemoteV1/app.config +++ b/mRemoteV1/app.config @@ -1,741 +1,757 @@ - + + - -
- -
- - -
-
- - - - - - - - - - + +
+ +
+ + +
+
+ + - - - - + + + + + + + - - - - - - - - - - - - + + + + - - - - 0, 0 - - - 0, 0 - - - Normal - - - False - - - True - - - - - - True - - - True - - - True - - - False - - - False - - - - - - True - - - True - - - False - - - False - - - True - - - False - - - False - - - noinfo - - - False - - - True - - - False - - - False - - - False - - - - - - 80 - - - False - - - - - - - - - - - - RDP - - - Default Settings - - - False - - - FitToWindow - - - Colors16Bit - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - DoNotPlay - - - 2 - - - False - - - False - - - False - - - 0 - - - False - - - True - - - 0, 0 - - - Bottom - - - True - - - 3, 24 - - - Top - - - False - - - False - - - - - - - - - - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - EncrBasic - - - False - - - - - - - - - False - - - False - - - False - - - True - - - False - - - False - - - AuthVNC - - - ColNormal - - - SmartSAspect - - - False - - - CompNone - - - EncHextile - - - - - - - - - 0 - - - ProxyNone - - - - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - False - - - NoAuth - - - False - - - 5500 - - - False - - - - - - IE - - - False - - - - - - False - - - False - - - - - - False - - - - - - False - - - False - - - 14 - - - 1980-01-01 - - - False - - - Never - - - Yes - - - mRemoteNG - - - False - - - False - - - False - - - False - - - False - - - False - - - 5 - - - - - - - - - - - - - - - - - - False - - - False - - - False - - - False - - - 4 - - - mRemoteNG - - - 10 - - - {0}.{1:yyyyMMdd-HHmmssffff}.backup - - - False - - - True - - - False - - - False - - - release - - - - - - True - - - - - - - - - True - - - - - - True - - - False - - - False - - - RDP - - - 9/9, 33/8 - - - 9/8, 34/8 - - - False - - - 20 - - - AES - - - GCM - - - 1000 - - - Dynamic - - - False - - - 0 - - - False - - - False - - - False - - - False - - - 00000000-0000-0000-0000-000000000000 - - - - - - False - - - True - - - True - - - True - - - False - - - False - - - True - - - True - - - False - - - False - - - False - - - False - - - True - - - True - - - False - - - - - - - - - - - - General - - - True - - - False - - - False - - - False - - - False - - - 0, 0 - - - - - - False - - - False - - - General - + + + + + + + + + + + + + + + + + 0, 0 + + + 0, 0 + + + Normal + + + False + + + True + + + + + + True + + + True + + + True + + + False + + + False + + + + + + True + + + True + + + False + + + False + + + True + + + False + + + False + + + noinfo + + + False + + + True + + + False + + + False + + + False + + + + + + 80 + + + False + + + + + + + + + + + + RDP + + + Default Settings + + + False + + + FitToWindow + + + Colors16Bit + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + DoNotPlay + + + 2 + + + False + + + False + + + False + + + 0 + + + False + + + True + + + 0, 0 + + + Bottom + + + True + + + 3, 24 + + + Top + + + False + + + False + + + + + + + + + + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + EncrBasic + + + False + + + + + + + + + False + + + False + + + False + + + True + + + False + + + False + + + AuthVNC + + + ColNormal + + + SmartSAspect + + + False + + + CompNone + + + EncHextile + + + + + + + + + 0 + + + ProxyNone + + + + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + False + + + NoAuth + + + False + + + 5500 + + + False + + + + + + IE + + + False + + + + + + False + + + False + + + + + + False + + + + + + False + + + False + + + 14 + + + 1980-01-01 + + + False + + + Never + + + Yes + + + mRemoteNG + + + False + + + False + + + False + + + False + + + False + + + False + + + 5 + + + + + + + + + + + + + + + + + + False + + + False + + + False + + + False + + + 4 + + + mRemoteNG + + + 10 + + + {0}.{1:yyyyMMdd-HHmmssffff}.backup + + + False + + + True + + + False + + + False + + + release + + + + + + True + + + + + + + + + True + + + + + + True + + + False + + + False + + + RDP + + + 9/9, 33/8 + + + 9/8, 34/8 + + + False + + + 20 + + + AES + + + GCM + + + 1000 + + + Dynamic + + + False + + + 0 + + + False + + + False + + + False + + + False + + + 00000000-0000-0000-0000-000000000000 + + + + + + False + + + True + + + True + + + True + + + False + + + False + + + True + + + True + + + False + + + False + + + False + + + False + + + True + + + True + + + True + + + + + + + + + + + + General + + + True + + + False + + + False + + + False + + + False + + + 0, 0 + + + + + + False + + + False + + + General + True - - False - - - False + + False + + + False 00000000-0000-0000-0000-000000000000 - - - True - - - - - - - https://mremoteng.org/ - - - cs-CZ,de,el,en,en-US,es-AR,es,fr,hu,it,ja-JP,ko-KR,nb-NO,nl,pt,pt-BR,pl,ru,uk,tr-TR,zh-CN,zh-TW - - - - - - - - - - - - - - - \ No newline at end of file + + + True + + + False + + + + + + + https://mremoteng.org/ + + + cs-CZ,de,el,en,en-US,es-AR,es,fr,hu,it,ja-JP,ko-KR,nb-NO,nl,pt,pt-BR,pl,ru,uk,tr-TR,zh-CN,zh-TW + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mRemoteV1/mRemoteV1.csproj b/mRemoteV1/mRemoteV1.csproj index dedfb180..00020583 100644 --- a/mRemoteV1/mRemoteV1.csproj +++ b/mRemoteV1/mRemoteV1.csproj @@ -63,11 +63,6 @@ ..\packages\log4net.2.0.8\lib\net45-full\log4net.dll - - False - References\MagicLibrary.dll - True - ..\packages\ObjectListView.Official.2.9.1\lib\net20\ObjectListView.dll @@ -246,6 +241,9 @@ + + Component + @@ -756,6 +754,23 @@ Component + + + Form + + + ConnectionTab.cs + + + Component + + + Form + + + Component + + Component @@ -1069,6 +1084,9 @@ UnhandledExceptionWindow.cs + + ConnectionTab.cs + CommandButton.cs @@ -1140,6 +1158,7 @@ + @@ -1320,6 +1339,9 @@ + + + Designer PreserveNewest diff --git a/mRemoteV1/packages.config b/mRemoteV1/packages.config index f64e2f54..0ad6b1a6 100644 --- a/mRemoteV1/packages.config +++ b/mRemoteV1/packages.config @@ -1,13 +1,14 @@  + - - - - - - - - - - + + + + + + + + + + \ No newline at end of file