lib updates

correct build number calculations - now its days from last release + hour + minute of build
some changes to migrate to json schema + preparation of using db to save settings
This commit is contained in:
Dimitrij
2024-05-03 14:40:52 +01:00
parent 711a751117
commit 83f3846ce6
294 changed files with 2216 additions and 2174 deletions

View File

@@ -34,7 +34,7 @@ namespace ExternalConnectors.DSS
try
{
// display gui and ask for data
SSConnectionForm f = new SSConnectionForm();
SSConnectionForm f = new();
string? un = key.GetValue("Username") as string;
f.tbUsername.Text = un ?? "";
f.tbPassword.Text = SSConnectionData.ssPassword; // in OTP refresh cases, this value might already be filled
@@ -212,7 +212,7 @@ namespace ExternalConnectors.DSS
private static string DecodePrivateKey(string encryptedPrivateKey, string password)
{
TextReader textReader = new StringReader(encryptedPrivateKey);
PemReader pemReader = new PemReader(textReader, new PasswordFinder(password));
PemReader pemReader = new(textReader, new PasswordFinder(password));
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
@@ -242,10 +242,10 @@ namespace ExternalConnectors.DSS
// read private key pem string to rsacryptoserviceprovider
public static RSACryptoServiceProvider ImportPrivateKey(string pem)
{
PemReader pr = new PemReader(new StringReader(pem));
PemReader pr = new(new StringReader(pem));
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSACryptoServiceProvider rsa = new();
rsa.ImportParameters(rsaParams);
return rsa;
}

View File

@@ -15,9 +15,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.Core" Version="3.7.300.17" />
<PackageReference Include="AWSSDK.EC2" Version="3.7.309.1" />
<PackageReference Include="BouncyCastle.Cryptography" Version="2.2.1" />
<PackageReference Include="AWSSDK.Core" Version="3.7.303.25" />
<PackageReference Include="AWSSDK.EC2" Version="3.7.326" />
<PackageReference Include="BouncyCastle.Cryptography" Version="2.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

View File

@@ -35,13 +35,13 @@ namespace mRemoteNG.App
if (!FipsPolicyEnabledForServer2003() && !FipsPolicyEnabledForServer2008AndNewer()) return;
var errorText = string.Format(Language.ErrorFipsPolicyIncompatible, GeneralAppInfo.ProductName);
string errorText = string.Format(Language.ErrorFipsPolicyIncompatible, GeneralAppInfo.ProductName);
messageCollector.AddMessage(MessageClass.ErrorMsg, errorText, true);
//About to pop up a message, let's not block it...
FrmSplashScreenNew.GetInstance().Close();
var ShouldIStayOrShouldIGo = CTaskDialog.MessageBox(Application.ProductName, Language.CompatibilityProblemDetected, errorText, "", "", Language.CheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.OkCancel, ESysIcons.Warning, ESysIcons.Warning);
DialogResult ShouldIStayOrShouldIGo = CTaskDialog.MessageBox(Application.ProductName, Language.CompatibilityProblemDetected, errorText, "", "", Language.CheckboxDoNotShowThisMessageAgain, ETaskDialogButtons.OkCancel, ESysIcons.Warning, ESysIcons.Warning);
if (CTaskDialog.VerificationChecked && ShouldIStayOrShouldIGo == DialogResult.OK)
{
messageCollector.AddMessage(MessageClass.ErrorMsg, "User requests that FIPS check be overridden", true);
@@ -56,7 +56,7 @@ namespace mRemoteNG.App
private static bool FipsPolicyEnabledForServer2003()
{
var regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa");
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa");
if (!(regKey?.GetValue("FIPSAlgorithmPolicy") is int fipsPolicy))
return false;
return fipsPolicy != 0;
@@ -64,7 +64,7 @@ namespace mRemoteNG.App
private static bool FipsPolicyEnabledForServer2008AndNewer()
{
var regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy");
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy");
if (!(regKey?.GetValue("Enabled") is int fipsPolicy))
return false;
return fipsPolicy != 0;
@@ -77,7 +77,7 @@ namespace mRemoteNG.App
if (!Settings.Default.CompatibilityWarnLenovoAutoScrollUtility)
return;
var proccesses = new Process[] { };
Process[] proccesses = new Process[] { };
try
{
proccesses = Process.GetProcessesByName("virtscrl");

View File

@@ -25,9 +25,9 @@ namespace mRemoteNG.App
{
try
{
var saveFilter = new SaveFilter();
SaveFilter saveFilter = new();
using (var exportForm = new FrmExport())
using (FrmExport exportForm = new())
{
if (selectedNode?.GetTreeNodeType() == TreeNodeType.Container)
exportForm.SelectedFolder = selectedNode as ContainerInfo;
@@ -81,9 +81,9 @@ namespace mRemoteNG.App
switch (saveFormat)
{
case SaveFormat.mRXML:
var cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
var rootNode = exportTarget.GetRootParent() as RootNodeInfo;
var connectionNodeSerializer = new XmlConnectionNodeSerializer28(
ICryptographyProvider cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
RootNodeInfo rootNode = exportTarget.GetRootParent() as RootNodeInfo;
XmlConnectionNodeSerializer28 connectionNodeSerializer = new(
cryptographyProvider,
rootNode?.PasswordString
.ConvertToSecureString() ??
@@ -102,8 +102,8 @@ namespace mRemoteNG.App
throw new ArgumentOutOfRangeException(nameof(saveFormat), saveFormat, null);
}
var serializedData = serializer.Serialize(exportTarget);
var fileDataProvider = new FileDataProvider(fileName);
string serializedData = serializer.Serialize(exportTarget);
FileDataProvider fileDataProvider = new(fileName);
fileDataProvider.Save(serializedData);
}
catch (Exception ex)

View File

@@ -19,13 +19,13 @@ namespace mRemoteNG.App
{
try
{
using (var openFileDialog = new OpenFileDialog())
using (OpenFileDialog openFileDialog = new())
{
openFileDialog.CheckFileExists = true;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Multiselect = true;
var fileTypes = new List<string>();
List<string> fileTypes = new();
fileTypes.AddRange(new[] {Language.FilterAllImportable, "*.xml;*.rdp;*.rdg;*.dat;*.csv"});
fileTypes.AddRange(new[] {Language.FiltermRemoteXML, "*.xml"});
fileTypes.AddRange(new[] {Language.FiltermRemoteCSV, "*.csv"});
@@ -60,13 +60,13 @@ namespace mRemoteNG.App
{
using (Runtime.ConnectionsService.BatchedSavingContext())
{
using (var openFileDialog = new OpenFileDialog())
using (OpenFileDialog openFileDialog = new())
{
openFileDialog.CheckFileExists = true;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Multiselect = false;
var fileTypes = new List<string>();
List<string> fileTypes = new();
fileTypes.AddRange(new[] {Language.FiltermRemoteRemoteDesktopManagerCSV, "*.csv"});
openFileDialog.Filter = string.Join("|", fileTypes.ToArray());
@@ -74,7 +74,7 @@ namespace mRemoteNG.App
if (openFileDialog.ShowDialog() != DialogResult.OK)
return;
var importer = new RemoteDesktopManagerImporter();
RemoteDesktopManagerImporter importer = new();
importer.Import(openFileDialog.FileName, importDestinationContainer);
}
}
@@ -93,11 +93,11 @@ namespace mRemoteNG.App
{
using (connectionsService.BatchedSavingContext())
{
foreach (var fileName in filePaths)
foreach (string fileName in filePaths)
{
try
{
var importer = BuildConnectionImporterFromFileExtension(fileName);
IConnectionImporter<string> importer = BuildConnectionImporterFromFileExtension(fileName);
importer.Import(fileName, importDestinationContainer);
}
catch (Exception ex)
@@ -134,7 +134,7 @@ namespace mRemoteNG.App
{
using (Runtime.ConnectionsService.BatchedSavingContext())
{
var importer = new PortScanImporter(protocol);
PortScanImporter importer = new(protocol);
importer.Import(hosts, importDestinationContainer);
}
}
@@ -162,7 +162,7 @@ namespace mRemoteNG.App
private static IConnectionImporter<string> BuildConnectionImporterFromFileExtension(string fileName)
{
// TODO: Use the file contents to determine the file type instead of trusting the extension
var extension = Path.GetExtension(fileName) ?? "";
string extension = Path.GetExtension(fileName) ?? "";
switch (extension.ToLowerInvariant())
{
case ".xml":

View File

@@ -9,6 +9,6 @@ namespace mRemoteNG.App.Info
public static readonly string DefaultConnectionsPath = SettingsFileInfo.SettingsPath;
public static readonly string DefaultConnectionsFile = "confCons.xml";
public static readonly string DefaultConnectionsFileNew = "confConsNew.xml";
public static readonly Version ConnectionFileVersion = new Version(3, 0);
public static readonly Version ConnectionFileVersion = new(3, 0);
}
}

View File

@@ -18,25 +18,25 @@ namespace mRemoteNG.App.Info
public const string UrlForum = "https://www.reddit.com/r/mRemoteNG";
public const string UrlBugs = "https://bugs.mremoteng.org";
public const string UrlDocumentation = "https://mremoteng.readthedocs.io/en/latest/";
public static string ApplicationVersion = Application.ProductVersion;
public static readonly string ApplicationVersion = Application.ProductVersion;
public static readonly string ProductName = Application.ProductName;
public static readonly string Copyright = ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCopyrightAttribute), false))?.Copyright;
public static readonly string HomePath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
//public static string ReportingFilePath = "";
public static readonly string PuttyPath = HomePath + "\\PuTTYNG.exe";
private static readonly string puttyPath = HomePath + "\\PuTTYNG.exe";
public static string UserAgent
{
get
{
var details = new List<string>
{
List<string> details =
[
"compatible",
OSVersion.Platform == PlatformID.Win32NT
? $"Windows NT {OSVersion.Version.Major}.{OSVersion.Version.Minor}"
: OSVersion.VersionString
};
];
if (Is64BitProcess)
{
details.Add("WOW64");
@@ -44,15 +44,17 @@ namespace mRemoteNG.App.Info
details.Add(Thread.CurrentThread.CurrentUICulture.Name);
details.Add($".NET CLR {Environment.Version}");
var detailsString = string.Join("; ", details.ToArray());
string detailsString = string.Join("; ", [.. details]);
return $"Mozilla/5.0 ({detailsString}) {ProductName}/{ApplicationVersion}";
}
}
public static string PuttyPath => puttyPath;
public static Version GetApplicationVersion()
{
System.Version.TryParse(ApplicationVersion, out var v);
_ = System.Version.TryParse(ApplicationVersion, out Version v);
return v;
}
}

View File

@@ -24,7 +24,7 @@ namespace mRemoteNG.App.Info
public static Uri GetUpdateChannelInfo()
{
var channel = IsValidChannel(Properties.OptionsUpdatesPage.Default.UpdateChannel) ? Properties.OptionsUpdatesPage.Default.UpdateChannel : STABLE;
string channel = IsValidChannel(Properties.OptionsUpdatesPage.Default.UpdateChannel) ? Properties.OptionsUpdatesPage.Default.UpdateChannel : STABLE;
return GetUpdateTxtUri(channel);
}

View File

@@ -24,9 +24,9 @@ namespace mRemoteNG.App.Initialization
if (Directory.Exists(_path) == false)
return;
foreach (var f in Directory.GetFiles(_path, "*.ico", SearchOption.AllDirectories))
foreach (string f in Directory.GetFiles(_path, "*.ico", SearchOption.AllDirectories))
{
var fInfo = new FileInfo(f);
FileInfo fInfo = new(f);
Array.Resize(ref ConnectionIcon.Icons, ConnectionIcon.Icons.Length + 1);
ConnectionIcon.Icons.SetValue(fInfo.Name.Replace(".ico", ""), ConnectionIcon.Icons.Length - 1);
}

View File

@@ -19,9 +19,9 @@ namespace mRemoteNG.App.Initialization
IMessage[] messages = args.NewItems.Cast<IMessage>().ToArray();
foreach (var printer in messageWriterList)
foreach (IMessageWriter printer in messageWriterList)
{
foreach (var message in messages)
foreach (IMessage message in messages)
{
printer.Write(message);
}

View File

@@ -29,24 +29,24 @@ namespace mRemoteNG.App.Initialization
private void LogSystemData()
{
var osData = GetOperatingSystemData();
var architecture = GetArchitectureData();
var nonEmptyData = Array.FindAll(new[] {osData, architecture}, s => !string.IsNullOrEmpty(s));
var data = string.Join(" ", nonEmptyData);
string osData = GetOperatingSystemData();
string architecture = GetArchitectureData();
string[] nonEmptyData = Array.FindAll(new[] {osData, architecture}, s => !string.IsNullOrEmpty(s));
string data = string.Join(" ", nonEmptyData);
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
private string GetOperatingSystemData()
{
var osVersion = string.Empty;
var servicePack = string.Empty;
string osVersion = string.Empty;
string servicePack = string.Empty;
try
{
foreach (var o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary=True")
foreach (ManagementBaseObject o in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem WHERE Primary=True")
.Get())
{
var managementObject = (ManagementObject)o;
ManagementObject managementObject = (ManagementObject)o;
osVersion = Convert.ToString(managementObject.GetPropertyValue("Caption"))?.Trim();
servicePack = GetOSServicePack(servicePack, managementObject);
}
@@ -56,13 +56,13 @@ namespace mRemoteNG.App.Initialization
_messageCollector.AddExceptionMessage("Error retrieving operating system information from WMI.", ex);
}
var osData = string.Join(" ", osVersion, servicePack);
string osData = string.Join(" ", osVersion, servicePack);
return osData;
}
private string GetOSServicePack(string servicePack, ManagementObject managementObject)
{
var servicePackNumber = Convert.ToInt32(managementObject.GetPropertyValue("ServicePackMajorVersion"));
int servicePackNumber = Convert.ToInt32(managementObject.GetPropertyValue("ServicePackMajorVersion"));
if (servicePackNumber != 0)
{
servicePack = $"Service Pack {servicePackNumber}";
@@ -73,13 +73,13 @@ namespace mRemoteNG.App.Initialization
private string GetArchitectureData()
{
var architecture = string.Empty;
string architecture = string.Empty;
try
{
foreach (var o in new ManagementObjectSearcher("SELECT AddressWidth FROM Win32_Processor WHERE DeviceID=\'CPU0\'").Get())
foreach (ManagementBaseObject o in new ManagementObjectSearcher("SELECT AddressWidth FROM Win32_Processor WHERE DeviceID=\'CPU0\'").Get())
{
var managementObject = (ManagementObject)o;
var addressWidth = Convert.ToInt32(managementObject.GetPropertyValue("AddressWidth"));
ManagementObject managementObject = (ManagementObject)o;
int addressWidth = Convert.ToInt32(managementObject.GetPropertyValue("AddressWidth"));
architecture = $"{addressWidth}-bit";
}
}
@@ -93,7 +93,7 @@ namespace mRemoteNG.App.Initialization
private void LogApplicationData()
{
var data = $"{Application.ProductName} {Application.ProductVersion}";
string data = $"{Application.ProductName} {Application.ProductVersion}";
if (Runtime.IsPortableEdition)
data += $" {Language.PortableEdition}";
data += " starting.";
@@ -102,19 +102,19 @@ namespace mRemoteNG.App.Initialization
private void LogCmdLineArgs()
{
var data = $"Command Line: {string.Join(" ", Environment.GetCommandLineArgs())}";
string data = $"Command Line: {string.Join(" ", Environment.GetCommandLineArgs())}";
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
private void LogClrData()
{
var data = $"Microsoft .NET CLR {Environment.Version}";
string data = $"Microsoft .NET CLR {Environment.Version}";
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
private void LogCultureData()
{
var data = $"System Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}";
string data = $"System Culture: {Thread.CurrentThread.CurrentUICulture.Name}/{Thread.CurrentThread.CurrentUICulture.NativeName}";
_messageCollector.AddMessage(MessageClass.InformationMsg, data, true);
}
}

View File

@@ -12,7 +12,7 @@ namespace mRemoteNG.App
[SupportedOSPlatform("windows")]
public class Logger
{
public static readonly Logger Instance = new Logger();
public static readonly Logger Instance = new();
public ILog Log { get; private set; }
@@ -43,7 +43,7 @@ namespace mRemoteNG.App
IAppender[] appenders = repository.GetAppenders();
foreach (var appender in appenders)
foreach (IAppender appender in appenders)
{
RollingFileAppender fileAppender = (RollingFileAppender)appender;
if (fileAppender is not { Name: "LogFileAppender" }) continue;

View File

@@ -48,7 +48,7 @@ namespace mRemoteNG.App
_frmSplashScreen = FrmSplashScreenNew.GetInstance();
var targetScreen = Screen.PrimaryScreen;
Screen targetScreen = Screen.PrimaryScreen;
Rectangle viewport = targetScreen.WorkingArea;
_frmSplashScreen.Top = viewport.Top;
@@ -70,7 +70,7 @@ namespace mRemoteNG.App
private static void StartApplicationAsSingleInstance()
{
const string mutexID = "mRemoteNG_SingleInstanceMutex";
_mutex = new Mutex(false, mutexID, out var newInstanceCreated);
_mutex = new Mutex(false, mutexID, out bool newInstanceCreated);
if (!newInstanceCreated)
{
SwitchToCurrentInstance();
@@ -83,7 +83,7 @@ namespace mRemoteNG.App
private static void SwitchToCurrentInstance()
{
var singletonInstanceWindowHandle = GetRunningSingletonInstanceWindowHandle();
IntPtr singletonInstanceWindowHandle = GetRunningSingletonInstanceWindowHandle();
if (singletonInstanceWindowHandle == IntPtr.Zero) return;
if (NativeMethods.IsIconic(singletonInstanceWindowHandle) != 0)
_ = NativeMethods.ShowWindow(singletonInstanceWindowHandle, (int)NativeMethods.SW_RESTORE);
@@ -92,9 +92,9 @@ namespace mRemoteNG.App
private static IntPtr GetRunningSingletonInstanceWindowHandle()
{
var windowHandle = IntPtr.Zero;
var currentProcess = Process.GetCurrentProcess();
foreach (var enumeratedProcess in Process.GetProcessesByName(currentProcess.ProcessName))
IntPtr windowHandle = IntPtr.Zero;
Process currentProcess = Process.GetCurrentProcess();
foreach (Process enumeratedProcess in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (enumeratedProcess.Id != currentProcess.Id &&
enumeratedProcess.MainModule.FileName == currentProcess.MainModule.FileName &&
@@ -119,7 +119,7 @@ namespace mRemoteNG.App
if (FrmMain.Default.IsDisposed) return;
var window = new FrmUnhandledException(e.Exception, false);
FrmUnhandledException window = new(e.Exception, false);
window.ShowDialog(FrmMain.Default);
}
@@ -129,7 +129,7 @@ namespace mRemoteNG.App
//if (!FrmSplashScreenNew.GetInstance().IsDisposed)
// FrmSplashScreenNew.GetInstance().Close();
var window = new FrmUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
FrmUnhandledException window = new(e.ExceptionObject as Exception, e.IsTerminating);
window.ShowDialog(FrmMain.Default);
}
}

View File

@@ -58,7 +58,7 @@ namespace mRemoteNG.App
public static void LoadConnectionsAsync()
{
var t = new Thread(LoadConnectionsBGd);
Thread t = new(LoadConnectionsBGd);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
@@ -77,7 +77,7 @@ namespace mRemoteNG.App
/// </param>
public static void LoadConnections(bool withDialog = false)
{
var connectionFileName = "";
string connectionFileName = "";
try
{
@@ -86,7 +86,7 @@ namespace mRemoteNG.App
if (withDialog)
{
var loadDialog = DialogFactory.BuildLoadConnectionsDialog();
OpenFileDialog loadDialog = DialogFactory.BuildLoadConnectionsDialog();
if (loadDialog.ShowDialog() != DialogResult.OK)
return;
@@ -120,7 +120,7 @@ namespace mRemoteNG.App
if (Properties.OptionsDBsPage.Default.UseSQLServer)
{
MessageCollector.AddExceptionMessage(Language.LoadFromSqlFailed, ex);
var commandButtons = string.Join("|", Language._TryAgain, Language.CommandOpenConnectionFile, string.Format(Language.CommandExitProgram, Application.ProductName));
string commandButtons = string.Join("|", Language._TryAgain, Language.CommandOpenConnectionFile, string.Format(Language.CommandExitProgram, Application.ProductName));
CTaskDialog.ShowCommandBox(Application.ProductName, Language.LoadFromSqlFailed, Language.LoadFromSqlFailedContent, MiscTools.GetExceptionMessageRecursive(ex), "", "", commandButtons, false, ESysIcons.Error, ESysIcons.Error);
switch (CTaskDialog.CommandButtonResult)
{
@@ -152,7 +152,7 @@ namespace mRemoteNG.App
Language.Exit
};
var answered = false;
bool answered = false;
while (!answered)
{
try

View File

@@ -10,8 +10,8 @@ namespace mRemoteNG.App
[SupportedOSPlatform("windows")]
public static void SendFormToScreen(Screen screen)
{
var frmMain = FrmMain.Default;
var wasMax = false;
FrmMain frmMain = FrmMain.Default;
bool wasMax = false;
if (frmMain.WindowState == FormWindowState.Maximized)
{

View File

@@ -34,14 +34,10 @@ namespace mRemoteNG.App
_connectionIconLoader = new ConnectionIconLoader(GeneralAppInfo.HomePath + "\\Icons\\");
}
static Startup()
{
}
public void InitializeProgram(MessageCollector messageCollector)
{
Debug.Print("---------------------------" + Environment.NewLine + "[START] - " + Convert.ToString(DateTime.Now, CultureInfo.InvariantCulture));
var startupLogger = new StartupDataLogger(messageCollector);
StartupDataLogger startupLogger = new(messageCollector);
startupLogger.LogStartupData();
CompatibilityChecker.CheckCompatibility(messageCollector);
ParseCommandLineArgs(messageCollector);
@@ -53,7 +49,7 @@ namespace mRemoteNG.App
private static void ParseCommandLineArgs(MessageCollector messageCollector)
{
var interpreter = new StartupArgumentsInterpreter(messageCollector);
StartupArgumentsInterpreter interpreter = new(messageCollector);
interpreter.ParseArguments(Environment.GetCommandLineArgs());
}
@@ -77,8 +73,7 @@ namespace mRemoteNG.App
return;
}
var nextUpdateCheck =
Convert.ToDateTime(Properties.OptionsUpdatesPage.Default.CheckForUpdatesLastCheck.Add(TimeSpan.FromDays(Convert.ToDouble(Properties.OptionsUpdatesPage.Default.CheckForUpdatesFrequencyDays))));
DateTime nextUpdateCheck = Convert.ToDateTime(Properties.OptionsUpdatesPage.Default.CheckForUpdatesLastCheck.Add(TimeSpan.FromDays(Convert.ToDouble(Properties.OptionsUpdatesPage.Default.CheckForUpdatesFrequencyDays))));
if (!Properties.OptionsUpdatesPage.Default.UpdatePending && DateTime.UtcNow < nextUpdateCheck)
{
return;

View File

@@ -24,11 +24,11 @@ namespace mRemoteNG.App
private SupportedCultures()
{
foreach (var CultureName in Properties.AppUI.Default.SupportedUICultures.Split(','))
foreach (string CultureName in Properties.AppUI.Default.SupportedUICultures.Split(','))
{
try
{
var CultureInfo = new CultureInfo(CultureName.Trim());
CultureInfo CultureInfo = new(CultureName.Trim());
Add(CultureInfo.Name, CultureInfo.TextInfo.ToTitleCase(CultureInfo.NativeName));
}
catch (Exception ex)
@@ -57,13 +57,13 @@ namespace mRemoteNG.App
public static string get_CultureName(string CultureNativeName)
{
var Names = new string[SingletonInstance.Count + 1];
var NativeNames = new string[SingletonInstance.Count + 1];
string[] Names = new string[SingletonInstance.Count + 1];
string[] NativeNames = new string[SingletonInstance.Count + 1];
SingletonInstance.Keys.CopyTo(Names, 0);
SingletonInstance.Values.CopyTo(NativeNames, 0);
for (var Index = 0; Index <= SingletonInstance.Count; Index++)
for (int Index = 0; Index <= SingletonInstance.Count; Index++)
{
if (NativeNames[Index] == CultureNativeName)
{
@@ -83,8 +83,8 @@ namespace mRemoteNG.App
{
get
{
var ValueList = new List<string>();
foreach (var Value in SingletonInstance.Values)
List<string> ValueList = new();
foreach (string Value in SingletonInstance.Values)
{
ValueList.Add(Value);
}

View File

@@ -60,13 +60,13 @@ namespace mRemoteNG.App.Update
private void SetDefaultProxySettings()
{
var shouldWeUseProxy = Properties.OptionsUpdatesPage.Default.UpdateUseProxy;
var proxyAddress = Properties.OptionsUpdatesPage.Default.UpdateProxyAddress;
var port = Properties.OptionsUpdatesPage.Default.UpdateProxyPort;
var useAuthentication = Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication;
var username = Properties.OptionsUpdatesPage.Default.UpdateProxyAuthUser;
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
var password = cryptographyProvider.Decrypt(Properties.OptionsUpdatesPage.Default.UpdateProxyAuthPass, Runtime.EncryptionKey);
bool shouldWeUseProxy = Properties.OptionsUpdatesPage.Default.UpdateUseProxy;
string proxyAddress = Properties.OptionsUpdatesPage.Default.UpdateProxyAddress;
int port = Properties.OptionsUpdatesPage.Default.UpdateProxyPort;
bool useAuthentication = Properties.OptionsUpdatesPage.Default.UpdateProxyUseAuthentication;
string username = Properties.OptionsUpdatesPage.Default.UpdateProxyAuthUser;
LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string password = cryptographyProvider.Decrypt(Properties.OptionsUpdatesPage.Default.UpdateProxyAuthPass, Runtime.EncryptionKey);
SetProxySettings(shouldWeUseProxy, proxyAddress, port, useAuthentication, username, password);
}
@@ -132,19 +132,19 @@ namespace mRemoteNG.App.Update
try
{
_getUpdateInfoCancelToken = new CancellationTokenSource();
using var response = await _httpClient.GetAsync(CurrentUpdateInfo.DownloadAddress, HttpCompletionOption.ResponseHeadersRead, _getUpdateInfoCancelToken.Token);
var buffer = new byte[_bufferLength];
var totalBytes = response.Content.Headers.ContentLength ?? 0;
var readBytes = 0L;
using HttpResponseMessage response = await _httpClient.GetAsync(CurrentUpdateInfo.DownloadAddress, HttpCompletionOption.ResponseHeadersRead, _getUpdateInfoCancelToken.Token);
byte[] buffer = new byte[_bufferLength];
long totalBytes = response.Content.Headers.ContentLength ?? 0;
long readBytes = 0L;
await using (var httpStream = await response.Content.ReadAsStreamAsync(_getUpdateInfoCancelToken.Token))
await using (Stream httpStream = await response.Content.ReadAsStreamAsync(_getUpdateInfoCancelToken.Token))
{
await using var fileStream = new FileStream(CurrentUpdateInfo.UpdateFilePath, FileMode.Create,
await using FileStream fileStream = new(CurrentUpdateInfo.UpdateFilePath, FileMode.Create,
FileAccess.Write, FileShare.None, _bufferLength, true);
while (readBytes <= totalBytes || !_getUpdateInfoCancelToken.IsCancellationRequested)
{
var bytesRead =
int bytesRead =
await httpStream.ReadAsync(buffer, 0, _bufferLength, _getUpdateInfoCancelToken.Token);
if (bytesRead == 0)
{
@@ -156,13 +156,13 @@ namespace mRemoteNG.App.Update
readBytes += bytesRead;
var percentComplete = (int)(readBytes * 100 / totalBytes);
int percentComplete = (int)(readBytes * 100 / totalBytes);
progress.Report(percentComplete);
}
}
#if !PORTABLE
var updateAuthenticode = new Authenticode(CurrentUpdateInfo.UpdateFilePath)
Authenticode updateAuthenticode = new(CurrentUpdateInfo.UpdateFilePath)
{
RequireThumbprintMatch = true,
ThumbprintToMatch = CurrentUpdateInfo.CertificateThumbprint
@@ -179,10 +179,10 @@ namespace mRemoteNG.App.Update
}
#endif
using var checksum = SHA512.Create();
await using var stream = File.OpenRead(CurrentUpdateInfo.UpdateFilePath);
var hash = await checksum.ComputeHashAsync(stream);
var hashString = BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
using SHA512 checksum = SHA512.Create();
await using FileStream stream = File.OpenRead(CurrentUpdateInfo.UpdateFilePath);
byte[] hash = await checksum.ComputeHashAsync(stream);
string hashString = BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
if (!hashString.Equals(CurrentUpdateInfo.Checksum))
throw new Exception("SHA512 Hashes didn't match!");
} finally{
@@ -202,7 +202,7 @@ namespace mRemoteNG.App.Update
_httpClient.Dispose();
}
var httpClientHandler = new HttpClientHandler();
HttpClientHandler httpClientHandler = new();
if (_webProxy != null)
{
httpClientHandler.UseProxy = true;
@@ -224,7 +224,7 @@ namespace mRemoteNG.App.Update
try
{
_getUpdateInfoCancelToken = new CancellationTokenSource();
var updateInfo = await _httpClient.GetStringAsync(UpdateChannelInfo.GetUpdateChannelInfo(), _getUpdateInfoCancelToken.Token);
string updateInfo = await _httpClient.GetStringAsync(UpdateChannelInfo.GetUpdateChannelInfo(), _getUpdateInfoCancelToken.Token);
CurrentUpdateInfo = UpdateInfo.FromString(updateInfo);
Properties.OptionsUpdatesPage.Default.CheckForUpdatesLastCheck = DateTime.UtcNow;

View File

@@ -34,19 +34,19 @@ namespace mRemoteNG.App.Update
// no separators means no valid update data...
if (content.Trim().IndexOfAny(keyValueSeparators) == -1) return;
using (var sr = new StringReader(content))
using (StringReader sr = new(content))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var trimmedLine = line.Trim();
string trimmedLine = line.Trim();
if (trimmedLine.Length == 0)
continue;
if (trimmedLine.Substring(0, 1).IndexOfAny(commentCharacters) != -1)
continue;
var parts = trimmedLine.Split(keyValueSeparators, 2);
string[] parts = trimmedLine.Split(keyValueSeparators, 2);
if (parts.Length != 2)
continue;
@@ -68,13 +68,13 @@ namespace mRemoteNG.App.Update
public Version GetVersion(string key = "Version")
{
var value = GetString(key);
string value = GetString(key);
return string.IsNullOrEmpty(value) ? null : new Version(value);
}
public Uri GetUri(string key)
{
var value = GetString(key);
string value = GetString(key);
return string.IsNullOrEmpty(value) ? null : new Uri(value);
}
@@ -85,8 +85,8 @@ namespace mRemoteNG.App.Update
public string GetFileName()
{
var value = GetString("dURL");
var sv = value.Split('/');
string value = GetString("dURL");
string[] sv = value.Split('/');
return sv[sv.Length - 1];
}

View File

@@ -22,14 +22,14 @@ namespace mRemoteNG.App.Update
public static UpdateInfo FromString(string input)
{
var newInfo = new UpdateInfo();
UpdateInfo newInfo = new();
if (string.IsNullOrEmpty(input))
{
newInfo.IsValid = false;
}
else
{
var updateFile = new UpdateFile(input);
UpdateFile updateFile = new(input);
newInfo.Version = updateFile.GetVersion();
newInfo.DownloadAddress = updateFile.GetUri("dURL");
newInfo.ChangeLogAddress = updateFile.GetUri("clURL");

View File

@@ -34,7 +34,7 @@ namespace mRemoteNG.App
{
try
{
var dockPanel = FrmMain.Default.pnlDock;
WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel = FrmMain.Default.pnlDock;
// ReSharper disable once SwitchStatementMissingSomeCases
switch (windowType)
{

View File

@@ -27,10 +27,10 @@ namespace mRemoteNG.Config.Connections
public void Save(ConnectionTreeModel connectionTreeModel, string propertyNameTrigger = "")
{
var csvConnectionsSerializer =
new CsvConnectionsSerializerMremotengFormat(_saveFilter, Runtime.CredentialProviderCatalog);
var dataProvider = new FileDataProvider(_connectionFileName);
var csvContent = csvConnectionsSerializer.Serialize(connectionTreeModel);
CsvConnectionsSerializerMremotengFormat csvConnectionsSerializer =
new(_saveFilter, Runtime.CredentialProviderCatalog);
FileDataProvider dataProvider = new(_connectionFileName);
string csvContent = csvConnectionsSerializer.Serialize(connectionTreeModel);
dataProvider.Save(csvContent);
}
}

View File

@@ -29,7 +29,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
{
RaiseUpdateCheckStartedEvent();
ConnectToSqlDb();
var updateIsAvailable = DatabaseIsMoreUpToDateThanUs();
bool updateIsAvailable = DatabaseIsMoreUpToDateThanUs();
if (updateIsAvailable)
RaiseConnectionsUpdateAvailableEvent();
RaiseUpdateCheckFinishedEvent(updateIsAvailable);
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
public void IsUpdateAvailableAsync()
{
var thread = new Thread(() => IsUpdateAvailable());
Thread thread = new(() => IsUpdateAvailable());
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
@@ -57,14 +57,14 @@ namespace mRemoteNG.Config.Connections.Multiuser
private bool DatabaseIsMoreUpToDateThanUs()
{
var lastUpdateInDb = GetLastUpdateTimeFromDbResponse();
var amTheLastoneUpdated = CheckIfIAmTheLastOneUpdated(lastUpdateInDb);
DateTime lastUpdateInDb = GetLastUpdateTimeFromDbResponse();
bool amTheLastoneUpdated = CheckIfIAmTheLastOneUpdated(lastUpdateInDb);
return (lastUpdateInDb > LastUpdateTime && !amTheLastoneUpdated);
}
private bool CheckIfIAmTheLastOneUpdated(DateTime lastUpdateInDb)
{
DateTime lastSqlUpdateWithoutMilliseconds = new DateTime(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), LastUpdateTime.Kind);
DateTime lastSqlUpdateWithoutMilliseconds = new(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), LastUpdateTime.Kind);
return lastUpdateInDb == lastSqlUpdateWithoutMilliseconds;
}
@@ -104,7 +104,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
private void RaiseUpdateCheckFinishedEvent(bool updateAvailable)
{
var args = new ConnectionsUpdateCheckFinishedEventArgs {UpdateAvailable = updateAvailable};
ConnectionsUpdateCheckFinishedEventArgs args = new() { UpdateAvailable = updateAvailable};
UpdateCheckFinished?.Invoke(this, args);
}
@@ -113,7 +113,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
private void RaiseConnectionsUpdateAvailableEvent()
{
Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, "Remote connection update is available");
var args = new ConnectionsUpdateAvailableEventArgs(_dbConnector, _lastDatabaseUpdateTime);
ConnectionsUpdateAvailableEventArgs args = new(_dbConnector, _lastDatabaseUpdateTime);
ConnectionsUpdateAvailable?.Invoke(this, args);
}

View File

@@ -27,7 +27,7 @@ namespace mRemoteNG.Config.Connections
connectionsLoadedEventArgs.NewConnectionTreeModel.CollectionChanged += ConnectionTreeModelOnCollectionChanged;
connectionsLoadedEventArgs.NewConnectionTreeModel.PropertyChanged += ConnectionTreeModelOnPropertyChanged;
foreach (var oldTree in connectionsLoadedEventArgs.PreviousConnectionTreeModel)
foreach (Tree.ConnectionTreeModel oldTree in connectionsLoadedEventArgs.PreviousConnectionTreeModel)
{
oldTree.CollectionChanged -= ConnectionTreeModelOnCollectionChanged;
oldTree.PropertyChanged -= ConnectionTreeModelOnPropertyChanged;

View File

@@ -37,39 +37,39 @@ namespace mRemoteNG.Config.Connections
public ConnectionTreeModel Load()
{
var connector = DatabaseConnectorFactory.DatabaseConnectorFromSettings();
var dataProvider = new SqlDataProvider(connector);
var metaDataRetriever = new SqlDatabaseMetaDataRetriever();
var databaseVersionVerifier = new SqlDatabaseVersionVerifier(connector);
var cryptoProvider = new LegacyRijndaelCryptographyProvider();
var metaData = metaDataRetriever.GetDatabaseMetaData(connector) ?? HandleFirstRun(metaDataRetriever, connector);
var decryptionKey = GetDecryptionKey(metaData);
IDatabaseConnector connector = DatabaseConnectorFactory.DatabaseConnectorFromSettings();
SqlDataProvider dataProvider = new(connector);
SqlDatabaseMetaDataRetriever metaDataRetriever = new();
SqlDatabaseVersionVerifier databaseVersionVerifier = new(connector);
LegacyRijndaelCryptographyProvider cryptoProvider = new();
SqlConnectionListMetaData metaData = metaDataRetriever.GetDatabaseMetaData(connector) ?? HandleFirstRun(metaDataRetriever, connector);
Optional<SecureString> decryptionKey = GetDecryptionKey(metaData);
if (!decryptionKey.Any())
throw new Exception("Could not load SQL connections");
databaseVersionVerifier.VerifyDatabaseVersion(metaData.ConfVersion);
var dataTable = dataProvider.Load();
var deserializer = new DataTableDeserializer(cryptoProvider, decryptionKey.First());
var connectionTree = deserializer.Deserialize(dataTable);
System.Data.DataTable dataTable = dataProvider.Load();
DataTableDeserializer deserializer = new(cryptoProvider, decryptionKey.First());
ConnectionTreeModel connectionTree = deserializer.Deserialize(dataTable);
ApplyLocalConnectionProperties(connectionTree.RootNodes.First(i => i is RootNodeInfo));
return connectionTree;
}
private Optional<SecureString> GetDecryptionKey(SqlConnectionListMetaData metaData)
{
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
var cipherText = metaData.Protected;
var authenticator = new PasswordAuthenticator(cryptographyProvider, cipherText, AuthenticationRequestor);
var authenticated = authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword.ConvertToSecureString());
LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string cipherText = metaData.Protected;
PasswordAuthenticator authenticator = new(cryptographyProvider, cipherText, AuthenticationRequestor);
bool authenticated = authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword.ConvertToSecureString());
return authenticated ? authenticator.LastAuthenticatedPassword : Optional<SecureString>.Empty;
}
private void ApplyLocalConnectionProperties(ContainerInfo rootNode)
{
var localPropertiesXml = _dataProvider.Load();
var localConnectionProperties = _localConnectionPropertiesDeserializer.Deserialize(localPropertiesXml);
string localPropertiesXml = _dataProvider.Load();
IEnumerable<LocalConnectionPropertiesModel> localConnectionProperties = _localConnectionPropertiesDeserializer.Deserialize(localPropertiesXml);
rootNode
.GetRecursiveChildList()

View File

@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Connections
public void Save(ConnectionTreeModel connectionTreeModel, string propertyNameTrigger = "")
{
var rootTreeNode = connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First();
RootNodeInfo rootTreeNode = connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First();
UpdateLocalConnectionProperties(rootTreeNode);
@@ -54,12 +54,12 @@ namespace mRemoteNG.Config.Connections
return;
}
using (var dbConnector = DatabaseConnectorFactory.DatabaseConnectorFromSettings())
using (IDatabaseConnector dbConnector = DatabaseConnectorFactory.DatabaseConnectorFromSettings())
{
dbConnector.Connect();
var databaseVersionVerifier = new SqlDatabaseVersionVerifier(dbConnector);
var metaDataRetriever = new SqlDatabaseMetaDataRetriever();
var metaData = metaDataRetriever.GetDatabaseMetaData(dbConnector);
SqlDatabaseVersionVerifier databaseVersionVerifier = new(dbConnector);
SqlDatabaseMetaDataRetriever metaDataRetriever = new();
SqlConnectionListMetaData metaData = metaDataRetriever.GetDatabaseMetaData(dbConnector);
if (!databaseVersionVerifier.VerifyDatabaseVersion(metaData.ConfVersion))
{
@@ -93,7 +93,7 @@ namespace mRemoteNG.Config.Connections
private void UpdateLocalConnectionProperties(ContainerInfo rootNode)
{
var a = rootNode.GetRecursiveChildList().Select(info => new LocalConnectionPropertiesModel
IEnumerable<LocalConnectionPropertiesModel> a = rootNode.GetRecursiveChildList().Select(info => new LocalConnectionPropertiesModel
{
ConnectionId = info.ConstantID,
Connected = info.OpenConnections.Count > 0,
@@ -101,7 +101,7 @@ namespace mRemoteNG.Config.Connections
Favorite = info.Favorite,
});
var serializedProperties = _localPropertiesSerializer.Serialize(a);
string serializedProperties = _localPropertiesSerializer.Serialize(a);
_dataProvider.Save(serializedProperties);
Runtime.MessageCollector.AddMessage(MessageClass.DebugMsg, "Saved local connection properties");
}
@@ -109,13 +109,13 @@ namespace mRemoteNG.Config.Connections
private void UpdateRootNodeTable(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
// TODO: use transaction, but method not used at all?
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string strProtected;
if (rootTreeNode != null)
{
if (rootTreeNode.Password)
{
var password = rootTreeNode.PasswordString.ConvertToSecureString();
System.Security.SecureString password = rootTreeNode.PasswordString.ConvertToSecureString();
strProtected = cryptographyProvider.Encrypt("ThisIsProtected", password);
}
else
@@ -128,7 +128,7 @@ namespace mRemoteNG.Config.Connections
strProtected = cryptographyProvider.Encrypt("ThisIsNotProtected", Runtime.EncryptionKey);
}
var dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
System.Data.Common.DbCommand dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
dbQuery.ExecuteNonQuery();
if (rootTreeNode != null)
@@ -148,11 +148,11 @@ namespace mRemoteNG.Config.Connections
private void UpdateConnectionsTable(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
SqlDataProvider dataProvider = new SqlDataProvider(databaseConnector);
SqlDataProvider dataProvider = new(databaseConnector);
DataTable currentDataTable = dataProvider.Load();
LegacyRijndaelCryptographyProvider cryptoProvider = new LegacyRijndaelCryptographyProvider();
DataTableSerializer serializer = new DataTableSerializer(_saveFilter, cryptoProvider, rootTreeNode.PasswordString.ConvertToSecureString());
LegacyRijndaelCryptographyProvider cryptoProvider = new();
DataTableSerializer serializer = new(_saveFilter, cryptoProvider, rootTreeNode.PasswordString.ConvertToSecureString());
serializer.SetSourceDataTable(currentDataTable);
DataTable dataTable = serializer.Serialize(rootTreeNode);
@@ -163,7 +163,7 @@ namespace mRemoteNG.Config.Connections
private void UpdateUpdatesTable(IDatabaseConnector databaseConnector)
{
// TODO: use transaction
var dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblUpdate");
System.Data.Common.DbCommand dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblUpdate");
dbQuery.ExecuteNonQuery();
dbQuery = databaseConnector.DbCommand("INSERT INTO tblUpdate (LastUpdate) VALUES('" + MiscTools.DBDate(DateTime.Now.ToUniversalTime()) + "')");
dbQuery.ExecuteNonQuery();

View File

@@ -27,15 +27,15 @@ namespace mRemoteNG.Config.Connections
public ConnectionTreeModel Load()
{
var dataProvider = new FileDataProvider(_connectionFilePath);
var xmlString = dataProvider.Load();
var deserializer = new XmlConnectionsDeserializer(PromptForPassword);
FileDataProvider dataProvider = new(_connectionFilePath);
string xmlString = dataProvider.Load();
XmlConnectionsDeserializer deserializer = new(PromptForPassword);
return deserializer.Deserialize(xmlString);
}
private Optional<SecureString> PromptForPassword()
{
var password = MiscTools.PasswordDialog(Path.GetFileName(_connectionFilePath), false);
Optional<SecureString> password = MiscTools.PasswordDialog(Path.GetFileName(_connectionFilePath), false);
return password;
}
}

View File

@@ -30,15 +30,15 @@ namespace mRemoteNG.Config.Connections
{
try
{
var cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
var serializerFactory = new XmlConnectionSerializerFactory();
var xmlConnectionsSerializer = serializerFactory.Build(cryptographyProvider, connectionTreeModel, _saveFilter, Properties.OptionsSecurityPage.Default.EncryptCompleteConnectionsFile);
ICryptographyProvider cryptographyProvider = new CryptoProviderFactoryFromSettings().Build();
XmlConnectionSerializerFactory serializerFactory = new();
var rootNode = connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First();
var xml = xmlConnectionsSerializer.Serialize(rootNode);
Serializers.ISerializer<Connection.ConnectionInfo, string> xmlConnectionsSerializer = serializerFactory.Build(cryptographyProvider, connectionTreeModel, _saveFilter, Properties.OptionsSecurityPage.Default.EncryptCompleteConnectionsFile);
var fileDataProvider = new FileDataProviderWithRollingBackup(_connectionFileName);
RootNodeInfo rootNode = connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First();
string xml = xmlConnectionsSerializer.Serialize(rootNode);
FileDataProviderWithRollingBackup fileDataProvider = new(_connectionFileName);
fileDataProvider.Save(xml);
}
catch (Exception ex)

View File

@@ -17,19 +17,19 @@ namespace mRemoteNG.Config
// maps a connectioninfo (by its id) to the credential object that was harvested
public Dictionary<Guid, ICredentialRecord> ConnectionToCredentialMap { get; } =
new Dictionary<Guid, ICredentialRecord>();
[];
public IEnumerable<ICredentialRecord> Harvest(XDocument xDocument, SecureString decryptionKey)
{
if (xDocument == null)
throw new ArgumentNullException(nameof(xDocument));
var cryptoProvider = new CryptoProviderFactoryFromXml(xDocument.Root).Build();
ICryptographyProvider cryptoProvider = new CryptoProviderFactoryFromXml(xDocument.Root).Build();
foreach (var element in xDocument.Descendants("Node"))
foreach (XElement element in xDocument.Descendants("Node"))
{
if (!EntryHasSomeCredentialData(element)) continue;
var newCredential = BuildCredential(element, cryptoProvider, decryptionKey);
ICredentialRecord newCredential = BuildCredential(element, cryptoProvider, decryptionKey);
Guid connectionId;
Guid.TryParse(element.Attribute("Id")?.Value, out connectionId);
@@ -40,7 +40,7 @@ namespace mRemoteNG.Config
if (ConnectionToCredentialMap.Values.Contains(newCredential, _credentialComparer))
{
var existingCredential = ConnectionToCredentialMap.Values.First(record => _credentialComparer.Equals(newCredential, record));
ICredentialRecord existingCredential = ConnectionToCredentialMap.Values.First(record => _credentialComparer.Equals(newCredential, record));
ConnectionToCredentialMap.Add(connectionId, existingCredential);
}
else
@@ -52,7 +52,7 @@ namespace mRemoteNG.Config
private ICredentialRecord BuildCredential(XElement element, ICryptographyProvider cryptographyProvider, SecureString decryptionKey)
{
var credential = new CredentialRecord
CredentialRecord credential = new()
{
Title = $"{element.Attribute("Username")?.Value}\\{element.Attribute("Domain")?.Value}",
Username = element.Attribute("Username")?.Value,

View File

@@ -27,7 +27,7 @@ namespace mRemoteNG.Config
public IEnumerable<ICredentialRecord> Load(SecureString key)
{
var serializedCredentials = _dataProvider.Load();
string serializedCredentials = _dataProvider.Load();
return _deserializer.Deserialize(serializedCredentials, key);
}
}

View File

@@ -26,7 +26,7 @@ namespace mRemoteNG.Config
public void Save(IEnumerable<ICredentialRecord> credentialRecords, SecureString key)
{
var serializedCredentials = _serializer.Serialize(credentialRecords, key);
string serializedCredentials = _serializer.Serialize(credentialRecords, key);
_dataProvider.Save(serializedCredentials);
}
}

View File

@@ -26,7 +26,7 @@ namespace mRemoteNG.Config
[SupportedOSPlatform("windows")]
public IEnumerable<ICredentialRepository> Load()
{
var data = _dataProvider.Load();
string data = _dataProvider.Load();
return _deserializer.Deserialize(data);
}
}

View File

@@ -20,8 +20,8 @@ namespace mRemoteNG.Config
public void Save(IEnumerable<ICredentialRepository> repositories, string propertyNameTrigger = "")
{
var serializer = new CredentialRepositoryListSerializer();
var data = serializer.Serialize(repositories);
CredentialRepositoryListSerializer serializer = new();
string data = serializer.Serialize(repositories);
_dataProvider.Save(data);
}
}

View File

@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.DataProviders
if (WeDontNeedToBackup(fileName))
return;
var backupFileName =
string backupFileName =
string.Format(Properties.OptionsBackupPage.Default.BackupFileNameFormat, fileName, DateTime.Now);
File.Copy(fileName, backupFileName);
}

View File

@@ -7,23 +7,23 @@ namespace mRemoteNG.Config.DataProviders
{
public void PruneBackupFiles(string filePath, int maxBackupsToKeep)
{
var fileName = Path.GetFileName(filePath);
var directoryName = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
string directoryName = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(directoryName))
return;
var searchPattern = string.Format(Properties.OptionsBackupPage.Default.BackupFileNameFormat, fileName, "*");
var files = Directory.GetFiles(directoryName, searchPattern);
string searchPattern = string.Format(Properties.OptionsBackupPage.Default.BackupFileNameFormat, fileName, "*");
string[] files = Directory.GetFiles(directoryName, searchPattern);
if (files.Length <= maxBackupsToKeep)
return;
var filesToDelete = files
System.Collections.Generic.IEnumerable<string> filesToDelete = files
.OrderByDescending(s => s)
.Skip(maxBackupsToKeep);
foreach (var file in filesToDelete)
foreach (string file in filesToDelete)
{
File.Delete(file);
}

View File

@@ -18,7 +18,7 @@ namespace mRemoteNG.Config.DataProviders
public virtual string Load()
{
var fileContents = "";
string fileContents = "";
try
{
if (!File.Exists(FilePath))
@@ -70,7 +70,7 @@ namespace mRemoteNG.Config.DataProviders
private void CreateMissingDirectories()
{
var dirname = Path.GetDirectoryName(FilePath);
string dirname = Path.GetDirectoryName(FilePath);
if (dirname == null) return;
Directory.CreateDirectory(dirname);
}

View File

@@ -20,12 +20,12 @@ namespace mRemoteNG.Config.DataProviders
public DataTable Load()
{
var dataTable = new DataTable();
var dbQuery = DatabaseConnector.DbCommand("SELECT * FROM tblCons ORDER BY PositionID ASC");
DataTable dataTable = new();
System.Data.Common.DbCommand dbQuery = DatabaseConnector.DbCommand("SELECT * FROM tblCons ORDER BY PositionID ASC");
DatabaseConnector.AssociateItemToThisConnector(dbQuery);
if (!DatabaseConnector.IsConnected)
OpenConnection();
var dbDataReader = dbQuery.ExecuteReader(CommandBehavior.CloseConnection);
System.Data.Common.DbDataReader dbDataReader = dbQuery.ExecuteReader(CommandBehavior.CloseConnection);
if (dbDataReader.HasRows)
dataTable.Load(dbDataReader);
@@ -47,16 +47,18 @@ namespace mRemoteNG.Config.DataProviders
{
SqlConnection sqlConnection = (SqlConnection)DatabaseConnector.DbConnection();
using SqlTransaction transaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.Serializable);
using SqlCommand sqlCommand = new SqlCommand();
using SqlCommand sqlCommand = new();
sqlCommand.Connection = sqlConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
using SqlDataAdapter dataAdapter = new SqlDataAdapter();
using SqlDataAdapter dataAdapter = new();
dataAdapter.SelectCommand = sqlCommand;
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
// Avoid optimistic concurrency, check if it is necessary.
builder.ConflictOption = ConflictOption.OverwriteChanges;
SqlCommandBuilder builder = new(dataAdapter)
{
// Avoid optimistic concurrency, check if it is necessary.
ConflictOption = ConflictOption.OverwriteChanges
};
dataAdapter.UpdateCommand = builder.GetUpdateCommand();
dataAdapter.DeleteCommand = builder.GetDeleteCommand();
@@ -66,15 +68,15 @@ namespace mRemoteNG.Config.DataProviders
}
else if (DatabaseConnector.GetType() == typeof(MySqlDatabaseConnector))
{
var dbConnection = (MySqlConnection) DatabaseConnector.DbConnection();
MySqlConnection dbConnection = (MySqlConnection) DatabaseConnector.DbConnection();
using MySqlTransaction transaction = dbConnection.BeginTransaction(System.Data.IsolationLevel.Serializable);
using MySqlCommand sqlCommand = new MySqlCommand();
using MySqlCommand sqlCommand = new();
sqlCommand.Connection = dbConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
using MySqlDataAdapter dataAdapter = new MySqlDataAdapter(sqlCommand);
using MySqlDataAdapter dataAdapter = new(sqlCommand);
dataAdapter.UpdateBatchSize = 1000;
using MySqlCommandBuilder cb = new MySqlCommandBuilder(dataAdapter);
using MySqlCommandBuilder cb = new(dataAdapter);
dataAdapter.Update(dataTable);
transaction.Commit();
}

View File

@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.DatabaseConnectors
string username,
string password)
{
using (var dbConnector = DatabaseConnectorFactory.DatabaseConnector(type, server, database, username, password))
using (IDatabaseConnector dbConnector = DatabaseConnectorFactory.DatabaseConnector(type, server, database, username, password))
{
try
{

View File

@@ -10,12 +10,12 @@ namespace mRemoteNG.Config.DatabaseConnectors
public static IDatabaseConnector DatabaseConnectorFromSettings()
{
// TODO: add custom port handling?
var sqlType = Properties.OptionsDBsPage.Default.SQLServerType;
var sqlHost = Properties.OptionsDBsPage.Default.SQLHost;
var sqlCatalog = Properties.OptionsDBsPage.Default.SQLDatabaseName;
var sqlUsername = Properties.OptionsDBsPage.Default.SQLUser;
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
var sqlPassword = cryptographyProvider.Decrypt(Properties.OptionsDBsPage.Default.SQLPass, Runtime.EncryptionKey);
string sqlType = Properties.OptionsDBsPage.Default.SQLServerType;
string sqlHost = Properties.OptionsDBsPage.Default.SQLHost;
string sqlCatalog = Properties.OptionsDBsPage.Default.SQLDatabaseName;
string sqlUsername = Properties.OptionsDBsPage.Default.SQLUser;
LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string sqlPassword = cryptographyProvider.Decrypt(Properties.OptionsDBsPage.Default.SQLPass, Runtime.EncryptionKey);
return DatabaseConnector(sqlType, sqlHost, sqlCatalog, sqlUsername, sqlPassword);
}

View File

@@ -54,7 +54,7 @@ namespace mRemoteNG.Config.DatabaseConnectors
private void BuildDbConnectionStringWithCustomCredentials()
{
string[] hostParts = _dbHost.Split(new char[] { ':' }, 2);
var _dbPort = (hostParts.Length == 2) ? hostParts[1] : "1433";
string _dbPort = (hostParts.Length == 2) ? hostParts[1] : "1433";
_dbConnectionString = new SqlConnectionStringBuilder
{

View File

@@ -21,11 +21,11 @@ namespace mRemoteNG.Config.Import
try
{
ldapPath.ThrowIfNullOrEmpty(nameof(ldapPath));
var deserializer = new ActiveDirectoryDeserializer(ldapPath, importSubOu);
var connectionTreeModel = deserializer.Deserialize();
var importedRootNode = connectionTreeModel.RootNodes.First();
ActiveDirectoryDeserializer deserializer = new(ldapPath, importSubOu);
Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize();
ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
var childrenToAdd = importedRootNode.Children.ToArray();
Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
catch (Exception ex)

View File

@@ -24,12 +24,12 @@ namespace mRemoteNG.Config.Import
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
$"Unable to import file. File does not exist. Path: {filePath}");
var dataProvider = new FileDataProvider(filePath);
var xmlString = dataProvider.Load();
var xmlConnectionsDeserializer = new CsvConnectionsDeserializerMremotengFormat();
var connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString);
FileDataProvider dataProvider = new(filePath);
string xmlString = dataProvider.Load();
CsvConnectionsDeserializerMremotengFormat xmlConnectionsDeserializer = new();
Tree.ConnectionTreeModel connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString);
var rootImportContainer = new ContainerInfo {Name = Path.GetFileNameWithoutExtension(filePath)};
ContainerInfo rootImportContainer = new() { Name = Path.GetFileNameWithoutExtension(filePath)};
rootImportContainer.AddChildRange(connectionTreeModel.RootNodes.First().Children.ToArray());
destinationContainer.AddChild(rootImportContainer);
}

View File

@@ -26,12 +26,12 @@ namespace mRemoteNG.Config.Import
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
$"Unable to import file. File does not exist. Path: {fileName}");
var dataProvider = new FileDataProvider(fileName);
var xmlString = dataProvider.Load();
var xmlConnectionsDeserializer = new XmlConnectionsDeserializer();
var connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString, true);
FileDataProvider dataProvider = new(fileName);
string xmlString = dataProvider.Load();
XmlConnectionsDeserializer xmlConnectionsDeserializer = new();
Tree.ConnectionTreeModel connectionTreeModel = xmlConnectionsDeserializer.Deserialize(xmlString, true);
var rootImportContainer = new ContainerInfo {Name = Path.GetFileNameWithoutExtension(fileName)};
ContainerInfo rootImportContainer = new() { Name = Path.GetFileNameWithoutExtension(fileName)};
rootImportContainer.AddChildRange(connectionTreeModel.RootNodes.First().Children.ToArray());
destinationContainer.AddChild(rootImportContainer);
}

View File

@@ -21,12 +21,12 @@ namespace mRemoteNG.Config.Import
public void Import(IEnumerable<ScanHost> hosts, ContainerInfo destinationContainer)
{
var deserializer = new PortScanDeserializer(_targetProtocolType);
var connectionTreeModel = deserializer.Deserialize(hosts);
PortScanDeserializer deserializer = new(_targetProtocolType);
Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(hosts);
var importedRootNode = connectionTreeModel.RootNodes.First();
ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
var childrenToAdd = importedRootNode.Children.ToArray();
Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
}

View File

@@ -12,15 +12,15 @@ namespace mRemoteNG.Config.Import
{
public void Import(string filePath, ContainerInfo destinationContainer)
{
var dataProvider = new FileDataProvider(filePath);
var xmlContent = dataProvider.Load();
FileDataProvider dataProvider = new(filePath);
string xmlContent = dataProvider.Load();
var deserializer = new PuttyConnectionManagerDeserializer();
var connectionTreeModel = deserializer.Deserialize(xmlContent);
PuttyConnectionManagerDeserializer deserializer = new();
Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(xmlContent);
var importedRootNode = connectionTreeModel.RootNodes.First();
ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
var childrenToAdd = importedRootNode.Children.ToArray();
Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
}

View File

@@ -13,13 +13,13 @@ namespace mRemoteNG.Config.Import
{
public void Import(string fileName, ContainerInfo destinationContainer)
{
var dataProvider = new FileDataProvider(fileName);
var content = dataProvider.Load();
FileDataProvider dataProvider = new(fileName);
string content = dataProvider.Load();
var deserializer = new RemoteDesktopConnectionDeserializer();
var connectionTreeModel = deserializer.Deserialize(content);
RemoteDesktopConnectionDeserializer deserializer = new();
Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(content);
var importedConnection = connectionTreeModel.RootNodes.First().Children.First();
Connection.ConnectionInfo importedConnection = connectionTreeModel.RootNodes.First().Children.First();
if (importedConnection == null) return;
importedConnection.Name = Path.GetFileNameWithoutExtension(fileName);

View File

@@ -12,15 +12,15 @@ namespace mRemoteNG.Config.Import
{
public void Import(string filePath, ContainerInfo destinationContainer)
{
var dataProvider = new FileDataProvider(filePath);
var fileContent = dataProvider.Load();
FileDataProvider dataProvider = new(filePath);
string fileContent = dataProvider.Load();
var deserializer = new RemoteDesktopConnectionManagerDeserializer();
var connectionTreeModel = deserializer.Deserialize(fileContent);
RemoteDesktopConnectionManagerDeserializer deserializer = new();
Tree.ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(fileContent);
var importedRootNode = connectionTreeModel.RootNodes.First();
ContainerInfo importedRootNode = connectionTreeModel.RootNodes.First();
if (importedRootNode == null) return;
var childrenToAdd = importedRootNode.Children.ToArray();
Connection.ConnectionInfo[] childrenToAdd = importedRootNode.Children.ToArray();
destinationContainer.AddChildRange(childrenToAdd);
}
}

View File

@@ -27,15 +27,15 @@ namespace mRemoteNG.Config.Import
if (!File.Exists(filePath))
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"Unable to import file. File does not exist. Path: {filePath}");
var dataProvider = new FileDataProvider(filePath);
var csvString = dataProvider.Load();
FileDataProvider dataProvider = new(filePath);
string csvString = dataProvider.Load();
if (!string.IsNullOrEmpty(csvString))
{
var csvDeserializer = new CsvConnectionsDeserializerRdmFormat();
var connectionTreeModel = csvDeserializer.Deserialize(csvString);
CsvConnectionsDeserializerRdmFormat csvDeserializer = new();
Tree.ConnectionTreeModel connectionTreeModel = csvDeserializer.Deserialize(csvString);
var rootContainer = new ContainerInfo { Name = Path.GetFileNameWithoutExtension(filePath) };
ContainerInfo rootContainer = new() { Name = Path.GetFileNameWithoutExtension(filePath) };
rootContainer.AddChildRange(connectionTreeModel.RootNodes);
destinationContainer.AddChild(rootContainer);
}

View File

@@ -31,12 +31,12 @@ namespace mRemoteNG.Config.Import
$"Unable to import file. File does not exist. Path: {fileName}");
var dataProvider = new FileDataProvider(fileName);
var content = dataProvider.Load();
var deserializer = new SecureCRTFileDeserializer();
var connectionTreeModel = deserializer.Deserialize(content);
FileDataProvider dataProvider = new(fileName);
string content = dataProvider.Load();
SecureCRTFileDeserializer deserializer = new();
ConnectionTreeModel connectionTreeModel = deserializer.Deserialize(content);
var rootImportContainer = new ContainerInfo { Name = Path.GetFileNameWithoutExtension(fileName) };
ContainerInfo rootImportContainer = new() { Name = Path.GetFileNameWithoutExtension(fileName) };
rootImportContainer.AddChildRange(connectionTreeModel.RootNodes.First().Children.ToArray());
destinationContainer.AddChild(rootImportContainer);
}

View File

@@ -24,15 +24,15 @@ namespace mRemoteNG.Config.Putty
public virtual IEnumerable<PuttySessionInfo> GetSessions()
{
var sessionNamesFromProvider = GetSessionNames(true);
string[] sessionNamesFromProvider = GetSessionNames(true);
foreach (var sessionName in GetSessionNamesToAdd(sessionNamesFromProvider))
foreach (string sessionName in GetSessionNamesToAdd(sessionNamesFromProvider))
{
var sessionInfo = GetSession(sessionName);
PuttySessionInfo sessionInfo = GetSession(sessionName);
AddSession(sessionInfo);
}
foreach (var session in GetSessionToRemove(sessionNamesFromProvider))
foreach (PuttySessionInfo session in GetSessionToRemove(sessionNamesFromProvider))
{
RemoveSession(session);
}
@@ -44,18 +44,18 @@ namespace mRemoteNG.Config.Putty
private IEnumerable<string> GetSessionNamesToAdd(IEnumerable<string> sessionNamesFromProvider)
{
if (sessionNamesFromProvider == null) { return Enumerable.Empty<string>(); }
var currentlyKnownSessionNames = Sessions.Select(session => session.Name);
var sessionNamesToAdd = sessionNamesFromProvider.Except(currentlyKnownSessionNames);
IEnumerable<string> currentlyKnownSessionNames = Sessions.Select(session => session.Name);
IEnumerable<string> sessionNamesToAdd = sessionNamesFromProvider.Except(currentlyKnownSessionNames);
return sessionNamesToAdd;
}
private IEnumerable<PuttySessionInfo> GetSessionToRemove(IEnumerable<string> sessionNamesFromProvider)
{
if (sessionNamesFromProvider == null) return Enumerable.Empty<PuttySessionInfo>();
var currentlyKnownSessionNames = Sessions.Select(session => session.Name);
var normalizedSessionNames =
IEnumerable<string> currentlyKnownSessionNames = Sessions.Select(session => session.Name);
IEnumerable<string> normalizedSessionNames =
sessionNamesFromProvider.Select(name => WebUtility.UrlDecode(name));
var sessionNamesToRemove = currentlyKnownSessionNames.Except(normalizedSessionNames);
IEnumerable<string> sessionNamesToRemove = currentlyKnownSessionNames.Except(normalizedSessionNames);
return Sessions.Where(session => sessionNamesToRemove.Contains(session.Name));
}

View File

@@ -14,11 +14,11 @@ namespace mRemoteNG.Config.Putty
{
public static PuttySessionsManager Instance { get; } = new PuttySessionsManager();
private readonly List<AbstractPuttySessionsProvider> _providers = new List<AbstractPuttySessionsProvider>();
private readonly List<AbstractPuttySessionsProvider> _providers = [];
public IEnumerable<AbstractPuttySessionsProvider> Providers => _providers;
public List<RootPuttySessionsNodeInfo> RootPuttySessionsNodes { get; } = new List<RootPuttySessionsNodeInfo>();
public List<RootPuttySessionsNodeInfo> RootPuttySessionsNodes { get; } = [];
private PuttySessionsManager()
{
@@ -30,7 +30,7 @@ namespace mRemoteNG.Config.Putty
public void AddSessions()
{
foreach (var provider in Providers)
foreach (AbstractPuttySessionsProvider provider in Providers)
{
AddSessionsFromProvider(provider);
}
@@ -40,7 +40,7 @@ namespace mRemoteNG.Config.Putty
{
puttySessionProvider.ThrowIfNull(nameof(puttySessionProvider));
var rootTreeNode = puttySessionProvider.RootInfo;
RootPuttySessionsNodeInfo rootTreeNode = puttySessionProvider.RootInfo;
puttySessionProvider.GetSessions();
if (!RootPuttySessionsNodes.Contains(rootTreeNode) && rootTreeNode.HasChildren())
@@ -50,7 +50,7 @@ namespace mRemoteNG.Config.Putty
public void StartWatcher()
{
foreach (var provider in Providers)
foreach (AbstractPuttySessionsProvider provider in Providers)
{
provider.StartWatcher();
provider.PuttySessionChanged += PuttySessionChanged;
@@ -59,7 +59,7 @@ namespace mRemoteNG.Config.Putty
public void StopWatcher()
{
foreach (var provider in Providers)
foreach (AbstractPuttySessionsProvider provider in Providers)
{
provider.StopWatcher();
provider.PuttySessionChanged -= PuttySessionChanged;
@@ -79,7 +79,7 @@ namespace mRemoteNG.Config.Putty
public void AddProviders(IEnumerable<AbstractPuttySessionsProvider> newProviders)
{
foreach (var provider in newProviders)
foreach (AbstractPuttySessionsProvider provider in newProviders)
AddProvider(provider);
}
@@ -105,8 +105,8 @@ namespace mRemoteNG.Config.Putty
private string[] GetSessionNames(bool raw = false)
{
var sessionNames = new List<string>();
foreach (var provider in Providers)
List<string> sessionNames = new();
foreach (AbstractPuttySessionsProvider provider in Providers)
{
if (!IsProviderEnabled(provider))
{
@@ -121,7 +121,7 @@ namespace mRemoteNG.Config.Putty
private bool IsProviderEnabled(AbstractPuttySessionsProvider puttySessionsProvider)
{
var enabled = true;
bool enabled = true;
if (!(puttySessionsProvider is PuttySessionsRegistryProvider)) enabled = false;
return enabled;

View File

@@ -24,11 +24,11 @@ namespace mRemoteNG.Config.Putty
public override string[] GetSessionNames(bool raw = false)
{
var sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
RegistryKey sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
if (sessionsKey == null) return Array.Empty<string>();
var sessionNames = new List<string>();
foreach (var sessionName in sessionsKey.GetSubKeyNames())
List<string> sessionNames = new();
foreach (string sessionName in sessionsKey.GetSubKeyNames())
{
sessionNames.Add(raw ? sessionName
: WebUtility.UrlDecode(sessionName.Replace("+", "%2B")));
@@ -47,13 +47,13 @@ namespace mRemoteNG.Config.Putty
if (string.IsNullOrEmpty(sessionName))
return null;
var sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
var sessionKey = sessionsKey?.OpenSubKey(sessionName);
RegistryKey sessionsKey = Registry.CurrentUser.OpenSubKey(PuttySessionsKey);
RegistryKey sessionKey = sessionsKey?.OpenSubKey(sessionName);
if (sessionKey == null) return null;
sessionName = WebUtility.UrlDecode(sessionName.Replace("+", "%2B"));
var sessionInfo = new PuttySessionInfo
PuttySessionInfo sessionInfo = new()
{
PuttySession = sessionName,
Name = sessionName,
@@ -62,7 +62,7 @@ namespace mRemoteNG.Config.Putty
};
var protocol = string.IsNullOrEmpty(sessionKey.GetValue("Protocol")?.ToString())
string protocol = string.IsNullOrEmpty(sessionKey.GetValue("Protocol")?.ToString())
? "ssh"
: sessionKey.GetValue("Protocol").ToString();
@@ -77,7 +77,7 @@ namespace mRemoteNG.Config.Putty
case "serial":
return null;
case "ssh":
int.TryParse(sessionKey.GetValue("SshProt")?.ToString(), out var sshVersion);
int.TryParse(sessionKey.GetValue("SshProt")?.ToString(), out int sshVersion);
/* Per PUTTY.H in PuTTYNG & PuTTYNG Upstream (PuTTY proper currently)
* expect 0 for SSH1, 3 for SSH2 ONLY
* 1 for SSH1 with a 2 fallback
@@ -94,7 +94,7 @@ namespace mRemoteNG.Config.Putty
return null;
}
int.TryParse(sessionKey.GetValue("PortNumber")?.ToString(), out var portNumber);
int.TryParse(sessionKey.GetValue("PortNumber")?.ToString(), out int portNumber);
if (portNumber == default(int))
sessionInfo.SetDefaultPort();
else
@@ -109,13 +109,13 @@ namespace mRemoteNG.Config.Putty
try
{
var keyName = string.Join("\\", CurrentUserSid, PuttySessionsKey).Replace("\\", "\\\\");
var sessionsKey = Registry.Users.OpenSubKey(keyName);
string keyName = string.Join("\\", CurrentUserSid, PuttySessionsKey).Replace("\\", "\\\\");
RegistryKey sessionsKey = Registry.Users.OpenSubKey(keyName);
if (sessionsKey == null)
{
Registry.Users.CreateSubKey(keyName);
}
var query = new WqlEventQuery($"SELECT * FROM RegistryTreeChangeEvent WHERE Hive = \'HKEY_USERS\' AND RootPath = \'{keyName}\'");
WqlEventQuery query = new($"SELECT * FROM RegistryTreeChangeEvent WHERE Hive = \'HKEY_USERS\' AND RootPath = \'{keyName}\'");
_eventWatcher = new ManagementEventWatcher(query);
_eventWatcher.EventArrived += OnManagementEventArrived;
_eventWatcher.Start();

View File

@@ -8,10 +8,10 @@ namespace mRemoteNG.Config.Serializers
{
public void EnsureElementsHaveIds(XDocument xdoc)
{
foreach (var element in xdoc.Descendants("Node"))
foreach (XElement element in xdoc.Descendants("Node"))
{
if (element.Attribute("Id") != null) continue;
var id = Guid.NewGuid();
Guid id = Guid.NewGuid();
element.Add(new XAttribute("Id", id));
}
}

View File

@@ -18,34 +18,34 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
{
public ConnectionTreeModel Deserialize(string serializedData)
{
var lines = serializedData.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries);
var csvHeaders = new List<string>();
string[] lines = serializedData.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries);
List<string> csvHeaders = new();
// used to map a connectioninfo to it's parent's GUID
var parentMapping = new Dictionary<ConnectionInfo, string>();
Dictionary<ConnectionInfo, string> parentMapping = new();
for (var lineNumber = 0; lineNumber < lines.Length; lineNumber++)
for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
var line = lines[lineNumber].Split(';');
string[] line = lines[lineNumber].Split(';');
if (lineNumber == 0)
csvHeaders = line.ToList();
else
{
var connectionInfo = ParseConnectionInfo(csvHeaders, line);
ConnectionInfo connectionInfo = ParseConnectionInfo(csvHeaders, line);
parentMapping.Add(connectionInfo, line[csvHeaders.IndexOf("Parent")]);
}
}
var root = CreateTreeStructure(parentMapping);
var connectionTreeModel = new ConnectionTreeModel();
RootNodeInfo root = CreateTreeStructure(parentMapping);
ConnectionTreeModel connectionTreeModel = new();
connectionTreeModel.AddRootNode(root);
return connectionTreeModel;
}
private RootNodeInfo CreateTreeStructure(Dictionary<ConnectionInfo, string> parentMapping)
{
var root = new RootNodeInfo(RootNodeType.Connection);
RootNodeInfo root = new(RootNodeType.Connection);
foreach (var node in parentMapping)
foreach (KeyValuePair<ConnectionInfo, string> node in parentMapping)
{
// no parent mapped, add to root
if (string.IsNullOrEmpty(node.Value))
@@ -55,7 +55,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
}
// search for parent in the list by GUID
var parent = parentMapping
ContainerInfo parent = parentMapping
.Keys
.OfType<ContainerInfo>()
.FirstOrDefault(info => info.ConstantID == node.Value);
@@ -75,15 +75,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
private ConnectionInfo ParseConnectionInfo(IList<string> headers, string[] connectionCsv)
{
var nodeType = headers.Contains("NodeType")
TreeNodeType nodeType = headers.Contains("NodeType")
? (TreeNodeType)Enum.Parse(typeof(TreeNodeType), connectionCsv[headers.IndexOf("NodeType")], true)
: TreeNodeType.Connection;
var nodeId = headers.Contains("Id")
string nodeId = headers.Contains("Id")
? connectionCsv[headers.IndexOf("Id")]
: Guid.NewGuid().ToString();
var connectionRecord = nodeType == TreeNodeType.Connection
ConnectionInfo connectionRecord = nodeType == TreeNodeType.Connection
? new ConnectionInfo(nodeId)
: new ContainerInfo(nodeId);

View File

@@ -34,14 +34,14 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
{
connectionTreeModel.ThrowIfNull(nameof(connectionTreeModel));
var rootNode = connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
ContainerInfo rootNode = connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
return Serialize(rootNode);
}
public string Serialize(ConnectionInfo serializationTarget)
{
serializationTarget.ThrowIfNull(nameof(serializationTarget));
var sb = new StringBuilder();
StringBuilder sb = new();
WriteCsvHeader(sb);
SerializeNodesRecursive(serializationTarget, sb);
@@ -81,10 +81,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
private void SerializeNodesRecursive(ConnectionInfo node, StringBuilder sb)
{
var nodeAsContainer = node as ContainerInfo;
ContainerInfo nodeAsContainer = node as ContainerInfo;
if (nodeAsContainer != null)
{
foreach (var child in nodeAsContainer.Children)
foreach (ConnectionInfo child in nodeAsContainer.Children)
{
SerializeNodesRecursive(child, sb);
}
@@ -272,7 +272,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv
private string FormatForCsv(object value)
{
var cleanedString = value.ToString().Replace(";", "");
string cleanedString = value.ToString().Replace(";", "");
return cleanedString + ";";
}
}

View File

@@ -24,15 +24,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
public CsvConnectionsDeserializerRdmFormat()
{
_connectionTypes = new List<RemoteDesktopManagerConnectionInfo>
{
_connectionTypes =
[
new(ProtocolType.RDP, "RDP (Microsoft Remote Desktop)", 3389, "Remote Desktop"),
new(ProtocolType.SSH2, "SSH Shell", 22, "SSH")
};
];
_groups = new HashSet<string>();
_groups = [];
Containers = new List<ContainerInfo>();
Containers = [];
}
private List<ContainerInfo> Containers { get; }
@@ -44,42 +44,42 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
/// <returns></returns>
public ConnectionTreeModel Deserialize(string serializedData)
{
var lines = serializedData.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
var csvHeaders = new List<string>();
string[] lines = serializedData.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
List<string> csvHeaders = new();
var connections = new List<(ConnectionInfo, string)>(); // (ConnectionInfo, group)
List<(ConnectionInfo, string)> connections = new(); // (ConnectionInfo, group)
for (var lineNumber = 0; lineNumber < lines.Length; lineNumber++)
for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
var line = lines[lineNumber].Split(',');
string[] line = lines[lineNumber].Split(',');
if (lineNumber == 0)
{
csvHeaders = line.ToList();
}
else
{
var (connectionInfo, group) = ParseConnectionInfo(csvHeaders, line);
(ConnectionInfo connectionInfo, string group) = ParseConnectionInfo(csvHeaders, line);
if (connectionInfo == default) continue;
connections.Add((connectionInfo, group));
}
}
var connectionTreeModel = new ConnectionTreeModel();
var unsortedConnections = new ContainerInfo { Name = "Unsorted" };
ConnectionTreeModel connectionTreeModel = new();
ContainerInfo unsortedConnections = new() { Name = "Unsorted" };
foreach (var containerInfo in Containers) connectionTreeModel.AddRootNode(containerInfo);
foreach (ContainerInfo containerInfo in Containers) connectionTreeModel.AddRootNode(containerInfo);
var allChildren = Containers.SelectMany(x => x.GetRecursiveChildList().Select(y => (ContainerInfo)y)).ToList();
List<ContainerInfo> allChildren = Containers.SelectMany(x => x.GetRecursiveChildList().Select(y => (ContainerInfo)y)).ToList();
foreach (var (connection, path) in connections)
foreach ((ConnectionInfo connection, string path) in connections)
if (string.IsNullOrEmpty(path))
{
unsortedConnections.AddChild(connection);
}
else
{
var container = allChildren.FirstOrDefault(x => x.ConstantID == path);
ContainerInfo container = allChildren.FirstOrDefault(x => x.ConstantID == path);
if (container == default) continue;
container.AddChild(connection);
@@ -101,30 +101,30 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
{
if (headers.Count != connectionCsv.Count) return default;
var hostString = connectionCsv[headers.IndexOf("Host")].Trim();
string hostString = connectionCsv[headers.IndexOf("Host")].Trim();
if (string.IsNullOrEmpty(hostString)) return default;
var hostType = Uri.CheckHostName(hostString);
UriHostNameType hostType = Uri.CheckHostName(hostString);
if (hostType == UriHostNameType.Unknown) return default;
var connectionTypeString = connectionCsv[headers.IndexOf("ConnectionType")];
string connectionTypeString = connectionCsv[headers.IndexOf("ConnectionType")];
if (string.IsNullOrEmpty(connectionTypeString)) return default;
var connectionType = _connectionTypes.FirstOrDefault(x => x.Name == connectionTypeString);
RemoteDesktopManagerConnectionInfo connectionType = _connectionTypes.FirstOrDefault(x => x.Name == connectionTypeString);
if (connectionType == default) return default;
var portString = connectionCsv[headers.IndexOf("Port")] ?? connectionType.Port.ToString();
if (!int.TryParse(portString, out var port)) port = connectionType.Port;
string portString = connectionCsv[headers.IndexOf("Port")] ?? connectionType.Port.ToString();
if (!int.TryParse(portString, out int port)) port = connectionType.Port;
var name = connectionCsv[headers.IndexOf("Name")];
var description = connectionCsv[headers.IndexOf("Description")];
var group = connectionCsv[headers.IndexOf("Group")];
string name = connectionCsv[headers.IndexOf("Name")];
string description = connectionCsv[headers.IndexOf("Description")];
string group = connectionCsv[headers.IndexOf("Group")];
var username = connectionCsv[headers.IndexOf("CredentialUserName")];
var domain = connectionCsv[headers.IndexOf("CredentialDomain")];
var password = connectionCsv[headers.IndexOf("CredentialPassword")];
string username = connectionCsv[headers.IndexOf("CredentialUserName")];
string domain = connectionCsv[headers.IndexOf("CredentialDomain")];
string password = connectionCsv[headers.IndexOf("CredentialPassword")];
var connectionInfo = new ConnectionInfo(Guid.NewGuid().ToString())
ConnectionInfo connectionInfo = new(Guid.NewGuid().ToString())
{
Name = name,
Hostname = hostString,
@@ -140,10 +140,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
if (!string.IsNullOrEmpty(group))
if (group.Contains('\\'))
{
var groupParts = group.Split('\\').ToList();
var parentContainerName = groupParts[0];
List<string> groupParts = group.Split('\\').ToList();
string parentContainerName = groupParts[0];
var parentContainer = Containers.FirstOrDefault(x => x.Name == parentContainerName);
ContainerInfo parentContainer = Containers.FirstOrDefault(x => x.Name == parentContainerName);
if (parentContainer == default)
{
parentContainer = new ContainerInfo(group) { Name = parentContainerName };
@@ -168,13 +168,13 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
{
if (_groups.Contains(group)) return;
var groupCount = groupParts.Count;
int groupCount = groupParts.Count;
while (groupCount > 0)
{
var childName = groupParts[0];
var newContainer = new ContainerInfo(group) { Name = childName };
string childName = groupParts[0];
ContainerInfo newContainer = new(group) { Name = childName };
var childrenNames = parentContainer.GetRecursiveChildList().Select(x => x.Name).ToList();
List<string> childrenNames = parentContainer.GetRecursiveChildList().Select(x => x.Name).ToList();
if (!childrenNames.Any())
{
groupCount = AddChild(parentContainer, newContainer, groupCount);
@@ -184,7 +184,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopMa
if (groupParts.Count > 1)
{
var childContainer = (ContainerInfo)parentContainer.Children.FirstOrDefault(x => x.Name == childName);
ContainerInfo childContainer = (ContainerInfo)parentContainer.Children.FirstOrDefault(x => x.Name == childName);
if (childContainer == default)
{
groupCount = AddChild(parentContainer, newContainer, groupCount);

View File

@@ -33,15 +33,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
public ConnectionTreeModel Deserialize(DataTable table)
{
var connectionList = CreateNodesFromTable(table);
var connectionTreeModel = CreateNodeHierarchy(connectionList, table);
List<ConnectionInfo> connectionList = CreateNodesFromTable(table);
ConnectionTreeModel connectionTreeModel = CreateNodeHierarchy(connectionList, table);
Runtime.ConnectionsService.IsConnectionsFileLoaded = true;
return connectionTreeModel;
}
private List<ConnectionInfo> CreateNodesFromTable(DataTable table)
{
var nodeList = new List<ConnectionInfo>();
List<ConnectionInfo> nodeList = new();
foreach (DataRow row in table.Rows)
{
// ReSharper disable once SwitchStatementMissingSomeCases
@@ -61,16 +61,16 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private ConnectionInfo DeserializeConnectionInfo(DataRow row)
{
var connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
var connectionInfo = new ConnectionInfo(connectionId);
string connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
ConnectionInfo connectionInfo = new(connectionId);
PopulateConnectionInfoFromDatarow(row, connectionInfo);
return connectionInfo;
}
private ContainerInfo DeserializeContainerInfo(DataRow row)
{
var containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
var containerInfo = new ContainerInfo(containerId);
string containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
ContainerInfo containerInfo = new(containerId);
PopulateConnectionInfoFromDatarow(row, containerInfo);
return containerInfo;
}
@@ -258,8 +258,8 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private ConnectionTreeModel CreateNodeHierarchy(List<ConnectionInfo> connectionList, DataTable dataTable)
{
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection, "0")
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo rootNode = new(RootNodeType.Connection, "0")
{
PasswordString = _decryptionKey.ConvertToUnsecureString()
};
@@ -267,9 +267,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
foreach (DataRow row in dataTable.Rows)
{
var id = (string)row["ConstantID"];
var connectionInfo = connectionList.First(node => node.ConstantID == id);
var parentId = (string)row["ParentID"];
string id = (string)row["ConstantID"];
ConnectionInfo connectionInfo = connectionList.First(node => node.ConstantID == id);
string parentId = (string)row["ParentID"];
if (parentId == "0" || connectionList.All(node => node.ConstantID != parentId))
rootNode.AddChild(connectionInfo);
else

View File

@@ -21,7 +21,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private readonly SecureString _encryptionKey;
private DataTable _dataTable;
private DataTable _sourceDataTable;
private readonly Dictionary<string, int> _sourcePrimaryKeyDict = new Dictionary<string, int>();
private readonly Dictionary<string, int> _sourcePrimaryKeyDict = [];
private const string TABLE_NAME = "tblCons";
private readonly SaveFilter _saveFilter;
private int _currentNodeIndex;
@@ -69,7 +69,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
List<string> entryToDelete = _sourcePrimaryKeyDict.Keys.ToList();
foreach (var entry in entryToDelete)
foreach (string entry in entryToDelete)
{
_dataTable.Rows.Find(entry)?.Delete();
}
@@ -277,7 +277,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
SerializeConnectionInfo(connectionInfo);
}
var containerInfo = connectionInfo as ContainerInfo;
ContainerInfo containerInfo = connectionInfo as ContainerInfo;
if (containerInfo == null) return;
foreach (ConnectionInfo child in containerInfo.Children)
@@ -288,7 +288,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private bool IsRowUpdated(ConnectionInfo connectionInfo, DataRow dataRow)
{
var isFieldNotChange = dataRow["Name"].Equals(connectionInfo.Name) &&
bool isFieldNotChange = dataRow["Name"].Equals(connectionInfo.Name) &&
dataRow["Type"].Equals(connectionInfo.GetTreeNodeType().ToString()) &&
dataRow["ParentID"].Equals(connectionInfo.Parent?.ConstantID ?? "") &&
dataRow["PositionID"].Equals(_currentNodeIndex) &&
@@ -370,7 +370,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
isFieldNotChange = isFieldNotChange && dataRow["VNCViewOnly"].Equals(connectionInfo.VNCViewOnly);
isFieldNotChange = isFieldNotChange && dataRow["VmId"].Equals(connectionInfo.VmId);
var isInheritanceFieldNotChange = false;
bool isInheritanceFieldNotChange = false;
if (_saveFilter.SaveInheritance)
{
isInheritanceFieldNotChange =
@@ -519,7 +519,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
dataRow["InheritVNCViewOnly"].Equals(false);
}
var pwd = dataRow["Password"].Equals(_saveFilter.SavePassword ? _cryptographyProvider.Encrypt(connectionInfo.Password, _encryptionKey) : "") &&
bool pwd = dataRow["Password"].Equals(_saveFilter.SavePassword ? _cryptographyProvider.Encrypt(connectionInfo.Password, _encryptionKey) : "") &&
dataRow["VNCProxyPassword"].Equals(_cryptographyProvider.Encrypt(connectionInfo.VNCProxyPassword, _encryptionKey)) &&
dataRow["RDGatewayPassword"].Equals(_cryptographyProvider.Encrypt(connectionInfo.RDGatewayPassword, _encryptionKey));
return !(pwd && isFieldNotChange && isInheritanceFieldNotChange);
@@ -528,7 +528,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private void SerializeConnectionInfo(ConnectionInfo connectionInfo)
{
_currentNodeIndex++;
var isNewRow = false;
bool isNewRow = false;
DataRow dataRow = _dataTable.Rows.Find(connectionInfo.ConstantID);
if (dataRow == null)
{
@@ -540,7 +540,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
_sourcePrimaryKeyDict.Remove(connectionInfo.ConstantID);
}
var tmp = IsRowUpdated(connectionInfo, dataRow);
bool tmp = IsRowUpdated(connectionInfo, dataRow);
if (!tmp)
{
return;

View File

@@ -16,15 +16,15 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
public string Serialize(IEnumerable<LocalConnectionPropertiesModel> models)
{
var localConnections = models
IEnumerable<XElement> localConnections = models
.Select(m => new XElement("Node",
new XAttribute("ConnectionId", m.ConnectionId),
new XAttribute("Connected", m.Connected),
new XAttribute("Expanded", m.Expanded),
new XAttribute("Favorite", m.Favorite)));
var root = new XElement("LocalConnections", localConnections);
var xdoc = new XDocument(new XDeclaration("1.0", "utf-8", null), root);
XElement root = new("LocalConnections", localConnections);
XDocument xdoc = new(new XDeclaration("1.0", "utf-8", null), root);
return WriteXmlToString(xdoc);
}
@@ -33,7 +33,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
if (string.IsNullOrWhiteSpace(serializedData))
return Enumerable.Empty<LocalConnectionPropertiesModel>();
var xdoc = XDocument.Parse(serializedData);
XDocument xdoc = XDocument.Parse(serializedData);
return xdoc
.Descendants("Node")
.Where(e => e.Attribute("ConnectionId") != null)
@@ -49,14 +49,13 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
private static string WriteXmlToString(XNode xmlDocument)
{
string xmlString;
var xmlWriterSettings = new XmlWriterSettings
{Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
var memoryStream = new MemoryStream();
using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
XmlWriterSettings xmlWriterSettings = new() { Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
MemoryStream memoryStream = new();
using (XmlWriter xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xmlDocument.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
var streamReader = new StreamReader(memoryStream, Encoding.UTF8, true);
StreamReader streamReader = new(memoryStream, Encoding.UTF8, true);
memoryStream.Seek(0, SeekOrigin.Begin);
xmlString = streamReader.ReadToEnd();
}

View File

@@ -71,7 +71,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
// TODO: use transaction
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
LegacyRijndaelCryptographyProvider cryptographyProvider = new();
string strProtected;
@@ -93,7 +93,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
strProtected = cryptographyProvider.Encrypt("ThisIsNotProtected", Runtime.EncryptionKey);
}
var cmd = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
DbCommand cmd = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
cmd.ExecuteNonQuery();
if (rootTreeNode != null)
@@ -118,9 +118,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
try
{
// ANSI SQL way. Works in PostgreSQL, MSSQL, MySQL.
var database_name = Properties.OptionsDBsPage.Default.SQLDatabaseName;
var cmd = databaseConnector.DbCommand("select case when exists((select * from information_schema.tables where table_name = '" + tableName + "' and table_schema='"+ database_name + "')) then 1 else 0 end");
var cmdResult = Convert.ToInt16(cmd.ExecuteScalar());
string database_name = Properties.OptionsDBsPage.Default.SQLDatabaseName;
DbCommand cmd = databaseConnector.DbCommand("select case when exists((select * from information_schema.tables where table_name = '" + tableName + "' and table_schema='"+ database_name + "')) then 1 else 0 end");
short cmdResult = Convert.ToInt16(cmd.ExecuteScalar());
exists = (cmdResult == 1);
}
catch

View File

@@ -34,7 +34,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement Serialize(ConnectionInfo connectionInfo)
{
var element = new XElement(XName.Get("Node", ""));
XElement element = new(XName.Get("Node", ""));
SetElementAttributes(element, connectionInfo);
SetInheritanceAttributes(element, connectionInfo);
return element;
@@ -42,7 +42,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void SetElementAttributes(XContainer element, ConnectionInfo connectionInfo)
{
var nodeAsContainer = connectionInfo as ContainerInfo;
ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo;
element.Add(new XAttribute("Name", connectionInfo.Name));
element.Add(new XAttribute("Type", connectionInfo.GetTreeNodeType().ToString()));
if (nodeAsContainer != null)
@@ -141,7 +141,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (_saveFilter.SaveInheritance)
{
var inheritance = connectionInfo.Inheritance;
ConnectionInfoInheritance inheritance = connectionInfo.Inheritance;
if (inheritance.CacheBitmaps)
element.Add(new XAttribute("InheritCacheBitmaps", inheritance.CacheBitmaps.ToString().ToLowerInvariant()));

View File

@@ -30,7 +30,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement Serialize(ConnectionInfo connectionInfo)
{
var element = new XElement(XName.Get("Node", ""));
XElement element = new(XName.Get("Node", ""));
SetElementAttributes(element, connectionInfo);
SetInheritanceAttributes(element, connectionInfo);
return element;
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void SetElementAttributes(XContainer element, ConnectionInfo connectionInfo)
{
var nodeAsContainer = connectionInfo as ContainerInfo;
ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo;
element.Add(new XAttribute("Name", connectionInfo.Name));
element.Add(new XAttribute("VmId", connectionInfo.VmId));
element.Add(new XAttribute("UseVmId", connectionInfo.UseVmId));
@@ -162,7 +162,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (_saveFilter.SaveInheritance)
{
var inheritance = connectionInfo.Inheritance;
ConnectionInfoInheritance inheritance = connectionInfo.Inheritance;
if (inheritance.CacheBitmaps)
element.Add(new XAttribute("InheritCacheBitmaps", inheritance.CacheBitmaps.ToString().ToLowerInvariant()));

View File

@@ -30,7 +30,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement Serialize(ConnectionInfo connectionInfo)
{
var element = new XElement(XName.Get("Node", ""));
XElement element = new(XName.Get("Node", ""));
SetElementAttributes(element, connectionInfo);
SetInheritanceAttributes(element, connectionInfo);
return element;
@@ -38,7 +38,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void SetElementAttributes(XContainer element, ConnectionInfo connectionInfo)
{
var nodeAsContainer = connectionInfo as ContainerInfo;
ContainerInfo nodeAsContainer = connectionInfo as ContainerInfo;
element.Add(new XAttribute("Name", connectionInfo.Name));
element.Add(new XAttribute("VmId", connectionInfo.VmId));
element.Add(new XAttribute("UseVmId", connectionInfo.UseVmId));
@@ -163,7 +163,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (!_saveFilter.SaveInheritance) return;
var inheritance = connectionInfo.Inheritance;
ConnectionInfoInheritance inheritance = connectionInfo.Inheritance;
if (inheritance.CacheBitmaps)
element.Add(new XAttribute("InheritCacheBitmaps", inheritance.CacheBitmaps.ToString().ToLowerInvariant()));

View File

@@ -16,12 +16,12 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
SaveFilter saveFilter = null,
bool useFullEncryption = false)
{
var encryptionKey = connectionTreeModel
System.Security.SecureString encryptionKey = connectionTreeModel
.RootNodes.OfType<RootNodeInfo>()
.First().PasswordString
.ConvertToSecureString();
var connectionNodeSerializer = new XmlConnectionNodeSerializer28(
XmlConnectionNodeSerializer28 connectionNodeSerializer = new(
cryptographyProvider,
encryptionKey,
saveFilter ?? new SaveFilter());

View File

@@ -23,7 +23,7 @@ using System.Runtime.Versioning;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
[SupportedOSPlatform("windows")]
public class XmlConnectionsDeserializer : IDeserializer<string, ConnectionTreeModel>
public class XmlConnectionsDeserializer(Func<Optional<SecureString>> authenticationRequestor = null) : IDeserializer<string, ConnectionTreeModel>
{
private XmlDocument _xmlDocument;
private double _confVersion;
@@ -32,12 +32,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private const double MaxSupportedConfVersion = 2.8;
private readonly RootNodeInfo _rootNodeInfo = new(RootNodeType.Connection);
public Func<Optional<SecureString>> AuthenticationRequestor { get; set; }
public XmlConnectionsDeserializer(Func<Optional<SecureString>> authenticationRequestor = null)
{
AuthenticationRequestor = authenticationRequestor;
}
public Func<Optional<SecureString>> AuthenticationRequestor { get; set; } = authenticationRequestor;
public ConnectionTreeModel Deserialize(string xml)
{
@@ -52,16 +47,16 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
LoadXmlConnectionData(xml);
ValidateConnectionFileVersion();
var rootXmlElement = _xmlDocument.DocumentElement;
XmlElement rootXmlElement = _xmlDocument.DocumentElement;
InitializeRootNode(rootXmlElement);
CreateDecryptor(_rootNodeInfo, rootXmlElement);
var connectionTreeModel = new ConnectionTreeModel();
ConnectionTreeModel connectionTreeModel = new();
connectionTreeModel.AddRootNode(_rootNodeInfo);
if (_confVersion > 1.3)
{
var protectedString = _xmlDocument.DocumentElement?.Attributes["Protected"]?.Value;
string protectedString = _xmlDocument.DocumentElement?.Attributes["Protected"]?.Value;
if (!_decryptor.ConnectionsFileIsAuthentic(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()))
{
return null;
@@ -70,10 +65,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (_confVersion >= 2.6)
{
var fullFileEncryptionValue = rootXmlElement.GetAttributeAsBool("FullFileEncryption");
bool fullFileEncryptionValue = rootXmlElement.GetAttributeAsBool("FullFileEncryption");
if (fullFileEncryptionValue)
{
var decryptedContent = _decryptor.Decrypt(rootXmlElement.InnerText);
string decryptedContent = _decryptor.Decrypt(rootXmlElement.InnerText);
rootXmlElement.InnerXml = decryptedContent;
}
}
@@ -118,28 +113,14 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void ShowIncompatibleVersionDialogBox()
{
CTaskDialog.ShowTaskDialogBox(
FrmMain.Default,
Application.ProductName,
"Incompatible connection file format",
$"The format of this connection file is not supported. Please upgrade to a newer version of {Application.ProductName}.",
string
.Format("{1}{0}File Format Version: {2}{0}Highest Supported Version: {3}",
Environment.NewLine,
ConnectionFileName, _confVersion, MaxSupportedConfVersion),
"",
"",
"",
"",
ETaskDialogButtons.Ok,
ESysIcons.Error,
ESysIcons.Error
);
CTaskDialog.ShowTaskDialogBox(FrmMain.Default, Application.ProductName, "Incompatible connection file format", $"The format of this connection file is not supported. Please upgrade to a newer version of {Application.ProductName}.",
string .Format("{1}{0}File Format Version: {2}{0}Highest Supported Version: {3}", Environment.NewLine, ConnectionFileName, _confVersion, MaxSupportedConfVersion),
"", "", "", "", ETaskDialogButtons.Ok, ESysIcons.Error, ESysIcons.Error);
}
private void InitializeRootNode(XmlElement connectionsRootElement)
{
var rootNodeName = connectionsRootElement?.Attributes["Name"]?.Value.Trim();
string rootNodeName = connectionsRootElement?.Attributes["Name"]?.Value.Trim();
_rootNodeInfo.Name = rootNodeName;
}
@@ -147,9 +128,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
if (_confVersion >= 2.6)
{
var engine = connectionsRootElement.GetAttributeAsEnum<BlockCipherEngines>("EncryptionEngine");
var mode = connectionsRootElement.GetAttributeAsEnum<BlockCipherModes>("BlockCipherMode");
var keyDerivationIterations = connectionsRootElement.GetAttributeAsInt("KdfIterations");
BlockCipherEngines engine = connectionsRootElement.GetAttributeAsEnum<BlockCipherEngines>("EncryptionEngine");
BlockCipherModes mode = connectionsRootElement.GetAttributeAsEnum<BlockCipherModes>("BlockCipherMode");
int keyDerivationIterations = connectionsRootElement.GetAttributeAsInt("KdfIterations");
_decryptor = new XmlConnectionsDecryptor(engine, mode, rootNodeInfo)
{
@@ -173,17 +154,17 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (!parentXmlNode.HasChildNodes) return;
foreach (XmlNode xmlNode in parentXmlNode.ChildNodes)
{
var nodeType = xmlNode.GetAttributeAsEnum("Type", TreeNodeType.Connection);
TreeNodeType nodeType = xmlNode.GetAttributeAsEnum("Type", TreeNodeType.Connection);
// ReSharper disable once SwitchStatementMissingSomeCases
switch (nodeType)
{
case TreeNodeType.Connection:
var connectionInfo = GetConnectionInfoFromXml(xmlNode);
ConnectionInfo connectionInfo = GetConnectionInfoFromXml(xmlNode);
parentContainer.AddChild(connectionInfo);
break;
case TreeNodeType.Container:
var containerInfo = new ContainerInfo();
ContainerInfo containerInfo = new();
if (_confVersion >= 0.9)
containerInfo.CopyFrom(GetConnectionInfoFromXml(xmlNode));
@@ -210,10 +191,10 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (xmlnode?.Attributes == null)
return null;
var connectionId = xmlnode.GetAttributeAsString("Id");
string connectionId = xmlnode.GetAttributeAsString("Id");
if (string.IsNullOrWhiteSpace(connectionId))
connectionId = Guid.NewGuid().ToString();
var connectionInfo = new ConnectionInfo(connectionId);
ConnectionInfo connectionInfo = new(connectionId);
try
{

View File

@@ -26,19 +26,19 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XDocument CompileDocument(ConnectionTreeModel connectionTreeModel, bool fullFileEncryption)
{
var rootNodeInfo = GetRootNodeFromConnectionTreeModel(connectionTreeModel);
RootNodeInfo rootNodeInfo = GetRootNodeFromConnectionTreeModel(connectionTreeModel);
return CompileDocument(rootNodeInfo, fullFileEncryption);
}
public XDocument CompileDocument(ConnectionInfo serializationTarget, bool fullFileEncryption)
{
var rootNodeInfo = GetRootNodeFromConnectionInfo(serializationTarget);
RootNodeInfo rootNodeInfo = GetRootNodeFromConnectionInfo(serializationTarget);
_encryptionKey = rootNodeInfo.PasswordString.ConvertToSecureString();
var rootElement = CompileRootNode(rootNodeInfo, fullFileEncryption);
XElement rootElement = CompileRootNode(rootNodeInfo, fullFileEncryption);
CompileRecursive(serializationTarget, rootElement);
var xmlDeclaration = new XDeclaration("1.0", "utf-8", null);
var xmlDocument = new XDocument(xmlDeclaration, rootElement);
XDeclaration xmlDeclaration = new("1.0", "utf-8", null);
XDocument xmlDocument = new(xmlDeclaration, rootElement);
if (fullFileEncryption)
xmlDocument = new XmlConnectionsDocumentEncryptor(_cryptographyProvider).EncryptDocument(xmlDocument, _encryptionKey);
return xmlDocument;
@@ -46,7 +46,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void CompileRecursive(ConnectionInfo serializationTarget, XContainer parentElement)
{
var newElement = parentElement;
XContainer newElement = parentElement;
if (serializationTarget is not RootNodeInfo)
{
newElement = CompileConnectionInfoNode(serializationTarget);
@@ -54,7 +54,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
}
if (serializationTarget is not ContainerInfo serializationTargetAsContainer) return;
foreach (var child in serializationTargetAsContainer.Children.ToArray())
foreach (ConnectionInfo child in serializationTargetAsContainer.Children.ToArray())
CompileRecursive(child, newElement);
}
@@ -74,7 +74,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private XElement CompileRootNode(RootNodeInfo rootNodeInfo, bool fullFileEncryption)
{
var rootNodeSerializer = new XmlRootNodeSerializer();
XmlRootNodeSerializer rootNodeSerializer = new();
return rootNodeSerializer.SerializeRootNodeInfo(rootNodeInfo, _cryptographyProvider, _connectionNodeSerializer.Version, fullFileEncryption);
}

View File

@@ -15,30 +15,30 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XDocument EncryptDocument(XDocument documentToEncrypt, SecureString encryptionKey)
{
var contentToEncrypt = GetContentToEncrypt(documentToEncrypt.Root);
var encryptedContent = _cryptographyProvider.Encrypt(contentToEncrypt, encryptionKey);
var encryptedDocument = ReplaceInnerXml(documentToEncrypt, encryptedContent);
string contentToEncrypt = GetContentToEncrypt(documentToEncrypt.Root);
string encryptedContent = _cryptographyProvider.Encrypt(contentToEncrypt, encryptionKey);
XDocument encryptedDocument = ReplaceInnerXml(documentToEncrypt, encryptedContent);
return encryptedDocument;
}
private string GetContentToEncrypt(XNode element)
{
var reader = element.CreateReader();
System.Xml.XmlReader reader = element.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
private XDocument ReplaceInnerXml(XDocument originalDocument, string newContent)
{
var newRootElement = ShallowCloneRootNode(originalDocument.Root);
XElement newRootElement = ShallowCloneRootNode(originalDocument.Root);
newRootElement.SetValue(newContent);
return new XDocument(newRootElement);
}
private XElement ShallowCloneRootNode(XElement originalElement)
{
var newElement = new XElement(originalElement.Name);
foreach (var attribute in originalElement.Attributes())
XElement newElement = new(originalElement.Name);
foreach (XAttribute attribute in originalElement.Attributes())
newElement.Add(new XAttribute(attribute));
return newElement;
}

View File

@@ -32,7 +32,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public string Serialize(ConnectionTreeModel connectionTreeModel)
{
var rootNode = (RootNodeInfo)connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
RootNodeInfo rootNode = (RootNodeInfo)connectionTreeModel.RootNodes.First(node => node is RootNodeInfo);
return SerializeConnectionsData(rootNode);
}
@@ -43,12 +43,12 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private string SerializeConnectionsData(ConnectionInfo serializationTarget)
{
var xml = "";
string xml = "";
try
{
var documentCompiler =
new XmlConnectionsDocumentCompiler(_cryptographyProvider, _connectionNodeSerializer);
var xmlDocument = documentCompiler.CompileDocument(serializationTarget, UseFullEncryption);
XmlConnectionsDocumentCompiler documentCompiler =
new(_cryptographyProvider, _connectionNodeSerializer);
XDocument xmlDocument = documentCompiler.CompileDocument(serializationTarget, UseFullEncryption);
xml = WriteXmlToString(xmlDocument);
}
catch (Exception ex)
@@ -62,14 +62,13 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private static string WriteXmlToString(XNode xmlDocument)
{
string xmlString;
var xmlWriterSettings = new XmlWriterSettings
{Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
var memoryStream = new MemoryStream();
using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
XmlWriterSettings xmlWriterSettings = new() { Indent = true, IndentChars = " ", Encoding = Encoding.UTF8};
MemoryStream memoryStream = new();
using (XmlWriter xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xmlDocument.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
var streamReader = new StreamReader(memoryStream, Encoding.UTF8, true);
StreamReader streamReader = new(memoryStream, Encoding.UTF8, true);
memoryStream.Seek(0, SeekOrigin.Begin);
xmlString = streamReader.ReadToEnd();
}

View File

@@ -7,28 +7,28 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
{
public static string GetAttributeAsString(this XmlNode xmlNode, string attribute, string defaultValue = "")
{
var value = xmlNode?.Attributes?[attribute]?.Value;
string value = xmlNode?.Attributes?[attribute]?.Value;
return value ?? defaultValue;
}
public static bool GetAttributeAsBool(this XmlNode xmlNode, string attribute, bool defaultValue = false)
{
var value = xmlNode?.Attributes?[attribute]?.Value;
string value = xmlNode?.Attributes?[attribute]?.Value;
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
return bool.TryParse(value, out var valueAsBool)
return bool.TryParse(value, out bool valueAsBool)
? valueAsBool
: defaultValue;
}
public static int GetAttributeAsInt(this XmlNode xmlNode, string attribute, int defaultValue = 0)
{
var value = xmlNode?.Attributes?[attribute]?.Value;
string value = xmlNode?.Attributes?[attribute]?.Value;
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
return int.TryParse(value, out var valueAsBool)
return int.TryParse(value, out int valueAsBool)
? valueAsBool
: defaultValue;
}
@@ -36,11 +36,11 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public static T GetAttributeAsEnum<T>(this XmlNode xmlNode, string attribute, T defaultValue = default)
where T : struct
{
var value = xmlNode?.Attributes?[attribute]?.Value;
string value = xmlNode?.Attributes?[attribute]?.Value;
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
return Enum.TryParse<T>(value, true, out var valueAsEnum)
return Enum.TryParse<T>(value, true, out T valueAsEnum)
? valueAsEnum
: defaultValue;
}

View File

@@ -12,7 +12,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
public XElement SerializeRootNodeInfo(RootNodeInfo rootNodeInfo, ICryptographyProvider cryptographyProvider, Version version, bool fullFileEncryption = false)
{
XNamespace xmlNamespace = "http://mremoteng.org";
var element = new XElement(xmlNamespace + "Connections");
XElement element = new(xmlNamespace + "Connections");
element.Add(new XAttribute(XNamespace.Xmlns + "mrng", xmlNamespace));
element.Add(new XAttribute(XName.Get("Name"), rootNodeInfo.Name));
element.Add(new XAttribute(XName.Get("Export"), "false"));
@@ -27,9 +27,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private XAttribute CreateProtectedAttribute(RootNodeInfo rootNodeInfo, ICryptographyProvider cryptographyProvider)
{
var attribute = new XAttribute(XName.Get("Protected"), "");
var plainText = rootNodeInfo.Password ? "ThisIsProtected" : "ThisIsNotProtected";
var encryptionPassword = rootNodeInfo.PasswordString.ConvertToSecureString();
XAttribute attribute = new(XName.Get("Protected"), "");
string plainText = rootNodeInfo.Password ? "ThisIsProtected" : "ThisIsNotProtected";
System.Security.SecureString encryptionPassword = rootNodeInfo.PasswordString.ConvertToSecureString();
attribute.Value = cryptographyProvider.Encrypt(plainText, encryptionPassword);
return attribute;
}

View File

@@ -30,9 +30,9 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer
public IEnumerable<ICredentialRepository> Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml)) return new ICredentialRepository[0];
var xdoc = XDocument.Parse(xml);
var repoEntries = xdoc.Descendants("CredentialRepository");
var xmlRepoFactory = new XmlCredentialRepositoryFactory(_serializer, _deserializer);
XDocument xdoc = XDocument.Parse(xml);
IEnumerable<XElement> repoEntries = xdoc.Descendants("CredentialRepository");
XmlCredentialRepositoryFactory xmlRepoFactory = new(_serializer, _deserializer);
return repoEntries.Select(xmlRepoFactory.Build);
}
}

View File

@@ -11,8 +11,8 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer
{
public string Serialize(IEnumerable<ICredentialRepository> credentialProviderCatalog)
{
var xmlDocument = new XDocument(new XDeclaration("1.0", "utf-8", null));
var rootElement = new XElement("CredentialRepositories",
XDocument xmlDocument = new(new XDeclaration("1.0", "utf-8", null));
XElement rootElement = new("CredentialRepositories",
from provider in credentialProviderCatalog
select new XElement("CredentialRepository",
new XAttribute("Id", provider.Config.Id),
@@ -22,8 +22,8 @@ namespace mRemoteNG.Config.Serializers.CredentialProviderSerializer
)
);
xmlDocument.Add(rootElement);
var declaration = xmlDocument.Declaration.ToString();
var documentBody = xmlDocument.ToString();
string declaration = xmlDocument.Declaration.ToString();
string documentBody = xmlDocument.ToString();
return string.Concat(declaration, Environment.NewLine, documentBody);
}
}

View File

@@ -25,21 +25,21 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
public IEnumerable<ICredentialRecord> Deserialize(string xml, SecureString key)
{
var decryptedXml = DecryptPasswords(xml, key);
string decryptedXml = DecryptPasswords(xml, key);
return _baseDeserializer.Deserialize(decryptedXml);
}
private string DecryptPasswords(string xml, SecureString key)
{
if (string.IsNullOrEmpty(xml)) return xml;
var xdoc = XDocument.Parse(xml);
var cryptoProvider = new CryptoProviderFactoryFromXml(xdoc.Root).Build();
XDocument xdoc = XDocument.Parse(xml);
ICryptographyProvider cryptoProvider = new CryptoProviderFactoryFromXml(xdoc.Root).Build();
DecryptAuthHeader(xdoc.Root, cryptoProvider, key);
foreach (var credentialElement in xdoc.Descendants())
foreach (XElement credentialElement in xdoc.Descendants())
{
var passwordAttribute = credentialElement.Attribute("Password");
XAttribute passwordAttribute = credentialElement.Attribute("Password");
if (passwordAttribute == null) continue;
var decryptedPassword = cryptoProvider.Decrypt(passwordAttribute.Value, key);
string decryptedPassword = cryptoProvider.Decrypt(passwordAttribute.Value, key);
passwordAttribute.SetValue(decryptedPassword);
}
@@ -48,7 +48,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
private void DecryptAuthHeader(XElement rootElement, ICryptographyProvider cryptographyProvider, SecureString key)
{
var authAttribute = rootElement.Attribute("Auth");
XAttribute authAttribute = rootElement.Attribute("Auth");
if (authAttribute == null)
throw new EncryptionException("Could not find Auth header in the XML repository root element.");
cryptographyProvider.Decrypt(authAttribute.Value, key);

View File

@@ -29,20 +29,20 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
if (credentialRecords == null)
throw new ArgumentNullException(nameof(credentialRecords));
var baseReturn = _baseSerializer.Serialize(credentialRecords);
var encryptedReturn = EncryptPasswordAttributes(baseReturn, key);
string baseReturn = _baseSerializer.Serialize(credentialRecords);
string encryptedReturn = EncryptPasswordAttributes(baseReturn, key);
return encryptedReturn;
}
private string EncryptPasswordAttributes(string xml, SecureString encryptionKey)
{
var xdoc = XDocument.Parse(xml);
XDocument xdoc = XDocument.Parse(xml);
SetEncryptionAttributes(xdoc, encryptionKey);
foreach (var element in xdoc.Descendants())
foreach (XElement element in xdoc.Descendants())
{
var passwordAttribute = element.Attribute("Password");
XAttribute passwordAttribute = element.Attribute("Password");
if (passwordAttribute == null) continue;
var encryptedPassword = _cryptographyProvider.Encrypt(passwordAttribute.Value, encryptionKey);
string encryptedPassword = _cryptographyProvider.Encrypt(passwordAttribute.Value, encryptionKey);
passwordAttribute.Value = encryptedPassword;
}

View File

@@ -14,11 +14,11 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
public IEnumerable<ICredentialRecord> Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml)) return new ICredentialRecord[0];
var xdoc = XDocument.Parse(xml);
var rootElement = xdoc.Root;
XDocument xdoc = XDocument.Parse(xml);
XElement rootElement = xdoc.Root;
ValidateSchemaVersion(rootElement);
var credentials = from element in xdoc.Descendants("Credential")
IEnumerable<CredentialRecord> credentials = from element in xdoc.Descendants("Credential")
select new CredentialRecord(Guid.Parse(element.Attribute("Id")?.Value ??
Guid.NewGuid().ToString()))
{
@@ -32,7 +32,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
private void ValidateSchemaVersion(XElement rootElement)
{
var docSchemaVersion = rootElement?.Attribute("SchemaVersion")?.Value;
string docSchemaVersion = rootElement?.Attribute("SchemaVersion")?.Value;
if (docSchemaVersion != SchemaVersion)
throw new Exception($"The schema version of this document is not supported by this class. Document Version: {docSchemaVersion} Supported Version: {SchemaVersion}");
}

View File

@@ -13,7 +13,7 @@ namespace mRemoteNG.Config.Serializers.CredentialSerializer
public string Serialize(IEnumerable<ICredentialRecord> credentialRecords)
{
var xdoc = new XDocument(
XDocument xdoc = new(
new XElement("Credentials",
new XAttribute("SchemaVersion", Version.ToString(2)),
from r in credentialRecords

View File

@@ -28,8 +28,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize()
{
var connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
ImportContainers(_ldapPath, root);
@@ -39,10 +39,10 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportContainers(string ldapPath, ContainerInfo parentContainer)
{
var match = Regex.Match(ldapPath, "ou=([^,]*)", RegexOptions.IgnoreCase);
var name = match.Success ? match.Groups[1].Captures[0].Value : Language.ActiveDirectory;
Match match = Regex.Match(ldapPath, "ou=([^,]*)", RegexOptions.IgnoreCase);
string name = match.Success ? match.Groups[1].Captures[0].Value : Language.ActiveDirectory;
var newContainer = new ContainerInfo {Name = name};
ContainerInfo newContainer = new() { Name = name};
parentContainer.AddChild(newContainer);
ImportComputers(ldapPath, newContainer);
@@ -53,17 +53,17 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
try
{
const string ldapFilter = "(|(objectClass=computer)(objectClass=organizationalUnit))";
using (var ldapSearcher = new DirectorySearcher())
using (DirectorySearcher ldapSearcher = new())
{
ldapSearcher.SearchRoot = new DirectoryEntry(ldapPath);
ldapSearcher.Filter = ldapFilter;
ldapSearcher.SearchScope = SearchScope.OneLevel;
ldapSearcher.PropertiesToLoad.AddRange(new[] {"securityEquals", "cn", "objectClass"});
var ldapResults = ldapSearcher.FindAll();
SearchResultCollection ldapResults = ldapSearcher.FindAll();
foreach (SearchResult ldapResult in ldapResults)
{
using (var directoryEntry = ldapResult.GetDirectoryEntry())
using (DirectoryEntry directoryEntry = ldapResult.GetDirectoryEntry())
{
if (directoryEntry.Properties["objectClass"].Contains("organizationalUnit"))
{
@@ -88,11 +88,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void DeserializeConnection(DirectoryEntry directoryEntry, ContainerInfo parentContainer)
{
var displayName = Convert.ToString(directoryEntry.Properties["cn"].Value);
var description = Convert.ToString(directoryEntry.Properties["Description"].Value);
var hostName = Convert.ToString(directoryEntry.Properties["dNSHostName"].Value);
string displayName = Convert.ToString(directoryEntry.Properties["cn"].Value);
string description = Convert.ToString(directoryEntry.Properties["Description"].Value);
string hostName = Convert.ToString(directoryEntry.Properties["dNSHostName"].Value);
var newConnectionInfo = new ConnectionInfo
ConnectionInfo newConnectionInfo = new()
{
Name = displayName,
Hostname = hostName,

View File

@@ -21,11 +21,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(IEnumerable<ScanHost> scannedHosts)
{
var connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
foreach (var host in scannedHosts)
foreach (ScanHost host in scannedHosts)
ImportScannedHost(host, root);
return connectionTreeModel;
@@ -33,8 +33,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportScannedHost(ScanHost host, ContainerInfo parentContainer)
{
var finalProtocol = default(ProtocolType);
var protocolValid = true;
ProtocolType finalProtocol = default(ProtocolType);
bool protocolValid = true;
switch (_targetProtocolType)
{
@@ -72,7 +72,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
}
if (!protocolValid) return;
var newConnectionInfo = new ConnectionInfo
ConnectionInfo newConnectionInfo = new()
{
Name = host.HostNameWithoutDomain,
Hostname = host.HostName,

View File

@@ -15,16 +15,16 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
{
public ConnectionTreeModel Deserialize(string puttycmConnectionsXml)
{
var connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
var xmlDocument = new XmlDocument();
XmlDocument xmlDocument = new();
xmlDocument.LoadXml(puttycmConnectionsXml);
var configurationNode = xmlDocument.SelectSingleNode("/configuration");
XmlNode configurationNode = xmlDocument.SelectSingleNode("/configuration");
var rootNodes = configurationNode?.SelectNodes("./root");
XmlNodeList rootNodes = configurationNode?.SelectNodes("./root");
if (rootNodes == null) return connectionTreeModel;
foreach (XmlNode rootNode in rootNodes)
{
@@ -38,9 +38,9 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
{
VerifyNodeType(xmlNode);
var newContainer = ImportContainer(xmlNode, parentContainer);
ContainerInfo newContainer = ImportContainer(xmlNode, parentContainer);
var childNodes = xmlNode.SelectNodes("./*");
XmlNodeList childNodes = xmlNode.SelectNodes("./*");
if (childNodes == null) return;
foreach (XmlNode childNode in childNodes)
{
@@ -60,7 +60,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void VerifyNodeType(XmlNode xmlNode)
{
var xmlNodeType = xmlNode?.Attributes?["type"].Value;
string xmlNodeType = xmlNode?.Attributes?["type"].Value;
switch (xmlNode?.Name)
{
case "root":
@@ -86,7 +86,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ContainerInfo ImportContainer(XmlNode containerNode, ContainerInfo parentContainer)
{
var containerInfo = new ContainerInfo
ContainerInfo containerInfo = new()
{
Name = containerNode.Attributes?["name"].Value,
IsExpanded = bool.Parse(containerNode.Attributes?["expanded"].InnerText ?? "false")
@@ -97,22 +97,22 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportConnection(XmlNode connectionNode, ContainerInfo parentContainer)
{
var connectionNodeType = connectionNode.Attributes?["type"].Value;
string connectionNodeType = connectionNode.Attributes?["type"].Value;
if (string.Compare(connectionNodeType, "PuTTY", StringComparison.OrdinalIgnoreCase) != 0)
throw (new FileFormatException($"Unrecognized connection node type ({connectionNodeType})."));
var connectionInfo = ConnectionInfoFromXml(connectionNode);
ConnectionInfo connectionInfo = ConnectionInfoFromXml(connectionNode);
parentContainer.AddChild(connectionInfo);
}
private ConnectionInfo ConnectionInfoFromXml(XmlNode xmlNode)
{
var connectionInfoNode = xmlNode.SelectSingleNode("./connection_info");
XmlNode connectionInfoNode = xmlNode.SelectSingleNode("./connection_info");
var name = connectionInfoNode?.SelectSingleNode("./name")?.InnerText;
var connectionInfo = new ConnectionInfo {Name = name};
string name = connectionInfoNode?.SelectSingleNode("./name")?.InnerText;
ConnectionInfo connectionInfo = new() { Name = name};
var protocol = connectionInfoNode?.SelectSingleNode("./protocol")?.InnerText;
string protocol = connectionInfoNode?.SelectSingleNode("./protocol")?.InnerText;
switch (protocol?.ToLowerInvariant())
{
case "telnet":
@@ -131,7 +131,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
// ./commandline
connectionInfo.Description = connectionInfoNode.SelectSingleNode("./description")?.InnerText;
var loginNode = xmlNode.SelectSingleNode("./login");
XmlNode loginNode = xmlNode.SelectSingleNode("./login");
connectionInfo.Username = loginNode?.SelectSingleNode("login")?.InnerText;
connectionInfo.Password = loginNode?.SelectSingleNode("password")?.InnerText;
// ./prompt

View File

@@ -14,20 +14,20 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(string rdcFileContent)
{
var connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
var connectionInfo = new ConnectionInfo();
foreach (var line in rdcFileContent.Split(Environment.NewLine.ToCharArray()))
ConnectionInfo connectionInfo = new();
foreach (string line in rdcFileContent.Split(Environment.NewLine.ToCharArray()))
{
var parts = line.Split(new[] { ':' }, 3);
string[] parts = line.Split(new[] { ':' }, 3);
if (parts.Length < 3)
{
continue;
}
var key = parts[0].Trim();
var value = parts[2].Trim();
string key = parts[0].Trim();
string value = parts[2].Trim();
SetConnectionInfoParameter(connectionInfo, key, value);
}
@@ -43,7 +43,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
switch (key.ToLower())
{
case "full address":
var uri = new Uri("dummyscheme" + Uri.SchemeDelimiter + value);
Uri uri = new("dummyscheme" + Uri.SchemeDelimiter + value);
if (!string.IsNullOrEmpty(uri.Host))
connectionInfo.Hostname = uri.Host;
if (uri.Port != -1)

View File

@@ -22,18 +22,18 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(string rdcmConnectionsXml)
{
var connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo root = new(RootNodeType.Connection);
var xmlDocument = new XmlDocument();
XmlDocument xmlDocument = new();
xmlDocument.LoadXml(rdcmConnectionsXml);
var rdcManNode = xmlDocument.SelectSingleNode("/RDCMan");
XmlNode rdcManNode = xmlDocument.SelectSingleNode("/RDCMan");
VerifySchemaVersion(rdcManNode);
VerifyFileVersion(rdcManNode);
var fileNode = rdcManNode?.SelectSingleNode("./file");
XmlNode fileNode = rdcManNode?.SelectSingleNode("./file");
ImportFileOrGroup(fileNode, root);
connectionTreeModel.AddRootNode(root);
@@ -42,7 +42,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void VerifySchemaVersion(XmlNode rdcManNode)
{
if (!int.TryParse(rdcManNode?.Attributes?["schemaVersion"]?.Value, out var version))
if (!int.TryParse(rdcManNode?.Attributes?["schemaVersion"]?.Value, out int version))
throw new FileFormatException("Could not find schema version attribute.");
if (version != 1 && version != 3)
@@ -55,10 +55,10 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void VerifyFileVersion(XmlNode rdcManNode)
{
var versionAttribute = rdcManNode?.Attributes?["programVersion"]?.Value;
string versionAttribute = rdcManNode?.Attributes?["programVersion"]?.Value;
if (versionAttribute != null)
{
var version = new Version(versionAttribute);
Version version = new(versionAttribute);
if (!(version == new Version(2, 7)) && !(version == new Version(2, 83)))
{
throw new FileFormatException($"Unsupported file version ({version}).");
@@ -66,10 +66,10 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
}
else
{
var versionNode = rdcManNode?.SelectSingleNode("./version")?.InnerText;
string versionNode = rdcManNode?.SelectSingleNode("./version")?.InnerText;
if (versionNode != null)
{
var version = new Version(versionNode);
Version version = new(versionNode);
if (!(version == new Version(2, 2)))
{
throw new FileFormatException($"Unsupported file version ({version}).");
@@ -84,9 +84,9 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void ImportFileOrGroup(XmlNode xmlNode, ContainerInfo parentContainer)
{
var newContainer = ImportContainer(xmlNode, parentContainer);
ContainerInfo newContainer = ImportContainer(xmlNode, parentContainer);
var childNodes = xmlNode.SelectNodes("./group|./server");
XmlNodeList childNodes = xmlNode.SelectNodes("./group|./server");
if (childNodes == null) return;
foreach (XmlNode childNode in childNodes)
{
@@ -111,8 +111,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
containerPropertiesNode = containerPropertiesNode.SelectSingleNode("./properties");
}
var newContainer = new ContainerInfo();
var connectionInfo = ConnectionInfoFromXml(containerPropertiesNode);
ContainerInfo newContainer = new();
ConnectionInfo connectionInfo = ConnectionInfoFromXml(containerPropertiesNode);
newContainer.CopyFrom(connectionInfo);
if (_schemaVersion == 3)
@@ -121,7 +121,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
containerPropertiesNode = containerPropertiesNode.SelectSingleNode("./properties");
}
newContainer.Name = containerPropertiesNode?.SelectSingleNode("./name")?.InnerText ?? Language.NewFolder;
if (bool.TryParse(containerPropertiesNode?.SelectSingleNode("./expanded")?.InnerText, out var expanded))
if (bool.TryParse(containerPropertiesNode?.SelectSingleNode("./expanded")?.InnerText, out bool expanded))
newContainer.IsExpanded = expanded;
parentContainer.AddChild(newContainer);
return newContainer;
@@ -129,15 +129,15 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private static void ImportServer(XmlNode serverNode, ContainerInfo parentContainer)
{
var newConnectionInfo = ConnectionInfoFromXml(serverNode);
ConnectionInfo newConnectionInfo = ConnectionInfoFromXml(serverNode);
parentContainer.AddChild(newConnectionInfo);
}
private static ConnectionInfo ConnectionInfoFromXml(XmlNode xmlNode)
{
var connectionInfo = new ConnectionInfo {Protocol = ProtocolType.RDP};
ConnectionInfo connectionInfo = new() { Protocol = ProtocolType.RDP};
var propertiesNode = xmlNode.SelectSingleNode("./properties");
XmlNode propertiesNode = xmlNode.SelectSingleNode("./properties");
if (_schemaVersion == 1)
propertiesNode = xmlNode; // Version 2.2 defines the container name at the root instead
@@ -145,7 +145,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Hostname = propertiesNode?.SelectSingleNode("./name")?.InnerText ?? "";
var connectionDisplayName = propertiesNode?.SelectSingleNode("./displayName")?.InnerText;
string connectionDisplayName = propertiesNode?.SelectSingleNode("./displayName")?.InnerText;
connectionInfo.Name = !string.IsNullOrWhiteSpace(connectionDisplayName)
? connectionDisplayName
: string.IsNullOrWhiteSpace(connectionInfo.Hostname)
@@ -154,12 +154,12 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Description = propertiesNode?.SelectSingleNode("./comment")?.InnerText ?? string.Empty;
var logonCredentialsNode = xmlNode.SelectSingleNode("./logonCredentials");
XmlNode logonCredentialsNode = xmlNode.SelectSingleNode("./logonCredentials");
if (logonCredentialsNode?.Attributes?["inherit"]?.Value == "None")
{
connectionInfo.Username = logonCredentialsNode.SelectSingleNode("userName")?.InnerText ?? string.Empty;
var passwordNode = logonCredentialsNode.SelectSingleNode("./password");
XmlNode passwordNode = logonCredentialsNode.SelectSingleNode("./password");
if (_schemaVersion == 1) // Version 2.2 allows clear text passwords
{
connectionInfo.Password = passwordNode?.Attributes?["storeAsClearText"]?.Value == "True"
@@ -180,14 +180,14 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.Domain = true;
}
var connectionSettingsNode = xmlNode.SelectSingleNode("./connectionSettings");
XmlNode connectionSettingsNode = xmlNode.SelectSingleNode("./connectionSettings");
if (connectionSettingsNode?.Attributes?["inherit"]?.Value == "None")
{
if (bool.TryParse(connectionSettingsNode.SelectSingleNode("./connectToConsole")?.InnerText, out var useConsole))
if (bool.TryParse(connectionSettingsNode.SelectSingleNode("./connectToConsole")?.InnerText, out bool useConsole))
connectionInfo.UseConsoleSession = useConsole;
connectionInfo.RDPStartProgram = connectionSettingsNode.SelectSingleNode("./startProgram")?.InnerText ?? string.Empty;
connectionInfo.RDPStartProgramWorkDir = connectionSettingsNode.SelectSingleNode("./startProgramWorkDir")?.InnerText ?? string.Empty;
if (int.TryParse(connectionSettingsNode.SelectSingleNode("./port")?.InnerText, out var port))
if (int.TryParse(connectionSettingsNode.SelectSingleNode("./port")?.InnerText, out int port))
connectionInfo.Port = port;
}
else
@@ -196,7 +196,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.Port = true;
}
var gatewaySettingsNode = xmlNode.SelectSingleNode("./gatewaySettings");
XmlNode gatewaySettingsNode = xmlNode.SelectSingleNode("./gatewaySettings");
if (gatewaySettingsNode?.Attributes?["inherit"]?.Value == "None")
{
connectionInfo.RDGatewayUsageMethod =
@@ -206,7 +206,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.RDGatewayHostname = gatewaySettingsNode.SelectSingleNode("./hostName")?.InnerText ?? string.Empty;
connectionInfo.RDGatewayUsername = gatewaySettingsNode.SelectSingleNode("./userName")?.InnerText ?? string.Empty;
var passwordNode = gatewaySettingsNode.SelectSingleNode("./password");
XmlNode passwordNode = gatewaySettingsNode.SelectSingleNode("./password");
connectionInfo.RDGatewayPassword = passwordNode?.Attributes?["storeAsClearText"]?.Value == "True"
? passwordNode.InnerText
: DecryptRdcManPassword(passwordNode?.InnerText);
@@ -225,11 +225,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.RDGatewayDomain = true;
}
var remoteDesktopNode = xmlNode.SelectSingleNode("./remoteDesktop");
XmlNode remoteDesktopNode = xmlNode.SelectSingleNode("./remoteDesktop");
if (remoteDesktopNode?.Attributes?["inherit"]?.Value == "None")
{
connectionInfo.Resolution =
Enum.TryParse<RDPResolutions>(remoteDesktopNode.SelectSingleNode("./size")?.InnerText.Replace(" ", ""), true, out var rdpResolution)
Enum.TryParse<RDPResolutions>(remoteDesktopNode.SelectSingleNode("./size")?.InnerText.Replace(" ", ""), true, out RDPResolutions rdpResolution)
? rdpResolution
: RDPResolutions.FitToWindow;
@@ -243,7 +243,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Resolution = RDPResolutions.Fullscreen;
}
if (Enum.TryParse<RDPColors>(remoteDesktopNode.SelectSingleNode("./colorDepth")?.InnerText, true, out var rdpColors))
if (Enum.TryParse<RDPColors>(remoteDesktopNode.SelectSingleNode("./colorDepth")?.InnerText, true, out RDPColors rdpColors))
connectionInfo.Colors = rdpColors;
}
else
@@ -252,7 +252,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.Colors = true;
}
var localResourcesNode = xmlNode.SelectSingleNode("./localResources");
XmlNode localResourcesNode = xmlNode.SelectSingleNode("./localResources");
if (localResourcesNode?.Attributes?["inherit"]?.Value == "None")
{
// ReSharper disable once SwitchStatementMissingSomeCases
@@ -293,19 +293,19 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
}
// ./redirectClipboard
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectDrives")?.InnerText, out var redirectDisks))
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectDrives")?.InnerText, out bool redirectDisks))
connectionInfo.RedirectDiskDrives = redirectDisks ? RDPDiskDrives.Local : RDPDiskDrives.None;
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPorts")?.InnerText, out var redirectPorts))
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPorts")?.InnerText, out bool redirectPorts))
connectionInfo.RedirectPorts = redirectPorts;
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPrinters")?.InnerText, out var redirectPrinters))
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectPrinters")?.InnerText, out bool redirectPrinters))
connectionInfo.RedirectPrinters = redirectPrinters;
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectSmartCards")?.InnerText, out var redirectSmartCards))
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectSmartCards")?.InnerText, out bool redirectSmartCards))
connectionInfo.RedirectSmartCards = redirectSmartCards;
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectClipboard")?.InnerText, out var redirectClipboard))
if (bool.TryParse(localResourcesNode?.SelectSingleNode("./redirectClipboard")?.InnerText, out bool redirectClipboard))
connectionInfo.RedirectClipboard = redirectClipboard;
}
else
@@ -319,7 +319,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
connectionInfo.Inheritance.RedirectClipboard = true;
}
var securitySettingsNode = xmlNode.SelectSingleNode("./securitySettings");
XmlNode securitySettingsNode = xmlNode.SelectSingleNode("./securitySettings");
if (securitySettingsNode?.Attributes?["inherit"]?.Value == "None")
{
// ReSharper disable once SwitchStatementMissingSomeCases
@@ -358,9 +358,9 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
try
{
var plaintextData = ProtectedData.Unprotect(Convert.FromBase64String(ciphertext), new byte[] { },
byte[] plaintextData = ProtectedData.Unprotect(Convert.FromBase64String(ciphertext), new byte[] { },
DataProtectionScope.LocalMachine);
var charArray = Encoding.Unicode.GetChars(plaintextData);
char[] charArray = Encoding.Unicode.GetChars(plaintextData);
return new string(charArray);
}
catch (Exception /*ex*/)

View File

@@ -18,14 +18,14 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
public ConnectionTreeModel Deserialize(string content)
{
var connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
ConnectionTreeModel connectionTreeModel = new();
RootNodeInfo root = new(RootNodeType.Connection);
connectionTreeModel.AddRootNode(root);
var xmlDocument = new XmlDocument();
XmlDocument xmlDocument = new();
xmlDocument.LoadXml(content);
var sessionsNode = xmlDocument.SelectSingleNode("/VanDyke/key[@name=\"Sessions\"]");
XmlNode sessionsNode = xmlDocument.SelectSingleNode("/VanDyke/key[@name=\"Sessions\"]");
ImportRootOrContainer(sessionsNode, root);
@@ -34,17 +34,17 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportRootOrContainer(XmlNode rootNode, ContainerInfo parentContainer)
{
var newContainer = ImportContainer(rootNode, parentContainer);
ContainerInfo newContainer = ImportContainer(rootNode, parentContainer);
if (rootNode.ChildNodes.Count == 0)
return;
foreach (XmlNode child in rootNode.ChildNodes)
{
var name = child.Attributes["name"].Value;
string name = child.Attributes["name"].Value;
if (name == "Default" || name == "Default_LocalShell")
continue;
var nodeType = GetFolderOrSession(child);
SecureCRTNodeType nodeType = GetFolderOrSession(child);
switch (nodeType)
{
case SecureCRTNodeType.folder:
@@ -59,7 +59,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private void ImportConnection(XmlNode childNode, ContainerInfo parentContainer)
{
var connectionInfo = ConnectionInfoFromXml(childNode);
ConnectionInfo connectionInfo = ConnectionInfoFromXml(childNode);
if (connectionInfo == null)
return;
@@ -68,7 +68,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ContainerInfo ImportContainer(XmlNode containerNode, ContainerInfo parentContainer)
{
var containerInfo = new ContainerInfo
ContainerInfo containerInfo = new()
{
Name = containerNode.Attributes["name"].InnerText
};
@@ -86,7 +86,7 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ConnectionInfo ConnectionInfoFromXml(XmlNode xmlNode)
{
var connectionInfo = new ConnectionInfo();
ConnectionInfo connectionInfo = new();
try
{
connectionInfo.Name = xmlNode.Attributes["name"].InnerText;
@@ -131,11 +131,11 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private ProtocolType GetProtocolFromNode(XmlNode xmlNode)
{
var protocolNode = xmlNode.SelectSingleNode("string[@name=\"Protocol Name\"]");
XmlNode protocolNode = xmlNode.SelectSingleNode("string[@name=\"Protocol Name\"]");
if (protocolNode == null)
throw new FileFormatException($"Protocol node not found");
var protocolText = protocolNode.InnerText.ToUpper();
string protocolText = protocolNode.InnerText.ToUpper();
switch (protocolText)
{
case "RDP":
@@ -157,8 +157,8 @@ namespace mRemoteNG.Config.Serializers.MiscSerializers
private string GetDescriptionFromNode(XmlNode xmlNode)
{
var description = string.Empty;
var descNode = xmlNode.SelectSingleNode("array[@name=\"Description\"]");
string description = string.Empty;
XmlNode descNode = xmlNode.SelectSingleNode("array[@name=\"Description\"]");
foreach(XmlNode n in descNode.ChildNodes)
{
description += n.InnerText + " ";

View File

@@ -11,7 +11,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlDatabaseVersionVerifier
{
private readonly Version _currentSupportedVersion = new Version(3, 0);
private readonly Version _currentSupportedVersion = new(3, 0);
private readonly IDatabaseConnector _databaseConnector;
@@ -31,7 +31,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
return true;
}
var dbUpgraders = new IVersionUpgrader[]
IVersionUpgrader[] dbUpgraders = new IVersionUpgrader[]
{
new SqlVersion22To23Upgrader(_databaseConnector),
new SqlVersion23To24Upgrader(_databaseConnector),

View File

@@ -32,7 +32,7 @@ ADD EnableFontSmoothing bit NOT NULL DEFAULT 0,
InheritEnableFontSmoothing bit NOT NULL DEFAULT 0,
InheritEnableDesktopComposition bit NOT NULL DEFAULT 0;";
var dbCommand = _databaseConnector.DbCommand(sqlText);
System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();

View File

@@ -30,7 +30,7 @@ ALTER TABLE tblCons
ADD UseCredSsp bit NOT NULL DEFAULT 1,
InheritUseCredSsp bit NOT NULL DEFAULT 0;";
var dbCommand = _databaseConnector.DbCommand(sqlText);
System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();

View File

@@ -31,7 +31,7 @@ ADD LoadBalanceInfo varchar (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
AutomaticResize bit NOT NULL DEFAULT 1,
InheritLoadBalanceInfo bit NOT NULL DEFAULT 0,
InheritAutomaticResize bit NOT NULL DEFAULT 0;";
var dbCommand = _databaseConnector.DbCommand(sqlText);
System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
return new Version(2, 5);

View File

@@ -35,7 +35,7 @@ ADD RDPMinutesToIdleTimeout int NOT NULL DEFAULT 0,
InheritSoundQuality bit NOT NULL DEFAULT 0;
UPDATE tblRoot
SET ConfVersion='2.6'";
var dbCommand = _databaseConnector.DbCommand(sqlText);
System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
return new Version(2, 6);

View File

@@ -44,7 +44,7 @@ ADD RedirectClipboard bit NOT NULL,
InheritUseEnhancedMode bit NOT NULL;
UPDATE tblRoot
SET ConfVersion='2.7'";
var dbCommand = _databaseConnector.DbCommand(sqlText);
System.Data.Common.DbCommand dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
}
catch (SqlException)

View File

@@ -10,7 +10,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlVersion28To29Upgrader : IVersionUpgrader
{
private readonly Version _version = new Version(2, 9);
private readonly Version _version = new(2, 9);
private readonly IDatabaseConnector _databaseConnector;
public SqlVersion28To29Upgrader(IDatabaseConnector databaseConnector)
@@ -91,7 +91,7 @@ ALTER TABLE tblRoot ALTER COLUMN [ConfVersion] VARCHAR(15) NOT NULL;
const string msSqlUpdate = @"UPDATE tblRoot SET ConfVersion=@confVersion;";
using (var sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
using (DbTransaction sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
{
DbCommand dbCommand;
if (_databaseConnector.GetType() == typeof(MSSqlDatabaseConnector))
@@ -114,7 +114,7 @@ ALTER TABLE tblRoot ALTER COLUMN [ConfVersion] VARCHAR(15) NOT NULL;
{
throw new Exception("Unknown database back-end");
}
var pConfVersion = dbCommand.CreateParameter();
DbParameter pConfVersion = dbCommand.CreateParameter();
pConfVersion.ParameterName = "confVersion";
pConfVersion.Value = _version.ToString();
pConfVersion.DbType = System.Data.DbType.String;

View File

@@ -10,7 +10,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlVersion29To30Upgrader : IVersionUpgrader
{
private readonly Version _version = new Version(3, 0);
private readonly Version _version = new(3, 0);
private readonly IDatabaseConnector _databaseConnector;
public SqlVersion29To30Upgrader(IDatabaseConnector databaseConnector)
@@ -157,7 +157,7 @@ ALTER TABLE tblCons ADD `UserViaAPI` varchar(512) NOT NULL;
const string msSqlUpdate = @"UPDATE tblRoot SET ConfVersion=@confVersion;";
using (var sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
using (DbTransaction sqlTran = _databaseConnector.DbConnection().BeginTransaction(System.Data.IsolationLevel.Serializable))
{
DbCommand dbCommand;
if (_databaseConnector.GetType() == typeof(MSSqlDatabaseConnector))
@@ -180,7 +180,7 @@ ALTER TABLE tblCons ADD `UserViaAPI` varchar(512) NOT NULL;
{
throw new Exception("Unknown database back-end");
}
var pConfVersion = dbCommand.CreateParameter();
DbParameter pConfVersion = dbCommand.CreateParameter();
pConfVersion.ParameterName = "confVersion";
pConfVersion.Value = _version.ToString();
pConfVersion.DbType = System.Data.DbType.String;

View File

@@ -49,7 +49,7 @@ namespace mRemoteNG.Config.Serializers
if (string.IsNullOrEmpty(xml)) return "";
if (xml.Contains("<?xml version=\"1.0\" encoding=\"utf-8\"?>")) return xml;
var decryptedContent = "";
string decryptedContent = "";
bool notDecr;
try
@@ -84,7 +84,7 @@ namespace mRemoteNG.Config.Serializers
public bool ConnectionsFileIsAuthentic(string protectedString, SecureString password)
{
var connectionsFileIsNotEncrypted = false;
bool connectionsFileIsNotEncrypted = false;
try
{
connectionsFileIsNotEncrypted = _cryptographyProvider.Decrypt(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()) == "ThisIsNotProtected";
@@ -98,8 +98,8 @@ namespace mRemoteNG.Config.Serializers
private bool Authenticate(string cipherText, SecureString password)
{
var authenticator = new PasswordAuthenticator(_cryptographyProvider, cipherText, AuthenticationRequestor);
var authenticated = authenticator.Authenticate(password);
PasswordAuthenticator authenticator = new(_cryptographyProvider, cipherText, AuthenticationRequestor);
bool authenticated = authenticator.Authenticate(password);
if (!authenticated)
return false;

View File

@@ -33,15 +33,15 @@ namespace mRemoteNG.Config.Settings
{
while (_mainForm.pnlDock.Contents.Count > 0)
{
var dc = (DockContent)_mainForm.pnlDock.Contents[0];
DockContent dc = (DockContent)_mainForm.pnlDock.Contents[0];
dc.Close();
}
#if !PORTABLE
var oldPath =
string oldPath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\" + GeneralAppInfo.ProductName + "\\" + SettingsFileInfo.LayoutFileName;
#endif
var newPath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
string newPath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
if (File.Exists(newPath))
{
_mainForm.pnlDock.LoadFromXml(newPath, GetContentFromPersistString);

View File

@@ -37,7 +37,7 @@ namespace mRemoteNG.Config.Settings
Directory.CreateDirectory(SettingsFileInfo.SettingsPath);
}
var serializedLayout = _dockPanelSerializer.Serialize(FrmMain.Default.pnlDock);
string serializedLayout = _dockPanelSerializer.Serialize(FrmMain.Default.pnlDock);
_dataProvider.Save(serializedLayout);
}
catch (Exception ex)

View File

@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.Settings
throw new ArgumentNullException(nameof(dockPanel));
XDocument xdoc;
using (var memoryStream = new MemoryStream())
using (MemoryStream memoryStream = new())
{
dockPanel.SaveAsXml(memoryStream, Encoding.UTF8);
memoryStream.Position = 0;

View File

@@ -36,11 +36,11 @@ namespace mRemoteNG.Config.Settings
public void LoadExternalAppsFromXML()
{
#if !PORTABLE
var oldPath =
string oldPath =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GeneralAppInfo.ProductName, SettingsFileInfo.ExtAppsFilesName);
#endif
var newPath = Path.Combine(SettingsFileInfo.SettingsPath, SettingsFileInfo.ExtAppsFilesName);
var xDom = new XmlDocument();
string newPath = Path.Combine(SettingsFileInfo.SettingsPath, SettingsFileInfo.ExtAppsFilesName);
XmlDocument xDom = new();
if (File.Exists(newPath))
{
_messageCollector.AddMessage(MessageClass.InformationMsg, $"Loading External Apps from: {newPath}",
@@ -69,7 +69,7 @@ namespace mRemoteNG.Config.Settings
foreach (XmlElement xEl in xDom.DocumentElement.ChildNodes)
{
var extA = new ExternalTool
ExternalTool extA = new()
{
DisplayName = xEl.Attributes["DisplayName"].Value,
FileName = xEl.Attributes["FileName"].Value,

View File

@@ -22,8 +22,8 @@ namespace mRemoteNG.Config.Settings
Directory.CreateDirectory(SettingsFileInfo.SettingsPath);
}
var xmlTextWriter =
new XmlTextWriter(SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.ExtAppsFilesName,
XmlTextWriter xmlTextWriter =
new(SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.ExtAppsFilesName,
Encoding.UTF8)
{
Formatting = Formatting.Indented,
@@ -33,7 +33,7 @@ namespace mRemoteNG.Config.Settings
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("Apps");
foreach (var extA in externalTools)
foreach (ExternalTool extA in externalTools)
{
xmlTextWriter.WriteStartElement("App");
xmlTextWriter.WriteAttributeString("DisplayName", "", extA.DisplayName);

View File

@@ -115,7 +115,7 @@ namespace mRemoteNG.Config.Settings.Providers
public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context,
SettingsPropertyCollection collection)
{
var values = new SettingsPropertyValueCollection();
SettingsPropertyValueCollection values = new();
foreach (SettingsProperty property in collection)
{
@@ -130,9 +130,9 @@ namespace mRemoteNG.Config.Settings.Providers
private void SetValue(SettingsPropertyValue propertyValue)
{
var targetNode = IsGlobal(propertyValue.Property) ? _globalSettingsNode : _localSettingsNode;
XmlNode targetNode = IsGlobal(propertyValue.Property) ? _globalSettingsNode : _localSettingsNode;
var settingNode = targetNode.SelectSingleNode($"setting[@name='{propertyValue.Name}']");
XmlNode settingNode = targetNode.SelectSingleNode($"setting[@name='{propertyValue.Name}']");
if (settingNode != null)
settingNode.InnerText = propertyValue.SerializedValue.ToString();
@@ -140,7 +140,7 @@ namespace mRemoteNG.Config.Settings.Providers
{
settingNode = _rootDocument.CreateElement("setting");
var nameAttribute = _rootDocument.CreateAttribute("name");
XmlAttribute nameAttribute = _rootDocument.CreateAttribute("name");
nameAttribute.Value = propertyValue.Name;
settingNode.Attributes?.Append(nameAttribute);
@@ -152,8 +152,8 @@ namespace mRemoteNG.Config.Settings.Providers
private string GetValue(SettingsProperty property)
{
var targetNode = IsGlobal(property) ? _globalSettingsNode : _localSettingsNode;
var settingNode = targetNode.SelectSingleNode($"setting[@name='{property.Name}']");
XmlNode targetNode = IsGlobal(property) ? _globalSettingsNode : _localSettingsNode;
XmlNode settingNode = targetNode.SelectSingleNode($"setting[@name='{property.Name}']");
if (settingNode == null)
return property.DefaultValue != null ? property.DefaultValue.ToString() : string.Empty;
@@ -174,7 +174,7 @@ namespace mRemoteNG.Config.Settings.Providers
private XmlNode GetSettingsNode(string name)
{
var settingsNode = _rootNode.SelectSingleNode(name);
XmlNode settingsNode = _rootNode.SelectSingleNode(name);
if (settingsNode != null) return settingsNode;
settingsNode = _rootDocument.CreateElement(name);
@@ -185,7 +185,7 @@ namespace mRemoteNG.Config.Settings.Providers
private static XmlDocument GetBlankXmlDocument()
{
var blankXmlDocument = new XmlDocument();
XmlDocument blankXmlDocument = new();
blankXmlDocument.AppendChild(blankXmlDocument.CreateXmlDeclaration("1.0", "utf-8", string.Empty));
blankXmlDocument.AppendChild(blankXmlDocument.CreateElement(_rootNodeName));

View File

@@ -108,8 +108,8 @@ namespace mRemoteNG.Config.Settings
// Make sure the form is visible on the screen
const int minHorizontal = 300;
const int minVertical = 150;
var screenBounds = Screen.FromHandle(MainForm.Handle).Bounds;
var newBounds = MainForm.Bounds;
Rectangle screenBounds = Screen.FromHandle(MainForm.Handle).Bounds;
Rectangle newBounds = MainForm.Bounds;
if (newBounds.Right < screenBounds.Left + minHorizontal)
newBounds.X = screenBounds.Left + minHorizontal - newBounds.Width;
@@ -198,7 +198,7 @@ namespace mRemoteNG.Config.Settings
/// </summary>
private void ResetAllToolbarLocations()
{
var tempToolStrip = new ToolStripPanel();
ToolStripPanel tempToolStrip = new();
tempToolStrip.Join(_mainMenu);
tempToolStrip.Join(_quickConnectToolStrip);
tempToolStrip.Join(_externalToolsToolStrip);
@@ -208,7 +208,7 @@ namespace mRemoteNG.Config.Settings
private void AddMainMenuPanel()
{
SetToolstripGripStyle(_mainMenu);
var toolStripPanel = ToolStripPanelFromString("top");
ToolStripPanel toolStripPanel = ToolStripPanelFromString("top");
toolStripPanel.Join(_mainMenu, new Point(3, 0));
}
@@ -216,7 +216,7 @@ namespace mRemoteNG.Config.Settings
{
SetToolstripGripStyle(_quickConnectToolStrip);
_quickConnectToolStrip.Visible = Properties.Settings.Default.QuickyTBVisible;
var toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.QuickyTBParentDock);
ToolStripPanel toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.QuickyTBParentDock);
toolStripPanel.Join(_quickConnectToolStrip, Properties.Settings.Default.QuickyTBLocation);
}
@@ -224,7 +224,7 @@ namespace mRemoteNG.Config.Settings
{
SetToolstripGripStyle(_externalToolsToolStrip);
_externalToolsToolStrip.Visible = Properties.Settings.Default.ExtAppsTBVisible;
var toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.ExtAppsTBParentDock);
ToolStripPanel toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.ExtAppsTBParentDock);
toolStripPanel.Join(_externalToolsToolStrip, Properties.Settings.Default.ExtAppsTBLocation);
}
@@ -232,7 +232,7 @@ namespace mRemoteNG.Config.Settings
{
SetToolstripGripStyle(_multiSshToolStrip);
_multiSshToolStrip.Visible = Properties.Settings.Default.MultiSshToolbarVisible;
var toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.MultiSshToolbarParentDock);
ToolStripPanel toolStripPanel = ToolStripPanelFromString(Properties.Settings.Default.MultiSshToolbarParentDock);
toolStripPanel.Join(_multiSshToolStrip, Properties.Settings.Default.MultiSshToolbarLocation);
}

View File

@@ -17,7 +17,7 @@ namespace mRemoteNG.Config.Settings
{
try
{
var windowPlacement = new WindowPlacement(FrmMain.Default);
WindowPlacement windowPlacement = new(FrmMain.Default);
if (frmMain.WindowState == FormWindowState.Minimized & windowPlacement.RestoreToMaximized)
{
frmMain.Opacity = 0;
@@ -110,8 +110,8 @@ namespace mRemoteNG.Config.Settings
private static void SaveDockPanelLayout()
{
var panelLayoutXmlFilePath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
var panelLayoutSaver = new DockPanelLayoutSaver(
string panelLayoutXmlFilePath = SettingsFileInfo.SettingsPath + "\\" + SettingsFileInfo.LayoutFileName;
DockPanelLayoutSaver panelLayoutSaver = new(
new DockPanelLayoutSerializer(),
new FileDataProvider(panelLayoutXmlFilePath)
);
@@ -120,7 +120,7 @@ namespace mRemoteNG.Config.Settings
private static void SaveExternalApps()
{
var externalAppsSaver = new ExternalAppsSaver();
ExternalAppsSaver externalAppsSaver = new();
externalAppsSaver.Save(Runtime.ExternalToolsService.ExternalTools);
}
}

View File

@@ -128,8 +128,8 @@ namespace mRemoteNG.Connection
LocalizedAttributes.LocalizedDescription(nameof(Language.PropertyDescriptionDescription))]
public virtual string Description
{
get => GetPropertyValue("Description", _description);
set => SetField(ref _description, value, "Description");
get => GetPropertyValue(nameof(Description), _description);
set => SetField(ref _description, value, nameof(Description));
}
[LocalizedAttributes.LocalizedCategory(nameof(Language.Display)),

Some files were not shown because too many files have changed in this diff Show More