Merge pull request #2399 from BlueBlock/fix_database_use

Fix database use
This commit is contained in:
Dimitrij
2023-03-23 22:01:40 +00:00
committed by GitHub
66 changed files with 5022 additions and 4708 deletions

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(2, 9);
public static readonly Version ConnectionFileVersion = new Version(3, 0);
}
}

View File

@@ -105,7 +105,7 @@ namespace mRemoteNG.App
if (Properties.OptionsDBsPage.Default.UseSQLServer)
{
ConnectionsService.LastSqlUpdate = DateTime.Now;
ConnectionsService.LastSqlUpdate = DateTime.Now.ToUniversalTime();
}
else
{

View File

@@ -51,9 +51,7 @@ namespace mRemoteNG.Config.Connections.Multiuser
}
catch (Exception e)
{
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg,
"Unable to connect to Sql DB to check for updates." +
Environment.NewLine + e.Message, true);
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, $"Unable to connect to SQL DB to check for updates.{Environment.NewLine}{e.Message}", true);
}
}
@@ -66,31 +64,31 @@ namespace mRemoteNG.Config.Connections.Multiuser
private bool CheckIfIAmTheLastOneUpdated(DateTime lastUpdateInDb)
{
DateTime lastSqlUpdateWithoutMilliseconds =
new DateTime(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond),
LastUpdateTime.Kind);
DateTime lastSqlUpdateWithoutMilliseconds = new DateTime(LastUpdateTime.Ticks - (LastUpdateTime.Ticks % TimeSpan.TicksPerSecond), LastUpdateTime.Kind);
return lastUpdateInDb == lastSqlUpdateWithoutMilliseconds;
}
private DateTime GetLastUpdateTimeFromDbResponse()
{
var lastUpdateInDb = default(DateTime);
DateTime lastUpdateInDb = default(DateTime);
try
{
var sqlReader = _dbQuery.ExecuteReader(CommandBehavior.CloseConnection);
DbDataReader sqlReader = _dbQuery.ExecuteReader(CommandBehavior.CloseConnection);
sqlReader.Read();
if (sqlReader.HasRows)
{
lastUpdateInDb = Convert.ToDateTime(sqlReader["LastUpdate"]);
}
sqlReader.Close();
}
catch (Exception ex)
{
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg,
"Error executing Sql query to get updates from the DB." +
Environment.NewLine + ex.Message, true);
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, "Error executing SQL query to get updates from the DB." + Environment.NewLine + ex.Message, true);
}
_lastDatabaseUpdateTime = lastUpdateInDb;
return lastUpdateInDb;
}

View File

@@ -6,7 +6,7 @@ using System.Security;
using mRemoteNG.Config.DatabaseConnectors;
using mRemoteNG.Config.DataProviders;
using mRemoteNG.Config.Serializers;
using mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Sql;
using mRemoteNG.Config.Serializers.Versioning;
using mRemoteNG.Container;
using mRemoteNG.Security;
@@ -21,20 +21,17 @@ namespace mRemoteNG.Config.Connections
[SupportedOSPlatform("windows")]
public class SqlConnectionsLoader : IConnectionsLoader
{
private readonly IDeserializer<string, IEnumerable<LocalConnectionPropertiesModel>>
_localConnectionPropertiesDeserializer;
private readonly IDeserializer<string, IEnumerable<LocalConnectionPropertiesModel>> _localConnectionPropertiesDeserializer;
private readonly IDataProvider<string> _dataProvider;
public Func<Optional<SecureString>> AuthenticationRequestor { get; set; } =
() => MiscTools.PasswordDialog("", false);
private Func<Optional<SecureString>> AuthenticationRequestor { get; set; } = () => MiscTools.PasswordDialog("", false);
public SqlConnectionsLoader(
IDeserializer<string, IEnumerable<LocalConnectionPropertiesModel>> localConnectionPropertiesDeserializer,
IDataProvider<string> dataProvider)
{
_localConnectionPropertiesDeserializer =
localConnectionPropertiesDeserializer.ThrowIfNull(nameof(localConnectionPropertiesDeserializer));
_localConnectionPropertiesDeserializer = localConnectionPropertiesDeserializer.ThrowIfNull(nameof(localConnectionPropertiesDeserializer));
_dataProvider = dataProvider.ThrowIfNull(nameof(dataProvider));
}
@@ -45,9 +42,7 @@ namespace mRemoteNG.Config.Connections
var metaDataRetriever = new SqlDatabaseMetaDataRetriever();
var databaseVersionVerifier = new SqlDatabaseVersionVerifier(connector);
var cryptoProvider = new LegacyRijndaelCryptographyProvider();
var metaData = metaDataRetriever.GetDatabaseMetaData(connector) ??
HandleFirstRun(metaDataRetriever, connector);
var metaData = metaDataRetriever.GetDatabaseMetaData(connector) ?? HandleFirstRun(metaDataRetriever, connector);
var decryptionKey = GetDecryptionKey(metaData);
if (!decryptionKey.Any())
@@ -66,13 +61,9 @@ namespace mRemoteNG.Config.Connections
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
var cipherText = metaData.Protected;
var authenticator = new PasswordAuthenticator(cryptographyProvider, cipherText, AuthenticationRequestor);
var authenticated =
authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword
.ConvertToSecureString());
var authenticated = authenticator.Authenticate(new RootNodeInfo(RootNodeType.Connection).DefaultPassword.ConvertToSecureString());
if (authenticated)
return authenticator.LastAuthenticatedPassword;
return Optional<SecureString>.Empty;
return authenticated ? authenticator.LastAuthenticatedPassword : Optional<SecureString>.Empty;
}
private void ApplyLocalConnectionProperties(ContainerInfo rootNode)

View File

@@ -1,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Data;
using System.Linq;
using mRemoteNG.App;
using mRemoteNG.App.Info;
using mRemoteNG.Config.DatabaseConnectors;
using mRemoteNG.Config.DataProviders;
using mRemoteNG.Config.Serializers;
using mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql;
using mRemoteNG.Config.Serializers.Versioning;
using mRemoteNG.Connection;
using mRemoteNG.Container;
@@ -18,8 +17,8 @@ using mRemoteNG.Tools;
using mRemoteNG.Tree;
using mRemoteNG.Tree.Root;
using mRemoteNG.Resources.Language;
using mRemoteNG.Properties;
using System.Runtime.Versioning;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Sql;
namespace mRemoteNG.Config.Connections
{
@@ -32,9 +31,7 @@ namespace mRemoteNG.Config.Connections
public SqlConnectionsSaver(SaveFilter saveFilter, ISerializer<IEnumerable<LocalConnectionPropertiesModel>, string> localPropertieSerializer, IDataProvider<string> localPropertiesDataProvider)
{
if (saveFilter == null)
throw new ArgumentNullException(nameof(saveFilter));
_saveFilter = saveFilter;
_saveFilter = saveFilter ?? throw new ArgumentNullException(nameof(saveFilter));
_localPropertiesSerializer = localPropertieSerializer.ThrowIfNull(nameof(localPropertieSerializer));
_dataProvider = localPropertiesDataProvider.ThrowIfNull(nameof(localPropertiesDataProvider));
}
@@ -111,6 +108,7 @@ namespace mRemoteNG.Config.Connections
private void UpdateRootNodeTable(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
// TODO: use transaction, but method not used at all?
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
string strProtected;
if (rootTreeNode != null)
@@ -130,7 +128,7 @@ namespace mRemoteNG.Config.Connections
strProtected = cryptographyProvider.Encrypt("ThisIsNotProtected", Runtime.EncryptionKey);
}
var dbQuery = databaseConnector.DbCommand("DELETE FROM tblRoot");
var dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
dbQuery.ExecuteNonQuery();
if (rootTreeNode != null)
@@ -139,37 +137,35 @@ namespace mRemoteNG.Config.Connections
databaseConnector.DbCommand(
"INSERT INTO tblRoot (Name, Export, Protected, ConfVersion) VALUES('" +
MiscTools.PrepareValueForDB(rootTreeNode.Name) + "', 0, '" + strProtected + "','" +
ConnectionsFileInfo.ConnectionFileVersion.ToString() + "')");
ConnectionsFileInfo.ConnectionFileVersion + "')");
dbQuery.ExecuteNonQuery();
}
else
{
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
$"UpdateRootNodeTable: rootTreeNode was null. Could not insert!");
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"UpdateRootNodeTable: rootTreeNode was null. Could not insert!");
}
}
private void UpdateConnectionsTable(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
var dataProvider = new SqlDataProvider(databaseConnector);
var currentDataTable = dataProvider.Load();
SqlDataProvider dataProvider = new SqlDataProvider(databaseConnector);
DataTable currentDataTable = dataProvider.Load();
var cryptoProvider = new LegacyRijndaelCryptographyProvider();
var serializer = new DataTableSerializer(_saveFilter, cryptoProvider,
rootTreeNode.PasswordString.ConvertToSecureString());
LegacyRijndaelCryptographyProvider cryptoProvider = new LegacyRijndaelCryptographyProvider();
DataTableSerializer serializer = new DataTableSerializer(_saveFilter, cryptoProvider, rootTreeNode.PasswordString.ConvertToSecureString());
serializer.SetSourceDataTable(currentDataTable);
var dataTable = serializer.Serialize(rootTreeNode);
//var dbQuery = databaseConnector.DbCommand("DELETE FROM tblCons");
//dbQuery.ExecuteNonQuery();
DataTable dataTable = serializer.Serialize(rootTreeNode);
dataProvider.Save(dataTable);
}
private void UpdateUpdatesTable(IDatabaseConnector databaseConnector)
{
var dbQuery = databaseConnector.DbCommand("DELETE FROM tblUpdate");
// TODO: use transaction
var dbQuery = databaseConnector.DbCommand("TRUNCATE TABLE tblUpdate");
dbQuery.ExecuteNonQuery();
dbQuery = databaseConnector.DbCommand("INSERT INTO tblUpdate (LastUpdate) VALUES('" + MiscTools.DBDate(DateTime.Now) + "')");
dbQuery = databaseConnector.DbCommand("INSERT INTO tblUpdate (LastUpdate) VALUES('" + MiscTools.DBDate(DateTime.Now.ToUniversalTime()) + "')");
dbQuery.ExecuteNonQuery();
}

View File

@@ -2,7 +2,6 @@
using mRemoteNG.Config.DatabaseConnectors;
using mRemoteNG.Messages;
using mRemoteNG.App;
using mRemoteNG.Properties;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using System.Runtime.Versioning;
@@ -38,8 +37,7 @@ namespace mRemoteNG.Config.DataProviders
{
if (DbUserIsReadOnly())
{
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg,
"Trying to save connections but the SQL read only checkbox is checked, aborting!");
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Trying to save connections but the SQL read only checkbox is checked, aborting!");
return;
}
@@ -48,54 +46,37 @@ namespace mRemoteNG.Config.DataProviders
if (DatabaseConnector.GetType() == typeof(MSSqlDatabaseConnector))
{
SqlConnection sqlConnection = (SqlConnection)DatabaseConnector.DbConnection();
using (SqlTransaction transaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.Serializable))
{
using (SqlCommand sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
using (SqlDataAdapter dataAdpater = new SqlDataAdapter())
{
dataAdpater.SelectCommand = sqlCommand;
using SqlTransaction transaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.Serializable);
using SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
using SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = sqlCommand;
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdpater);
// Avoid optimistic concurrency, check if it is necessary.
builder.ConflictOption = ConflictOption.OverwriteChanges;
dataAdpater.UpdateCommand = builder.GetUpdateCommand();
dataAdpater.DeleteCommand = builder.GetDeleteCommand();
dataAdpater.InsertCommand = builder.GetInsertCommand();
dataAdpater.Update(dataTable);
transaction.Commit();
}
}
}
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
// Avoid optimistic concurrency, check if it is necessary.
builder.ConflictOption = ConflictOption.OverwriteChanges;
dataAdapter.UpdateCommand = builder.GetUpdateCommand();
dataAdapter.DeleteCommand = builder.GetDeleteCommand();
dataAdapter.InsertCommand = builder.GetInsertCommand();
dataAdapter.Update(dataTable);
transaction.Commit();
}
else if (DatabaseConnector.GetType() == typeof(MySqlDatabaseConnector))
{
var dbConnection = (MySqlConnection) DatabaseConnector.DbConnection();
using (MySqlTransaction transaction = dbConnection.BeginTransaction(System.Data.IsolationLevel.Serializable))
{
using (MySqlCommand sqlCommand = new MySqlCommand())
{
sqlCommand.Connection = dbConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(sqlCommand))
{
dataAdapter.UpdateBatchSize = 1000;
using (MySqlCommandBuilder cb = new MySqlCommandBuilder(dataAdapter))
{
dataAdapter.Update(dataTable);
transaction.Commit();
}
}
}
}
using MySqlTransaction transaction = dbConnection.BeginTransaction(System.Data.IsolationLevel.Serializable);
using MySqlCommand sqlCommand = new MySqlCommand();
sqlCommand.Connection = dbConnection;
sqlCommand.Transaction = transaction;
sqlCommand.CommandText = "SELECT * FROM tblCons";
using MySqlDataAdapter dataAdapter = new MySqlDataAdapter(sqlCommand);
dataAdapter.UpdateBatchSize = 1000;
using MySqlCommandBuilder cb = new MySqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
transaction.Commit();
}
}

View File

@@ -1,15 +1,15 @@
using mRemoteNG.App;
using mRemoteNG.Properties;
using mRemoteNG.Security.SymmetricEncryption;
using System.Runtime.Versioning;
namespace mRemoteNG.Config.DatabaseConnectors
{
[SupportedOSPlatform("windows")]
public class DatabaseConnectorFactory
public static class DatabaseConnectorFactory
{
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;

View File

@@ -31,6 +31,7 @@ namespace mRemoteNG.Config.DatabaseConnectors
public MySqlDatabaseConnector(string host, string database, string username, string password)
{
// TODO: add custom port handling?
string[] hostParts = host.Split(new char[]{':'}, 2);
_dbHost = hostParts[0];
_dbPort = (hostParts.Length == 2)?hostParts[1]:"3306";
@@ -48,9 +49,9 @@ namespace mRemoteNG.Config.DatabaseConnectors
private void BuildSqlConnectionString()
{
_dbConnectionString = $"server={_dbHost};user={_dbUsername};database={_dbName};port={_dbPort};password={_dbPassword}";
_dbConnectionString = $"server={_dbHost};user={_dbUsername};database={_dbName};port={_dbPort};password={_dbPassword};";
}
public void Connect()
{
_dbConnection.Open();

View File

@@ -1,282 +1,282 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Versioning;
using System.Security;
using mRemoteNG.App;
using mRemoteNG.Connection;
using mRemoteNG.Connection.Protocol;
using mRemoteNG.Connection.Protocol.Http;
using mRemoteNG.Connection.Protocol.RDP;
using mRemoteNG.Connection.Protocol.VNC;
using mRemoteNG.Container;
using mRemoteNG.Security;
using mRemoteNG.Tools;
using mRemoteNG.Tree;
using mRemoteNG.Tree.Root;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
{
[SupportedOSPlatform("windows")]
public class DataTableDeserializer : IDeserializer<DataTable, ConnectionTreeModel>
{
private readonly ICryptographyProvider _cryptographyProvider;
private readonly SecureString _decryptionKey;
public DataTableDeserializer(ICryptographyProvider cryptographyProvider, SecureString decryptionKey)
{
_cryptographyProvider = cryptographyProvider.ThrowIfNull(nameof(cryptographyProvider));
_decryptionKey = decryptionKey.ThrowIfNull(nameof(decryptionKey));
}
public ConnectionTreeModel Deserialize(DataTable table)
{
var connectionList = CreateNodesFromTable(table);
var connectionTreeModel = CreateNodeHierarchy(connectionList, table);
Runtime.ConnectionsService.IsConnectionsFileLoaded = true;
return connectionTreeModel;
}
private List<ConnectionInfo> CreateNodesFromTable(DataTable table)
{
var nodeList = new List<ConnectionInfo>();
foreach (DataRow row in table.Rows)
{
// ReSharper disable once SwitchStatementMissingSomeCases
switch ((string)row["Type"])
{
case "Connection":
nodeList.Add(DeserializeConnectionInfo(row));
break;
case "Container":
nodeList.Add(DeserializeContainerInfo(row));
break;
}
}
return nodeList;
}
private ConnectionInfo DeserializeConnectionInfo(DataRow row)
{
var connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
var connectionInfo = new ConnectionInfo(connectionId);
PopulateConnectionInfoFromDatarow(row, connectionInfo);
return connectionInfo;
}
private ContainerInfo DeserializeContainerInfo(DataRow row)
{
var containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
var containerInfo = new ContainerInfo(containerId);
PopulateConnectionInfoFromDatarow(row, containerInfo);
return containerInfo;
}
private void PopulateConnectionInfoFromDatarow(DataRow dataRow, ConnectionInfo connectionInfo)
{
connectionInfo.Name = (string)dataRow["Name"];
// This throws a NPE - Parent is a connectionInfo object which will be null at this point.
// The Parent object is linked properly later in CreateNodeHierarchy()
//connectionInfo.Parent.ConstantID = (string)dataRow["ParentID"];
connectionInfo.Description = (string)dataRow["Description"];
connectionInfo.Icon = (string)dataRow["Icon"];
connectionInfo.Panel = (string)dataRow["Panel"];
//connectionInfo.ExternalCredentialProvider = (ExternalCredentialProvider)Enum.Parse(typeof(ExternalCredentialProvider), (string)dataRow["ExternalCredentialProvider"]);
//connectionInfo.UserViaAPI = (string)dataRow["UserViaAPI"];
connectionInfo.Username = (string)dataRow["Username"];
connectionInfo.Domain = (string)dataRow["Domain"];
connectionInfo.Password = DecryptValue((string)dataRow["Password"]);
connectionInfo.Hostname = (string)dataRow["Hostname"];
//connectionInfo.ExternalAddressProvider = (ExternalAddressProvider)Enum.Parse(typeof(ExternalAddressProvider), (string)dataRow["ExternalAddressProvider"]);
//connectionInfo.EC2Region = (string)dataRow["EC2Region"];
//connectionInfo.EC2InstanceId = (string)dataRow["EC2InstanceId"];
connectionInfo.VmId = (string)dataRow["VmId"];
connectionInfo.UseEnhancedMode = (bool)dataRow["UseEnhancedMode"];
connectionInfo.Protocol = (ProtocolType)Enum.Parse(typeof(ProtocolType), (string)dataRow["Protocol"]);
connectionInfo.SSHTunnelConnectionName = (string)dataRow["SSHTunnelConnectionName"];
connectionInfo.OpeningCommand = (string)dataRow["OpeningCommand"];
connectionInfo.SSHOptions = (string)dataRow["SSHOptions"];
connectionInfo.PuttySession = (string)dataRow["PuttySession"];
connectionInfo.Port = (int)dataRow["Port"];
connectionInfo.UseConsoleSession = (bool)dataRow["ConnectToConsole"];
connectionInfo.UseCredSsp = (bool)dataRow["UseCredSsp"];
connectionInfo.UseRestrictedAdmin = (bool)dataRow["UseRestrictedAdmin"];
connectionInfo.UseRCG = (bool)dataRow["UseRCG"];
connectionInfo.UseVmId = (bool)dataRow["UseVmId"];
connectionInfo.RenderingEngine = (HTTPBase.RenderingEngine)Enum.Parse(typeof(HTTPBase.RenderingEngine), (string)dataRow["RenderingEngine"]);
connectionInfo.RDPAuthenticationLevel = (AuthenticationLevel)Enum.Parse(typeof(AuthenticationLevel), (string)dataRow["RDPAuthenticationLevel"]);
connectionInfo.RDPMinutesToIdleTimeout = (int)dataRow["RDPMinutesToIdleTimeout"];
connectionInfo.RDPAlertIdleTimeout = (bool)dataRow["RDPAlertIdleTimeout"];
connectionInfo.LoadBalanceInfo = (string)dataRow["LoadBalanceInfo"];
connectionInfo.Colors = (RDPColors)Enum.Parse(typeof(RDPColors), (string)dataRow["Colors"]);
connectionInfo.Resolution = (RDPResolutions)Enum.Parse(typeof(RDPResolutions), (string)dataRow["Resolution"]);
connectionInfo.AutomaticResize = (bool)dataRow["AutomaticResize"];
connectionInfo.DisplayWallpaper = (bool)dataRow["DisplayWallpaper"];
connectionInfo.DisplayThemes = (bool)dataRow["DisplayThemes"];
connectionInfo.EnableFontSmoothing = (bool)dataRow["EnableFontSmoothing"];
connectionInfo.EnableDesktopComposition = (bool)dataRow["EnableDesktopComposition"];
connectionInfo.DisableFullWindowDrag = (bool)dataRow["DisableFullWindowDrag"];
connectionInfo.DisableMenuAnimations = (bool)dataRow["DisableMenuAnimations"];
connectionInfo.DisableCursorShadow = (bool)dataRow["DisableCursorShadow"];
connectionInfo.DisableCursorBlinking = (bool)dataRow["DisableCursorBlinking"];
connectionInfo.CacheBitmaps = (bool)dataRow["CacheBitmaps"];
connectionInfo.RedirectDiskDrives = (RDPDiskDrives)Enum.Parse(typeof(RDPDiskDrives), (string)dataRow["RedirectDiskDrives"]);
connectionInfo.RedirectDiskDrivesCustom = (string)dataRow["RedirectDiskDrivesCustom"];
connectionInfo.RedirectPorts = (bool)dataRow["RedirectPorts"];
connectionInfo.RedirectPrinters = (bool)dataRow["RedirectPrinters"];
connectionInfo.RedirectClipboard = (bool)dataRow["RedirectClipboard"];
connectionInfo.RedirectSmartCards = (bool)dataRow["RedirectSmartCards"];
connectionInfo.RedirectSound = (RDPSounds)Enum.Parse(typeof(RDPSounds), (string)dataRow["RedirectSound"]);
connectionInfo.SoundQuality = (RDPSoundQuality)Enum.Parse(typeof(RDPSoundQuality), (string)dataRow["SoundQuality"]);
connectionInfo.RedirectAudioCapture = (bool)dataRow["RedirectAudioCapture"];
connectionInfo.RDPStartProgram = (string)dataRow["StartProgram"];
connectionInfo.RDPStartProgramWorkDir = (string)dataRow["StartProgramWorkDir"];
connectionInfo.RedirectKeys = (bool)dataRow["RedirectKeys"];
connectionInfo.OpeningCommand = (string)dataRow["OpeningCommand"];
connectionInfo.PreExtApp = (string)dataRow["PreExtApp"];
connectionInfo.PostExtApp = (string)dataRow["PostExtApp"];
connectionInfo.MacAddress = (string)dataRow["MacAddress"];
connectionInfo.UserField = (string)dataRow["UserField"];
connectionInfo.ExtApp = (string)dataRow["ExtApp"];
connectionInfo.VNCCompression = (ProtocolVNC.Compression)Enum.Parse(typeof(ProtocolVNC.Compression), (string)dataRow["VNCCompression"]);
connectionInfo.VNCEncoding = (ProtocolVNC.Encoding)Enum.Parse(typeof(ProtocolVNC.Encoding), (string)dataRow["VNCEncoding"]);
connectionInfo.VNCAuthMode = (ProtocolVNC.AuthMode)Enum.Parse(typeof(ProtocolVNC.AuthMode), (string)dataRow["VNCAuthMode"]);
connectionInfo.VNCProxyType = (ProtocolVNC.ProxyType)Enum.Parse(typeof(ProtocolVNC.ProxyType), (string)dataRow["VNCProxyType"]);
connectionInfo.VNCProxyIP = (string)dataRow["VNCProxyIP"];
connectionInfo.VNCProxyPort = (int)dataRow["VNCProxyPort"];
connectionInfo.VNCProxyUsername = (string)dataRow["VNCProxyUsername"];
connectionInfo.VNCProxyPassword = DecryptValue((string)dataRow["VNCProxyPassword"]);
connectionInfo.VNCColors = (ProtocolVNC.Colors)Enum.Parse(typeof(ProtocolVNC.Colors), (string)dataRow["VNCColors"]);
connectionInfo.VNCSmartSizeMode = (ProtocolVNC.SmartSizeMode)Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), (string)dataRow["VNCSmartSizeMode"]);
connectionInfo.VNCViewOnly = (bool)dataRow["VNCViewOnly"];
connectionInfo.RDGatewayUsageMethod = (RDGatewayUsageMethod)Enum.Parse(typeof(RDGatewayUsageMethod), (string)dataRow["RDGatewayUsageMethod"]);
connectionInfo.RDGatewayHostname = (string)dataRow["RDGatewayHostname"];
connectionInfo.RDGatewayUseConnectionCredentials = (RDGatewayUseConnectionCredentials)Enum.Parse(typeof(RDGatewayUseConnectionCredentials), (string)dataRow["RDGatewayUseConnectionCredentials"]);
connectionInfo.RDGatewayUsername = (string)dataRow["RDGatewayUsername"];
connectionInfo.RDGatewayPassword = DecryptValue((string)dataRow["RDGatewayPassword"]);
connectionInfo.RDGatewayDomain = (string)dataRow["RDGatewayDomain"];
//connectionInfo.RDGatewayExternalCredentialProvider = (ExternalCredentialProvider)Enum.Parse(typeof(ExternalCredentialProvider), (string)dataRow["RDGatewayExternalCredentialProvider"]);
//connectionInfo.RDGatewayUserViaAPI = (string)dataRow["RDGatewayUserViaAPI"];
if (!dataRow.IsNull("RdpVersion")) // table allows null values which must be handled
if (Enum.TryParse((string)dataRow["RdpVersion"], true, out RdpVersion rdpVersion))
connectionInfo.RdpVersion = rdpVersion;
connectionInfo.Inheritance.CacheBitmaps = (bool)dataRow["InheritCacheBitmaps"];
connectionInfo.Inheritance.Colors = (bool)dataRow["InheritColors"];
connectionInfo.Inheritance.Description = (bool)dataRow["InheritDescription"];
connectionInfo.Inheritance.DisplayThemes = (bool)dataRow["InheritDisplayThemes"];
connectionInfo.Inheritance.DisplayWallpaper = (bool)dataRow["InheritDisplayWallpaper"];
connectionInfo.Inheritance.EnableFontSmoothing = (bool)dataRow["InheritEnableFontSmoothing"];
connectionInfo.Inheritance.EnableDesktopComposition = (bool)dataRow["InheritEnableDesktopComposition"];
connectionInfo.Inheritance.DisableFullWindowDrag = (bool)dataRow["InheritDisableFullWindowDrag"];
connectionInfo.Inheritance.DisableMenuAnimations = (bool)dataRow["InheritDisableMenuAnimations"];
connectionInfo.Inheritance.DisableCursorShadow = (bool)dataRow["InheritDisableCursorShadow"];
connectionInfo.Inheritance.DisableCursorBlinking = (bool)dataRow["InheritDisableCursorBlinking"];
//connectionInfo.Inheritance.ExternalCredentialProvider = (bool)dataRow["InheritExternalCredentialProvider"];
//connectionInfo.Inheritance.UserViaAPI = (bool)dataRow["InheritUserViaAPI"];
connectionInfo.Inheritance.Domain = (bool)dataRow["InheritDomain"];
connectionInfo.Inheritance.Icon = (bool)dataRow["InheritIcon"];
connectionInfo.Inheritance.Panel = (bool)dataRow["InheritPanel"];
connectionInfo.Inheritance.Password = (bool)dataRow["InheritPassword"];
connectionInfo.Inheritance.Port = (bool)dataRow["InheritPort"];
connectionInfo.Inheritance.Protocol = (bool)dataRow["InheritProtocol"];
connectionInfo.Inheritance.SSHTunnelConnectionName = (bool)dataRow["InheritSSHTunnelConnectionName"];
connectionInfo.Inheritance.OpeningCommand = (bool)dataRow["InheritOpeningCommand"];
connectionInfo.Inheritance.SSHOptions = (bool)dataRow["InheritSSHOptions"];
connectionInfo.Inheritance.PuttySession = (bool)dataRow["InheritPuttySession"];
connectionInfo.Inheritance.RedirectDiskDrives = (bool)dataRow["InheritRedirectDiskDrives"];
connectionInfo.Inheritance.RedirectDiskDrivesCustom = (bool)dataRow["InheritRedirectDiskDrivesCustom"];
connectionInfo.Inheritance.RedirectKeys = (bool)dataRow["InheritRedirectKeys"];
connectionInfo.Inheritance.RedirectPorts = (bool)dataRow["InheritRedirectPorts"];
connectionInfo.Inheritance.RedirectPrinters = (bool)dataRow["InheritRedirectPrinters"];
connectionInfo.Inheritance.RedirectClipboard = (bool)dataRow["InheritRedirectClipboard"];
connectionInfo.Inheritance.RedirectSmartCards = (bool)dataRow["InheritRedirectSmartCards"];
connectionInfo.Inheritance.RedirectSound = (bool)dataRow["InheritRedirectSound"];
connectionInfo.Inheritance.SoundQuality = (bool)dataRow["InheritSoundQuality"];
connectionInfo.Inheritance.RedirectAudioCapture = (bool)dataRow["InheritRedirectAudioCapture"];
connectionInfo.Inheritance.Resolution = (bool)dataRow["InheritResolution"];
connectionInfo.Inheritance.AutomaticResize = (bool)dataRow["InheritAutomaticResize"];
connectionInfo.Inheritance.UseConsoleSession = (bool)dataRow["InheritUseConsoleSession"];
connectionInfo.Inheritance.UseCredSsp = (bool)dataRow["InheritUseCredSsp"];
connectionInfo.Inheritance.UseRestrictedAdmin = (bool)dataRow["InheritUseRestrictedAdmin"];
connectionInfo.Inheritance.UseRCG = (bool)dataRow["InheritUseRCG"];
connectionInfo.Inheritance.UseVmId = (bool)dataRow["InheritUseVmId"];
connectionInfo.Inheritance.UseEnhancedMode = (bool)dataRow["InheritUseEnhancedMode"];
connectionInfo.Inheritance.VmId = (bool)dataRow["InheritVmId"];
connectionInfo.Inheritance.RenderingEngine = (bool)dataRow["InheritRenderingEngine"];
connectionInfo.Inheritance.Username = (bool)dataRow["InheritUsername"];
connectionInfo.Inheritance.RDPAuthenticationLevel = (bool)dataRow["InheritRDPAuthenticationLevel"];
connectionInfo.Inheritance.RDPAlertIdleTimeout = (bool)dataRow["InheritRDPAlertIdleTimeout"];
connectionInfo.Inheritance.RDPMinutesToIdleTimeout = (bool)dataRow["InheritRDPMinutesToIdleTimeout"];
connectionInfo.Inheritance.LoadBalanceInfo = (bool)dataRow["InheritLoadBalanceInfo"];
connectionInfo.Inheritance.OpeningCommand = (bool)dataRow["InheritOpeningCommand"];
connectionInfo.Inheritance.PreExtApp = (bool)dataRow["InheritPreExtApp"];
connectionInfo.Inheritance.PostExtApp = (bool)dataRow["InheritPostExtApp"];
connectionInfo.Inheritance.MacAddress = (bool)dataRow["InheritMacAddress"];
connectionInfo.Inheritance.UserField = (bool)dataRow["InheritUserField"];
connectionInfo.Inheritance.ExtApp = (bool)dataRow["InheritExtApp"];
connectionInfo.Inheritance.VNCCompression = (bool)dataRow["InheritVNCCompression"];
connectionInfo.Inheritance.VNCEncoding = (bool)dataRow["InheritVNCEncoding"];
connectionInfo.Inheritance.VNCAuthMode = (bool)dataRow["InheritVNCAuthMode"];
connectionInfo.Inheritance.VNCProxyType = (bool)dataRow["InheritVNCProxyType"];
connectionInfo.Inheritance.VNCProxyIP = (bool)dataRow["InheritVNCProxyIP"];
connectionInfo.Inheritance.VNCProxyPort = (bool)dataRow["InheritVNCProxyPort"];
connectionInfo.Inheritance.VNCProxyUsername = (bool)dataRow["InheritVNCProxyUsername"];
connectionInfo.Inheritance.VNCProxyPassword = (bool)dataRow["InheritVNCProxyPassword"];
connectionInfo.Inheritance.VNCColors = (bool)dataRow["InheritVNCColors"];
connectionInfo.Inheritance.VNCSmartSizeMode = (bool)dataRow["InheritVNCSmartSizeMode"];
connectionInfo.Inheritance.VNCViewOnly = (bool)dataRow["InheritVNCViewOnly"];
connectionInfo.Inheritance.RDGatewayUsageMethod = (bool)dataRow["InheritRDGatewayUsageMethod"];
connectionInfo.Inheritance.RDGatewayHostname = (bool)dataRow["InheritRDGatewayHostname"];
connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = (bool)dataRow["InheritRDGatewayUseConnectionCredentials"];
connectionInfo.Inheritance.RDGatewayUsername = (bool)dataRow["InheritRDGatewayUsername"];
connectionInfo.Inheritance.RDGatewayPassword = (bool)dataRow["InheritRDGatewayPassword"];
connectionInfo.Inheritance.RDGatewayDomain = (bool)dataRow["InheritRDGatewayDomain"];
//connectionInfo.Inheritance.RDGatewayExternalCredentialProvider = (bool)dataRow["InheritRDGatewayExternalCredentialProvider"];
//connectionInfo.Inheritance.RDGatewayUserViaAPI = (bool)dataRow["InheritRDGatewayUserViaAPI"];
connectionInfo.Inheritance.RdpVersion = (bool)dataRow["InheritRdpVersion"];
}
private string DecryptValue(string cipherText)
{
try
{
return _cryptographyProvider.Decrypt(cipherText, _decryptionKey);
}
catch (EncryptionException)
{
// value may not be encrypted
return cipherText;
}
}
private ConnectionTreeModel CreateNodeHierarchy(List<ConnectionInfo> connectionList, DataTable dataTable)
{
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection, "0")
{
PasswordString = _decryptionKey.ConvertToUnsecureString()
};
connectionTreeModel.AddRootNode(rootNode);
foreach (DataRow row in dataTable.Rows)
{
var id = (string)row["ConstantID"];
var connectionInfo = connectionList.First(node => node.ConstantID == id);
var parentId = (string)row["ParentID"];
if (parentId == "0" || connectionList.All(node => node.ConstantID != parentId))
rootNode.AddChild(connectionInfo);
else
(connectionList.First(node => node.ConstantID == parentId) as ContainerInfo)?.AddChild(
connectionInfo);
}
return connectionTreeModel;
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Versioning;
using System.Security;
using mRemoteNG.App;
using mRemoteNG.Connection;
using mRemoteNG.Connection.Protocol;
using mRemoteNG.Connection.Protocol.Http;
using mRemoteNG.Connection.Protocol.RDP;
using mRemoteNG.Connection.Protocol.VNC;
using mRemoteNG.Container;
using mRemoteNG.Messages;
using mRemoteNG.Security;
using mRemoteNG.Tools;
using mRemoteNG.Tree;
using mRemoteNG.Tree.Root;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
[SupportedOSPlatform("windows")]
public class DataTableDeserializer : IDeserializer<DataTable, ConnectionTreeModel>
{
private readonly ICryptographyProvider _cryptographyProvider;
private readonly SecureString _decryptionKey;
public DataTableDeserializer(ICryptographyProvider cryptographyProvider, SecureString decryptionKey)
{
_cryptographyProvider = cryptographyProvider.ThrowIfNull(nameof(cryptographyProvider));
_decryptionKey = decryptionKey.ThrowIfNull(nameof(decryptionKey));
}
public ConnectionTreeModel Deserialize(DataTable table)
{
var connectionList = CreateNodesFromTable(table);
var connectionTreeModel = CreateNodeHierarchy(connectionList, table);
Runtime.ConnectionsService.IsConnectionsFileLoaded = true;
return connectionTreeModel;
}
private List<ConnectionInfo> CreateNodesFromTable(DataTable table)
{
var nodeList = new List<ConnectionInfo>();
foreach (DataRow row in table.Rows)
{
// ReSharper disable once SwitchStatementMissingSomeCases
switch ((string)row["Type"])
{
case "Connection":
nodeList.Add(DeserializeConnectionInfo(row));
break;
case "Container":
nodeList.Add(DeserializeContainerInfo(row));
break;
}
}
return nodeList;
}
private ConnectionInfo DeserializeConnectionInfo(DataRow row)
{
var connectionId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
var connectionInfo = new ConnectionInfo(connectionId);
PopulateConnectionInfoFromDatarow(row, connectionInfo);
return connectionInfo;
}
private ContainerInfo DeserializeContainerInfo(DataRow row)
{
var containerId = row["ConstantID"] as string ?? Guid.NewGuid().ToString();
var containerInfo = new ContainerInfo(containerId);
PopulateConnectionInfoFromDatarow(row, containerInfo);
return containerInfo;
}
private void PopulateConnectionInfoFromDatarow(DataRow dataRow, ConnectionInfo connectionInfo)
{
connectionInfo.Name = (string)dataRow["Name"];
// This throws a NPE - Parent is a connectionInfo object which will be null at this point.
// The Parent object is linked properly later in CreateNodeHierarchy()
//connectionInfo.Parent.ConstantID = (string)dataRow["ParentID"];
//connectionInfo.EC2InstanceId = (string)dataRow["EC2InstanceId"];
//connectionInfo.EC2Region = (string)dataRow["EC2Region"];
//connectionInfo.ExternalAddressProvider = (ExternalAddressProvider)Enum.Parse(typeof(ExternalAddressProvider), (string)dataRow["ExternalAddressProvider"]);
//connectionInfo.ExternalCredentialProvider = (ExternalCredentialProvider)Enum.Parse(typeof(ExternalCredentialProvider), (string)dataRow["ExternalCredentialProvider"]);
//connectionInfo.RDGatewayExternalCredentialProvider = (ExternalCredentialProvider)Enum.Parse(typeof(ExternalCredentialProvider), (string)dataRow["RDGatewayExternalCredentialProvider"]);
//connectionInfo.RDGatewayUserViaAPI = (string)dataRow["RDGatewayUserViaAPI"];
//connectionInfo.UserViaAPI = (string)dataRow["UserViaAPI"];
connectionInfo.AutomaticResize = MiscTools.GetBooleanValue(dataRow["AutomaticResize"]);
connectionInfo.CacheBitmaps = MiscTools.GetBooleanValue(dataRow["CacheBitmaps"]);
connectionInfo.Colors = (RDPColors)Enum.Parse(typeof(RDPColors), (string)dataRow["Colors"]);
connectionInfo.Description = (string)dataRow["Description"];
connectionInfo.DisableCursorBlinking = MiscTools.GetBooleanValue(dataRow["DisableCursorBlinking"]);
connectionInfo.DisableCursorShadow = MiscTools.GetBooleanValue(dataRow["DisableCursorShadow"]);
connectionInfo.DisableFullWindowDrag = MiscTools.GetBooleanValue(dataRow["DisableFullWindowDrag"]);
connectionInfo.DisableMenuAnimations = MiscTools.GetBooleanValue(dataRow["DisableMenuAnimations"]);
connectionInfo.DisplayThemes = MiscTools.GetBooleanValue(dataRow["DisplayThemes"]);
connectionInfo.DisplayWallpaper = MiscTools.GetBooleanValue(dataRow["DisplayWallpaper"]);
connectionInfo.Domain = (string)dataRow["Domain"];
connectionInfo.EnableDesktopComposition = MiscTools.GetBooleanValue(dataRow["EnableDesktopComposition"]);
connectionInfo.EnableFontSmoothing = MiscTools.GetBooleanValue(dataRow["EnableFontSmoothing"]);
connectionInfo.ExtApp = (string)dataRow["ExtApp"];
connectionInfo.Hostname = (string)dataRow["Hostname"];
connectionInfo.Icon = (string)dataRow["Icon"];
connectionInfo.LoadBalanceInfo = (string)dataRow["LoadBalanceInfo"];
connectionInfo.MacAddress = (string)dataRow["MacAddress"];
connectionInfo.OpeningCommand = (string)dataRow["OpeningCommand"];
connectionInfo.OpeningCommand = (string)dataRow["OpeningCommand"];
connectionInfo.Panel = (string)dataRow["Panel"];
connectionInfo.Password = DecryptValue((string)dataRow["Password"]);
connectionInfo.Port = (int)dataRow["Port"];
connectionInfo.PostExtApp = (string)dataRow["PostExtApp"];
connectionInfo.PreExtApp = (string)dataRow["PreExtApp"];
connectionInfo.Protocol = (ProtocolType)Enum.Parse(typeof(ProtocolType), (string)dataRow["Protocol"]);
connectionInfo.PuttySession = (string)dataRow["PuttySession"];
connectionInfo.RDGatewayDomain = (string)dataRow["RDGatewayDomain"];
connectionInfo.RDGatewayHostname = (string)dataRow["RDGatewayHostname"];
connectionInfo.RDGatewayPassword = DecryptValue((string)dataRow["RDGatewayPassword"]);
connectionInfo.RDGatewayUsageMethod = (RDGatewayUsageMethod)Enum.Parse(typeof(RDGatewayUsageMethod), (string)dataRow["RDGatewayUsageMethod"]);
connectionInfo.RDGatewayUseConnectionCredentials = (RDGatewayUseConnectionCredentials)Enum.Parse(typeof(RDGatewayUseConnectionCredentials), (string)dataRow["RDGatewayUseConnectionCredentials"]);
connectionInfo.RDGatewayUsername = (string)dataRow["RDGatewayUsername"];
connectionInfo.RDPAlertIdleTimeout = MiscTools.GetBooleanValue(dataRow["RDPAlertIdleTimeout"]);
connectionInfo.RDPAuthenticationLevel = (AuthenticationLevel)Enum.Parse(typeof(AuthenticationLevel), (string)dataRow["RDPAuthenticationLevel"]);
connectionInfo.RDPMinutesToIdleTimeout = (int)dataRow["RDPMinutesToIdleTimeout"];
connectionInfo.RDPStartProgram = (string)dataRow["StartProgram"];
connectionInfo.RDPStartProgramWorkDir = (string)dataRow["StartProgramWorkDir"];
connectionInfo.RedirectAudioCapture = MiscTools.GetBooleanValue(dataRow["RedirectAudioCapture"]);
connectionInfo.RedirectClipboard = MiscTools.GetBooleanValue(dataRow["RedirectClipboard"]);
connectionInfo.RedirectDiskDrives = (RDPDiskDrives)Enum.Parse(typeof(RDPDiskDrives), (string)dataRow["RedirectDiskDrives"]);
connectionInfo.RedirectDiskDrivesCustom = (string)dataRow["RedirectDiskDrivesCustom"];
connectionInfo.RedirectKeys = MiscTools.GetBooleanValue(dataRow["RedirectKeys"]);
connectionInfo.RedirectPorts = MiscTools.GetBooleanValue(dataRow["RedirectPorts"]);
connectionInfo.RedirectPrinters = MiscTools.GetBooleanValue(dataRow["RedirectPrinters"]);
connectionInfo.RedirectSmartCards = MiscTools.GetBooleanValue(dataRow["RedirectSmartCards"]);
connectionInfo.RedirectSound = (RDPSounds)Enum.Parse(typeof(RDPSounds), (string)dataRow["RedirectSound"]);
connectionInfo.RenderingEngine = (HTTPBase.RenderingEngine)Enum.Parse(typeof(HTTPBase.RenderingEngine), (string)dataRow["RenderingEngine"]);
connectionInfo.Resolution = (RDPResolutions)Enum.Parse(typeof(RDPResolutions), (string)dataRow["Resolution"]);
connectionInfo.SoundQuality = (RDPSoundQuality)Enum.Parse(typeof(RDPSoundQuality), (string)dataRow["SoundQuality"]);
connectionInfo.SSHOptions = (string)dataRow["SSHOptions"];
connectionInfo.SSHTunnelConnectionName = (string)dataRow["SSHTunnelConnectionName"];
connectionInfo.UseConsoleSession = MiscTools.GetBooleanValue(dataRow["ConnectToConsole"]);
connectionInfo.UseCredSsp = MiscTools.GetBooleanValue(dataRow["UseCredSsp"]);
connectionInfo.UseEnhancedMode = MiscTools.GetBooleanValue(dataRow["UseEnhancedMode"]);
connectionInfo.UseRCG = MiscTools.GetBooleanValue(dataRow["UseRCG"]);
connectionInfo.UseRestrictedAdmin = MiscTools.GetBooleanValue(dataRow["UseRestrictedAdmin"]);
connectionInfo.UserField = (string)dataRow["UserField"];
connectionInfo.Username = (string)dataRow["Username"];
connectionInfo.UseVmId = MiscTools.GetBooleanValue(dataRow["UseVmId"]);
connectionInfo.VmId = (string)dataRow["VmId"];
connectionInfo.VNCAuthMode = (ProtocolVNC.AuthMode)Enum.Parse(typeof(ProtocolVNC.AuthMode), (string)dataRow["VNCAuthMode"]);
connectionInfo.VNCColors = (ProtocolVNC.Colors)Enum.Parse(typeof(ProtocolVNC.Colors), (string)dataRow["VNCColors"]);
connectionInfo.VNCCompression = (ProtocolVNC.Compression)Enum.Parse(typeof(ProtocolVNC.Compression), (string)dataRow["VNCCompression"]);
connectionInfo.VNCEncoding = (ProtocolVNC.Encoding)Enum.Parse(typeof(ProtocolVNC.Encoding), (string)dataRow["VNCEncoding"]);
connectionInfo.VNCProxyIP = (string)dataRow["VNCProxyIP"];
connectionInfo.VNCProxyPassword = DecryptValue((string)dataRow["VNCProxyPassword"]);
connectionInfo.VNCProxyPort = (int)dataRow["VNCProxyPort"];
connectionInfo.VNCProxyType = (ProtocolVNC.ProxyType)Enum.Parse(typeof(ProtocolVNC.ProxyType), (string)dataRow["VNCProxyType"]);
connectionInfo.VNCProxyUsername = (string)dataRow["VNCProxyUsername"];
connectionInfo.VNCSmartSizeMode = (ProtocolVNC.SmartSizeMode)Enum.Parse(typeof(ProtocolVNC.SmartSizeMode), (string)dataRow["VNCSmartSizeMode"]);
connectionInfo.VNCViewOnly = MiscTools.GetBooleanValue(dataRow["VNCViewOnly"]);
if (!dataRow.IsNull("RdpVersion")) // table allows null values which must be handled
if (Enum.TryParse((string)dataRow["RdpVersion"], true, out RdpVersion rdpVersion))
connectionInfo.RdpVersion = rdpVersion;
//connectionInfo.Inheritance.ExternalCredentialProvider = MiscTools.GetBooleanValue(dataRow["InheritExternalCredentialProvider"]);
//connectionInfo.Inheritance.RDGatewayExternalCredentialProvider = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayExternalCredentialProvider"]);
//connectionInfo.Inheritance.RDGatewayUserViaAPI = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayUserViaAPI"]);
//connectionInfo.Inheritance.UserViaAPI = MiscTools.GetBooleanValue(dataRow["InheritUserViaAPI"]);
connectionInfo.Inheritance.AutomaticResize = MiscTools.GetBooleanValue(dataRow["InheritAutomaticResize"]);
connectionInfo.Inheritance.CacheBitmaps = MiscTools.GetBooleanValue(dataRow["InheritCacheBitmaps"]);
connectionInfo.Inheritance.Colors = MiscTools.GetBooleanValue(dataRow["InheritColors"]);
connectionInfo.Inheritance.Description = MiscTools.GetBooleanValue(dataRow["InheritDescription"]);
connectionInfo.Inheritance.DisableCursorBlinking = MiscTools.GetBooleanValue(dataRow["InheritDisableCursorBlinking"]);
connectionInfo.Inheritance.DisableCursorShadow = MiscTools.GetBooleanValue(dataRow["InheritDisableCursorShadow"]);
connectionInfo.Inheritance.DisableFullWindowDrag = MiscTools.GetBooleanValue(dataRow["InheritDisableFullWindowDrag"]);
connectionInfo.Inheritance.DisableMenuAnimations = MiscTools.GetBooleanValue(dataRow["InheritDisableMenuAnimations"]);
connectionInfo.Inheritance.DisplayThemes = MiscTools.GetBooleanValue(dataRow["InheritDisplayThemes"]);
connectionInfo.Inheritance.DisplayWallpaper = MiscTools.GetBooleanValue(dataRow["InheritDisplayWallpaper"]);
connectionInfo.Inheritance.Domain = MiscTools.GetBooleanValue(dataRow["InheritDomain"]);
connectionInfo.Inheritance.EnableDesktopComposition = MiscTools.GetBooleanValue(dataRow["InheritEnableDesktopComposition"]);
connectionInfo.Inheritance.EnableFontSmoothing = MiscTools.GetBooleanValue(dataRow["InheritEnableFontSmoothing"]);
connectionInfo.Inheritance.ExtApp = MiscTools.GetBooleanValue(dataRow["InheritExtApp"]);
connectionInfo.Inheritance.Icon = MiscTools.GetBooleanValue(dataRow["InheritIcon"]);
connectionInfo.Inheritance.LoadBalanceInfo = MiscTools.GetBooleanValue(dataRow["InheritLoadBalanceInfo"]);
connectionInfo.Inheritance.MacAddress = MiscTools.GetBooleanValue(dataRow["InheritMacAddress"]);
connectionInfo.Inheritance.OpeningCommand = MiscTools.GetBooleanValue(dataRow["InheritOpeningCommand"]);
connectionInfo.Inheritance.OpeningCommand = MiscTools.GetBooleanValue(dataRow["InheritOpeningCommand"]);
connectionInfo.Inheritance.Panel = MiscTools.GetBooleanValue(dataRow["InheritPanel"]);
connectionInfo.Inheritance.Password = MiscTools.GetBooleanValue(dataRow["InheritPassword"]);
connectionInfo.Inheritance.Port = MiscTools.GetBooleanValue(dataRow["InheritPort"]);
connectionInfo.Inheritance.PostExtApp = MiscTools.GetBooleanValue(dataRow["InheritPostExtApp"]);
connectionInfo.Inheritance.PreExtApp = MiscTools.GetBooleanValue(dataRow["InheritPreExtApp"]);
connectionInfo.Inheritance.Protocol = MiscTools.GetBooleanValue(dataRow["InheritProtocol"]);
connectionInfo.Inheritance.PuttySession = MiscTools.GetBooleanValue(dataRow["InheritPuttySession"]);
connectionInfo.Inheritance.RDGatewayDomain = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayDomain"]);
connectionInfo.Inheritance.RDGatewayHostname = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayHostname"]);
connectionInfo.Inheritance.RDGatewayPassword = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayPassword"]);
connectionInfo.Inheritance.RDGatewayUsageMethod = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayUsageMethod"]);
connectionInfo.Inheritance.RDGatewayUseConnectionCredentials = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayUseConnectionCredentials"]);
connectionInfo.Inheritance.RDGatewayUsername = MiscTools.GetBooleanValue(dataRow["InheritRDGatewayUsername"]);
connectionInfo.Inheritance.RDPAlertIdleTimeout = MiscTools.GetBooleanValue(dataRow["InheritRDPAlertIdleTimeout"]);
connectionInfo.Inheritance.RDPAuthenticationLevel = MiscTools.GetBooleanValue(dataRow["InheritRDPAuthenticationLevel"]);
connectionInfo.Inheritance.RDPMinutesToIdleTimeout = MiscTools.GetBooleanValue(dataRow["InheritRDPMinutesToIdleTimeout"]);
connectionInfo.Inheritance.RdpVersion = MiscTools.GetBooleanValue(dataRow["InheritRdpVersion"]);
connectionInfo.Inheritance.RedirectAudioCapture = MiscTools.GetBooleanValue(dataRow["InheritRedirectAudioCapture"]);
connectionInfo.Inheritance.RedirectClipboard = MiscTools.GetBooleanValue(dataRow["InheritRedirectClipboard"]);
connectionInfo.Inheritance.RedirectDiskDrives = MiscTools.GetBooleanValue(dataRow["InheritRedirectDiskDrives"]);
connectionInfo.Inheritance.RedirectDiskDrivesCustom = MiscTools.GetBooleanValue(dataRow["InheritRedirectDiskDrivesCustom"]);
connectionInfo.Inheritance.RedirectKeys = MiscTools.GetBooleanValue(dataRow["InheritRedirectKeys"]);
connectionInfo.Inheritance.RedirectPorts = MiscTools.GetBooleanValue(dataRow["InheritRedirectPorts"]);
connectionInfo.Inheritance.RedirectPrinters = MiscTools.GetBooleanValue(dataRow["InheritRedirectPrinters"]);
connectionInfo.Inheritance.RedirectSmartCards = MiscTools.GetBooleanValue(dataRow["InheritRedirectSmartCards"]);
connectionInfo.Inheritance.RedirectSound = MiscTools.GetBooleanValue(dataRow["InheritRedirectSound"]);
connectionInfo.Inheritance.RenderingEngine = MiscTools.GetBooleanValue(dataRow["InheritRenderingEngine"]);
connectionInfo.Inheritance.Resolution = MiscTools.GetBooleanValue(dataRow["InheritResolution"]);
connectionInfo.Inheritance.SoundQuality = MiscTools.GetBooleanValue(dataRow["InheritSoundQuality"]);
connectionInfo.Inheritance.SSHOptions = MiscTools.GetBooleanValue(dataRow["InheritSSHOptions"]);
connectionInfo.Inheritance.SSHTunnelConnectionName = MiscTools.GetBooleanValue(dataRow["InheritSSHTunnelConnectionName"]);
connectionInfo.Inheritance.UseConsoleSession = MiscTools.GetBooleanValue(dataRow["InheritUseConsoleSession"]);
connectionInfo.Inheritance.UseCredSsp = MiscTools.GetBooleanValue(dataRow["InheritUseCredSsp"]);
connectionInfo.Inheritance.UseEnhancedMode = MiscTools.GetBooleanValue(dataRow["InheritUseEnhancedMode"]);
connectionInfo.Inheritance.UseRCG = MiscTools.GetBooleanValue(dataRow["InheritUseRCG"]);
connectionInfo.Inheritance.UseRestrictedAdmin = MiscTools.GetBooleanValue(dataRow["InheritUseRestrictedAdmin"]);
connectionInfo.Inheritance.UserField = MiscTools.GetBooleanValue(dataRow["InheritUserField"]);
connectionInfo.Inheritance.Username = MiscTools.GetBooleanValue(dataRow["InheritUsername"]);
connectionInfo.Inheritance.UseVmId = MiscTools.GetBooleanValue(dataRow["InheritUseVmId"]);
connectionInfo.Inheritance.VmId = MiscTools.GetBooleanValue(dataRow["InheritVmId"]);
connectionInfo.Inheritance.VNCAuthMode = MiscTools.GetBooleanValue(dataRow["InheritVNCAuthMode"]);
connectionInfo.Inheritance.VNCColors = MiscTools.GetBooleanValue(dataRow["InheritVNCColors"]);
connectionInfo.Inheritance.VNCCompression = MiscTools.GetBooleanValue(dataRow["InheritVNCCompression"]);
connectionInfo.Inheritance.VNCEncoding = MiscTools.GetBooleanValue(dataRow["InheritVNCEncoding"]);
connectionInfo.Inheritance.VNCProxyIP = MiscTools.GetBooleanValue(dataRow["InheritVNCProxyIP"]);
connectionInfo.Inheritance.VNCProxyPassword = MiscTools.GetBooleanValue(dataRow["InheritVNCProxyPassword"]);
connectionInfo.Inheritance.VNCProxyPort = MiscTools.GetBooleanValue(dataRow["InheritVNCProxyPort"]);
connectionInfo.Inheritance.VNCProxyType = MiscTools.GetBooleanValue(dataRow["InheritVNCProxyType"]);
connectionInfo.Inheritance.VNCProxyUsername = MiscTools.GetBooleanValue(dataRow["InheritVNCProxyUsername"]);
connectionInfo.Inheritance.VNCSmartSizeMode = MiscTools.GetBooleanValue(dataRow["InheritVNCSmartSizeMode"]);
connectionInfo.Inheritance.VNCViewOnly = MiscTools.GetBooleanValue(dataRow["InheritVNCViewOnly"]);
}
private string DecryptValue(string cipherText)
{
try
{
return _cryptographyProvider.Decrypt(cipherText, _decryptionKey);
}
catch (EncryptionException)
{
// value may not be encrypted
return cipherText;
}
}
private ConnectionTreeModel CreateNodeHierarchy(List<ConnectionInfo> connectionList, DataTable dataTable)
{
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection, "0")
{
PasswordString = _decryptionKey.ConvertToUnsecureString()
};
connectionTreeModel.AddRootNode(rootNode);
foreach (DataRow row in dataTable.Rows)
{
var id = (string)row["ConstantID"];
var connectionInfo = connectionList.First(node => node.ConstantID == id);
var parentId = (string)row["ParentID"];
if (parentId == "0" || connectionList.All(node => node.ConstantID != parentId))
rootNode.AddChild(connectionInfo);
else
(connectionList.First(node => node.ConstantID == parentId) as ContainerInfo)?.AddChild(connectionInfo);
}
return connectionTreeModel;
}
}
}

View File

@@ -1,4 +1,4 @@
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
public class LocalConnectionPropertiesModel
{

View File

@@ -6,7 +6,7 @@ using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
public class LocalConnectionPropertiesXmlSerializer :
ISerializer<IEnumerable<LocalConnectionPropertiesModel>, string>,

View File

@@ -1,6 +1,6 @@
using System;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
public class SqlConnectionListMetaData
{

View File

@@ -2,6 +2,7 @@
using System.Data.Common;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security;
using mRemoteNG.App;
using mRemoteNG.App.Info;
using mRemoteNG.Config.DatabaseConnectors;
@@ -11,7 +12,7 @@ using mRemoteNG.Security.SymmetricEncryption;
using mRemoteNG.Tools;
using mRemoteNG.Tree.Root;
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Sql
{
[SupportedOSPlatform("windows")]
public class SqlDatabaseMetaDataRetriever
@@ -48,7 +49,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
{
Name = dbDataReader["Name"] as string ?? "",
Protected = dbDataReader["Protected"] as string ?? "",
Export = (bool)dbDataReader["Export"],
Export = dbDataReader["Export"].Equals(1),
ConfVersion = new Version(Convert.ToString(dbDataReader["confVersion"], CultureInfo.InvariantCulture) ?? string.Empty)
};
}
@@ -68,13 +69,18 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
public void WriteDatabaseMetaData(RootNodeInfo rootTreeNode, IDatabaseConnector databaseConnector)
{
// TODO: use transaction
var cryptographyProvider = new LegacyRijndaelCryptographyProvider();
string strProtected;
if (rootTreeNode != null)
{
if (rootTreeNode.Password)
{
var password = rootTreeNode.PasswordString.ConvertToSecureString();
SecureString password = rootTreeNode.PasswordString.ConvertToSecureString();
strProtected = cryptographyProvider.Encrypt("ThisIsProtected", password);
}
else
@@ -87,7 +93,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
strProtected = cryptographyProvider.Encrypt("ThisIsNotProtected", Runtime.EncryptionKey);
}
var cmd = databaseConnector.DbCommand("DELETE FROM tblRoot");
var cmd = databaseConnector.DbCommand("TRUNCATE TABLE tblRoot");
cmd.ExecuteNonQuery();
if (rootTreeNode != null)
@@ -95,7 +101,8 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
cmd = databaseConnector.DbCommand(
"INSERT INTO tblRoot (Name, Export, Protected, ConfVersion) VALUES('" +
MiscTools.PrepareValueForDB(rootTreeNode.Name) + "', 0, '" + strProtected + "','" +
ConnectionsFileInfo.ConnectionFileVersion.ToString() + "')");
ConnectionsFileInfo.ConnectionFileVersion + "')");
cmd.ExecuteNonQuery();
}
else
@@ -112,8 +119,8 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
{
// ANSI SQL way. Works in PostgreSQL, MSSQL, MySQL.
var cmd = databaseConnector.DbCommand("select case when exists((select * from information_schema.tables where table_name = '" + tableName + "')) then 1 else 0 end");
cmd.ExecuteNonQuery();
exists = (int)(long)cmd.ExecuteScalar()! == 1;
var cmdResult = Convert.ToInt16(cmd.ExecuteScalar());
exists = (cmdResult == 1);
}
catch
{
@@ -121,7 +128,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
{
// Other RDBMS. Graceful degradation
exists = true;
var cmdOthers = databaseConnector.DbCommand("select 1 from " + tableName + " where 1 = 0");
DbCommand cmdOthers = databaseConnector.DbCommand("select 1 from " + tableName + " where 1 = 0");
cmdOthers.ExecuteNonQuery();
}
catch
@@ -136,9 +143,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql
private void InitializeDatabaseSchema(IDatabaseConnector databaseConnector)
{
string sql;
var t = databaseConnector.GetType();
if (databaseConnector.GetType() == typeof(MSSqlDatabaseConnector))
{
sql = @"
@@ -204,13 +209,14 @@ CREATE TABLE [dbo].[tblCons] (
[RdpVersion] varchar(10) NULL,
[RedirectAudioCapture] bit NOT NULL,
[RedirectClipboard] bit NOT NULL,
[RedirectDiskDrives] bit NOT NULL,
[RedirectDiskDrives] varchar(32) DEFAULT NULL,
[RedirectDiskDrivesCustom] varchar(32) DEFAULT NULL,
[RedirectKeys] bit NOT NULL,
[RedirectPorts] bit NOT NULL,
[RedirectPrinters] bit NOT NULL,
[RedirectSmartCards] bit NOT NULL,
[RedirectSound] varchar(64) NOT NULL,
[RenderingEngine] varchar(16) NULL,
[RenderingEngine] varchar(32) NULL,
[Resolution] varchar(32) NOT NULL,
[SSHOptions] varchar(1024) NOT NULL,
[SSHTunnelConnectionName] varchar(128) NOT NULL,
@@ -275,6 +281,7 @@ CREATE TABLE [dbo].[tblCons] (
[InheritRedirectAudioCapture] bit NOT NULL,
[InheritRedirectClipboard] bit NOT NULL,
[InheritRedirectDiskDrives] bit NOT NULL,
[InheritRedirectDiskDrivesCustom] bit NOT NULL,
[InheritRedirectKeys] bit NOT NULL,
[InheritRedirectPorts] bit NOT NULL,
[InheritRedirectPrinters] bit NOT NULL,
@@ -358,24 +365,24 @@ CREATE TABLE `tblCons` (
`LastChange` datetime NOT NULL,
`Name` varchar(128) NOT NULL,
`Type` varchar(32) NOT NULL,
`Expanded` tinyint(1) NOT NULL,
`AutomaticResize` tinyint(1) NOT NULL DEFAULT 1,
`CacheBitmaps` tinyint(1) NOT NULL,
`Expanded` tinyint NOT NULL,
`AutomaticResize` tinyint NOT NULL DEFAULT 1,
`CacheBitmaps` tinyint NOT NULL,
`Colors` varchar(32) NOT NULL,
`ConnectToConsole` tinyint(1) NOT NULL,
`Connected` tinyint(1) NOT NULL,
`ConnectToConsole` tinyint NOT NULL,
`Connected` tinyint NOT NULL,
`Description` varchar(1024) DEFAULT NULL,
`DisableCursorBlinking` tinyint(1) NOT NULL,
`DisableCursorShadow` tinyint(1) NOT NULL,
`DisableFullWindowDrag` tinyint(1) NOT NULL,
`DisableMenuAnimations` tinyint(1) NOT NULL,
`DisplayThemes` tinyint(1) NOT NULL,
`DisplayWallpaper` tinyint(1) NOT NULL,
`DisableCursorBlinking` tinyint NOT NULL,
`DisableCursorShadow` tinyint NOT NULL,
`DisableFullWindowDrag` tinyint NOT NULL,
`DisableMenuAnimations` tinyint NOT NULL,
`DisplayThemes` tinyint NOT NULL,
`DisplayWallpaper` tinyint NOT NULL,
`Domain` varchar(512) DEFAULT NULL,
`EnableDesktopComposition` tinyint(1) NOT NULL,
`EnableFontSmoothing` tinyint(1) NOT NULL,
`EnableDesktopComposition` tinyint NOT NULL,
`EnableFontSmoothing` tinyint NOT NULL,
`ExtApp` varchar(256) DEFAULT NULL,
`Favorite` tinyint(1) NOT NULL,
`Favorite` tinyint NOT NULL,
`Hostname` varchar(512) DEFAULT NULL,
`Icon` varchar(128) NOT NULL,
`LoadBalanceInfo` varchar(1024) DEFAULT NULL,
@@ -394,26 +401,27 @@ CREATE TABLE `tblCons` (
`RDGatewayUsageMethod` varchar(32) NOT NULL,
`RDGatewayUseConnectionCredentials` varchar(32) NOT NULL,
`RDGatewayUsername` varchar(512) DEFAULT NULL,
`RDPAlertIdleTimeout` tinyint(1) NOT NULL,
`RDPAlertIdleTimeout` tinyint NOT NULL,
`RDPAuthenticationLevel` varchar(32) NOT NULL,
`RDPMinutesToIdleTimeout` int(11) NOT NULL,
`RdpVersion` varchar(10) DEFAULT NULL,
`RedirectAudioCapture` tinyint(1) NOT NULL,
`RedirectClipboard` tinyint(1) NOT NULL,
`RedirectDiskDrives` tinyint(1) NOT NULL,
`RedirectKeys` tinyint(1) NOT NULL,
`RedirectPorts` tinyint(1) NOT NULL,
`RedirectPrinters` tinyint(1) NOT NULL,
`RedirectSmartCards` tinyint(1) NOT NULL,
`RedirectAudioCapture` tinyint NOT NULL,
`RedirectClipboard` tinyint NOT NULL,
`RedirectDiskDrives` varchar(32) DEFAULT NULL,
`RedirectDiskDrivesCustom` varchar(32) DEFAULT NULL,
`RedirectKeys` tinyint NOT NULL,
`RedirectPorts` tinyint NOT NULL,
`RedirectPrinters` tinyint NOT NULL,
`RedirectSmartCards` tinyint NOT NULL,
`RedirectSound` varchar(64) NOT NULL,
`RenderingEngine` varchar(16) DEFAULT NULL,
`RenderingEngine` varchar(32) DEFAULT NULL,
`Resolution` varchar(32) NOT NULL,
`SSHOptions` varchar(1024) NOT NULL,
`SSHTunnelConnectionName` varchar(128) NOT NULL,
`SoundQuality` varchar(20) NOT NULL,
`UseCredSsp` tinyint(1) NOT NULL,
`UseEnhancedMode` tinyint(1) NOT NULL,
`UseVmId` tinyint(1) NOT NULL,
`UseCredSsp` tinyint NOT NULL,
`UseEnhancedMode` tinyint NOT NULL,
`UseVmId` tinyint NOT NULL,
`UserField` varchar(256) DEFAULT NULL,
`Username` varchar(512) DEFAULT NULL,
`VNCAuthMode` varchar(10) DEFAULT NULL,
@@ -426,85 +434,86 @@ CREATE TABLE `tblCons` (
`VNCProxyType` varchar(20) DEFAULT NULL,
`VNCProxyUsername` varchar(512) DEFAULT NULL,
`VNCSmartSizeMode` varchar(20) DEFAULT NULL,
`VNCViewOnly` tinyint(1) NOT NULL,
`VNCViewOnly` tinyint NOT NULL,
`VmId` varchar(512) DEFAULT NULL,
`ICAEncryptionStrength` varchar(32) NOT NULL,
`InheritAutomaticResize` tinyint(1) NOT NULL,
`InheritCacheBitmaps` tinyint(1) NOT NULL,
`InheritColors` tinyint(1) NOT NULL,
`InheritDescription` tinyint(1) NOT NULL,
`InheritDisableCursorBlinking` tinyint(1) NOT NULL,
`InheritDisableCursorShadow` tinyint(1) NOT NULL,
`InheritDisableFullWindowDrag` tinyint(1) NOT NULL,
`InheritDisableMenuAnimations` tinyint(1) NOT NULL,
`InheritDisplayThemes` tinyint(1) NOT NULL,
`InheritDisplayWallpaper` tinyint(1) NOT NULL,
`InheritDomain` tinyint(1) NOT NULL,
`InheritEnableDesktopComposition` tinyint(1) NOT NULL,
`InheritEnableFontSmoothing` tinyint(1) NOT NULL,
`InheritExtApp` tinyint(1) NOT NULL,
`InheritFavorite` tinyint(1) NOT NULL,
`InheritICAEncryptionStrength` tinyint(1) NOT NULL,
`InheritIcon` tinyint(1) NOT NULL,
`InheritLoadBalanceInfo` tinyint(1) NOT NULL,
`InheritMacAddress` tinyint(1) NOT NULL,
`InheritOpeningCommand` tinyint(1) NOT NULL,
`InheritPanel` tinyint(1) NOT NULL,
`InheritPassword` tinyint(1) NOT NULL,
`InheritPort` tinyint(1) NOT NULL,
`InheritPostExtApp` tinyint(1) NOT NULL,
`InheritPreExtApp` tinyint(1) NOT NULL,
`InheritProtocol` tinyint(1) NOT NULL,
`InheritPuttySession` tinyint(1) NOT NULL,
`InheritRDGatewayDomain` tinyint(1) NOT NULL,
`InheritRDGatewayHostname` tinyint(1) NOT NULL,
`InheritRDGatewayPassword` tinyint(1) NOT NULL,
`InheritRDGatewayUsageMethod` tinyint(1) NOT NULL,
`InheritRDGatewayUseConnectionCredentials` tinyint(1) NOT NULL,
`InheritRDGatewayExternalCredentialProvider` tinyint(1) NOT NULL,
`InheritRDGatewayUsername` tinyint(1) NOT NULL,
`InheritRDGatewayUserViaAPI` tinyint(1) NOT NULL,
`InheritRDPAlertIdleTimeout` tinyint(1) NOT NULL,
`InheritRDPAuthenticationLevel` tinyint(1) NOT NULL,
`InheritRDPMinutesToIdleTimeout` tinyint(1) NOT NULL,
`InheritRdpVersion` tinyint(1) NOT NULL,
`InheritRedirectAudioCapture` tinyint(1) NOT NULL,
`InheritRedirectClipboard` tinyint(1) NOT NULL,
`InheritRedirectDiskDrives` tinyint(1) NOT NULL,
`InheritRedirectKeys` tinyint(1) NOT NULL,
`InheritRedirectPorts` tinyint(1) NOT NULL,
`InheritRedirectPrinters` tinyint(1) NOT NULL,
`InheritRedirectSmartCards` tinyint(1) NOT NULL,
`InheritRedirectSound` tinyint(1) NOT NULL,
`InheritRenderingEngine` tinyint(1) NOT NULL,
`InheritResolution` tinyint(1) NOT NULL,
`InheritSSHOptions` tinyint(1) NOT NULL,
`InheritSSHTunnelConnectionName` tinyint(1) NOT NULL,
`InheritSoundQuality` tinyint(1) NOT NULL,
`InheritUseConsoleSession` tinyint(1) NOT NULL,
`InheritUseCredSsp` tinyint(1) NOT NULL,
`InheritUseRestrictedAdmin` tinyint(1) NOT NULL,
`InheritUseRCG` tinyint(1) NOT NULL,
`InheritExternalCredentialProvider` tinyint(1) NOT NULL,
`InheritUserViaAPI` tinyint(1) NOT NULL,
`UseRestrictedAdmin` tinyint(1) NOT NULL,
`UseRCG` tinyint(1) NOT NULL,
`InheritUseEnhancedMode` tinyint(1) DEFAULT NULL,
`InheritUseVmId` tinyint(1) DEFAULT NULL,
`InheritUserField` tinyint(1) NOT NULL,
`InheritUsername` tinyint(1) NOT NULL,
`InheritVNCAuthMode` tinyint(1) NOT NULL,
`InheritVNCColors` tinyint(1) NOT NULL,
`InheritVNCCompression` tinyint(1) NOT NULL,
`InheritVNCEncoding` tinyint(1) NOT NULL,
`InheritVNCProxyIP` tinyint(1) NOT NULL,
`InheritVNCProxyPassword` tinyint(1) NOT NULL,
`InheritVNCProxyPort` tinyint(1) NOT NULL,
`InheritVNCProxyType` tinyint(1) NOT NULL,
`InheritVNCProxyUsername` tinyint(1) NOT NULL,
`InheritVNCSmartSizeMode` tinyint(1) NOT NULL,
`InheritVNCViewOnly` tinyint(1) NOT NULL,
`InheritVmId` tinyint(1) NOT NULL,
`InheritAutomaticResize` tinyint NOT NULL,
`InheritCacheBitmaps` tinyint NOT NULL,
`InheritColors` tinyint NOT NULL,
`InheritDescription` tinyint NOT NULL,
`InheritDisableCursorBlinking` tinyint NOT NULL,
`InheritDisableCursorShadow` tinyint NOT NULL,
`InheritDisableFullWindowDrag` tinyint NOT NULL,
`InheritDisableMenuAnimations` tinyint NOT NULL,
`InheritDisplayThemes` tinyint NOT NULL,
`InheritDisplayWallpaper` tinyint NOT NULL,
`InheritDomain` tinyint NOT NULL,
`InheritEnableDesktopComposition` tinyint NOT NULL,
`InheritEnableFontSmoothing` tinyint NOT NULL,
`InheritExtApp` tinyint NOT NULL,
`InheritFavorite` tinyint NOT NULL,
`InheritICAEncryptionStrength` tinyint NOT NULL,
`InheritIcon` tinyint NOT NULL,
`InheritLoadBalanceInfo` tinyint NOT NULL,
`InheritMacAddress` tinyint NOT NULL,
`InheritOpeningCommand` tinyint NOT NULL,
`InheritPanel` tinyint NOT NULL,
`InheritPassword` tinyint NOT NULL,
`InheritPort` tinyint NOT NULL,
`InheritPostExtApp` tinyint NOT NULL,
`InheritPreExtApp` tinyint NOT NULL,
`InheritProtocol` tinyint NOT NULL,
`InheritPuttySession` tinyint NOT NULL,
`InheritRDGatewayDomain` tinyint NOT NULL,
`InheritRDGatewayHostname` tinyint NOT NULL,
`InheritRDGatewayPassword` tinyint NOT NULL,
`InheritRDGatewayUsageMethod` tinyint NOT NULL,
`InheritRDGatewayUseConnectionCredentials` tinyint NOT NULL,
`InheritRDGatewayExternalCredentialProvider` tinyint NOT NULL,
`InheritRDGatewayUsername` tinyint NOT NULL,
`InheritRDGatewayUserViaAPI` tinyint NOT NULL,
`InheritRDPAlertIdleTimeout` tinyint NOT NULL,
`InheritRDPAuthenticationLevel` tinyint NOT NULL,
`InheritRDPMinutesToIdleTimeout` tinyint NOT NULL,
`InheritRdpVersion` tinyint NOT NULL,
`InheritRedirectAudioCapture` tinyint NOT NULL,
`InheritRedirectClipboard` tinyint NOT NULL,
`InheritRedirectDiskDrives` tinyint NOT NULL,
`InheritRedirectDiskDrivesCustom` tinyint NOT NULL,
`InheritRedirectKeys` tinyint NOT NULL,
`InheritRedirectPorts` tinyint NOT NULL,
`InheritRedirectPrinters` tinyint NOT NULL,
`InheritRedirectSmartCards` tinyint NOT NULL,
`InheritRedirectSound` tinyint NOT NULL,
`InheritRenderingEngine` tinyint NOT NULL,
`InheritResolution` tinyint NOT NULL,
`InheritSSHOptions` tinyint NOT NULL,
`InheritSSHTunnelConnectionName` tinyint NOT NULL,
`InheritSoundQuality` tinyint NOT NULL,
`InheritUseConsoleSession` tinyint NOT NULL,
`InheritUseCredSsp` tinyint NOT NULL,
`InheritUseRestrictedAdmin` tinyint NOT NULL,
`InheritUseRCG` tinyint NOT NULL,
`InheritExternalCredentialProvider` tinyint NOT NULL,
`InheritUserViaAPI` tinyint NOT NULL,
`UseRestrictedAdmin` tinyint NOT NULL,
`UseRCG` tinyint NOT NULL,
`InheritUseEnhancedMode` tinyint DEFAULT NULL,
`InheritUseVmId` tinyint DEFAULT NULL,
`InheritUserField` tinyint NOT NULL,
`InheritUsername` tinyint NOT NULL,
`InheritVNCAuthMode` tinyint NOT NULL,
`InheritVNCColors` tinyint NOT NULL,
`InheritVNCCompression` tinyint NOT NULL,
`InheritVNCEncoding` tinyint NOT NULL,
`InheritVNCProxyIP` tinyint NOT NULL,
`InheritVNCProxyPassword` tinyint NOT NULL,
`InheritVNCProxyPort` tinyint NOT NULL,
`InheritVNCProxyType` tinyint NOT NULL,
`InheritVNCProxyUsername` tinyint NOT NULL,
`InheritVNCSmartSizeMode` tinyint NOT NULL,
`InheritVNCViewOnly` tinyint NOT NULL,
`InheritVmId` tinyint NOT NULL,
`StartProgram` varchar(512) DEFAULT NULL,
`StartProgramWorkDir` varchar(512) DEFAULT NULL,
`EC2Region` varchar(32) DEFAULT NULL,
@@ -526,7 +535,7 @@ DROP TABLE IF EXISTS `tblRoot`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tblRoot` (
`Name` varchar(2048) NOT NULL,
`Export` tinyint(1) NOT NULL,
`Export` tinyint NOT NULL,
`Protected` varchar(4048) NOT NULL,
`ConfVersion` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -555,6 +564,227 @@ CREATE TABLE `tblUpdate` (
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
";
// sql = @"
///*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
///*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
///*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
///*!40101 SET NAMES utf8 */;
///*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
///*!40103 SET TIME_ZONE='+00:00' */;
///*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
///*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
///*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
///*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
//--
//-- Table structure for table `tblCons`
//--
//DROP TABLE IF EXISTS `tblCons`;
///*!40101 SET @saved_cs_client = @@character_set_client */;
///*!40101 SET character_set_client = utf8 */;
//CREATE TABLE `tblCons` (
// `ID` int(11) NOT NULL AUTO_INCREMENT,
// `ConstantID` varchar(128) NOT NULL,
// `PositionID` int(11) NOT NULL,
// `ParentID` varchar(128) DEFAULT NULL,
// `LastChange` datetime NOT NULL,
// `Name` varchar(128) NOT NULL,
// `Type` varchar(32) NOT NULL,
// `Expanded` tinyint NOT NULL,
// `AutomaticResize` tinyint NOT NULL DEFAULT 1,
// `CacheBitmaps` tinyint NOT NULL,
// `Colors` varchar(32) NOT NULL,
// `ConnectToConsole` tinyint NOT NULL,
// `Connected` tinyint NOT NULL,
// `Description` varchar(1024) DEFAULT NULL,
// `DisableCursorBlinking` tinyint NOT NULL,
// `DisableCursorShadow` tinyint NOT NULL,
// `DisableFullWindowDrag` tinyint NOT NULL,
// `DisableMenuAnimations` tinyint NOT NULL,
// `DisplayThemes` tinyint NOT NULL,
// `DisplayWallpaper` tinyint NOT NULL,
// `Domain` varchar(512) DEFAULT NULL,
// `EnableDesktopComposition` tinyint NOT NULL,
// `EnableFontSmoothing` tinyint NOT NULL,
// `ExtApp` varchar(256) DEFAULT NULL,
// `Favorite` tinyint NOT NULL,
// `Hostname` varchar(512) DEFAULT NULL,
// `LoadBalanceInfo` varchar(1024) DEFAULT NULL,
// `MacAddress` varchar(32) DEFAULT NULL,
// `Panel` varchar(128) NOT NULL,
// `Password` varchar(1024) DEFAULT NULL,
// `Port` int(11) NOT NULL,
// `PostExtApp` varchar(256) DEFAULT NULL,
// `PreExtApp` varchar(256) DEFAULT NULL,
// `Protocol` varchar(32) NOT NULL,
// `PuttySession` varchar(128) DEFAULT NULL,
// `RDGatewayDomain` varchar(512) DEFAULT NULL,
// `RDGatewayHostname` varchar(512) DEFAULT NULL,
// `RDGatewayPassword` varchar(1024) DEFAULT NULL,
// `RDGatewayUsageMethod` varchar(32) NOT NULL,
// `RDGatewayUseConnectionCredentials` varchar(32) NOT NULL,
// `RDGatewayUsername` varchar(512) DEFAULT NULL,
// `RDPAlertIdleTimeout` tinyint NOT NULL,
// `RDPAuthenticationLevel` varchar(32) NOT NULL,
// `RDPMinutesToIdleTimeout` int(11) NOT NULL,
// `RdpVersion` varchar(10) DEFAULT NULL,
// `RedirectAudioCapture` tinyint NOT NULL,
// `RedirectClipboard` tinyint NOT NULL DEFAULT 0,
// `RedirectDiskDrives` tinyint NOT NULL,
// `RedirectKeys` tinyint NOT NULL,
// `RedirectPorts` tinyint NOT NULL,
// `RedirectPrinters` tinyint NOT NULL,
// `RedirectSmartCards` tinyint NOT NULL,
// `RedirectSound` varchar(64) NOT NULL,
// `RenderingEngine` varchar(10) DEFAULT NULL,
// `Resolution` varchar(32) NOT NULL,
// `SSHOptions` varchar(1024) NOT NULL,
// `SSHTunnelConnectionName` varchar(128) NOT NULL,
// `SoundQuality` varchar(20) NOT NULL,
// `UseCredSsp` tinyint NOT NULL,
// `UseEnhancedMode` tinyint DEFAULT NULL,
// `UseVmId` tinyint DEFAULT NULL,
// `UserField` varchar(256) DEFAULT NULL,
// `Username` varchar(512) DEFAULT NULL,
// `VNCAuthMode` varchar(10) DEFAULT NULL,
// `VNCColors` varchar(10) DEFAULT NULL,
// `VNCCompression` varchar(10) DEFAULT NULL,
// `VNCEncoding` varchar(20) DEFAULT NULL,
// `VNCProxyIP` varchar(128) DEFAULT NULL,
// `VNCProxyPassword` varchar(1024) DEFAULT NULL,
// `VNCProxyPort` int(11) DEFAULT NULL,
// `VNCProxyType` varchar(20) DEFAULT NULL,
// `VNCProxyUsername` varchar(512) DEFAULT NULL,
// `VNCSmartSizeMode` varchar(20) DEFAULT NULL,
// `VNCViewOnly` tinyint NOT NULL,
// `VmId` varchar(512) DEFAULT NULL,
// `ICAEncryptionStrength` varchar(32) NOT NULL,
// `Icon` varchar(128) NOT NULL,
// `InheritAutomaticResize` tinyint NOT NULL DEFAULT 0,
// `InheritCacheBitmaps` tinyint NOT NULL,
// `InheritColors` tinyint NOT NULL,
// `InheritDescription` tinyint NOT NULL,
// `InheritDisableCursorBlinking` tinyint NOT NULL,
// `InheritDisableCursorShadow` tinyint NOT NULL,
// `InheritDisableFullWindowDrag` tinyint NOT NULL,
// `InheritDisableMenuAnimations` tinyint NOT NULL,
// `InheritDisplayThemes` tinyint NOT NULL,
// `InheritDisplayWallpaper` tinyint NOT NULL,
// `InheritDomain` tinyint NOT NULL,
// `InheritEnableDesktopComposition` tinyint NOT NULL,
// `InheritEnableFontSmoothing` tinyint NOT NULL,
// `InheritExtApp` tinyint NOT NULL,
// `InheritFavorite` tinyint NOT NULL,
// `InheritICAEncryptionStrength` tinyint NOT NULL,
// `InheritIcon` tinyint NOT NULL,
// `InheritLoadBalanceInfo` tinyint NOT NULL DEFAULT 0,
// `InheritMacAddress` tinyint NOT NULL,
// `InheritPanel` tinyint NOT NULL,
// `InheritPassword` tinyint NOT NULL,
// `InheritPort` tinyint NOT NULL,
// `InheritPostExtApp` tinyint NOT NULL,
// `InheritPreExtApp` tinyint NOT NULL,
// `InheritProtocol` tinyint NOT NULL,
// `InheritPuttySession` tinyint NOT NULL,
// `InheritRDGatewayDomain` tinyint NOT NULL,
// `InheritRDGatewayHostname` tinyint NOT NULL,
// `InheritRDGatewayPassword` tinyint NOT NULL,
// `InheritRDGatewayUsageMethod` tinyint NOT NULL,
// `InheritRDGatewayUseConnectionCredentials` tinyint NOT NULL,
// `InheritRDGatewayUsername` tinyint NOT NULL,
// `InheritRDPAlertIdleTimeout` tinyint NOT NULL,
// `InheritRDPAuthenticationLevel` tinyint NOT NULL,
// `InheritRDPMinutesToIdleTimeout` tinyint NOT NULL,
// `InheritRdpVersion` tinyint NOT NULL DEFAULT 0,
// `InheritRedirectAudioCapture` tinyint NOT NULL,
// `InheritRedirectClipboard` tinyint NOT NULL DEFAULT 0,
// `InheritRedirectDiskDrives` tinyint NOT NULL,
// `InheritRedirectKeys` tinyint NOT NULL,
// `InheritRedirectPorts` tinyint NOT NULL,
// `InheritRedirectPrinters` tinyint NOT NULL,
// `InheritRedirectSmartCards` tinyint NOT NULL,
// `InheritRedirectSound` tinyint NOT NULL,
// `InheritRenderingEngine` tinyint NOT NULL,
// `InheritResolution` tinyint NOT NULL,
// `InheritSSHOptions` tinyint NOT NULL,
// `InheritSSHTunnelConnectionName` tinyint NOT NULL,
// `InheritSoundQuality` tinyint NOT NULL,
// `InheritUseConsoleSession` tinyint NOT NULL,
// `InheritUseCredSsp` tinyint NOT NULL,
// `InheritUseEnhancedMode` tinyint DEFAULT NULL,
// `InheritUseVmId` tinyint DEFAULT NULL,
// `InheritUserField` tinyint NOT NULL,
// `InheritUsername` tinyint NOT NULL,
// `InheritVNCAuthMode` tinyint NOT NULL,
// `InheritVNCColors` tinyint NOT NULL,
// `InheritVNCCompression` tinyint NOT NULL,
// `InheritVNCEncoding` tinyint NOT NULL,
// `InheritVNCProxyIP` tinyint NOT NULL,
// `InheritVNCProxyPassword` tinyint NOT NULL,
// `InheritVNCProxyPort` tinyint NOT NULL,
// `InheritVNCProxyType` tinyint NOT NULL,
// `InheritVNCProxyUsername` tinyint NOT NULL,
// `InheritVNCSmartSizeMode` tinyint NOT NULL,
// `InheritVNCViewOnly` tinyint NOT NULL,
// `InheritVmId` tinyint DEFAULT NULL,
// PRIMARY KEY (`ConstantID`),
// UNIQUE (`ID`)
//) ENGINE=InnoDB AUTO_INCREMENT=3324 DEFAULT CHARSET=latin1;
///*!40101 SET character_set_client = @saved_cs_client */;
//--
//-- Table structure for table `tblRoot`
//--
//DROP TABLE IF EXISTS `tblRoot`;
///*!40101 SET @saved_cs_client = @@character_set_client */;
///*!40101 SET character_set_client = utf8 */;
//CREATE TABLE `tblRoot` (
// `Name` varchar(2048) NOT NULL,
// `Export` tinyint NOT NULL,
// `Protected` varchar(4048) NOT NULL,
// `ConfVersion` double NOT NULL
//) ENGINE=InnoDB DEFAULT CHARSET=latin1;
///*!40101 SET character_set_client = @saved_cs_client */;
//--
//-- Table structure for table `tblUpdate`
//--
//DROP TABLE IF EXISTS `tblUpdate`;
///*!40101 SET @saved_cs_client = @@character_set_client */;
///*!40101 SET character_set_client = utf8 */;
//CREATE TABLE `tblUpdate` (
// `LastUpdate` datetime(3) DEFAULT NULL
//) ENGINE=InnoDB DEFAULT CHARSET=latin1;
///*!40101 SET character_set_client = @saved_cs_client */;
///*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
///*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
///*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
///*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
///*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
///*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
///*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
///*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
//";
}
else
{
@@ -567,7 +797,3 @@ CREATE TABLE `tblUpdate` (
}
}
//// MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(`ConstantID`),
//UNIQUE(`ID`)
// ) ENGINE = InnoDB AUTO_INCREMENT = 3324 DEFAULT ' at line 156'

View File

@@ -61,9 +61,8 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
if (_confVersion > 1.3)
{
var protectedString = _xmlDocument.DocumentElement?.Attributes["Protected"].Value;
if (!_decryptor.ConnectionsFileIsAuthentic(protectedString,
_rootNodeInfo.PasswordString.ConvertToSecureString()))
var protectedString = _xmlDocument.DocumentElement?.Attributes["Protected"]?.Value;
if (!_decryptor.ConnectionsFileIsAuthentic(protectedString, _rootNodeInfo.PasswordString.ConvertToSecureString()))
{
return null;
}
@@ -108,9 +107,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void ValidateConnectionFileVersion()
{
if (_xmlDocument.DocumentElement != null && _xmlDocument.DocumentElement.HasAttribute("ConfVersion"))
_confVersion =
Convert.ToDouble(_xmlDocument.DocumentElement.Attributes["ConfVersion"].Value.Replace(",", "."),
CultureInfo.InvariantCulture);
_confVersion = Convert.ToDouble(_xmlDocument.DocumentElement.Attributes["ConfVersion"]?.Value.Replace(",", "."), CultureInfo.InvariantCulture);
else
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, Language.OldConffile);
@@ -142,7 +139,7 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
private void InitializeRootNode(XmlElement connectionsRootElement)
{
var rootNodeName = connectionsRootElement?.Attributes["Name"].Value.Trim();
var rootNodeName = connectionsRootElement?.Attributes["Name"]?.Value.Trim();
_rootNodeInfo.Name = rootNodeName;
}
@@ -163,7 +160,9 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
else
{
_decryptor = new XmlConnectionsDecryptor(_rootNodeInfo)
{AuthenticationRequestor = AuthenticationRequestor};
{
AuthenticationRequestor = AuthenticationRequestor
};
}
}
@@ -365,13 +364,11 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
connectionInfo.Inheritance.Port = xmlnode.GetAttributeAsBool("InheritPort");
connectionInfo.Inheritance.Protocol = xmlnode.GetAttributeAsBool("InheritProtocol");
connectionInfo.Inheritance.PuttySession = xmlnode.GetAttributeAsBool("InheritPuttySession");
connectionInfo.Inheritance.RedirectDiskDrives =
xmlnode.GetAttributeAsBool("InheritRedirectDiskDrives");
connectionInfo.Inheritance.RedirectDiskDrives = xmlnode.GetAttributeAsBool("InheritRedirectDiskDrives");
connectionInfo.Inheritance.RedirectKeys = xmlnode.GetAttributeAsBool("InheritRedirectKeys");
connectionInfo.Inheritance.RedirectPorts = xmlnode.GetAttributeAsBool("InheritRedirectPorts");
connectionInfo.Inheritance.RedirectPrinters = xmlnode.GetAttributeAsBool("InheritRedirectPrinters");
connectionInfo.Inheritance.RedirectSmartCards =
xmlnode.GetAttributeAsBool("InheritRedirectSmartCards");
connectionInfo.Inheritance.RedirectSmartCards = xmlnode.GetAttributeAsBool("InheritRedirectSmartCards");
connectionInfo.Inheritance.RedirectSound = xmlnode.GetAttributeAsBool("InheritRedirectSound");
connectionInfo.Inheritance.RedirectAudioCapture = xmlnode.GetAttributeAsBool("RedirectAudioCapture");
connectionInfo.Inheritance.Resolution = xmlnode.GetAttributeAsBool("InheritResolution");
@@ -569,27 +566,27 @@ namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Xml
connectionInfo.Inheritance.RDGatewayExternalCredentialProvider = xmlnode.GetAttributeAsBool("InheritRDGatewayExternalCredentialProvider");
connectionInfo.Inheritance.RDGatewayUserViaAPI = xmlnode.GetAttributeAsBool("InheritRDGatewayUserViaAPI");
}
if (_confVersion >= 2.8)
switch (_confVersion)
{
connectionInfo.RedirectDiskDrives = xmlnode.GetAttributeAsEnum<RDPDiskDrives>("RedirectDiskDrives");
connectionInfo.RedirectDiskDrivesCustom = xmlnode.GetAttributeAsString("RedirectDiskDrivesCustom");
connectionInfo.Inheritance.RedirectDiskDrivesCustom = xmlnode.GetAttributeAsBool("InheritRedirectDiskDrivesCustom");
}
else if (_confVersion >= 0.5)
{
// used to be boolean
bool tmpRedirect = xmlnode.GetAttributeAsBool("RedirectDiskDrives");
if (tmpRedirect)
connectionInfo.RedirectDiskDrives = RDPDiskDrives.Local;
else
connectionInfo.RedirectDiskDrives = RDPDiskDrives.None;
case >= 3.0:
connectionInfo.RedirectDiskDrives = xmlnode.GetAttributeAsEnum<RDPDiskDrives>("RedirectDiskDrives");
connectionInfo.RedirectDiskDrivesCustom = xmlnode.GetAttributeAsString("RedirectDiskDrivesCustom");
connectionInfo.Inheritance.RedirectDiskDrivesCustom = xmlnode.GetAttributeAsBool("InheritRedirectDiskDrivesCustom");
break;
case >= 0.5:
{
// used to be boolean
bool tmpRedirect = xmlnode.GetAttributeAsBool("RedirectDiskDrives");
connectionInfo.RedirectDiskDrives = tmpRedirect ? RDPDiskDrives.Local : RDPDiskDrives.None;
break;
}
}
}
catch (Exception ex)
{
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
string.Format(Language.GetConnectionInfoFromXmlFailed,
connectionInfo.Name, ConnectionFileName, ex.Message));
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.GetConnectionInfoFromXmlFailed, connectionInfo.Name, ConnectionFileName, ex.Message));
}
return connectionInfo;

View File

@@ -11,26 +11,22 @@ namespace mRemoteNG.Config.Serializers.Versioning
[SupportedOSPlatform("windows")]
public class SqlDatabaseVersionVerifier
{
protected readonly Version currentSupportedVersion = new Version(2, 9);
private readonly Version _currentSupportedVersion = new Version(3, 0);
private readonly IDatabaseConnector _databaseConnector;
public SqlDatabaseVersionVerifier(IDatabaseConnector DatabaseConnector)
public SqlDatabaseVersionVerifier(IDatabaseConnector databaseConnector)
{
if (DatabaseConnector == null)
throw new ArgumentNullException(nameof(DatabaseConnector));
_databaseConnector = DatabaseConnector;
_databaseConnector = databaseConnector ?? throw new ArgumentNullException(nameof(databaseConnector));
}
public bool VerifyDatabaseVersion(Version dbVersion)
{
var isVerified = false;
try
{
var databaseVersion = dbVersion;
Version databaseVersion = dbVersion;
if (databaseVersion.Equals(new Version()))
if (databaseVersion.Equals(_currentSupportedVersion))
{
return true;
}
@@ -47,7 +43,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
new SqlVersion29To30Upgrader(_databaseConnector),
};
foreach (var upgrader in dbUpgraders)
foreach (IVersionUpgrader upgrader in dbUpgraders)
{
if (upgrader.CanUpgrade(databaseVersion))
{
@@ -56,23 +52,19 @@ namespace mRemoteNG.Config.Serializers.Versioning
}
// DB is at the highest current supported version
if (databaseVersion.CompareTo(currentSupportedVersion) == 0)
isVerified = true;
if (databaseVersion.CompareTo(_currentSupportedVersion) == 0)
{
return true;
}
if (isVerified == false)
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg,
string.Format(Language.ErrorBadDatabaseVersion,
databaseVersion,
GeneralAppInfo.ProductName));
Runtime.MessageCollector.AddMessage(MessageClass.WarningMsg, string.Format(Language.ErrorBadDatabaseVersion, databaseVersion, GeneralAppInfo.ProductName));
}
catch (Exception ex)
{
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
string.Format(Language.ErrorVerifyDatabaseVersionFailed,
ex.Message));
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.ErrorVerifyDatabaseVersionFailed, ex.Message));
}
return isVerified;
return false;
}
}
}

View File

@@ -13,10 +13,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
public SqlVersion22To23Upgrader(IDatabaseConnector databaseConnector)
{
if (databaseConnector == null)
throw new ArgumentNullException(nameof(databaseConnector));
_databaseConnector = databaseConnector;
_databaseConnector = databaseConnector ?? throw new ArgumentNullException(nameof(databaseConnector));
}
public bool CanUpgrade(Version currentVersion)
@@ -27,13 +24,16 @@ namespace mRemoteNG.Config.Serializers.Versioning
public Version Upgrade()
{
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.2 to version 2.3.");
const string sqlText = @"
ALTER TABLE tblCons
ADD EnableFontSmoothing bit NOT NULL DEFAULT 0,
EnableDesktopComposition bit NOT NULL DEFAULT 0,
InheritEnableFontSmoothing bit NOT NULL DEFAULT 0,
InheritEnableDesktopComposition bit NOT NULL DEFAULT 0;";
var dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
return new Version(2, 3);

View File

@@ -13,10 +13,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
public SqlVersion23To24Upgrader(IDatabaseConnector databaseConnector)
{
if (databaseConnector == null)
throw new ArgumentNullException(nameof(databaseConnector));
_databaseConnector = databaseConnector;
_databaseConnector = databaseConnector ?? throw new ArgumentNullException(nameof(databaseConnector));
}
public bool CanUpgrade(Version currentVersion)
@@ -26,13 +23,15 @@ namespace mRemoteNG.Config.Serializers.Versioning
public Version Upgrade()
{
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg,
"Upgrading database from version 2.3 to version 2.4.");
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Upgrading database from version 2.3 to version 2.4.");
const string sqlText = @"
ALTER TABLE tblCons
ADD UseCredSsp bit NOT NULL DEFAULT 1,
InheritUseCredSsp bit NOT NULL DEFAULT 0;";
var dbCommand = _databaseConnector.DbCommand(sqlText);
dbCommand.ExecuteNonQuery();
return new Version(2, 4);

View File

@@ -13,10 +13,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
public SqlVersion24To25Upgrader(IDatabaseConnector databaseConnector)
{
if (databaseConnector == null)
throw new ArgumentNullException(nameof(databaseConnector));
_databaseConnector = databaseConnector;
_databaseConnector = databaseConnector ?? throw new ArgumentNullException(nameof(databaseConnector));
}
public bool CanUpgrade(Version currentVersion)

View File

@@ -13,10 +13,7 @@ namespace mRemoteNG.Config.Serializers.Versioning
public SqlVersion25To26Upgrader(IDatabaseConnector databaseConnector)
{
if (databaseConnector == null)
throw new ArgumentNullException(nameof(databaseConnector));
_databaseConnector = databaseConnector;
_databaseConnector = databaseConnector ?? throw new ArgumentNullException(nameof(databaseConnector));
}
public bool CanUpgrade(Version currentVersion)

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 Version(2, 9);
private readonly IDatabaseConnector _databaseConnector;
public SqlVersion28To29Upgrader(IDatabaseConnector databaseConnector)
@@ -23,44 +23,44 @@ namespace mRemoteNG.Config.Serializers.Versioning
return currentVersion == new Version(2, 8) ||
// Support upgrading during dev revisions, 2.9.1, 2.9.2, etc...
(currentVersion <= new Version(2, 9) &&
currentVersion < version);
currentVersion < _version);
}
public Version Upgrade()
{
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg,
$"Upgrading database to version {version}.");
$"Upgrading database to version {_version}.");
// MYSQL
const string mySqlAlter = @"
ALTER TABLE tblCons ADD COLUMN `InheritUseRestrictedAdmin` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `UseRCG` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `UseRestrictedAdmin` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritUseRCG` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritRDGatewayExternalCredentialProvider` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritRDGatewayUserViaAPI` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritExternalCredentialProvider` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritUserViaAPI` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritUseRestrictedAdmin` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `UseRCG` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `UseRestrictedAdmin` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritUseRCG` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritRDGatewayExternalCredentialProvider` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritRDGatewayUserViaAPI` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritExternalCredentialProvider` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritUserViaAPI` tinyint NOT NULL;
ALTER TABLE tblCons ADD COLUMN `EC2Region` varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ADD COLUMN `EC2InstanceId` varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ADD COLUMN `ExternalCredentialProvider` varchar(256) DEFAULT NULL;
ALTER TABLE tblCons ADD COLUMN `ExternalAddressProvider` varchar(256) DEFAULT NULL;
SET SQL_SAFE_UPDATES=0;
UPDATE tblCons SET InheritUseEnhancedMode = 0 WHERE InheritUseEnhancedMode IS NULL;
ALTER TABLE tblCons MODIFY COLUMN InheritUseEnhancedMode tinyint(1) NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN InheritUseEnhancedMode tinyint NOT NULL;
UPDATE tblCons SET UseEnhancedMode = 0 WHERE UseEnhancedMode IS NULL;
ALTER TABLE tblCons MODIFY COLUMN UseEnhancedMode tinyint(1) NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN UseEnhancedMode tinyint NOT NULL;
UPDATE tblCons SET InheritVmId = 0 WHERE InheritVmId IS NULL;
ALTER TABLE tblCons MODIFY COLUMN InheritVmId tinyint(1) NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN InheritVmId tinyint NOT NULL;
UPDATE tblCons SET InheritUseVmId = 0 WHERE InheritUseVmId IS NULL;
ALTER TABLE tblCons MODIFY COLUMN InheritUseVmId tinyint(1) NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN InheritUseVmId tinyint NOT NULL;
UPDATE tblCons SET UseVmId = 0 WHERE UseVmId IS NULL;
ALTER TABLE tblCons MODIFY COLUMN UseVmId tinyint(1) NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN UseVmId tinyint NOT NULL;
SET SQL_SAFE_UPDATES=1;
ALTER TABLE tblRoot ALTER COLUMN ConfVersion VARCHAR(15) NOT NULL;
ALTER TABLE tblRoot MODIFY COLUMN ConfVersion VARCHAR(15) NOT NULL;
";
const string mySqlUpdate = @"UPDATE tblRoot SET ConfVersion=?;";
const string mySqlUpdate = @"SET SQL_SAFE_UPDATES=0; UPDATE tblRoot SET ConfVersion=?; SET SQL_SAFE_UPDATES=1;";
// MS-SQL
const string msSqlAlter = @"
@@ -116,7 +116,7 @@ ALTER TABLE tblRoot ALTER COLUMN [ConfVersion] VARCHAR(15) NOT NULL;
}
var pConfVersion = dbCommand.CreateParameter();
pConfVersion.ParameterName = "confVersion";
pConfVersion.Value = version.ToString();
pConfVersion.Value = _version.ToString();
pConfVersion.DbType = System.Data.DbType.String;
pConfVersion.Direction = System.Data.ParameterDirection.Input;
dbCommand.Parameters.Add(pConfVersion);
@@ -124,7 +124,7 @@ ALTER TABLE tblRoot ALTER COLUMN [ConfVersion] VARCHAR(15) NOT NULL;
dbCommand.ExecuteNonQuery();
sqlTran.Commit();
}
return version;
return _version;
}
}
}

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 Version(3, 0);
private readonly IDatabaseConnector _databaseConnector;
public SqlVersion29To30Upgrader(IDatabaseConnector databaseConnector)
@@ -23,25 +23,131 @@ namespace mRemoteNG.Config.Serializers.Versioning
return currentVersion == new Version(2, 9) ||
// Support upgrading during dev revisions, 2.9.1, 2.9.2, etc...
(currentVersion <= new Version(3, 0) &&
currentVersion < version);
currentVersion < _version);
}
public Version Upgrade()
{
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg,
$"Upgrading database to version {version}.");
$"Upgrading database to version {_version}.");
// MYSQL
const string mySqlAlter = @"
ALTER TABLE tblCons ALTER COLUMN `RedirectDiskDrives` varchar(32) DEFAULT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RenderingEngine` varchar(32) DEFAULT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectDiskDrives` varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ADD COLUMN `RedirectDiskDrivesCustom` varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritRedirectDiskDrivesCustom` tinyint(1) NOT NULL;
ALTER TABLE tblCons ADD COLUMN `InheritRedirectDiskDrivesCustom` tinyint NOT NULL;
-- mysql tinyint(1) is deprecated - modify all tinyint(1) columns to tinyint
ALTER TABLE tblCons MODIFY COLUMN `Expanded` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `AutomaticResize` tinyint NOT NULL DEFAULT '1';
ALTER TABLE tblCons MODIFY COLUMN `CacheBitmaps` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `ConnectToConsole` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `Connected` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `DisableCursorBlinking` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `DisableCursorShadow` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `DisableFullWindowDrag` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `DisableMenuAnimations` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `DisplayThemes` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `DisplayWallpaper` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `EnableDesktopComposition` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `EnableFontSmoothing` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `Favorite` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RDPAlertIdleTimeout` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectAudioCapture` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectClipboard` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectKeys` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectPorts` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectPrinters` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `RedirectSmartCards` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `UseCredSsp` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `UseEnhancedMode` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `UseVmId` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `VNCViewOnly` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritAutomaticResize` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritCacheBitmaps` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritColors` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDescription` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDisableCursorBlinking` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDisableCursorShadow` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDisableFullWindowDrag` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDisableMenuAnimations` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDisplayThemes` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDisplayWallpaper` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritDomain` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritEnableDesktopComposition` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritEnableFontSmoothing` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritExtApp` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritFavorite` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritICAEncryptionStrength` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritIcon` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritLoadBalanceInfo` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritMacAddress` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritOpeningCommand` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritPanel` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritPassword` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritPort` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritPostExtApp` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritPreExtApp` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritProtocol` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritPuttySession` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayDomain` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayHostname` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayPassword` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayUsageMethod` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayUseConnectionCredentials` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayExternalCredentialProvider` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayUsername` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDGatewayUserViaAPI` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDPAlertIdleTimeout` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDPAuthenticationLevel` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRDPMinutesToIdleTimeout` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRdpVersion` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectAudioCapture` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectClipboard` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectDiskDrives` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectDiskDrivesCustom` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectKeys` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectPorts` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectPrinters` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectSmartCards` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRedirectSound` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritRenderingEngine` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritResolution` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritSSHOptions` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritSSHTunnelConnectionName` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritSoundQuality` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUseConsoleSession` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUseCredSsp` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUseRestrictedAdmin` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUseRCG` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritExternalCredentialProvider` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUserViaAPI` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `UseRestrictedAdmin` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `UseRCG` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUseEnhancedMode` tinyint DEFAULT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUseVmId` tinyint DEFAULT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUserField` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritUsername` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCAuthMode` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCColors` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCCompression` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCEncoding` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCProxyIP` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCProxyPassword` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCProxyPort` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCProxyType` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCProxyUsername` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCSmartSizeMode` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVNCViewOnly` tinyint NOT NULL;
ALTER TABLE tblCons MODIFY COLUMN `InheritVmId` tinyint NOT NULL;
";
const string mySqlUpdate = @"UPDATE tblRoot SET ConfVersion=?;";
const string mySqlUpdate = @"SET SQL_SAFE_UPDATES=0; UPDATE tblRoot SET ConfVersion=?; SET SQL_SAFE_UPDATES=1;";
// MS-SQL
const string msSqlAlter = @"
ALTER TABLE tblCons ALTER COLUMN RenderingEngine varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ALTER COLUMN RedirectDiskDrives varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ADD RedirectDiskDrivesCustom varchar(32) DEFAULT NULL;
ALTER TABLE tblCons ADD InheritRedirectDiskDrivesCustom bit NOT NULL;
@@ -74,7 +180,7 @@ ALTER TABLE tblCons ADD InheritRedirectDiskDrivesCustom bit NOT NULL;
}
var pConfVersion = dbCommand.CreateParameter();
pConfVersion.ParameterName = "confVersion";
pConfVersion.Value = version.ToString();
pConfVersion.Value = _version.ToString();
pConfVersion.DbType = System.Data.DbType.String;
pConfVersion.Direction = System.Data.ParameterDirection.Input;
dbCommand.Parameters.Add(pConfVersion);
@@ -82,7 +188,7 @@ ALTER TABLE tblCons ADD InheritRedirectDiskDrivesCustom bit NOT NULL;
dbCommand.ExecuteNonQuery();
sqlTran.Commit();
}
return version;
return _version;
}
}
}

View File

@@ -30,25 +30,12 @@ namespace mRemoteNG.Config.Settings
public SettingsLoader(FrmMain mainForm, MessageCollector messageCollector, QuickConnectToolStrip quickConnectToolStrip, ExternalToolsToolStrip externalToolsToolStrip, MultiSshToolStrip multiSshToolStrip, MenuStrip mainMenu)
{
if (mainForm == null)
throw new ArgumentNullException(nameof(mainForm));
if (messageCollector == null)
throw new ArgumentNullException(nameof(messageCollector));
if (quickConnectToolStrip == null)
throw new ArgumentNullException(nameof(quickConnectToolStrip));
if (externalToolsToolStrip == null)
throw new ArgumentNullException(nameof(externalToolsToolStrip));
if (multiSshToolStrip == null)
throw new ArgumentNullException(nameof(multiSshToolStrip));
if (mainMenu == null)
throw new ArgumentNullException(nameof(mainMenu));
MainForm = mainForm;
_messageCollector = messageCollector;
_quickConnectToolStrip = quickConnectToolStrip;
_externalToolsToolStrip = externalToolsToolStrip;
_multiSshToolStrip = multiSshToolStrip;
_mainMenu = mainMenu;
MainForm = mainForm ?? throw new ArgumentNullException(nameof(mainForm));
_messageCollector = messageCollector ?? throw new ArgumentNullException(nameof(messageCollector));
_quickConnectToolStrip = quickConnectToolStrip ?? throw new ArgumentNullException(nameof(quickConnectToolStrip));
_externalToolsToolStrip = externalToolsToolStrip ?? throw new ArgumentNullException(nameof(externalToolsToolStrip));
_multiSshToolStrip = multiSshToolStrip ?? throw new ArgumentNullException(nameof(multiSshToolStrip));
_mainMenu = mainMenu ?? throw new ArgumentNullException(nameof(mainMenu));
_externalAppsLoader = new ExternalAppsLoader(MainForm, messageCollector, _externalToolsToolStrip);
}
@@ -162,6 +149,7 @@ namespace mRemoteNG.Config.Settings
private void EnsureSettingsAreSavedInNewestVersion()
{
// TODO: is this ever true and run?
if (Properties.App.Default.DoUpgrade)
UpgradeSettingsVersion();
}

View File

@@ -91,8 +91,8 @@ namespace mRemoteNG.Connection
private string _macAddress;
private string _openingCommand;
private string _userField;
private string _RDPStartProgram;
private string _RDPStartProgramWorkDir;
private string _rdpStartProgram;
private string _rdpStartProgramWorkDir;
private bool _favorite;
private ProtocolVNC.Compression _vncCompression;
@@ -870,8 +870,8 @@ namespace mRemoteNG.Connection
AttributeUsedInProtocol(ProtocolType.RDP)]
public virtual string RDPStartProgram
{
get => GetPropertyValue("RDPStartProgram", _RDPStartProgram);
set => SetField(ref _RDPStartProgram, value, "RDPStartProgram");
get => GetPropertyValue("RDPStartProgram", _rdpStartProgram);
set => SetField(ref _rdpStartProgram, value, "RDPStartProgram");
}
[LocalizedAttributes.LocalizedCategory(nameof(Language.Miscellaneous), 7),
@@ -880,8 +880,8 @@ namespace mRemoteNG.Connection
AttributeUsedInProtocol(ProtocolType.RDP)]
public virtual string RDPStartProgramWorkDir
{
get => GetPropertyValue("RDPStartProgramWorkDir", _RDPStartProgramWorkDir);
set => SetField(ref _RDPStartProgramWorkDir, value, "RDPStartProgramWorkDir");
get => GetPropertyValue("RDPStartProgramWorkDir", _rdpStartProgramWorkDir);
set => SetField(ref _rdpStartProgramWorkDir, value, "RDPStartProgramWorkDir");
}
#endregion

View File

@@ -9,7 +9,6 @@ using mRemoteNG.Config.Connections;
using mRemoteNG.Config.Connections.Multiuser;
using mRemoteNG.Config.DataProviders;
using mRemoteNG.Config.Putty;
using mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql;
using mRemoteNG.Connection.Protocol;
using mRemoteNG.Messages;
using mRemoteNG.Security;
@@ -19,6 +18,7 @@ using mRemoteNG.Tree.Root;
using mRemoteNG.UI;
using mRemoteNG.Resources.Language;
using System.Runtime.Versioning;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Sql;
namespace mRemoteNG.Connection
{
@@ -142,7 +142,7 @@ namespace mRemoteNG.Connection
var newConnectionTreeModel = connectionLoader.Load();
if (useDatabase)
LastSqlUpdate = DateTime.Now;
LastSqlUpdate = DateTime.Now.ToUniversalTime();
if (newConnectionTreeModel == null)
{
@@ -246,7 +246,7 @@ namespace mRemoteNG.Connection
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Saving connections...");
RemoteConnectionsSyncronizer?.Disable();
var previouslyUsingDatabase = UsingDatabase;
bool previouslyUsingDatabase = UsingDatabase;
var saver = useDatabase
? (ISaver<ConnectionTreeModel>)new SqlConnectionsSaver(saveFilter, _localConnectionPropertiesSerializer, _localConnectionPropertiesDataProvider)
@@ -255,12 +255,11 @@ namespace mRemoteNG.Connection
saver.Save(connectionTreeModel, propertyNameTrigger);
if (UsingDatabase)
LastSqlUpdate = DateTime.Now;
LastSqlUpdate = DateTime.Now.ToUniversalTime();
UsingDatabase = useDatabase;
ConnectionFileName = connectionFileName;
RaiseConnectionsSavedEvent(connectionTreeModel, previouslyUsingDatabase, UsingDatabase,
connectionFileName);
RaiseConnectionsSavedEvent(connectionTreeModel, previouslyUsingDatabase, UsingDatabase, connectionFileName);
Runtime.MessageCollector.AddMessage(MessageClass.InformationMsg, "Successfully saved connections");
}
catch (Exception ex)

View File

@@ -8,12 +8,9 @@ using System.IO;
using System.Security;
using mRemoteNG.App;
using mRemoteNG.Messages;
using mRemoteNG.Properties;
using mRemoteNG.UI.Forms;
using MySql.Data.Types;
using mRemoteNG.Resources.Language;
using static System.String;
using System.Windows;
using System.Runtime.Versioning;
namespace mRemoteNG.Tools
@@ -65,6 +62,26 @@ namespace mRemoteNG.Tools
return Number;
}
public static bool GetBooleanValue(object dataObject)
{
Type type = dataObject.GetType();
if (type == typeof(bool))
{
return (bool)dataObject;
}
if (type == typeof(string))
{
return (string)dataObject == "1";
}
if (type == typeof(sbyte))
{
return (sbyte)dataObject == 1;
}
Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, $"Conversion of object to boolean failed because the type, {type}, is not handled.");
return false;
}
public static string DBDate(DateTime Dt)
{
@@ -95,10 +112,10 @@ namespace mRemoteNG.Tools
switch (Properties.OptionsDBsPage.Default.SQLServerType)
{
case "mysql":
return new MySqlDateTime(DateTime.Now);
return new MySqlDateTime(DateTime.Now.ToUniversalTime());
case "mssql":
default:
return DateTime.Now;
return DateTime.Now.ToUniversalTime();
}
}
@@ -117,7 +134,7 @@ namespace mRemoteNG.Tools
var message = ex.Message;
if (ex.InnerException == null) return message;
var innerMessage = GetExceptionMessageRecursive(ex.InnerException, separator);
message = Join(separator, message, innerMessage);
message = String.Join(separator, message, innerMessage);
return message;
}

View File

@@ -7,41 +7,40 @@ using mRemoteNGTests.Properties;
using mRemoteNGTests.TestHelpers;
using NUnit.Framework;
namespace mRemoteNGTests.App
namespace mRemoteNGTests.App;
public class ImportTests
{
public class ImportTests
{
[Test]
public void ErrorHandlerCalledWhenUnsupportedFileExtensionFound()
{
using (FileTestHelpers.DisposableTempFile(out var file, ".blah"))
{
var conService = new ConnectionsService(PuttySessionsManager.Instance);
var container = new ContainerInfo();
var exceptionOccurred = false;
[Test]
public void ErrorHandlerCalledWhenUnsupportedFileExtensionFound()
{
using (FileTestHelpers.DisposableTempFile(out var file, ".blah"))
{
var conService = new ConnectionsService(PuttySessionsManager.Instance);
var container = new ContainerInfo();
var exceptionOccurred = false;
Import.HeadlessFileImport(new []{file}, container, conService, s => exceptionOccurred = true);
Import.HeadlessFileImport(new[] { file }, container, conService, s => exceptionOccurred = true);
Assert.That(exceptionOccurred);
}
}
Assert.That(exceptionOccurred);
}
}
[Test]
public void AnErrorInOneFileDoNotPreventOtherFilesFromProcessing()
{
using (FileTestHelpers.DisposableTempFile(out var badFile, ".blah"))
using (FileTestHelpers.DisposableTempFile(out var rdpFile, ".rdp"))
{
File.AppendAllText(rdpFile, Resources.test_remotedesktopconnection_rdp);
var conService = new ConnectionsService(PuttySessionsManager.Instance);
var container = new ContainerInfo();
var exceptionCount = 0;
Import.HeadlessFileImport(new[] { badFile, rdpFile }, container, conService, s => exceptionCount++);
[Test]
public void AnErrorInOneFileDoNotPreventOtherFilesFromProcessing()
{
using (FileTestHelpers.DisposableTempFile(out var badFile, ".blah"))
using (FileTestHelpers.DisposableTempFile(out var rdpFile, ".rdp"))
{
File.AppendAllText(rdpFile, Resources.test_remotedesktopconnection_rdp);
var conService = new ConnectionsService(PuttySessionsManager.Instance);
var container = new ContainerInfo();
var exceptionCount = 0;
Assert.That(exceptionCount, Is.EqualTo(1));
Assert.That(container.Children, Has.One.Items);
}
}
}
}
Import.HeadlessFileImport(new[] { badFile, rdpFile }, container, conService, s => exceptionCount++);
Assert.That(exceptionCount, Is.EqualTo(1));
Assert.That(container.Children, Has.One.Items);
}
}
}

View File

@@ -4,81 +4,80 @@ using mRemoteNG.App.Update;
using mRemoteNGTests.Properties;
using NUnit.Framework;
namespace mRemoteNGTests.App
namespace mRemoteNGTests.App;
[TestFixture]
public class UpdaterTests
{
[TestFixture]
public class UpdaterTests
[Test]
public void UpdateStableChannel()
{
[Test]
public void UpdateStableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.update);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateBetaChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.beta_update);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateDevChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.dev_update);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateStablePortableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.update_portable);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateBetaPortableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.beta_update_portable);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateDevPortableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.dev_update_portable);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.update);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
}
[Test]
public void UpdateBetaChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.beta_update);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateDevChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.dev_update);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateStablePortableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.update_portable);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateBetaPortableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.beta_update_portable);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
[Test]
public void UpdateDevPortableChannel()
{
GeneralAppInfo.ApplicationVersion = "1.0.0.0";
var CurrentUpdateInfo = UpdateInfo.FromString(Resources.dev_update_portable);
Assert.That(CurrentUpdateInfo.CheckIfValid(), Is.True);
Version v;
Version.TryParse(GeneralAppInfo.ApplicationVersion, out v);
var IsNewer = CurrentUpdateInfo.Version > v;
Assert.That(IsNewer, Is.True);
}
}

View File

@@ -3,40 +3,40 @@ using mRemoteNG.Config.Connections.Multiuser;
using mRemoteNG.Config.DatabaseConnectors;
using NSubstitute;
using NUnit.Framework;
// ReSharper disable ObjectCreationAsStatement
namespace mRemoteNGTests.Config.Connections.Multiuser
namespace mRemoteNGTests.Config.Connections.Multiuser;
public class ConnectionsUpdateAvailableEventArgsTests
{
public class ConnectionsUpdateAvailableEventArgsTests
private IDatabaseConnector _databaseConnector;
private DateTime _dateTime;
[SetUp]
public void Setup()
{
private IDatabaseConnector _databaseConnector;
private DateTime _dateTime;
_databaseConnector = Substitute.For<IDatabaseConnector>();
_dateTime = DateTime.MinValue;
}
[SetUp]
public void Setup()
{
_databaseConnector = Substitute.For<IDatabaseConnector>();
_dateTime = DateTime.MinValue;
}
[Test]
public void CantProvideNullDatabaseConnectorToCtor()
{
Assert.Throws<ArgumentNullException>(() => new ConnectionsUpdateAvailableEventArgs(null, _dateTime));
}
[Test]
public void CantProvideNullDatabaseConnectorToCtor()
{
Assert.Throws<ArgumentNullException>(() => new ConnectionsUpdateAvailableEventArgs(null, _dateTime));
}
[Test]
public void DatabaseConnectorPropertySet()
{
var eventArgs = new ConnectionsUpdateAvailableEventArgs(_databaseConnector, _dateTime);
Assert.That(eventArgs.DatabaseConnector, Is.EqualTo(_databaseConnector));
}
[Test]
public void DatabaseConnectorPropertySet()
{
var eventArgs = new ConnectionsUpdateAvailableEventArgs(_databaseConnector, _dateTime);
Assert.That(eventArgs.DatabaseConnector, Is.EqualTo(_databaseConnector));
}
[Test]
public void UpdateTimePropertySet()
{
var eventArgs = new ConnectionsUpdateAvailableEventArgs(_databaseConnector, _dateTime);
Assert.That(eventArgs.UpdateTime, Is.EqualTo(_dateTime));
}
[Test]
public void UpdateTimePropertySet()
{
var eventArgs = new ConnectionsUpdateAvailableEventArgs(_databaseConnector, _dateTime);
Assert.That(eventArgs.UpdateTime, Is.EqualTo(_dateTime));
}
}

View File

@@ -8,14 +8,13 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mRemoteNGTests.Config.Connections
namespace mRemoteNGTests.Config.Connections;
internal class XmlConnectionsLoaderTests
{
class XmlConnectionsLoaderTests
[Test]
public void ThrowsFileNotFound()
{
[Test]
public void ThrowsFileNotFound()
{
Assert.Throws<FileNotFoundException>(() => (new XmlConnectionsLoader(FileTestHelpers.NewTempFilePath())).Load());
}
Assert.Throws<FileNotFoundException>(() => new XmlConnectionsLoader(FileTestHelpers.NewTempFilePath()).Load());
}
}
}

View File

@@ -12,120 +12,117 @@ using System.Xml.Linq;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Xml;
namespace mRemoteNGTests.Config
{
namespace mRemoteNGTests.Config;
#pragma warning disable 618
public class CredentialHarvesterTests
public class CredentialHarvesterTests
{
private CredentialHarvester _credentialHarvester;
private ICryptographyProvider _cryptographyProvider;
private SecureString _key;
[SetUp]
public void Setup()
{
private CredentialHarvester _credentialHarvester;
private ICryptographyProvider _cryptographyProvider;
private SecureString _key;
[SetUp]
public void Setup()
{
_credentialHarvester = new CredentialHarvester();
_cryptographyProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
_key = "testKey123".ConvertToSecureString();
}
[Test]
public void HarvestsUsername()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Single().Username, Is.EqualTo(connection.Username));
}
[Test]
public void HarvestsDomain()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Single().Domain, Is.EqualTo(connection.Domain));
}
[Test]
public void HarvestsPassword()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Single().Password.ConvertToUnsecureString(), Is.EqualTo(connection.Password));
}
[Test]
public void DoesNotHarvestEmptyCredentials()
{
var connection = new ConnectionInfo();
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Count(), Is.EqualTo(0));
}
[Test]
public void HarvestsAllCredentials()
{
var container = new ContainerInfo();
var con1 = new ConnectionInfo {Username = "blah"};
var con2 = new ConnectionInfo {Username = "something"};
container.AddChildRange(new [] {con1, con2});
var xdoc = CreateTestData(container);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Count(), Is.EqualTo(2));
}
[Test]
public void OnlyReturnsUniqueCredentials()
{
var container = new ContainerInfo();
var con1 = new ConnectionInfo { Username = "something" };
var con2 = new ConnectionInfo { Username = "something" };
container.AddChildRange(new[] { con1, con2 });
var xdoc = CreateTestData(container);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Count(), Is.EqualTo(1));
}
[Test]
public void CredentialMapCorrectForSingleCredential()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var connectionGuid = Guid.Parse(connection.ConstantID);
var xdoc = CreateTestData(connection);
_credentialHarvester.Harvest(xdoc, _key);
var map = _credentialHarvester.ConnectionToCredentialMap;
Assert.That(map[connectionGuid].Username, Is.EqualTo(connection.Username));
}
[Test]
public void CredentialMapDoesntContainDuplicateCredentialObjects()
{
var container = new ContainerInfo();
var con1 = new ConnectionInfo { Username = "something" };
var con2 = new ConnectionInfo { Username = "something" };
container.AddChildRange(new[] { con1, con2 });
var xdoc = CreateTestData(container);
var con1Id = Guid.Parse(con1.ConstantID);
var con2Id = Guid.Parse(con2.ConstantID);
_credentialHarvester.Harvest(xdoc, _key);
var map = _credentialHarvester.ConnectionToCredentialMap;
Assert.That(map[con1Id], Is.EqualTo(map[con2Id]));
}
private XDocument CreateTestData(ConnectionInfo connectionInfo)
{
var rootNode = new RootNodeInfo(RootNodeType.Connection) {PasswordString = _key.ConvertToUnsecureString()};
rootNode.AddChild(connectionInfo);
var nodeSerializer = new XmlConnectionNodeSerializer27(_cryptographyProvider, _key, new SaveFilter());
var serializer = new XmlConnectionsSerializer(_cryptographyProvider, nodeSerializer);
var serializedData = serializer.Serialize(rootNode);
return XDocument.Parse(serializedData);
}
_credentialHarvester = new CredentialHarvester();
_cryptographyProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
_key = "testKey123".ConvertToSecureString();
}
#pragma warning restore 618
}
[Test]
public void HarvestsUsername()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Single().Username, Is.EqualTo(connection.Username));
}
[Test]
public void HarvestsDomain()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Single().Domain, Is.EqualTo(connection.Domain));
}
[Test]
public void HarvestsPassword()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Single().Password.ConvertToUnsecureString(), Is.EqualTo(connection.Password));
}
[Test]
public void DoesNotHarvestEmptyCredentials()
{
var connection = new ConnectionInfo();
var xdoc = CreateTestData(connection);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Count(), Is.EqualTo(0));
}
[Test]
public void HarvestsAllCredentials()
{
var container = new ContainerInfo();
var con1 = new ConnectionInfo { Username = "blah" };
var con2 = new ConnectionInfo { Username = "something" };
container.AddChildRange(new[] { con1, con2 });
var xdoc = CreateTestData(container);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Count(), Is.EqualTo(2));
}
[Test]
public void OnlyReturnsUniqueCredentials()
{
var container = new ContainerInfo();
var con1 = new ConnectionInfo { Username = "something" };
var con2 = new ConnectionInfo { Username = "something" };
container.AddChildRange(new[] { con1, con2 });
var xdoc = CreateTestData(container);
var credentials = _credentialHarvester.Harvest(xdoc, _key);
Assert.That(credentials.Count(), Is.EqualTo(1));
}
[Test]
public void CredentialMapCorrectForSingleCredential()
{
var connection = new ConnectionInfo { Username = "myuser", Domain = "somedomain", Password = "mypass" };
var connectionGuid = Guid.Parse(connection.ConstantID);
var xdoc = CreateTestData(connection);
_credentialHarvester.Harvest(xdoc, _key);
var map = _credentialHarvester.ConnectionToCredentialMap;
Assert.That(map[connectionGuid].Username, Is.EqualTo(connection.Username));
}
[Test]
public void CredentialMapDoesntContainDuplicateCredentialObjects()
{
var container = new ContainerInfo();
var con1 = new ConnectionInfo { Username = "something" };
var con2 = new ConnectionInfo { Username = "something" };
container.AddChildRange(new[] { con1, con2 });
var xdoc = CreateTestData(container);
var con1Id = Guid.Parse(con1.ConstantID);
var con2Id = Guid.Parse(con2.ConstantID);
_credentialHarvester.Harvest(xdoc, _key);
var map = _credentialHarvester.ConnectionToCredentialMap;
Assert.That(map[con1Id], Is.EqualTo(map[con2Id]));
}
private XDocument CreateTestData(ConnectionInfo connectionInfo)
{
var rootNode = new RootNodeInfo(RootNodeType.Connection) { PasswordString = _key.ConvertToUnsecureString() };
rootNode.AddChild(connectionInfo);
var nodeSerializer = new XmlConnectionNodeSerializer27(_cryptographyProvider, _key, new SaveFilter());
var serializer = new XmlConnectionsSerializer(_cryptographyProvider, nodeSerializer);
var serializedData = serializer.Serialize(rootNode);
return XDocument.Parse(serializedData);
}
}
#pragma warning restore 618

View File

@@ -7,36 +7,35 @@ using mRemoteNG.Credential;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config
namespace mRemoteNGTests.Config;
public class CredentialRecordLoaderTests
{
public class CredentialRecordLoaderTests
private CredentialRecordLoader _credentialRecordLoader;
private IDataProvider<string> _dataProvider;
private ISecureDeserializer<string, IEnumerable<ICredentialRecord>> _deserializer;
[SetUp]
public void Setup()
{
private CredentialRecordLoader _credentialRecordLoader;
private IDataProvider<string> _dataProvider;
private ISecureDeserializer<string, IEnumerable<ICredentialRecord>> _deserializer;
_dataProvider = Substitute.For<IDataProvider<string>>();
_deserializer = Substitute.For<ISecureDeserializer<string, IEnumerable<ICredentialRecord>>>();
_credentialRecordLoader = new CredentialRecordLoader(_dataProvider, _deserializer);
}
[SetUp]
public void Setup()
{
_dataProvider = Substitute.For<IDataProvider<string>>();
_deserializer = Substitute.For<ISecureDeserializer<string, IEnumerable<ICredentialRecord>>>();
_credentialRecordLoader = new CredentialRecordLoader(_dataProvider, _deserializer);
}
[Test]
public void LoadsFromDataProvider()
{
_credentialRecordLoader.Load(new SecureString());
_dataProvider.Received(1).Load();
}
[Test]
public void LoadsFromDataProvider()
{
_credentialRecordLoader.Load(new SecureString());
_dataProvider.Received(1).Load();
}
[Test]
public void DeserializesDataFromDataProvider()
{
var key = new SecureString();
_dataProvider.Load().Returns("mydata");
_credentialRecordLoader.Load(key);
_deserializer.Received(1).Deserialize("mydata", key);
}
[Test]
public void DeserializesDataFromDataProvider()
{
var key = new SecureString();
_dataProvider.Load().Returns("mydata");
_credentialRecordLoader.Load(key);
_deserializer.Received(1).Deserialize("mydata", key);
}
}

View File

@@ -3,48 +3,47 @@ using mRemoteNG.Config.DataProviders;
using mRemoteNGTests.TestHelpers;
using NUnit.Framework;
namespace mRemoteNGTests.Config.DataProviders
namespace mRemoteNGTests.Config.DataProviders;
public class FileBackupCreatorTests
{
public class FileBackupCreatorTests
private FileBackupCreator _fileBackupCreator;
private string _testFilePath;
private string _testFilePathBackup;
private string _testFileDirectory;
private string _testFileRollingBackup;
[SetUp]
public void Setup()
{
private FileBackupCreator _fileBackupCreator;
private string _testFilePath;
private string _testFilePathBackup;
private string _testFileDirectory;
private string _testFileRollingBackup;
_testFilePath = FileTestHelpers.NewTempFilePath();
_testFileDirectory = Path.GetDirectoryName(_testFilePath);
_testFileRollingBackup = Path.GetFileName(_testFilePath) + ".*-*.backup";
_testFilePathBackup = _testFilePath + ".backup";
_fileBackupCreator = new FileBackupCreator();
}
[SetUp]
public void Setup()
{
_testFilePath = FileTestHelpers.NewTempFilePath();
_testFileDirectory = Path.GetDirectoryName(_testFilePath);
_testFileRollingBackup = Path.GetFileName(_testFilePath) + ".*-*.backup";
_testFilePathBackup = _testFilePath + ".backup";
_fileBackupCreator = new FileBackupCreator();
}
[TearDown]
public void Teardown()
{
if (Directory.Exists(_testFileDirectory))
Directory.Delete(_testFileDirectory, true);
}
[TearDown]
public void Teardown()
{
if (Directory.Exists(_testFileDirectory))
Directory.Delete(_testFileDirectory, true);
}
[Test]
public void BackupCreatedWhenFileAlreadyExists()
{
File.WriteAllText(_testFilePath, "");
_fileBackupCreator.CreateBackupFile(_testFilePath);
var rollingBackupFiles = Directory.GetFiles(_testFileDirectory, _testFileRollingBackup);
Assert.That(rollingBackupFiles.Length, Is.EqualTo(1));
}
[Test]
public void BackupCreatedWhenFileAlreadyExists()
{
File.WriteAllText(_testFilePath, "");
_fileBackupCreator.CreateBackupFile(_testFilePath);
var rollingBackupFiles = Directory.GetFiles(_testFileDirectory, _testFileRollingBackup);
Assert.That(rollingBackupFiles.Length, Is.EqualTo(1));
}
[Test]
public void BackupNotCreatedIfFileDidntAlreadyExist()
{
_fileBackupCreator.CreateBackupFile(_testFilePath);
var backupFileExists = File.Exists(_testFilePathBackup);
Assert.That(backupFileExists, Is.False);
}
[Test]
public void BackupNotCreatedIfFileDidntAlreadyExist()
{
_fileBackupCreator.CreateBackupFile(_testFilePath);
var backupFileExists = File.Exists(_testFilePathBackup);
Assert.That(backupFileExists, Is.False);
}
}

View File

@@ -4,57 +4,56 @@ using mRemoteNG.Config.DataProviders;
using mRemoteNGTests.TestHelpers;
using NUnit.Framework;
namespace mRemoteNGTests.Config.DataProviders
namespace mRemoteNGTests.Config.DataProviders;
public class FileDataProviderTests
{
public class FileDataProviderTests
private FileDataProvider _dataProvider;
private string _testFilePath;
private string _testFileDirectory;
[SetUp]
public void Setup()
{
private FileDataProvider _dataProvider;
private string _testFilePath;
private string _testFileDirectory;
_testFilePath = FileTestHelpers.NewTempFilePath();
_testFileDirectory = Path.GetDirectoryName(_testFilePath);
_dataProvider = new FileDataProvider(_testFilePath);
}
[SetUp]
public void Setup()
{
_testFilePath = FileTestHelpers.NewTempFilePath();
_testFileDirectory = Path.GetDirectoryName(_testFilePath);
_dataProvider = new FileDataProvider(_testFilePath);
}
[TearDown]
public void Teardown()
{
if (Directory.Exists(_testFileDirectory))
Directory.Delete(_testFileDirectory, true);
}
[TearDown]
public void Teardown()
{
if (Directory.Exists(_testFileDirectory))
Directory.Delete(_testFileDirectory, true);
}
[Test]
public void SetsFileContent()
{
Assert.That(File.Exists(_testFilePath), Is.False);
var expectedFileContent = Guid.NewGuid().ToString();
_dataProvider.Save(expectedFileContent);
var fileContent = File.ReadAllText(_testFilePath);
Assert.That(fileContent, Is.EqualTo(expectedFileContent));
}
[Test]
public void SetsFileContent()
{
Assert.That(File.Exists(_testFilePath), Is.False);
var expectedFileContent = Guid.NewGuid().ToString();
_dataProvider.Save(expectedFileContent);
var fileContent = File.ReadAllText(_testFilePath);
Assert.That(fileContent, Is.EqualTo(expectedFileContent));
}
[Test]
public void LoadingFileThatDoesntExistProvidesEmptyString()
{
var fileThatShouldntExist = Guid.NewGuid().ToString();
var dataProvider = new FileDataProvider(fileThatShouldntExist);
var loadedData = dataProvider.Load();
Assert.That(loadedData, Is.Empty);
}
[Test]
public void LoadingFileThatDoesntExistProvidesEmptyString()
{
var fileThatShouldntExist = Guid.NewGuid().ToString();
var dataProvider = new FileDataProvider(fileThatShouldntExist);
var loadedData = dataProvider.Load();
Assert.That(loadedData, Is.Empty);
}
[Test]
public void SaveCreatesDirectoriesThatDontExist()
{
var folder1 = Guid.NewGuid().ToString();
var folder2 = Guid.NewGuid().ToString();
var fileThatShouldExist = Path.Combine(_testFileDirectory, folder1, folder2, Path.GetRandomFileName());
_dataProvider.FilePath = fileThatShouldExist;
_dataProvider.Save("");
Assert.That(File.Exists(fileThatShouldExist), Is.True);
}
[Test]
public void SaveCreatesDirectoriesThatDontExist()
{
var folder1 = Guid.NewGuid().ToString();
var folder2 = Guid.NewGuid().ToString();
var fileThatShouldExist = Path.Combine(_testFileDirectory, folder1, folder2, Path.GetRandomFileName());
_dataProvider.FilePath = fileThatShouldExist;
_dataProvider.Save("");
Assert.That(File.Exists(fileThatShouldExist), Is.True);
}
}

View File

@@ -4,50 +4,49 @@ using mRemoteNG.Config.DataProviders;
using mRemoteNGTests.TestHelpers;
using NUnit.Framework;
namespace mRemoteNGTests.Config.DataProviders
namespace mRemoteNGTests.Config.DataProviders;
public class FileDataProviderWithRollingBackupTests
{
public class FileDataProviderWithRollingBackupTests
private FileDataProviderWithRollingBackup _dataProvider;
private string _testFilePath;
private string _testFileDirectory;
private string _testFileRollingBackup;
[SetUp]
public void Setup()
{
private FileDataProviderWithRollingBackup _dataProvider;
private string _testFilePath;
private string _testFileDirectory;
private string _testFileRollingBackup;
_testFilePath = FileTestHelpers.NewTempFilePath();
_testFileDirectory = Path.GetDirectoryName(_testFilePath);
_testFileRollingBackup = Path.GetFileName(_testFilePath) + ".*-*.backup";
_dataProvider = new FileDataProviderWithRollingBackup(_testFilePath);
}
[SetUp]
public void Setup()
{
_testFilePath = FileTestHelpers.NewTempFilePath();
_testFileDirectory = Path.GetDirectoryName(_testFilePath);
_testFileRollingBackup = Path.GetFileName(_testFilePath) + ".*-*.backup";
_dataProvider = new FileDataProviderWithRollingBackup(_testFilePath);
}
[TearDown]
public void Teardown()
{
if (Directory.Exists(_testFileDirectory))
Directory.Delete(_testFileDirectory, true);
}
[TearDown]
public void Teardown()
{
if (Directory.Exists(_testFileDirectory))
Directory.Delete(_testFileDirectory, true);
}
[Test]
public void RollingBackupCreatedIfRegularBackupExists()
{
for (var i = 0; i < 3; i++)
{
_dataProvider.Save("");
Thread.Sleep(100);
}
var rollingBackupFiles = Directory.GetFiles(_testFileDirectory, _testFileRollingBackup);
Assert.That(rollingBackupFiles.Length, Is.EqualTo(2));
}
[Test]
public void NoRollingBackupCreatedIfRegularFileDoesntExists()
[Test]
public void RollingBackupCreatedIfRegularBackupExists()
{
for (var i = 0; i < 3; i++)
{
_dataProvider.Save("");
var rollingBackupFiles = Directory.GetFiles(_testFileDirectory, _testFileRollingBackup);
Assert.That(rollingBackupFiles.Length, Is.EqualTo(0));
Thread.Sleep(100);
}
var rollingBackupFiles = Directory.GetFiles(_testFileDirectory, _testFileRollingBackup);
Assert.That(rollingBackupFiles.Length, Is.EqualTo(2));
}
[Test]
public void NoRollingBackupCreatedIfRegularFileDoesntExists()
{
_dataProvider.Save("");
var rollingBackupFiles = Directory.GetFiles(_testFileDirectory, _testFileRollingBackup);
Assert.That(rollingBackupFiles.Length, Is.EqualTo(0));
}
}

View File

@@ -4,43 +4,42 @@ using mRemoteNG.Config.Serializers;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers
namespace mRemoteNGTests.Config.Serializers;
public class ConfConsEnsureConnectionsHaveIdsTests
{
public class ConfConsEnsureConnectionsHaveIdsTests
private ConfConsEnsureConnectionsHaveIds _consEnsureConnectionsHaveIds;
[SetUp]
public void Setup()
{
private ConfConsEnsureConnectionsHaveIds _consEnsureConnectionsHaveIds;
[SetUp]
public void Setup()
{
_consEnsureConnectionsHaveIds = new ConfConsEnsureConnectionsHaveIds();
}
[Test]
public void IdAttributeIsAddedIfItDidntExist()
{
var xdoc = CreateTestDocument();
_consEnsureConnectionsHaveIds.EnsureElementsHaveIds(xdoc);
var attribute = xdoc.Root?.Element("Node")?.Attribute("Id");
Assert.That(attribute, Is.Not.Null);
}
[Test]
public void NewIdAttributeShouldNotBeAnEmptyGuid()
{
var xdoc = CreateTestDocument();
_consEnsureConnectionsHaveIds.EnsureElementsHaveIds(xdoc);
var attribute = xdoc.Root?.Element("Node")?.Attribute("Id");
Assert.That(attribute?.Value, Is.Not.EqualTo(Guid.Empty.ToString()));
}
private XDocument CreateTestDocument()
{
var xdoc = new XDocument();
xdoc.Add(new XElement("Root",
new XElement("Node",
new XAttribute("Thingy",""))));
return xdoc;
}
_consEnsureConnectionsHaveIds = new ConfConsEnsureConnectionsHaveIds();
}
}
[Test]
public void IdAttributeIsAddedIfItDidntExist()
{
var xdoc = CreateTestDocument();
_consEnsureConnectionsHaveIds.EnsureElementsHaveIds(xdoc);
var attribute = xdoc.Root?.Element("Node")?.Attribute("Id");
Assert.That(attribute, Is.Not.Null);
}
[Test]
public void NewIdAttributeShouldNotBeAnEmptyGuid()
{
var xdoc = CreateTestDocument();
_consEnsureConnectionsHaveIds.EnsureElementsHaveIds(xdoc);
var attribute = xdoc.Root?.Element("Node")?.Attribute("Id");
Assert.That(attribute?.Value, Is.Not.EqualTo(Guid.Empty.ToString()));
}
private XDocument CreateTestDocument()
{
var xdoc = new XDocument();
xdoc.Add(new XElement("Root",
new XElement("Node",
new XAttribute("Thingy", ""))));
return xdoc;
}
}

View File

@@ -182,7 +182,7 @@ namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Csv
{
nameof(ConnectionInfoInheritance.EverythingInherited),
nameof(ConnectionInfoInheritance.Parent),
nameof(ConnectionInfoInheritance.EverythingInherited)
nameof(ConnectionInfoInheritance.EverythingInherited)
};
var properties = typeof(ConnectionInfoInheritance)
.GetProperties()
@@ -191,11 +191,11 @@ namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Csv
var testInheritance = GetTestConnectionWithAllInherited().Inheritance;
return properties
.Select(property =>
new TestCaseData(property.Name)
.Returns(property.GetValue(testInheritance)))
.ToList();
.Select(property =>
new TestCaseData(property.Name)
.Returns(property.GetValue(testInheritance)))
.ToList();
}
}
}
}
}

View File

@@ -10,146 +10,147 @@ using mRemoteNGTests.TestHelpers;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Csv
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Csv;
public class CsvConnectionsSerializerMremotengFormatTests
{
public class CsvConnectionsSerializerMremotengFormatTests
private ICredentialRepositoryList _credentialRepositoryList;
private const string ConnectionName = "myconnection";
private const string Username = "myuser";
private const string Domain = "mydomain";
private const string Password = "mypass123";
[OneTimeSetUp]
public void OneTimeSetup()
{
private ICredentialRepositoryList _credentialRepositoryList;
private const string ConnectionName = "myconnection";
private const string Username = "myuser";
private const string Domain = "mydomain";
private const string Password = "mypass123";
var credRecord = Substitute.For<ICredentialRecord>();
credRecord.Username.Returns(Username);
credRecord.Domain.Returns(Domain);
credRecord.Password.Returns(Password.ConvertToSecureString());
_credentialRepositoryList = Substitute.For<ICredentialRepositoryList>();
_credentialRepositoryList.GetCredentialRecord(new Guid()).ReturnsForAnyArgs(credRecord);
}
[OneTimeSetUp]
public void OneTimeSetup()
{
var credRecord = Substitute.For<ICredentialRecord>();
credRecord.Username.Returns(Username);
credRecord.Domain.Returns(Domain);
credRecord.Password.Returns(Password.ConvertToSecureString());
_credentialRepositoryList = Substitute.For<ICredentialRepositoryList>();
_credentialRepositoryList.GetCredentialRecord(new Guid()).ReturnsForAnyArgs(credRecord);
}
[Test]
public void SerializesNodeId()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var connectionInfo = BuildConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Does.Match(connectionInfo.ConstantID));
}
[Test]
public void SerializesNodeId()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var connectionInfo = BuildConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Does.Match(connectionInfo.ConstantID));
}
[Test]
public void DoesntSerializeTheRootNode()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var treeModel = new ConnectionTreeModelBuilder().Build();
var csv = serializer.Serialize(treeModel);
Assert.That(csv, Does.Not.Match($"{treeModel.RootNodes[0].ConstantID};.*;{TreeNodeType.Root}"));
}
[Test]
public void DoesntSerializeTheRootNode()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var treeModel = new ConnectionTreeModelBuilder().Build();
var csv = serializer.Serialize(treeModel);
Assert.That(csv, Does.Not.Match($"{treeModel.RootNodes[0].ConstantID};.*;{TreeNodeType.Root}"));
}
[TestCase(Username)]
[TestCase(Domain)]
[TestCase(Password)]
[TestCase("InheritColors")]
public void CreatesCsv(string valueThatShouldExist)
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var connectionInfo = BuildConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Does.Match(valueThatShouldExist));
}
[TestCase(Username)]
[TestCase(Domain)]
[TestCase(Password)]
[TestCase("InheritColors")]
public void CreatesCsv(string valueThatShouldExist)
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var connectionInfo = BuildConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Does.Match(valueThatShouldExist));
}
[TestCase(Username)]
[TestCase(Domain)]
[TestCase(Password)]
[TestCase("InheritColors")]
public void SerializerRespectsSaveFilterSettings(string valueThatShouldntExist)
{
var saveFilter = new SaveFilter(true);
var serializer = new CsvConnectionsSerializerMremotengFormat(saveFilter, _credentialRepositoryList);
var connectionInfo = BuildConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Does.Not.Match(valueThatShouldntExist));
}
[TestCase(Username)]
[TestCase(Domain)]
[TestCase(Password)]
[TestCase("InheritColors")]
public void SerializerRespectsSaveFilterSettings(string valueThatShouldntExist)
{
var saveFilter = new SaveFilter(true);
var serializer = new CsvConnectionsSerializerMremotengFormat(saveFilter, _credentialRepositoryList);
var connectionInfo = BuildConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Does.Not.Match(valueThatShouldntExist));
}
[Test]
public void CanSerializeEmptyConnectionInfo()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var connectionInfo = new ConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Is.Not.Empty);
}
[Test]
public void CanSerializeEmptyConnectionInfo()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var connectionInfo = new ConnectionInfo();
var csv = serializer.Serialize(connectionInfo);
Assert.That(csv, Is.Not.Empty);
}
[Test]
public void CantPassNullToConstructor()
{
Assert.Throws<ArgumentNullException>(() =>
new CsvConnectionsSerializerMremotengFormat(null, _credentialRepositoryList));
}
[Test]
public void CantPassNullToConstructor()
{
Assert.Throws<ArgumentNullException>(() => new CsvConnectionsSerializerMremotengFormat(null, _credentialRepositoryList));
}
[Test]
public void CantPassNullToSerializeConnectionInfo()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
Assert.Throws<ArgumentNullException>(() => serializer.Serialize((ConnectionInfo)null));
}
[Test]
public void CantPassNullToSerializeConnectionInfo()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
Assert.Throws<ArgumentNullException>(() => serializer.Serialize((ConnectionInfo)null));
}
[Test]
public void CantPassNullToSerializeConnectionTreeModel()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
Assert.Throws<ArgumentNullException>(() => serializer.Serialize((ConnectionTreeModel)null));
}
[Test]
public void CantPassNullToSerializeConnectionTreeModel()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
Assert.Throws<ArgumentNullException>(() => serializer.Serialize((ConnectionTreeModel)null));
}
[Test]
public void FoldersAreSerialized()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var container = BuildContainer();
var csv = serializer.Serialize(container);
Assert.That(csv, Does.Match(container.Name));
Assert.That(csv, Does.Match(container.Username));
Assert.That(csv, Does.Match(container.Domain));
Assert.That(csv, Does.Match(container.Password));
Assert.That(csv, Does.Contain(TreeNodeType.Container.ToString()));
}
[Test]
public void FoldersAreSerialized()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var container = BuildContainer();
var csv = serializer.Serialize(container);
Assert.That(csv, Does.Match(container.Name));
Assert.That(csv, Does.Match(container.Username));
Assert.That(csv, Does.Match(container.Domain));
Assert.That(csv, Does.Match(container.Password));
Assert.That(csv, Does.Contain(TreeNodeType.Container.ToString()));
}
[Test]
public void SerializationIncludesRawInheritedValuesIfObjectInheritsFromParentOutsideOfSerializationScope()
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var treeModel = new ConnectionTreeModelBuilder().Build();
var serializationTarget = treeModel.GetRecursiveChildList().First(info => info.Name == "folder3");
var csv = serializer.Serialize(serializationTarget);
var lineWithFolder3 = csv.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
.First(s => s.Contains(serializationTarget.Name));
Assert.That(lineWithFolder3, Does.Contain(serializationTarget.Username));
Assert.That(lineWithFolder3, Does.Contain(serializationTarget.Domain));
Assert.That(lineWithFolder3, Does.Contain(serializationTarget.Password));
}
[Test]
public void SerializationIncludesRawInheritedValuesIfObjectInheritsFromParentOutsideOfSerializationScope()
private ConnectionInfo BuildConnectionInfo()
{
return new ConnectionInfo
{
var serializer = new CsvConnectionsSerializerMremotengFormat(new SaveFilter(), _credentialRepositoryList);
var treeModel = new ConnectionTreeModelBuilder().Build();
var serializationTarget = treeModel.GetRecursiveChildList().First(info => info.Name == "folder3");
var csv = serializer.Serialize(serializationTarget);
var lineWithFolder3 = csv.Split(new[] {Environment.NewLine}, StringSplitOptions.None).First(s => s.Contains(serializationTarget.Name));
Assert.That(lineWithFolder3, Does.Contain(serializationTarget.Username));
Assert.That(lineWithFolder3, Does.Contain(serializationTarget.Domain));
Assert.That(lineWithFolder3, Does.Contain(serializationTarget.Password));
}
Name = ConnectionName,
Username = Username,
Domain = Domain,
Password = Password,
Inheritance = { Colors = true }
};
}
private ConnectionInfo BuildConnectionInfo()
private ContainerInfo BuildContainer()
{
return new ContainerInfo
{
return new ConnectionInfo
{
Name = ConnectionName,
Username = Username,
Domain = Domain,
Password = Password,
Inheritance = {Colors = true}
};
}
private ContainerInfo BuildContainer()
{
return new ContainerInfo
{
Name = "MyFolder",
Username = "BlahBlah1",
Domain = "aklkskkksh8",
Password = "qweraslkdjf87"
};
}
Name = "MyFolder",
Username = "BlahBlah1",
Domain = "aklkskkksh8",
Password = "qweraslkdjf87"
};
}
}

View File

@@ -12,76 +12,75 @@ using System.Xml;
using System.Xml.Schema;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Xml;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml;
public class ValidateXmlSchemas
{
public class ValidateXmlSchemas
private XmlConnectionsSerializer _serializer;
private ConnectionTreeModel _connectionTreeModel;
private ICryptographyProvider _cryptographyProvider;
private XmlReaderSettings _xmlReaderSettings;
[SetUp]
public void Setup()
{
private XmlConnectionsSerializer _serializer;
private ConnectionTreeModel _connectionTreeModel;
private ICryptographyProvider _cryptographyProvider;
private XmlReaderSettings _xmlReaderSettings;
_connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
root.AddChild(new ConnectionInfo());
_connectionTreeModel.AddRootNode(root);
[SetUp]
public void Setup()
_cryptographyProvider = new AeadCryptographyProvider();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_serializer = new XmlConnectionsSerializer(_cryptographyProvider, connectionNodeSerializer);
_xmlReaderSettings = new XmlReaderSettings
{
_connectionTreeModel = new ConnectionTreeModel();
var root = new RootNodeInfo(RootNodeType.Connection);
root.AddChild(new ConnectionInfo());
_connectionTreeModel.AddRootNode(root);
_cryptographyProvider = new AeadCryptographyProvider();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_serializer = new XmlConnectionsSerializer(_cryptographyProvider, connectionNodeSerializer);
_xmlReaderSettings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings
};
}
[Test]
public void ValidateSchema()
{
var sb = new StringBuilder();
var xml = _serializer.Serialize(_connectionTreeModel);
var schemaFileName = $"mremoteng_confcons_v{_serializer.Version.Major}_{_serializer.Version.Minor}.xsd";
var schemaFile = GetTargetPath(schemaFileName);
_xmlReaderSettings.Schemas.Add("http://mremoteng.org", schemaFile);
_xmlReaderSettings.ValidationEventHandler += (sender, args) =>
{
sb.AppendLine($"{args.Severity}: {args.Message}");
};
using (var stream = GenerateStreamFromString(xml))
{
var reader = XmlReader.Create(stream, _xmlReaderSettings);
while (reader.Read()) ;
}
Assert.That(sb.ToString(), Is.Empty);
}
public string GetTargetPath(string fileName, [CallerFilePath] string sourceFilePath = "")
{
var path = Path.GetDirectoryName(sourceFilePath);
var filePath = $@"{path}\..\..\..\..\..\mRemoteNG\Schemas\{fileName}";
return filePath;
}
private Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings
};
}
}
[Test]
public void ValidateSchema()
{
var sb = new StringBuilder();
var xml = _serializer.Serialize(_connectionTreeModel);
var schemaFileName = $"mremoteng_confcons_v{_serializer.Version.Major}_{_serializer.Version.Minor}.xsd";
var schemaFile = GetTargetPath(schemaFileName);
_xmlReaderSettings.Schemas.Add("http://mremoteng.org", schemaFile);
_xmlReaderSettings.ValidationEventHandler += (sender, args) =>
{
sb.AppendLine($"{args.Severity}: {args.Message}");
};
using (var stream = GenerateStreamFromString(xml))
{
var reader = XmlReader.Create(stream, _xmlReaderSettings);
while (reader.Read()) ;
}
Assert.That(sb.ToString(), Is.Empty);
}
public string GetTargetPath(string fileName, [CallerFilePath] string sourceFilePath = "")
{
var path = Path.GetDirectoryName(sourceFilePath);
var filePath = $@"{path}\..\..\..\..\..\mRemoteNG\Schemas\{fileName}";
return filePath;
}
private Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}

View File

@@ -9,156 +9,170 @@ using mRemoteNG.Tree;
using mRemoteNGTests.Properties;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml;
public class XmlConnectionsDeserializerTests
{
public class XmlConnectionsDeserializerTests
private XmlConnectionsDeserializer _xmlConnectionsDeserializer;
private ConnectionTreeModel _connectionTreeModel;
public void Setup(string confCons, string password)
{
private XmlConnectionsDeserializer _xmlConnectionsDeserializer;
private ConnectionTreeModel _connectionTreeModel;
public void Setup(string confCons, string password)
{
_xmlConnectionsDeserializer = new XmlConnectionsDeserializer(() => password.ConvertToSecureString());
_connectionTreeModel = _xmlConnectionsDeserializer.Deserialize(confCons);
}
[TearDown]
public void Teardown()
{
_xmlConnectionsDeserializer = null;
_connectionTreeModel = null;
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void DeserializingCreatesRootNode(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
Assert.That(_connectionTreeModel.RootNodes, Is.Not.Empty);
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void RootNodeHasThreeChildren(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
Assert.That(connectionRoot.Children.Count, Is.EqualTo(3));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void RootContainsFolder1(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
Assert.That(ContainsNodeNamed("Folder1", connectionRoot.Children), Is.True);
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder1ContainsThreeConnections(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder1 = GetFolderNamed("Folder1", connectionRoot.Children);
var folder1ConnectionCount = folder1?.Children.Count(node => !(node is ContainerInfo));
Assert.That(folder1ConnectionCount, Is.EqualTo(3));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder2ContainsThreeNodes(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder1Count = folder2?.Children.Count();
Assert.That(folder1Count, Is.EqualTo(3));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder21HasTwoNodes(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder21 = GetFolderNamed("Folder2.1", folder2.Children);
Assert.That(folder21.Children.Count, Is.EqualTo(2));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder211HasOneConnection(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder21 = GetFolderNamed("Folder2.1", folder2.Children);
var folder211 = GetFolderNamed("Folder2.1.1", folder21.Children);
var connectionCount = folder211.Children.Count(node => !(node is ContainerInfo));
Assert.That(connectionCount, Is.EqualTo(1));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder22InheritsUsername(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder22 = GetFolderNamed("Folder2.2", folder2.Children);
Assert.That(folder22.Inheritance.Username, Is.True);
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData), nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void ExpandedPropertyGetsDeserialized(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var folder1 = GetFolderNamed("Folder1", _connectionTreeModel.GetRecursiveChildList());
Assert.That(folder1.IsExpanded, Is.True);
}
private bool ContainsNodeNamed(string name, IEnumerable<ConnectionInfo> list)
{
return list.Any(node => node.Name == name);
}
private ContainerInfo GetFolderNamed(string name, IEnumerable<ConnectionInfo> list)
{
var folder = list.First(node => (node is ContainerInfo && node.Name == name)) as ContainerInfo;
return folder;
}
_xmlConnectionsDeserializer = new XmlConnectionsDeserializer(() => password.ConvertToSecureString());
_connectionTreeModel = _xmlConnectionsDeserializer.Deserialize(confCons);
}
public class XmlConnectionsDeserializerFixtureData
[TearDown]
public void Teardown()
{
public static IEnumerable FixtureParams
{
get
{
yield return new TestCaseData(new Datagram("confCons v2.5", Resources.confCons_v2_5, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.5 fullencryption", Resources.confCons_v2_5_fullencryption, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.5 custompassword,fullencryption", Resources.confCons_v2_5_passwordis_Password_fullencryption, "Password"));
yield return new TestCaseData(new Datagram("confCons v2.6", Resources.confCons_v2_6, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.6 5k Iterations", Resources.confCons_v2_6_5k_iterations, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.6 fullencryption", Resources.confCons_v2_6_fullencryption, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.6 custompassword", Resources.confCons_v2_6_passwordis_Password, "Password"));
yield return new TestCaseData(new Datagram("confCons v2.6 custompassword,fullencryption", Resources.confCons_v2_6_passwordis_Password_fullencryption, "Password"));
}
}
_xmlConnectionsDeserializer = null;
_connectionTreeModel = null;
}
public class Datagram
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void DeserializingCreatesRootNode(Datagram testData)
{
private readonly string _testName;
Setup(testData.ConfCons, testData.Password);
Assert.That(_connectionTreeModel.RootNodes, Is.Not.Empty);
}
public string ConfCons { get; set; }
public string Password { get; set; }
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void RootNodeHasThreeChildren(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
Assert.That(connectionRoot.Children.Count, Is.EqualTo(3));
}
public Datagram(string testName, string confCons, string password)
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void RootContainsFolder1(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
Assert.That(ContainsNodeNamed("Folder1", connectionRoot.Children), Is.True);
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder1ContainsThreeConnections(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder1 = GetFolderNamed("Folder1", connectionRoot.Children);
var folder1ConnectionCount = folder1?.Children.Count(node => !(node is ContainerInfo));
Assert.That(folder1ConnectionCount, Is.EqualTo(3));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder2ContainsThreeNodes(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder1Count = folder2?.Children.Count();
Assert.That(folder1Count, Is.EqualTo(3));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder21HasTwoNodes(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder21 = GetFolderNamed("Folder2.1", folder2.Children);
Assert.That(folder21.Children.Count, Is.EqualTo(2));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder211HasOneConnection(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder21 = GetFolderNamed("Folder2.1", folder2.Children);
var folder211 = GetFolderNamed("Folder2.1.1", folder21.Children);
var connectionCount = folder211.Children.Count(node => !(node is ContainerInfo));
Assert.That(connectionCount, Is.EqualTo(1));
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void Folder22InheritsUsername(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var connectionRoot = _connectionTreeModel.RootNodes[0];
var folder2 = GetFolderNamed("Folder2", connectionRoot.Children);
var folder22 = GetFolderNamed("Folder2.2", folder2.Children);
Assert.That(folder22.Inheritance.Username, Is.True);
}
[TestCaseSource(typeof(XmlConnectionsDeserializerFixtureData),
nameof(XmlConnectionsDeserializerFixtureData.FixtureParams))]
public void ExpandedPropertyGetsDeserialized(Datagram testData)
{
Setup(testData.ConfCons, testData.Password);
var folder1 = GetFolderNamed("Folder1", _connectionTreeModel.GetRecursiveChildList());
Assert.That(folder1.IsExpanded, Is.True);
}
private bool ContainsNodeNamed(string name, IEnumerable<ConnectionInfo> list)
{
return list.Any(node => node.Name == name);
}
private ContainerInfo GetFolderNamed(string name, IEnumerable<ConnectionInfo> list)
{
var folder = list.First(node => node is ContainerInfo && node.Name == name) as ContainerInfo;
return folder;
}
}
public class XmlConnectionsDeserializerFixtureData
{
public static IEnumerable FixtureParams
{
get
{
_testName = testName;
ConfCons = confCons;
Password = password;
yield return new TestCaseData(new Datagram("confCons v2.5", Resources.confCons_v2_5, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.5 fullencryption",
Resources.confCons_v2_5_fullencryption, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.5 custompassword,fullencryption",
Resources.confCons_v2_5_passwordis_Password_fullencryption, "Password"));
yield return new TestCaseData(new Datagram("confCons v2.6", Resources.confCons_v2_6, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.6 5k Iterations",
Resources.confCons_v2_6_5k_iterations, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.6 fullencryption",
Resources.confCons_v2_6_fullencryption, "mR3m"));
yield return new TestCaseData(new Datagram("confCons v2.6 custompassword",
Resources.confCons_v2_6_passwordis_Password, "Password"));
yield return new TestCaseData(new Datagram("confCons v2.6 custompassword,fullencryption",
Resources.confCons_v2_6_passwordis_Password_fullencryption, "Password"));
}
}
}
public override string ToString()
{
return _testName;
}
public class Datagram
{
private readonly string _testName;
public string ConfCons { get; set; }
public string Password { get; set; }
public Datagram(string testName, string confCons, string password)
{
_testName = testName;
ConfCons = confCons;
Password = password;
}
public override string ToString()
{
return _testName;
}
}

View File

@@ -9,104 +9,103 @@ using System.Linq;
using System.Xml.XPath;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Xml;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml;
public class XmlConnectionsDocumentCompilerTests
{
public class XmlConnectionsDocumentCompilerTests
private XmlConnectionsDocumentCompiler _documentCompiler;
private ConnectionTreeModel _connectionTreeModel;
private ICryptographyProvider _cryptographyProvider;
private ContainerInfo _folder1;
private ContainerInfo _folder2;
private ContainerInfo _folder3;
private ConnectionInfo _con0;
private ConnectionInfo _con1;
private ConnectionInfo _con2;
private ConnectionInfo _con3;
private ConnectionInfo _con4;
[SetUp]
public void Setup()
{
private XmlConnectionsDocumentCompiler _documentCompiler;
private ConnectionTreeModel _connectionTreeModel;
private ICryptographyProvider _cryptographyProvider;
private ContainerInfo _folder1;
private ContainerInfo _folder2;
private ContainerInfo _folder3;
private ConnectionInfo _con0;
private ConnectionInfo _con1;
private ConnectionInfo _con2;
private ConnectionInfo _con3;
private ConnectionInfo _con4;
_connectionTreeModel = SetupConnectionTreeModel();
_cryptographyProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_documentCompiler = new XmlConnectionsDocumentCompiler(_cryptographyProvider, connectionNodeSerializer);
}
[SetUp]
public void Setup()
{
_connectionTreeModel = SetupConnectionTreeModel();
_cryptographyProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_documentCompiler = new XmlConnectionsDocumentCompiler(_cryptographyProvider, connectionNodeSerializer);
}
[Test]
public void XDocumentHasXmlDeclaration()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, false);
Assert.That(xdoc.Declaration, Is.Not.Null);
}
[Test]
public void XDocumentHasXmlDeclaration()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, false);
Assert.That(xdoc.Declaration, Is.Not.Null);
}
[Test]
public void DocumentHasRootConnectionElement()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, false);
var rootElementName = xdoc.Root?.Name.LocalName;
Assert.That(rootElementName, Is.EqualTo("Connections"));
}
[Test]
public void DocumentHasRootConnectionElement()
{
var xdoc =_documentCompiler.CompileDocument(_connectionTreeModel, false);
var rootElementName = xdoc.Root?.Name.LocalName;
Assert.That(rootElementName, Is.EqualTo("Connections"));
}
[Test]
public void ConnectionNodesSerializedRecursively()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, false);
var con4 = xdoc.Root?.XPathSelectElement("Node[@Name='folder2']/Node[@Name='folder3']/Node[@Name='con4']");
Assert.That(con4, Is.Not.Null);
}
[Test]
public void ConnectionNodesSerializedRecursively()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, false);
var con4 = xdoc.Root?.XPathSelectElement("Node[@Name='folder2']/Node[@Name='folder3']/Node[@Name='con4']");
Assert.That(con4, Is.Not.Null);
}
[Test]
public void XmlContentEncryptedWhenFullFileEncryptionTurnedOn()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, true);
var rootElementValue = xdoc.Root?.Value;
Assert.That(rootElementValue, Is.Not.EqualTo(string.Empty));
}
[Test]
public void XmlContentEncryptedWhenFullFileEncryptionTurnedOn()
{
var xdoc = _documentCompiler.CompileDocument(_connectionTreeModel, true);
var rootElementValue = xdoc.Root?.Value;
Assert.That(rootElementValue, Is.Not.EqualTo(string.Empty));
}
private ConnectionTreeModel SetupConnectionTreeModel()
{
/*
* Root
* |--- con0
* |--- folder1
* | L--- con1
* L--- folder2
* |--- con2
* L--- folder3
* |--- con3
* L--- con4
*/
BuildTreeNodes();
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection);
rootNode.AddChild(_folder1);
rootNode.AddChild(_folder2);
rootNode.AddChild(_con0);
_folder1.AddChild(_con1);
_folder2.AddChild(_con2);
_folder2.AddChild(_folder3);
_folder3.AddChild(_con3);
_folder3.AddChild(_con4);
connectionTreeModel.AddRootNode(rootNode);
return connectionTreeModel;
}
private ConnectionTreeModel SetupConnectionTreeModel()
{
/*
* Root
* |--- con0
* |--- folder1
* | L--- con1
* L--- folder2
* |--- con2
* L--- folder3
* |--- con3
* L--- con4
*/
BuildTreeNodes();
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection);
rootNode.AddChild(_folder1);
rootNode.AddChild(_folder2);
rootNode.AddChild(_con0);
_folder1.AddChild(_con1);
_folder2.AddChild(_con2);
_folder2.AddChild(_folder3);
_folder3.AddChild(_con3);
_folder3.AddChild(_con4);
connectionTreeModel.AddRootNode(rootNode);
return connectionTreeModel;
}
private void BuildTreeNodes()
{
_folder1 = new ContainerInfo { Name = "folder1" };
_folder2 = new ContainerInfo { Name = "folder2" };
_folder3 = new ContainerInfo { Name = "folder3" };
_con0 = new ConnectionInfo { Name = "con0" };
_con1 = new ConnectionInfo { Name = "con1" };
_con2 = new ConnectionInfo { Name = "con2" };
_con3 = new ConnectionInfo { Name = "con3" };
_con4 = new ConnectionInfo { Name = "con4" };
}
private void BuildTreeNodes()
{
_folder1 = new ContainerInfo { Name = "folder1" };
_folder2 = new ContainerInfo { Name = "folder2" };
_folder3 = new ContainerInfo { Name = "folder3" };
_con0 = new ConnectionInfo { Name = "con0" };
_con1 = new ConnectionInfo { Name = "con1" };
_con2 = new ConnectionInfo { Name = "con2" };
_con3 = new ConnectionInfo { Name = "con3" };
_con4 = new ConnectionInfo { Name = "con4" };
}
}

View File

@@ -9,67 +9,68 @@ using System.Linq;
using System.Xml.Linq;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Xml;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml;
public class XmlConnectionsDocumentEncryptorTests
{
public class XmlConnectionsDocumentEncryptorTests
private XmlConnectionsDocumentEncryptor _documentEncryptor;
private XDocument _originalDocument;
[SetUp]
public void Setup()
{
private XmlConnectionsDocumentEncryptor _documentEncryptor;
private XDocument _originalDocument;
var connectionTreeModel = SetupConnectionTreeModel();
var cryptoProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
cryptoProvider,
connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_originalDocument =
new XmlConnectionsDocumentCompiler(cryptoProvider, connectionNodeSerializer).CompileDocument(
connectionTreeModel, false);
_documentEncryptor = new XmlConnectionsDocumentEncryptor(cryptoProvider);
}
[SetUp]
public void Setup()
{
var connectionTreeModel = SetupConnectionTreeModel();
var cryptoProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
cryptoProvider,
connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_originalDocument = new XmlConnectionsDocumentCompiler(cryptoProvider, connectionNodeSerializer).CompileDocument(connectionTreeModel, false);
_documentEncryptor = new XmlConnectionsDocumentEncryptor(cryptoProvider);
}
[Test]
public void RootNodeValueIsEncrypted()
{
var encryptedDocument = _documentEncryptor.EncryptDocument(_originalDocument, "mR3m".ConvertToSecureString());
var encryptedContent = encryptedDocument.Root?.Value;
Assert.That(encryptedContent, Is.Not.EqualTo(string.Empty));
}
[Test]
public void RootNodeValueIsEncrypted()
{
var encryptedDocument = _documentEncryptor.EncryptDocument(_originalDocument, "mR3m".ConvertToSecureString());
var encryptedContent = encryptedDocument.Root?.Value;
Assert.That(encryptedContent, Is.Not.EqualTo(string.Empty));
}
private ConnectionTreeModel SetupConnectionTreeModel()
{
/*
* Root
* |--- con0
* |--- folder1
* | L--- con1
* L--- folder2
* |--- con2
* L--- folder3
* |--- con3
* L--- con4
*/
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection);
var folder1 = new ContainerInfo { Name = "folder1" };
var folder2 = new ContainerInfo { Name = "folder2" };
var folder3 = new ContainerInfo { Name = "folder3" };
var con0 = new ConnectionInfo { Name = "con0" };
var con1 = new ConnectionInfo { Name = "con1" };
var con2 = new ConnectionInfo { Name = "con2" };
var con3 = new ConnectionInfo { Name = "con3" };
var con4 = new ConnectionInfo { Name = "con4" };
rootNode.AddChild(folder1);
rootNode.AddChild(folder2);
rootNode.AddChild(con0);
folder1.AddChild(con1);
folder2.AddChild(con2);
folder2.AddChild(folder3);
folder3.AddChild(con3);
folder3.AddChild(con4);
connectionTreeModel.AddRootNode(rootNode);
return connectionTreeModel;
}
private ConnectionTreeModel SetupConnectionTreeModel()
{
/*
* Root
* |--- con0
* |--- folder1
* | L--- con1
* L--- folder2
* |--- con2
* L--- folder3
* |--- con3
* L--- con4
*/
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection);
var folder1 = new ContainerInfo { Name = "folder1" };
var folder2 = new ContainerInfo { Name = "folder2" };
var folder3 = new ContainerInfo { Name = "folder3" };
var con0 = new ConnectionInfo { Name = "con0" };
var con1 = new ConnectionInfo { Name = "con1" };
var con2 = new ConnectionInfo { Name = "con2" };
var con3 = new ConnectionInfo { Name = "con3" };
var con4 = new ConnectionInfo { Name = "con4" };
rootNode.AddChild(folder1);
rootNode.AddChild(folder2);
rootNode.AddChild(con0);
folder1.AddChild(con1);
folder2.AddChild(con2);
folder2.AddChild(folder3);
folder3.AddChild(con3);
folder3.AddChild(con4);
connectionTreeModel.AddRootNode(rootNode);
return connectionTreeModel;
}
}

View File

@@ -10,103 +10,103 @@ using System.Xml;
using System.Xml.Linq;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Xml;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml;
public class XmlConnectionsSerializerTests
{
public class XmlConnectionsSerializerTests
private XmlConnectionsSerializer _serializer;
private ConnectionTreeModel _connectionTreeModel;
private ICryptographyProvider _cryptographyProvider;
[SetUp]
public void Setup()
{
private XmlConnectionsSerializer _serializer;
private ConnectionTreeModel _connectionTreeModel;
private ICryptographyProvider _cryptographyProvider;
_connectionTreeModel = SetupConnectionTreeModel();
_cryptographyProvider = new AeadCryptographyProvider();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_serializer = new XmlConnectionsSerializer(_cryptographyProvider, connectionNodeSerializer);
}
[SetUp]
public void Setup()
{
_connectionTreeModel = SetupConnectionTreeModel();
_cryptographyProvider = new AeadCryptographyProvider();
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter());
_serializer = new XmlConnectionsSerializer(_cryptographyProvider, connectionNodeSerializer);
}
[Test]
public void ChildNestingSerializedCorrectly()
{
var serializedConnections = _serializer.Serialize(_connectionTreeModel);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(serializedConnections);
var nodeCon4 =
xmlDoc.DocumentElement?.SelectSingleNode("Node[@Name='folder2']/Node[@Name='folder3']/Node[@Name='con4']");
Assert.That(nodeCon4, Is.Not.Null);
}
[Test]
public void ChildNestingSerializedCorrectly()
{
var serializedConnections = _serializer.Serialize(_connectionTreeModel);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(serializedConnections);
var nodeCon4 = xmlDoc.DocumentElement?.SelectSingleNode("Node[@Name='folder2']/Node[@Name='folder3']/Node[@Name='con4']");
Assert.That(nodeCon4, Is.Not.Null);
}
[Test]
public void SingleConnectionSerializedCorrectly()
{
var connectionInfo = new ConnectionInfo { Name = "myConnection" };
var serializedConnections = _serializer.Serialize(connectionInfo);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(serializedConnections);
var connectionNode = xmlDoc.DocumentElement?.SelectSingleNode($"Node[@Name='{connectionInfo.Name}']");
Assert.That(connectionNode, Is.Not.Null);
}
[Test]
public void SingleConnectionSerializedCorrectly()
[TestCase("Username", "")]
[TestCase("Domain", "")]
[TestCase("Password", "")]
[TestCase("InheritAutomaticResize", null)]
public void SerializerRespectsSaveFilterSettings(string attributeName, string expectedValue)
{
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter(true));
var serializer = new XmlConnectionsSerializer(_cryptographyProvider, connectionNodeSerializer);
var connectionInfo = new ConnectionInfo
{
var connectionInfo = new ConnectionInfo {Name = "myConnection"};
var serializedConnections = _serializer.Serialize(connectionInfo);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(serializedConnections);
var connectionNode = xmlDoc.DocumentElement?.SelectSingleNode($"Node[@Name='{connectionInfo.Name}']");
Assert.That(connectionNode, Is.Not.Null);
}
Name = "myConnection",
Inheritance = { AutomaticResize = true }
};
var serializedConnections = serializer.Serialize(connectionInfo);
var xdoc = XDocument.Parse(serializedConnections);
var attributeValue = xdoc.Root?.Element("Node")?.Attribute(attributeName)?.Value;
Assert.That(attributeValue, Is.EqualTo(expectedValue));
}
[TestCase("Username", "")]
[TestCase("Domain", "")]
[TestCase("Password", "")]
[TestCase("InheritAutomaticResize", null)]
public void SerializerRespectsSaveFilterSettings(string attributeName, string expectedValue)
{
var connectionNodeSerializer = new XmlConnectionNodeSerializer27(
_cryptographyProvider,
_connectionTreeModel.RootNodes.OfType<RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
new SaveFilter(true));
var serializer = new XmlConnectionsSerializer(_cryptographyProvider, connectionNodeSerializer);
var connectionInfo = new ConnectionInfo
{
Name = "myConnection",
Inheritance = {AutomaticResize = true}
};
var serializedConnections = serializer.Serialize(connectionInfo);
var xdoc = XDocument.Parse(serializedConnections);
var attributeValue = xdoc.Root?.Element("Node")?.Attribute(attributeName)?.Value;
Assert.That(attributeValue, Is.EqualTo(expectedValue));
}
private ConnectionTreeModel SetupConnectionTreeModel()
{
/*
* Root
* |--- con0
* |--- folder1
* | L--- con1
* L--- folder2
* |--- con2
* L--- folder3
* |--- con3
* L--- con4
*/
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection);
var folder1 = new ContainerInfo { Name = "folder1" };
var folder2 = new ContainerInfo { Name = "folder2" };
var folder3 = new ContainerInfo { Name = "folder3" };
var con0 = new ConnectionInfo { Name = "con0" };
var con1 = new ConnectionInfo { Name = "con1" };
var con2 = new ConnectionInfo { Name = "con2" };
var con3 = new ConnectionInfo { Name = "con3" };
var con4 = new ConnectionInfo { Name = "con4" };
rootNode.AddChild(folder1);
rootNode.AddChild(folder2);
rootNode.AddChild(con0);
folder1.AddChild(con1);
folder2.AddChild(con2);
folder2.AddChild(folder3);
folder3.AddChild(con3);
folder3.AddChild(con4);
connectionTreeModel.AddRootNode(rootNode);
return connectionTreeModel;
}
private ConnectionTreeModel SetupConnectionTreeModel()
{
/*
* Root
* |--- con0
* |--- folder1
* | L--- con1
* L--- folder2
* |--- con2
* L--- folder3
* |--- con3
* L--- con4
*/
var connectionTreeModel = new ConnectionTreeModel();
var rootNode = new RootNodeInfo(RootNodeType.Connection);
var folder1 = new ContainerInfo { Name = "folder1" };
var folder2 = new ContainerInfo { Name = "folder2" };
var folder3 = new ContainerInfo { Name = "folder3" };
var con0 = new ConnectionInfo { Name = "con0" };
var con1 = new ConnectionInfo { Name = "con1" };
var con2 = new ConnectionInfo { Name = "con2" };
var con3 = new ConnectionInfo { Name = "con3" };
var con4 = new ConnectionInfo { Name = "con4" };
rootNode.AddChild(folder1);
rootNode.AddChild(folder2);
rootNode.AddChild(con0);
folder1.AddChild(con1);
folder2.AddChild(con2);
folder2.AddChild(folder3);
folder3.AddChild(con3);
folder3.AddChild(con4);
connectionTreeModel.AddRootNode(rootNode);
return connectionTreeModel;
}
}

View File

@@ -8,115 +8,113 @@ using mRemoteNG.Security.SymmetricEncryption;
using mRemoteNG.Tree.Root;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml
namespace mRemoteNGTests.Config.Serializers.ConnectionSerializers.Xml;
public class XmlRootNodeSerializerTests
{
public class XmlRootNodeSerializerTests
private XmlRootNodeSerializer _rootNodeSerializer;
private ICryptographyProvider _cryptographyProvider;
private RootNodeInfo _rootNodeInfo;
private Version _version;
[SetUp]
public void Setup()
{
private XmlRootNodeSerializer _rootNodeSerializer;
private ICryptographyProvider _cryptographyProvider;
private RootNodeInfo _rootNodeInfo;
private Version _version;
_rootNodeSerializer = new XmlRootNodeSerializer();
_cryptographyProvider = new AeadCryptographyProvider();
_rootNodeInfo = new RootNodeInfo(RootNodeType.Connection);
_version = new Version(99, 1);
}
[SetUp]
public void Setup()
{
_rootNodeSerializer = new XmlRootNodeSerializer();
_cryptographyProvider = new AeadCryptographyProvider();
_rootNodeInfo = new RootNodeInfo(RootNodeType.Connection);
_version = new Version(99, 1);
}
[Test]
public void RootElementNamedConnections()
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
Assert.That(element.Name.LocalName, Is.EqualTo("Connections"));
}
[Test]
public void RootElementNamedConnections()
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
Assert.That(element.Name.LocalName, Is.EqualTo("Connections"));
}
[Test]
[SetUICulture("en-US")]
public void RootNodeInfoNameSerialized()
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("Name"))?.Value;
Assert.That(attributeValue, Is.EqualTo("Connections"));
}
[Test]
[SetUICulture("en-US")]
public void RootNodeInfoNameSerialized()
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("Name"))?.Value;
Assert.That(attributeValue, Is.EqualTo("Connections"));
}
[TestCaseSource(typeof(TestCaseSources), nameof(TestCaseSources.AllEngineAndModeCombos))]
public void EncryptionEngineSerialized(BlockCipherEngines engine, BlockCipherModes mode)
{
var cryptoProvider = new CryptoProviderFactory(engine, mode).Build();
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, cryptoProvider, _version);
var attributeValue = element.Attribute(XName.Get("EncryptionEngine"))?.Value;
Assert.That(attributeValue, Is.EqualTo(engine.ToString()));
}
[TestCaseSource(typeof(TestCaseSources), nameof(TestCaseSources.AllEngineAndModeCombos))]
public void EncryptionEngineSerialized(BlockCipherEngines engine, BlockCipherModes mode)
{
var cryptoProvider = new CryptoProviderFactory(engine, mode).Build();
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, cryptoProvider, _version);
var attributeValue = element.Attribute(XName.Get("EncryptionEngine"))?.Value;
Assert.That(attributeValue, Is.EqualTo(engine.ToString()));
}
[TestCaseSource(typeof(TestCaseSources), nameof(TestCaseSources.AllEngineAndModeCombos))]
public void EncryptionModeSerialized(BlockCipherEngines engine, BlockCipherModes mode)
{
var cryptoProvider = new CryptoProviderFactory(engine, mode).Build();
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, cryptoProvider, _version);
var attributeValue = element.Attribute(XName.Get("BlockCipherMode"))?.Value;
Assert.That(attributeValue, Is.EqualTo(mode.ToString()));
}
[TestCaseSource(typeof(TestCaseSources), nameof(TestCaseSources.AllEngineAndModeCombos))]
public void EncryptionModeSerialized(BlockCipherEngines engine, BlockCipherModes mode)
{
var cryptoProvider = new CryptoProviderFactory(engine, mode).Build();
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, cryptoProvider, _version);
var attributeValue = element.Attribute(XName.Get("BlockCipherMode"))?.Value;
Assert.That(attributeValue, Is.EqualTo(mode.ToString()));
}
[TestCase(1000)]
[TestCase(1234)]
[TestCase(9999)]
[TestCase(10000)]
public void KdfIterationsSerialized(int iterations)
{
_cryptographyProvider.KeyDerivationIterations = iterations;
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("KdfIterations"))?.Value;
Assert.That(attributeValue, Is.EqualTo(iterations.ToString()));
}
[TestCase(1000)]
[TestCase(1234)]
[TestCase(9999)]
[TestCase(10000)]
public void KdfIterationsSerialized(int iterations)
{
_cryptographyProvider.KeyDerivationIterations = iterations;
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("KdfIterations"))?.Value;
Assert.That(attributeValue, Is.EqualTo(iterations.ToString()));
}
[TestCase(true)]
[TestCase(false)]
public void FullFileEncryptionFlagSerialized(bool fullFileEncryption)
{
var element =
_rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version,
fullFileEncryption);
var attributeValue = element.Attribute(XName.Get("FullFileEncryption"))?.Value;
Assert.That(bool.Parse(attributeValue), Is.EqualTo(fullFileEncryption));
}
[TestCase(true)]
[TestCase(false)]
public void FullFileEncryptionFlagSerialized(bool fullFileEncryption)
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version, fullFileEncryption);
var attributeValue = element.Attribute(XName.Get("FullFileEncryption"))?.Value;
Assert.That(bool.Parse(attributeValue), Is.EqualTo(fullFileEncryption));
}
[TestCase("", "ThisIsNotProtected")]
[TestCase(null, "ThisIsNotProtected")]
[TestCase("mR3m", "ThisIsNotProtected")]
[TestCase("customPassword1", "ThisIsProtected")]
public void ProtectedStringSerialized(string customPassword, string expectedPlainText)
{
_rootNodeInfo.PasswordString = customPassword;
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("Protected"))?.Value;
var attributeValuePlainText =
_cryptographyProvider.Decrypt(attributeValue, _rootNodeInfo.PasswordString.ConvertToSecureString());
Assert.That(attributeValuePlainText, Is.EqualTo(expectedPlainText));
}
[TestCase("", "ThisIsNotProtected")]
[TestCase(null, "ThisIsNotProtected")]
[TestCase("mR3m", "ThisIsNotProtected")]
[TestCase("customPassword1", "ThisIsProtected")]
public void ProtectedStringSerialized(string customPassword, string expectedPlainText)
{
_rootNodeInfo.PasswordString = customPassword;
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("Protected"))?.Value;
var attributeValuePlainText = _cryptographyProvider.Decrypt(attributeValue, _rootNodeInfo.PasswordString.ConvertToSecureString());
Assert.That(attributeValuePlainText, Is.EqualTo(expectedPlainText));
}
[Test]
public void ConfVersionSerialized()
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("ConfVersion"))?.Value ?? "";
var confVersion = Version.Parse(attributeValue);
Assert.That(confVersion, Is.EqualTo(_version));
}
[Test]
public void ConfVersionSerialized()
private class TestCaseSources
{
public static IEnumerable AllEngineAndModeCombos
{
var element = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, _cryptographyProvider, _version);
var attributeValue = element.Attribute(XName.Get("ConfVersion"))?.Value ?? "";
var confVersion = Version.Parse(attributeValue);
Assert.That(confVersion, Is.EqualTo(_version));
}
private class TestCaseSources
{
public static IEnumerable AllEngineAndModeCombos
get
{
get
{
foreach (var engine in Enum.GetValues(typeof(BlockCipherEngines)))
{
foreach (var mode in Enum.GetValues(typeof(BlockCipherModes)))
{
yield return new TestCaseData(engine, mode);
}
}
}
foreach (var engine in Enum.GetValues(typeof(BlockCipherEngines)))
foreach (var mode in Enum.GetValues(typeof(BlockCipherModes)))
yield return new TestCaseData(engine, mode);
}
}
}

View File

@@ -5,33 +5,32 @@ using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers
namespace mRemoteNGTests.Config.Serializers;
public class CredentialProviderSerializerTests
{
public class CredentialProviderSerializerTests
private CredentialRepositoryListSerializer _credentialProviderSerializer;
[SetUp]
public void Setup()
{
private CredentialRepositoryListSerializer _credentialProviderSerializer;
_credentialProviderSerializer = new CredentialRepositoryListSerializer();
}
[SetUp]
public void Setup()
{
_credentialProviderSerializer = new CredentialRepositoryListSerializer();
}
private ICredentialRepository InitializeMockProvider()
{
var provider = Substitute.For<ICredentialRepository>();
provider.Config.TypeName.Returns("ProviderName");
provider.Config.Id.Returns(Guid.NewGuid());
return provider;
}
private ICredentialRepository InitializeMockProvider()
{
var provider = Substitute.For<ICredentialRepository>();
provider.Config.TypeName.Returns("ProviderName");
provider.Config.Id.Returns(Guid.NewGuid());
return provider;
}
[Test]
public void SerializeExists()
{
var mockProvider = InitializeMockProvider();
var providers = new[] { mockProvider };
var serializedContent = _credentialProviderSerializer.Serialize(providers);
Assert.That(serializedContent, Is.Not.Null);
}
[Test]
public void SerializeExists()
{
var mockProvider = InitializeMockProvider();
var providers = new[] { mockProvider };
var serializedContent = _credentialProviderSerializer.Serialize(providers);
Assert.That(serializedContent, Is.Not.Null);
}
}

View File

@@ -5,47 +5,46 @@ using mRemoteNG.Security;
using mRemoteNG.Security.SymmetricEncryption;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers;
public class XmlCredentialPasswordDecryptorDecoratorTests
{
public class XmlCredentialPasswordDecryptorDecoratorTests
private XmlCredentialPasswordDecryptorDecorator _sut;
private readonly SecureString _decryptionKey = "myKey1".ConvertToSecureString();
private string _unencryptedPassword = "myPassword1";
[SetUp]
public void Setup()
{
private XmlCredentialPasswordDecryptorDecorator _sut;
private readonly SecureString _decryptionKey = "myKey1".ConvertToSecureString();
private string _unencryptedPassword = "myPassword1";
var baseDeserializer = new XmlCredentialRecordDeserializer();
_sut = new XmlCredentialPasswordDecryptorDecorator(baseDeserializer);
}
[SetUp]
public void Setup()
{
var baseDeserializer = new XmlCredentialRecordDeserializer();
_sut = new XmlCredentialPasswordDecryptorDecorator(baseDeserializer);
}
[Test]
public void OutputedCredentialHasDecryptedPassword()
{
var xml = GenerateCredentialXml();
var output = _sut.Deserialize(xml, _decryptionKey);
Assert.That(output.First().Password.ConvertToUnsecureString(), Is.EqualTo(_unencryptedPassword));
}
[Test]
public void OutputedCredentialHasDecryptedPassword()
{
var xml = GenerateCredentialXml();
var output = _sut.Deserialize(xml, _decryptionKey);
Assert.That(output.First().Password.ConvertToUnsecureString(), Is.EqualTo(_unencryptedPassword));
}
[Test]
public void DecryptionThrowsExceptionWhenAuthHeaderNotFound()
{
var xml = GenerateCredentialXml(false);
Assert.Throws<EncryptionException>(() => _sut.Deserialize(xml, _decryptionKey));
}
[Test]
public void DecryptionThrowsExceptionWhenAuthHeaderNotFound()
{
var xml = GenerateCredentialXml(false);
Assert.Throws<EncryptionException>(() => _sut.Deserialize(xml, _decryptionKey));
}
private string GenerateCredentialXml(bool includeAuthHeader = true)
{
var cryptoProvider = new AeadCryptographyProvider();
var authHeader = includeAuthHeader ? $"Auth=\"{cryptoProvider.Encrypt("someheader", _decryptionKey)}\"" : "";
var encryptedPassword = cryptoProvider.Encrypt(_unencryptedPassword, _decryptionKey);
return
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
$"<Credentials EncryptionEngine=\"{cryptoProvider.CipherEngine}\" BlockCipherMode=\"{cryptoProvider.CipherMode}\" KdfIterations=\"{cryptoProvider.KeyDerivationIterations}\" {authHeader} SchemaVersion=\"1.0\">" +
$"<Credential Id=\"ce6b0397-d476-4ffe-884b-dbe9347a88a8\" Title=\"New Credential\" Username=\"asdfasdf\" Domain=\"\" Password=\"{encryptedPassword}\" />" +
"</Credentials>";
}
private string GenerateCredentialXml(bool includeAuthHeader = true)
{
var cryptoProvider = new AeadCryptographyProvider();
var authHeader = includeAuthHeader ? $"Auth=\"{cryptoProvider.Encrypt("someheader", _decryptionKey)}\"" : "";
var encryptedPassword = cryptoProvider.Encrypt(_unencryptedPassword, _decryptionKey);
return
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
$"<Credentials EncryptionEngine=\"{cryptoProvider.CipherEngine}\" BlockCipherMode=\"{cryptoProvider.CipherMode}\" KdfIterations=\"{cryptoProvider.KeyDerivationIterations}\" {authHeader} SchemaVersion=\"1.0\">" +
$"<Credential Id=\"ce6b0397-d476-4ffe-884b-dbe9347a88a8\" Title=\"New Credential\" Username=\"asdfasdf\" Domain=\"\" Password=\"{encryptedPassword}\" />" +
"</Credentials>";
}
}

View File

@@ -10,77 +10,76 @@ using mRemoteNG.Security;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers;
public class XmlCredentialPasswordEncryptorDecoratorTests
{
public class XmlCredentialPasswordEncryptorDecoratorTests
private XmlCredentialPasswordEncryptorDecorator _sut;
private const BlockCipherEngines CipherEngine = BlockCipherEngines.Twofish;
private const BlockCipherModes CipherMode = BlockCipherModes.EAX;
private const int KdfIterations = 2000;
private SecureString _key = "myKey1".ConvertToSecureString();
[SetUp]
public void Setup()
{
private XmlCredentialPasswordEncryptorDecorator _sut;
private const BlockCipherEngines CipherEngine = BlockCipherEngines.Twofish;
private const BlockCipherModes CipherMode = BlockCipherModes.EAX;
private const int KdfIterations = 2000;
private SecureString _key = "myKey1".ConvertToSecureString();
[SetUp]
public void Setup()
{
var cryptoProvider = SetupCryptoProvider();
var baseSerializer = SetupBaseSerializer();
_sut = new XmlCredentialPasswordEncryptorDecorator(cryptoProvider, baseSerializer);
}
var cryptoProvider = SetupCryptoProvider();
var baseSerializer = SetupBaseSerializer();
_sut = new XmlCredentialPasswordEncryptorDecorator(cryptoProvider, baseSerializer);
}
[Test]
public void CantPassNullCredentialList()
{
Assert.Throws<ArgumentNullException>(() => _sut.Serialize(null, new SecureString()));
}
[Test]
public void CantPassNullCredentialList()
{
Assert.Throws<ArgumentNullException>(() => _sut.Serialize(null, new SecureString()));
}
[Test]
public void EncryptsPasswordAttributesInXml()
{
var credList = Substitute.For<IEnumerable<ICredentialRecord>>();
var output = _sut.Serialize(credList, _key);
var outputAsXdoc = XDocument.Parse(output);
var firstElementPassword = outputAsXdoc.Root?.Descendants().First().FirstAttribute.Value;
Assert.That(firstElementPassword, Is.EqualTo("encrypted"));
}
[Test]
public void EncryptsPasswordAttributesInXml()
{
var credList = Substitute.For<IEnumerable<ICredentialRecord>>();
var output = _sut.Serialize(credList, _key);
var outputAsXdoc = XDocument.Parse(output);
var firstElementPassword = outputAsXdoc.Root?.Descendants().First().FirstAttribute.Value;
Assert.That(firstElementPassword, Is.EqualTo("encrypted"));
}
[TestCase("EncryptionEngine", CipherEngine)]
[TestCase("BlockCipherMode", CipherMode)]
[TestCase("KdfIterations", KdfIterations)]
[TestCase("Auth", "encrypted")]
public void SetsRootNodeEncryptionAttributes(string attributeName, object expectedValue)
{
var credList = Substitute.For<IEnumerable<ICredentialRecord>>();
var output = _sut.Serialize(credList, _key);
var outputAsXdoc = XDocument.Parse(output);
var authField = outputAsXdoc.Root?.Attribute(attributeName)?.Value;
Assert.That(authField, Is.EqualTo(expectedValue.ToString()));
}
[TestCase("EncryptionEngine", CipherEngine)]
[TestCase("BlockCipherMode", CipherMode)]
[TestCase("KdfIterations", KdfIterations)]
[TestCase("Auth", "encrypted")]
public void SetsRootNodeEncryptionAttributes(string attributeName, object expectedValue)
{
var credList = Substitute.For<IEnumerable<ICredentialRecord>>();
var output = _sut.Serialize(credList, _key);
var outputAsXdoc = XDocument.Parse(output);
var authField = outputAsXdoc.Root?.Attribute(attributeName)?.Value;
Assert.That(authField, Is.EqualTo(expectedValue.ToString()));
}
private ISerializer<IEnumerable<ICredentialRecord>, string> SetupBaseSerializer()
{
var baseSerializer = Substitute.For<ISerializer<IEnumerable<ICredentialRecord>, string>>();
var randomString = Guid.NewGuid().ToString();
baseSerializer.Serialize(null).ReturnsForAnyArgs(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<Root>" +
$"<Element1 Password=\"{randomString}\" />" +
$"<Element1 Password=\"{randomString}\">" +
$"<Element1 Password=\"{randomString}\" />" +
"</Element1>" +
"</Root>");
return baseSerializer;
}
private ISerializer<IEnumerable<ICredentialRecord>, string> SetupBaseSerializer()
{
var baseSerializer = Substitute.For<ISerializer<IEnumerable<ICredentialRecord>, string>>();
var randomString = Guid.NewGuid().ToString();
baseSerializer.Serialize(null).ReturnsForAnyArgs(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<Root>" +
$"<Element1 Password=\"{randomString}\" />" +
$"<Element1 Password=\"{randomString}\">" +
$"<Element1 Password=\"{randomString}\" />" +
"</Element1>" +
"</Root>");
return baseSerializer;
}
private ICryptographyProvider SetupCryptoProvider()
{
var cryptoProvider = Substitute.For<ICryptographyProvider>();
cryptoProvider.CipherEngine.Returns(CipherEngine);
cryptoProvider.CipherMode.Returns(CipherMode);
cryptoProvider.KeyDerivationIterations.Returns(KdfIterations);
cryptoProvider.Encrypt(null, null).ReturnsForAnyArgs("encrypted");
return cryptoProvider;
}
private ICryptographyProvider SetupCryptoProvider()
{
var cryptoProvider = Substitute.For<ICryptographyProvider>();
cryptoProvider.CipherEngine.Returns(CipherEngine);
cryptoProvider.CipherMode.Returns(CipherMode);
cryptoProvider.KeyDerivationIterations.Returns(KdfIterations);
cryptoProvider.Encrypt(null, null).ReturnsForAnyArgs("encrypted");
return cryptoProvider;
}
}

View File

@@ -4,87 +4,88 @@ using mRemoteNG.Config.Serializers.CredentialSerializer;
using mRemoteNG.Security;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers;
public class XmlCredentialRecordDeserializerTests
{
public class XmlCredentialRecordDeserializerTests
private XmlCredentialRecordDeserializer _deserializer;
private readonly Guid _id = Guid.NewGuid();
private const string Title = "sometitle";
private const string Username = "myusername";
private const string Domain = "mydomain";
private const string PlaintextPassword = "mypassword";
[SetUp]
public void Setup()
{
private XmlCredentialRecordDeserializer _deserializer;
private readonly Guid _id = Guid.NewGuid();
private const string Title = "sometitle";
private const string Username = "myusername";
private const string Domain = "mydomain";
private const string PlaintextPassword = "mypassword";
_deserializer = new XmlCredentialRecordDeserializer();
}
[Test]
public void HasCorrectId()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Id, Is.EqualTo(_id));
}
[Test]
public void HasCorrectTitle()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Title, Is.EqualTo(Title));
}
[Test]
public void HasCorrectUsername()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Username, Is.EqualTo(Username));
}
[Test]
public void HasCorrectDomain()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Domain, Is.EqualTo(Domain));
}
[Test]
public void HasCorrectPassword()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Password.ConvertToUnsecureString(), Is.EqualTo(PlaintextPassword));
}
[Test]
public void DeserializesAllCredentials()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.Count(), Is.EqualTo(2));
}
[Test]
public void CanDecryptNonStandardEncryptions()
{
var xml = GenerateXml(BlockCipherEngines.Serpent, BlockCipherModes.EAX, 3000);
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Password.ConvertToUnsecureString(), Is.EqualTo(PlaintextPassword));
}
[SetUp]
public void Setup()
{
_deserializer = new XmlCredentialRecordDeserializer();
}
[Test]
public void HasCorrectId()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Id, Is.EqualTo(_id));
}
[Test]
public void HasCorrectTitle()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Title, Is.EqualTo(Title));
}
[Test]
public void HasCorrectUsername()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Username, Is.EqualTo(Username));
}
[Test]
public void HasCorrectDomain()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Domain, Is.EqualTo(Domain));
}
[Test]
public void HasCorrectPassword()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Password.ConvertToUnsecureString(), Is.EqualTo(PlaintextPassword));
}
[Test]
public void DeserializesAllCredentials()
{
var xml = GenerateXml();
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.Count(), Is.EqualTo(2));
}
[Test]
public void CanDecryptNonStandardEncryptions()
{
var xml = GenerateXml(BlockCipherEngines.Serpent, BlockCipherModes.EAX, 3000);
var creds = _deserializer.Deserialize(xml);
Assert.That(creds.First().Password.ConvertToUnsecureString(), Is.EqualTo(PlaintextPassword));
}
private string GenerateXml(BlockCipherEngines engine = BlockCipherEngines.AES, BlockCipherModes mode = BlockCipherModes.GCM, int interations = 1000)
{
return $"<Credentials EncryptionEngine=\"{engine}\" BlockCipherMode=\"{mode}\" KdfIterations=\"{interations}\" SchemaVersion=\"1.0\">" +
$"<Credential Id=\"{_id}\" Title=\"{Title}\" Username=\"{Username}\" Domain=\"{Domain}\" Password=\"{PlaintextPassword}\" />" +
$"<Credential Id=\"{Guid.NewGuid()}\" Title=\"{Title}\" Username=\"{Username}\" Domain=\"{Domain}\" Password=\"{PlaintextPassword}\" />" +
"</Credentials>";
}
private string GenerateXml(BlockCipherEngines engine = BlockCipherEngines.AES,
BlockCipherModes mode = BlockCipherModes.GCM, int interations = 1000)
{
return
$"<Credentials EncryptionEngine=\"{engine}\" BlockCipherMode=\"{mode}\" KdfIterations=\"{interations}\" SchemaVersion=\"1.0\">" +
$"<Credential Id=\"{_id}\" Title=\"{Title}\" Username=\"{Username}\" Domain=\"{Domain}\" Password=\"{PlaintextPassword}\" />" +
$"<Credential Id=\"{Guid.NewGuid()}\" Title=\"{Title}\" Username=\"{Username}\" Domain=\"{Domain}\" Password=\"{PlaintextPassword}\" />" +
"</Credentials>";
}
}

View File

@@ -6,44 +6,50 @@ using System;
using System.Linq;
using System.Xml.Linq;
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers
namespace mRemoteNGTests.Config.Serializers.CredentialSerializers;
public class XmlCredentialSerializerTests
{
public class XmlCredentialSerializerTests
private XmlCredentialRecordSerializer _serializer;
private ICredentialRecord _cred1;
[SetUp]
public void Setup()
{
private XmlCredentialRecordSerializer _serializer;
private ICredentialRecord _cred1;
[SetUp]
public void Setup()
_serializer = new XmlCredentialRecordSerializer();
_cred1 = new CredentialRecord
{
_serializer = new XmlCredentialRecordSerializer();
_cred1 = new CredentialRecord { Title = "testcred", Username = "davids", Domain = "mydomain", Password = "mypass".ConvertToSecureString() };
}
Title = "testcred", Username = "davids", Domain = "mydomain", Password = "mypass".ConvertToSecureString()
};
}
[Test]
public void ProducesValidXml()
{
var serialized = _serializer.Serialize(new[] { _cred1 });
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Assert.DoesNotThrow(() => XDocument.Parse(serialized));
}
[Test]
public void ProducesValidXml()
{
var serialized = _serializer.Serialize(new[] { _cred1 });
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Assert.DoesNotThrow(() => XDocument.Parse(serialized));
}
[Test]
public void AllCredentialsSerialized()
[Test]
public void AllCredentialsSerialized()
{
var cred2 = new CredentialRecord
{
var cred2 = new CredentialRecord { Title = "testcred2", Username = "admin", Domain = "otherdomain", Password = "somepass".ConvertToSecureString() };
var serialized = _serializer.Serialize(new[] { _cred1, cred2 });
var serializedCount = XDocument.Parse(serialized).Descendants("Credential").Count();
Assert.That(serializedCount, Is.EqualTo(2));
}
Title = "testcred2", Username = "admin", Domain = "otherdomain",
Password = "somepass".ConvertToSecureString()
};
var serialized = _serializer.Serialize(new[] { _cred1, cred2 });
var serializedCount = XDocument.Parse(serialized).Descendants("Credential").Count();
Assert.That(serializedCount, Is.EqualTo(2));
}
[Test]
public void IncludesSchemaVersionParameter()
{
var serialized = _serializer.Serialize(new[] { _cred1 });
var xdoc = XDocument.Parse(serialized);
var version = Version.Parse(xdoc.Root?.Attribute("SchemaVersion")?.Value ?? "");
Assert.That(version, Is.EqualTo(_serializer.Version));
}
[Test]
public void IncludesSchemaVersionParameter()
{
var serialized = _serializer.Serialize(new[] { _cred1 });
var xdoc = XDocument.Parse(serialized);
var version = Version.Parse(xdoc.Root?.Attribute("SchemaVersion")?.Value ?? "");
Assert.That(version, Is.EqualTo(_serializer.Version));
}
}

View File

@@ -1,6 +1,6 @@
using System.Data;
using System.Security;
using mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Sql;
using mRemoteNG.Connection;
using mRemoteNG.Security;
using mRemoteNG.Security.SymmetricEncryption;
@@ -8,49 +8,48 @@ using mRemoteNG.Tree;
using mRemoteNGTests.TestHelpers;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers
namespace mRemoteNGTests.Config.Serializers;
public class DataTableDeserializerTests
{
public class DataTableDeserializerTests
private DataTableDeserializer _deserializer;
private ICryptographyProvider _cryptographyProvider;
[SetUp]
public void Setup()
{
private DataTableDeserializer _deserializer;
private ICryptographyProvider _cryptographyProvider;
_cryptographyProvider = new LegacyRijndaelCryptographyProvider();
}
[SetUp]
public void Setup()
{
_cryptographyProvider = new LegacyRijndaelCryptographyProvider();
}
[Test]
public void WeCanDeserializeATree()
{
var model = CreateConnectionTreeModel();
var dataTable = CreateDataTable(model.RootNodes[0]);
_deserializer = new DataTableDeserializer(_cryptographyProvider, new SecureString());
var output = _deserializer.Deserialize(dataTable);
Assert.That(output.GetRecursiveChildList().Count, Is.EqualTo(model.GetRecursiveChildList().Count));
}
[Test]
public void WeCanDeserializeATree()
{
var model = CreateConnectionTreeModel();
var dataTable = CreateDataTable(model.RootNodes[0]);
_deserializer = new DataTableDeserializer(_cryptographyProvider, new SecureString());
var output = _deserializer.Deserialize(dataTable);
Assert.That(output.GetRecursiveChildList().Count, Is.EqualTo(model.GetRecursiveChildList().Count));
}
[Test]
public void WeCanDeserializeASingleEntry()
{
var dataTable = CreateDataTable(new ConnectionInfo());
_deserializer = new DataTableDeserializer(_cryptographyProvider, new SecureString());
var output = _deserializer.Deserialize(dataTable);
Assert.That(output.GetRecursiveChildList().Count, Is.EqualTo(1));
}
[Test]
public void WeCanDeserializeASingleEntry()
{
var dataTable = CreateDataTable(new ConnectionInfo());
_deserializer = new DataTableDeserializer(_cryptographyProvider, new SecureString());
var output = _deserializer.Deserialize(dataTable);
Assert.That(output.GetRecursiveChildList().Count, Is.EqualTo(1));
}
private DataTable CreateDataTable(ConnectionInfo tableContent)
{
var serializer = new DataTableSerializer(new SaveFilter(), _cryptographyProvider, new SecureString());
return serializer.Serialize(tableContent);
}
private DataTable CreateDataTable(ConnectionInfo tableContent)
{
var serializer = new DataTableSerializer(new SaveFilter(), _cryptographyProvider, new SecureString());
return serializer.Serialize(tableContent);
}
private ConnectionTreeModel CreateConnectionTreeModel()
{
var builder = new ConnectionTreeModelBuilder();
return builder.Build();
}
private ConnectionTreeModel CreateConnectionTreeModel()
{
var builder = new ConnectionTreeModelBuilder();
return builder.Build();
}
}

View File

@@ -1,6 +1,6 @@
using System.Linq;
using System.Security;
using mRemoteNG.Config.Serializers.ConnectionSerializers.MsSql;
using mRemoteNG.Config.Serializers.ConnectionSerializers.Sql;
using mRemoteNG.Connection;
using mRemoteNG.Security;
using mRemoteNG.Security.SymmetricEncryption;
@@ -8,125 +8,123 @@ using mRemoteNG.Tree;
using mRemoteNGTests.TestHelpers;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers
namespace mRemoteNGTests.Config.Serializers;
public class DataTableSerializerTests
{
public class DataTableSerializerTests
private DataTableSerializer _dataTableSerializer;
private SaveFilter _saveFilter;
[SetUp]
public void Setup()
{
private DataTableSerializer _dataTableSerializer;
private SaveFilter _saveFilter;
_saveFilter = new SaveFilter();
_dataTableSerializer = new DataTableSerializer(
_saveFilter,
new LegacyRijndaelCryptographyProvider(),
new SecureString());
}
[SetUp]
public void Setup()
{
_saveFilter = new SaveFilter();
_dataTableSerializer = new DataTableSerializer(
_saveFilter,
new LegacyRijndaelCryptographyProvider(),
new SecureString());
}
[Test]
public void AllItemsSerialized()
{
var model = CreateConnectionTreeModel();
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows.Count, Is.EqualTo(model.GetRecursiveChildList().Count()));
}
[Test]
public void AllItemsSerialized()
{
var model = CreateConnectionTreeModel();
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows.Count, Is.EqualTo(model.GetRecursiveChildList().Count()));
}
[Test]
public void ReturnsEmptyDataTableWhenGivenEmptyConnectionTreeModel()
{
var model = new ConnectionTreeModel();
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows.Count, Is.EqualTo(0));
}
[Test]
public void ReturnsEmptyDataTableWhenGivenEmptyConnectionTreeModel()
{
var model = new ConnectionTreeModel();
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows.Count, Is.EqualTo(0));
}
[Test]
public void UsernameSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveUsername = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Username"], Is.Not.EqualTo(""));
}
[Test]
public void UsernameSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveUsername = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Username"], Is.Not.EqualTo(""));
}
[Test]
public void DomainSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveDomain = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Domain"], Is.Not.EqualTo(""));
}
[Test]
public void DomainSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveDomain = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Domain"], Is.Not.EqualTo(""));
}
[Test]
public void PasswordSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SavePassword = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Password"], Is.Not.EqualTo(""));
}
[Test]
public void PasswordSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SavePassword = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Password"], Is.Not.EqualTo(""));
}
[Test]
public void InheritanceSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveInheritance = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["InheritUsername"], Is.Not.EqualTo(""));
}
[Test]
public void InheritanceSerializedWhenSaveSecurityAllowsIt()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveInheritance = true;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["InheritUsername"], Is.Not.EqualTo(""));
}
[Test]
public void UsernameNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveUsername = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Username"], Is.EqualTo(""));
}
[Test]
public void UsernameNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveUsername = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Username"], Is.EqualTo(""));
}
[Test]
public void DomainNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveDomain = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Domain"], Is.EqualTo(""));
}
[Test]
public void DomainNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveDomain = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Domain"], Is.EqualTo(""));
}
[Test]
public void PasswordNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SavePassword = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Password"], Is.EqualTo(""));
}
[Test]
public void PasswordNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SavePassword = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["Password"], Is.EqualTo(""));
}
[Test]
public void InheritanceNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveInheritance = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["InheritUsername"], Is.False);
}
[Test]
public void InheritanceNotSerializedWhenSaveSecurityDisabled()
{
var model = CreateConnectionTreeModel();
_saveFilter.SaveInheritance = false;
var dataTable = _dataTableSerializer.Serialize(model);
Assert.That(dataTable.Rows[0]["InheritUsername"], Is.False);
}
[Test]
public void CanSerializeEmptyConnectionInfo()
{
var dataTable = _dataTableSerializer.Serialize(new ConnectionInfo());
Assert.That(dataTable.Rows.Count, Is.EqualTo(1));
}
[Test]
public void CanSerializeEmptyConnectionInfo()
{
var dataTable = _dataTableSerializer.Serialize(new ConnectionInfo());
Assert.That(dataTable.Rows.Count, Is.EqualTo(1));
}
private ConnectionTreeModel CreateConnectionTreeModel()
{
var builder = new ConnectionTreeModelBuilder();
return builder.Build();
}
private ConnectionTreeModel CreateConnectionTreeModel()
{
var builder = new ConnectionTreeModelBuilder();
return builder.Build();
}
}

View File

@@ -5,55 +5,53 @@ using mRemoteNG.Connection.Protocol;
using mRemoteNG.Tools;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.MiscSerializers
namespace mRemoteNGTests.Config.Serializers.MiscSerializers;
public class PortScanDeserializerTests
{
public class PortScanDeserializerTests
private PortScanDeserializer _deserializer;
private ConnectionInfo _importedConnectionInfo;
private const string ExpectedHostName = "server1.domain.com";
private const string ExpectedDisplayName = "server1";
private const ProtocolType ExpectedProtocolType = ProtocolType.SSH2;
[OneTimeSetUp]
public void OnetimeSetup()
{
private PortScanDeserializer _deserializer;
private ConnectionInfo _importedConnectionInfo;
private const string ExpectedHostName = "server1.domain.com";
private const string ExpectedDisplayName = "server1";
private const ProtocolType ExpectedProtocolType = ProtocolType.SSH2;
[OneTimeSetUp]
public void OnetimeSetup()
var host = new ScanHost("10.20.30.40")
{
var host = new ScanHost("10.20.30.40")
{
HostName = "server1.domain.com",
Ssh = true
};
_deserializer = new PortScanDeserializer(ProtocolType.SSH2);
var connectionTreeModel = _deserializer.Deserialize(new[] { host });
var root = connectionTreeModel.RootNodes.First();
_importedConnectionInfo = root.Children.First();
}
HostName = "server1.domain.com",
Ssh = true
};
_deserializer = new PortScanDeserializer(ProtocolType.SSH2);
var connectionTreeModel = _deserializer.Deserialize(new[] { host });
var root = connectionTreeModel.RootNodes.First();
_importedConnectionInfo = root.Children.First();
}
[OneTimeTearDown]
public void OnetimeTeardown()
{
_deserializer = null;
_importedConnectionInfo = null;
}
[OneTimeTearDown]
public void OnetimeTeardown()
{
_deserializer = null;
_importedConnectionInfo = null;
}
[Test]
public void DisplayNameImported()
{
Assert.That(_importedConnectionInfo.Name, Is.EqualTo(ExpectedDisplayName));
}
[Test]
public void DisplayNameImported()
{
Assert.That(_importedConnectionInfo.Name, Is.EqualTo(ExpectedDisplayName));
}
[Test]
public void HostNameImported()
{
Assert.That(_importedConnectionInfo.Hostname, Is.EqualTo(ExpectedHostName));
}
[Test]
public void HostNameImported()
{
Assert.That(_importedConnectionInfo.Hostname, Is.EqualTo(ExpectedHostName));
}
[Test]
public void ProtocolImported()
{
Assert.That(_importedConnectionInfo.Protocol, Is.EqualTo(ExpectedProtocolType));
}
[Test]
public void ProtocolImported()
{
Assert.That(_importedConnectionInfo.Protocol, Is.EqualTo(ExpectedProtocolType));
}
}

View File

@@ -6,106 +6,105 @@ using mRemoteNG.Container;
using mRemoteNGTests.Properties;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.MiscSerializers
namespace mRemoteNGTests.Config.Serializers.MiscSerializers;
public class PuttyConnectionManagerDeserializerTests
{
public class PuttyConnectionManagerDeserializerTests
private PuttyConnectionManagerDeserializer _deserializer;
private ContainerInfo _rootImportedFolder;
private const string ExpectedRootFolderName = "test_puttyConnectionManager_database";
private const string ExpectedConnectionDisplayName = "my ssh connection";
private const string ExpectedConnectionHostname = "server1.mydomain.com";
private const string ExpectedConnectionDescription = "My Description Here";
private const int ExpectedConnectionPort = 22;
private const ProtocolType ExpectedProtocolType = ProtocolType.SSH2;
private const string ExpectedPuttySession = "MyCustomPuttySession";
private const string ExpectedConnectionUsername = "mysshusername";
private const string ExpectedConnectionPassword = "password123";
[OneTimeSetUp]
public void OnetimeSetup()
{
private PuttyConnectionManagerDeserializer _deserializer;
private ContainerInfo _rootImportedFolder;
private const string ExpectedRootFolderName = "test_puttyConnectionManager_database";
private const string ExpectedConnectionDisplayName = "my ssh connection";
private const string ExpectedConnectionHostname = "server1.mydomain.com";
private const string ExpectedConnectionDescription = "My Description Here";
private const int ExpectedConnectionPort = 22;
private const ProtocolType ExpectedProtocolType = ProtocolType.SSH2;
private const string ExpectedPuttySession = "MyCustomPuttySession";
private const string ExpectedConnectionUsername = "mysshusername";
private const string ExpectedConnectionPassword = "password123";
var fileContents = Resources.test_puttyConnectionManager_database;
_deserializer = new PuttyConnectionManagerDeserializer();
var connectionTreeModel = _deserializer.Deserialize(fileContents);
var rootNode = connectionTreeModel.RootNodes.First();
_rootImportedFolder = rootNode.Children.Cast<ContainerInfo>().First();
}
[OneTimeTearDown]
public void OnetimeTeardown()
{
_deserializer = null;
_rootImportedFolder = null;
}
[OneTimeSetUp]
public void OnetimeSetup()
{
var fileContents = Resources.test_puttyConnectionManager_database;
_deserializer = new PuttyConnectionManagerDeserializer();
var connectionTreeModel = _deserializer.Deserialize(fileContents);
var rootNode = connectionTreeModel.RootNodes.First();
_rootImportedFolder = rootNode.Children.Cast<ContainerInfo>().First();
}
[Test]
public void RootFolderImportedWithCorrectName()
{
Assert.That(_rootImportedFolder.Name, Is.EqualTo(ExpectedRootFolderName));
}
[OneTimeTearDown]
public void OnetimeTeardown()
{
_deserializer = null;
_rootImportedFolder = null;
}
[Test]
public void ConnectionDisplayNameImported()
{
var connection = GetSshConnection();
Assert.That(connection.Name, Is.EqualTo(ExpectedConnectionDisplayName));
}
[Test]
public void RootFolderImportedWithCorrectName()
{
Assert.That(_rootImportedFolder.Name, Is.EqualTo(ExpectedRootFolderName));
}
[Test]
public void ConnectionHostNameImported()
{
var connection = GetSshConnection();
Assert.That(connection.Hostname, Is.EqualTo(ExpectedConnectionHostname));
}
[Test]
public void ConnectionDisplayNameImported()
{
var connection = GetSshConnection();
Assert.That(connection.Name, Is.EqualTo(ExpectedConnectionDisplayName));
}
[Test]
public void ConnectionDescriptionImported()
{
var connection = GetSshConnection();
Assert.That(connection.Description, Is.EqualTo(ExpectedConnectionDescription));
}
[Test]
public void ConnectionHostNameImported()
{
var connection = GetSshConnection();
Assert.That(connection.Hostname, Is.EqualTo(ExpectedConnectionHostname));
}
[Test]
public void ConnectionPortImported()
{
var connection = GetSshConnection();
Assert.That(connection.Port, Is.EqualTo(ExpectedConnectionPort));
}
[Test]
public void ConnectionDescriptionImported()
{
var connection = GetSshConnection();
Assert.That(connection.Description, Is.EqualTo(ExpectedConnectionDescription));
}
[Test]
public void ConnectionProtocolTypeImported()
{
var connection = GetSshConnection();
Assert.That(connection.Protocol, Is.EqualTo(ExpectedProtocolType));
}
[Test]
public void ConnectionPortImported()
{
var connection = GetSshConnection();
Assert.That(connection.Port, Is.EqualTo(ExpectedConnectionPort));
}
[Test]
public void ConnectionPuttySessionImported()
{
var connection = GetSshConnection();
Assert.That(connection.PuttySession, Is.EqualTo(ExpectedPuttySession));
}
[Test]
public void ConnectionProtocolTypeImported()
{
var connection = GetSshConnection();
Assert.That(connection.Protocol, Is.EqualTo(ExpectedProtocolType));
}
[Test]
public void ConnectionUsernameImported()
{
var connection = GetSshConnection();
Assert.That(connection.Username, Is.EqualTo(ExpectedConnectionUsername));
}
[Test]
public void ConnectionPuttySessionImported()
{
var connection = GetSshConnection();
Assert.That(connection.PuttySession, Is.EqualTo(ExpectedPuttySession));
}
[Test]
public void ConnectionPasswordImported()
{
var connection = GetSshConnection();
Assert.That(connection.Password, Is.EqualTo(ExpectedConnectionPassword));
}
[Test]
public void ConnectionUsernameImported()
{
var connection = GetSshConnection();
Assert.That(connection.Username, Is.EqualTo(ExpectedConnectionUsername));
}
[Test]
public void ConnectionPasswordImported()
{
var connection = GetSshConnection();
Assert.That(connection.Password, Is.EqualTo(ExpectedConnectionPassword));
}
private ConnectionInfo GetSshConnection()
{
var sshFolder = _rootImportedFolder.Children.OfType<ContainerInfo>().First(node => node.Name == "SSHFolder");
return sshFolder.Children.First();
}
private ConnectionInfo GetSshConnection()
{
var sshFolder = _rootImportedFolder.Children.OfType<ContainerInfo>().First(node => node.Name == "SSHFolder");
return sshFolder.Children.First();
}
}

View File

@@ -6,186 +6,185 @@ using NUnit.Framework;
using System.Linq;
using mRemoteNG.Config.Serializers.MiscSerializers;
namespace mRemoteNGTests.Config.Serializers.MiscSerializers
namespace mRemoteNGTests.Config.Serializers.MiscSerializers;
public class RemoteDesktopConnectionDeserializerTests
{
public class RemoteDesktopConnectionDeserializerTests
// .rdp file schema: https://technet.microsoft.com/en-us/library/ff393699(v=ws.10).aspx
private RemoteDesktopConnectionDeserializer _deserializer;
private ConnectionTreeModel _connectionTreeModel;
private const string ExpectedHostname = "testhostname.domain.com";
private const string ExpectedUserName = "myusernamehere";
private const string ExpectedDomain = "myspecialdomain";
private const string ExpectedGatewayHostname = "gatewayhostname.domain.com";
private const string ExpectedLoadBalanceInfo = "tsv://MS Terminal Services Plugin.1.RDS-NAME";
private const int ExpectedPort = 9933;
private const RDPColors ExpectedColors = RDPColors.Colors24Bit;
private const bool ExpectedBitmapCaching = true;
private const RDPResolutions ExpectedResolutionMode = RDPResolutions.FitToWindow;
private const bool ExpectedWallpaperDisplay = true;
private const bool ExpectedThemesDisplay = true;
private const bool ExpectedFontSmoothing = true;
private const bool ExpectedDesktopComposition = true;
private const bool ExpectedSmartcardRedirection = true;
private const RDPDiskDrives ExpectedDriveRedirection = RDPDiskDrives.Local;
private const bool ExpectedPortRedirection = true;
private const bool ExpectedPrinterRedirection = true;
private const RDPSounds ExpectedSoundRedirection = RDPSounds.BringToThisComputer;
private const string ExpectedStartProgram = "alternate shell";
[OneTimeSetUp]
public void OnetimeSetup()
{
// .rdp file schema: https://technet.microsoft.com/en-us/library/ff393699(v=ws.10).aspx
private RemoteDesktopConnectionDeserializer _deserializer;
private ConnectionTreeModel _connectionTreeModel;
private const string ExpectedHostname = "testhostname.domain.com";
private const string ExpectedUserName = "myusernamehere";
private const string ExpectedDomain = "myspecialdomain";
private const string ExpectedGatewayHostname = "gatewayhostname.domain.com";
private const string ExpectedLoadBalanceInfo = "tsv://MS Terminal Services Plugin.1.RDS-NAME";
private const int ExpectedPort = 9933;
private const RDPColors ExpectedColors = RDPColors.Colors24Bit;
private const bool ExpectedBitmapCaching = true;
private const RDPResolutions ExpectedResolutionMode = RDPResolutions.FitToWindow;
private const bool ExpectedWallpaperDisplay = true;
private const bool ExpectedThemesDisplay = true;
private const bool ExpectedFontSmoothing = true;
private const bool ExpectedDesktopComposition = true;
private const bool ExpectedSmartcardRedirection = true;
private const RDPDiskDrives ExpectedDriveRedirection = RDPDiskDrives.Local;
private const bool ExpectedPortRedirection = true;
private const bool ExpectedPrinterRedirection = true;
private const RDPSounds ExpectedSoundRedirection = RDPSounds.BringToThisComputer;
private const string ExpectedStartProgram = "alternate shell";
[OneTimeSetUp]
public void OnetimeSetup()
{
var connectionFileContents = Resources.test_remotedesktopconnection_rdp;
_deserializer = new RemoteDesktopConnectionDeserializer();
_connectionTreeModel = _deserializer.Deserialize(connectionFileContents);
}
[Test]
public void ConnectionTreeModelHasARootNode()
{
var numberOfRootNodes = _connectionTreeModel.RootNodes.Count;
Assert.That(numberOfRootNodes, Is.GreaterThan(0));
}
[Test]
public void RootNodeHasConnectionInfo()
{
var rootNodeContents = _connectionTreeModel.RootNodes.First().Children.OfType<ConnectionInfo>();
Assert.That(rootNodeContents, Is.Not.Empty);
}
[Test]
public void HostnameImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Hostname, Is.EqualTo(ExpectedHostname));
}
[Test]
public void PortImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Port, Is.EqualTo(ExpectedPort));
}
[Test]
public void UsernameImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Username, Is.EqualTo(ExpectedUserName));
}
[Test]
public void DomainImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Domain, Is.EqualTo(ExpectedDomain));
}
[Test]
public void RdpColorsImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Colors, Is.EqualTo(ExpectedColors));
}
[Test]
public void BitmapCachingImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.CacheBitmaps, Is.EqualTo(ExpectedBitmapCaching));
}
[Test]
public void ResolutionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Resolution, Is.EqualTo(ExpectedResolutionMode));
}
[Test]
public void DisplayWallpaperImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.DisplayWallpaper, Is.EqualTo(ExpectedWallpaperDisplay));
}
[Test]
public void DisplayThemesImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.DisplayThemes, Is.EqualTo(ExpectedThemesDisplay));
}
[Test]
public void FontSmoothingImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.EnableFontSmoothing, Is.EqualTo(ExpectedFontSmoothing));
}
[Test]
public void DesktopCompositionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.EnableDesktopComposition, Is.EqualTo(ExpectedDesktopComposition));
}
[Test]
public void SmartcardRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectSmartCards, Is.EqualTo(ExpectedSmartcardRedirection));
}
[Test]
public void DriveRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectDiskDrives, Is.EqualTo(ExpectedDriveRedirection));
}
[Test]
public void PortRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectPorts, Is.EqualTo(ExpectedPortRedirection));
}
[Test]
public void PrinterRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectPrinters, Is.EqualTo(ExpectedPrinterRedirection));
}
[Test]
public void SoundRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectSound, Is.EqualTo(ExpectedSoundRedirection));
}
[Test]
public void LoadBalanceInfoImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.LoadBalanceInfo, Is.EqualTo(ExpectedLoadBalanceInfo));
}
[Test]
public void StartProgramImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RDPStartProgram, Is.EqualTo(ExpectedStartProgram));
}
//[Test]
//public void GatewayHostnameImportedCorrectly()
//{
// var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
// Assert.That(connectionInfo.RDGatewayHostname, Is.EqualTo(_expectedGatewayHostname));
//}
var connectionFileContents = Resources.test_remotedesktopconnection_rdp;
_deserializer = new RemoteDesktopConnectionDeserializer();
_connectionTreeModel = _deserializer.Deserialize(connectionFileContents);
}
[Test]
public void ConnectionTreeModelHasARootNode()
{
var numberOfRootNodes = _connectionTreeModel.RootNodes.Count;
Assert.That(numberOfRootNodes, Is.GreaterThan(0));
}
[Test]
public void RootNodeHasConnectionInfo()
{
var rootNodeContents = _connectionTreeModel.RootNodes.First().Children.OfType<ConnectionInfo>();
Assert.That(rootNodeContents, Is.Not.Empty);
}
[Test]
public void HostnameImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Hostname, Is.EqualTo(ExpectedHostname));
}
[Test]
public void PortImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Port, Is.EqualTo(ExpectedPort));
}
[Test]
public void UsernameImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Username, Is.EqualTo(ExpectedUserName));
}
[Test]
public void DomainImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Domain, Is.EqualTo(ExpectedDomain));
}
[Test]
public void RdpColorsImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Colors, Is.EqualTo(ExpectedColors));
}
[Test]
public void BitmapCachingImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.CacheBitmaps, Is.EqualTo(ExpectedBitmapCaching));
}
[Test]
public void ResolutionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.Resolution, Is.EqualTo(ExpectedResolutionMode));
}
[Test]
public void DisplayWallpaperImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.DisplayWallpaper, Is.EqualTo(ExpectedWallpaperDisplay));
}
[Test]
public void DisplayThemesImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.DisplayThemes, Is.EqualTo(ExpectedThemesDisplay));
}
[Test]
public void FontSmoothingImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.EnableFontSmoothing, Is.EqualTo(ExpectedFontSmoothing));
}
[Test]
public void DesktopCompositionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.EnableDesktopComposition, Is.EqualTo(ExpectedDesktopComposition));
}
[Test]
public void SmartcardRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectSmartCards, Is.EqualTo(ExpectedSmartcardRedirection));
}
[Test]
public void DriveRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectDiskDrives, Is.EqualTo(ExpectedDriveRedirection));
}
[Test]
public void PortRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectPorts, Is.EqualTo(ExpectedPortRedirection));
}
[Test]
public void PrinterRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectPrinters, Is.EqualTo(ExpectedPrinterRedirection));
}
[Test]
public void SoundRedirectionImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RedirectSound, Is.EqualTo(ExpectedSoundRedirection));
}
[Test]
public void LoadBalanceInfoImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.LoadBalanceInfo, Is.EqualTo(ExpectedLoadBalanceInfo));
}
[Test]
public void StartProgramImportedCorrectly()
{
var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
Assert.That(connectionInfo.RDPStartProgram, Is.EqualTo(ExpectedStartProgram));
}
//[Test]
//public void GatewayHostnameImportedCorrectly()
//{
// var connectionInfo = _connectionTreeModel.RootNodes.First().Children.First();
// Assert.That(connectionInfo.RDGatewayHostname, Is.EqualTo(_expectedGatewayHostname));
//}
}

View File

@@ -10,196 +10,241 @@ using mRemoteNG.Container;
using mRemoteNGTests.Properties;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.MiscSerializers
namespace mRemoteNGTests.Config.Serializers.MiscSerializers;
public class RemoteDesktopConnectionManager27DeserializerTests
{
public class RemoteDesktopConnectionManager27DeserializerTests
private string _connectionFileContents;
private RemoteDesktopConnectionManagerDeserializer _deserializer;
private const string ExpectedName = "server1_displayname";
private const string ExpectedHostname = "server1";
private const string ExpectedDescription = "Comment text here";
private const string ExpectedUserViaAPI = "123";
private const string ExpectedUsername = "myusername1";
private const string ExpectedDomain = "mydomain";
private const string ExpectedPassword = "passwordHere!";
private const bool ExpectedUseConsoleSession = true;
private const int ExpectedPort = 9933;
private const RDGatewayUsageMethod ExpectedGatewayUsageMethod = RDGatewayUsageMethod.Always;
private const string ExpectedGatewayHostname = "gatewayserverhost.innerdomain.net";
private const string ExpectedGatewayUsername = "gatewayusername";
private const string ExpectedGatewayDomain = "innerdomain";
private const string ExpectedGatewayPassword = "gatewayPassword123";
private const RDPResolutions ExpectedRdpResolution = RDPResolutions.FitToWindow;
private const RDPColors ExpectedRdpColorDepth = RDPColors.Colors24Bit;
private const RDPSounds ExpectedAudioRedirection = RDPSounds.DoNotPlay;
private const bool ExpectedKeyRedirection = true;
private const bool ExpectedSmartcardRedirection = true;
private const RDPDiskDrives ExpectedDriveRedirection = RDPDiskDrives.Local;
private const bool ExpectedPortRedirection = true;
private const bool ExpectedPrinterRedirection = true;
private const AuthenticationLevel ExpectedAuthLevel = AuthenticationLevel.WarnOnFailedAuth;
private const string ExpectedStartProgram = "alternate shell";
[OneTimeSetUp]
public void OnetimeSetup()
{
private string _connectionFileContents;
private RemoteDesktopConnectionManagerDeserializer _deserializer;
private const string ExpectedName = "server1_displayname";
private const string ExpectedHostname = "server1";
private const string ExpectedDescription = "Comment text here";
private const string ExpectedUserViaAPI = "123";
private const string ExpectedUsername = "myusername1";
private const string ExpectedDomain = "mydomain";
private const string ExpectedPassword = "passwordHere!";
private const bool ExpectedUseConsoleSession = true;
private const int ExpectedPort = 9933;
private const RDGatewayUsageMethod ExpectedGatewayUsageMethod = RDGatewayUsageMethod.Always;
private const string ExpectedGatewayHostname = "gatewayserverhost.innerdomain.net";
private const string ExpectedGatewayUsername = "gatewayusername";
private const string ExpectedGatewayDomain = "innerdomain";
private const string ExpectedGatewayPassword = "gatewayPassword123";
private const RDPResolutions ExpectedRdpResolution = RDPResolutions.FitToWindow;
private const RDPColors ExpectedRdpColorDepth = RDPColors.Colors24Bit;
private const RDPSounds ExpectedAudioRedirection = RDPSounds.DoNotPlay;
private const bool ExpectedKeyRedirection = true;
private const bool ExpectedSmartcardRedirection = true;
private const RDPDiskDrives ExpectedDriveRedirection = RDPDiskDrives.Local;
private const bool ExpectedPortRedirection = true;
private const bool ExpectedPrinterRedirection = true;
private const AuthenticationLevel ExpectedAuthLevel = AuthenticationLevel.WarnOnFailedAuth;
private const string ExpectedStartProgram = "alternate shell";
_connectionFileContents = Resources.test_rdcman_v2_7_schema3;
_deserializer = new RemoteDesktopConnectionManagerDeserializer();
}
[OneTimeSetUp]
public void OnetimeSetup()
[Test]
public void ConnectionTreeModelHasARootNode()
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var numberOfRootNodes = connectionTreeModel.RootNodes.Count;
Assert.That(numberOfRootNodes, Is.GreaterThan(0));
}
[Test]
public void RootNodeHasContents()
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var rootNodeContents = connectionTreeModel.RootNodes.First().Children;
Assert.That(rootNodeContents, Is.Not.Empty);
}
[Test]
public void AllSubRootFoldersImported()
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var rootNode = connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var rootNodeContents =
importedRdcmanRootNode.Children.Count(node => node.Name == "Group1" || node.Name == "Group2");
Assert.That(rootNodeContents, Is.EqualTo(2));
}
[TestCaseSource(nameof(ExpectedPropertyValues))]
public void PropertiesWithValuesAreCorrectlyImported(Func<ConnectionInfo, object> propSelector,
object expectedValue)
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var connection = connectionTreeModel
.GetRecursiveChildList()
.OfType<ContainerInfo>()
.First(node => node.Name == "Group1")
.Children
.First();
Assert.That(propSelector(connection), Is.EqualTo(expectedValue));
}
[TestCaseSource(nameof(NullPropertyValues))]
public void PropertiesWithoutValuesAreIgnored(Func<ConnectionInfo, object> propSelector)
{
var connectionTreeModel = _deserializer.Deserialize(Resources.test_rdcman_v2_7_schema3_empty_values);
var importedConnection = connectionTreeModel
.GetRecursiveChildList()
.OfType<ContainerInfo>()
.First(node => node.Name == "Group1")
.Children
.First();
Assert.That(propSelector(importedConnection), Is.EqualTo(propSelector(new ConnectionInfo())));
}
[TestCaseSource(nameof(NullPropertyValues))]
public void NonExistantPropertiesAreIgnored(Func<ConnectionInfo, object> propSelector)
{
var connectionTreeModel = _deserializer.Deserialize(Resources.test_rdcman_v2_7_schema3_null_values);
var importedConnection = connectionTreeModel
.GetRecursiveChildList()
.OfType<ContainerInfo>()
.First(node => node.Name == "Group1")
.Children
.First();
Assert.That(propSelector(importedConnection), Is.EqualTo(propSelector(new ConnectionInfo())));
}
[Test]
public void ExceptionThrownOnBadSchemaVersion()
{
var badFileContents = Resources.test_rdcman_v2_2_badschemaversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnUnsupportedVersion()
{
var badFileContents = Resources.test_rdcman_badVersionNumber;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnNoVersion()
{
var badFileContents = Resources.test_rdcman_noversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
private static IEnumerable<TestCaseData> ExpectedPropertyValues()
{
return new[]
{
_connectionFileContents = Resources.test_rdcman_v2_7_schema3;
_deserializer = new RemoteDesktopConnectionManagerDeserializer();
}
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Name), ExpectedName).SetName(
nameof(ConnectionInfo.Name)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Hostname), ExpectedHostname).SetName(
nameof(ConnectionInfo.Hostname)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Description), ExpectedDescription).SetName(
nameof(ConnectionInfo.Description)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Username), ExpectedUsername).SetName(
nameof(ConnectionInfo.Username)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Domain), ExpectedDomain).SetName(
nameof(ConnectionInfo.Domain)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Protocol), ProtocolType.RDP).SetName(
nameof(ConnectionInfo.Protocol)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.UseConsoleSession), ExpectedUseConsoleSession)
.SetName(nameof(ConnectionInfo.UseConsoleSession)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Port), ExpectedPort).SetName(
nameof(ConnectionInfo.Port)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayUsageMethod),
ExpectedGatewayUsageMethod).SetName(nameof(ConnectionInfo.RDGatewayUsageMethod)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayHostname), ExpectedGatewayHostname)
.SetName(nameof(ConnectionInfo.RDGatewayHostname)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayUsername), ExpectedGatewayUsername)
.SetName(nameof(ConnectionInfo.RDGatewayUsername)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayDomain), ExpectedGatewayDomain).SetName(
nameof(ConnectionInfo.RDGatewayDomain)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Resolution), ExpectedRdpResolution).SetName(
nameof(ConnectionInfo.Resolution)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Colors), ExpectedRdpColorDepth).SetName(
nameof(ConnectionInfo.Colors)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectSound), ExpectedAudioRedirection)
.SetName(nameof(ConnectionInfo.RedirectSound)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectKeys), ExpectedKeyRedirection).SetName(
nameof(ConnectionInfo.RedirectKeys)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDPAuthenticationLevel), ExpectedAuthLevel)
.SetName(nameof(ConnectionInfo.RDPAuthenticationLevel)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectSmartCards),
ExpectedSmartcardRedirection).SetName(nameof(ConnectionInfo.RedirectSmartCards)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectPrinters), ExpectedPrinterRedirection)
.SetName(nameof(ConnectionInfo.RedirectPrinters)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectPorts), ExpectedPortRedirection).SetName(
nameof(ConnectionInfo.RedirectPorts)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectDiskDrives), ExpectedDriveRedirection)
.SetName(nameof(ConnectionInfo.RedirectDiskDrives)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDPStartProgram), ExpectedStartProgram).SetName(
nameof(ConnectionInfo.RDPStartProgram))
};
}
[Test]
public void ConnectionTreeModelHasARootNode()
private static IEnumerable<TestCaseData> NullPropertyValues()
{
return new[]
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var numberOfRootNodes = connectionTreeModel.RootNodes.Count;
Assert.That(numberOfRootNodes, Is.GreaterThan(0));
}
[Test]
public void RootNodeHasContents()
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var rootNodeContents = connectionTreeModel.RootNodes.First().Children;
Assert.That(rootNodeContents, Is.Not.Empty);
}
[Test]
public void AllSubRootFoldersImported()
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var rootNode = connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var rootNodeContents = importedRdcmanRootNode.Children.Count(node => node.Name == "Group1" || node.Name == "Group2");
Assert.That(rootNodeContents, Is.EqualTo(2));
}
[TestCaseSource(nameof(ExpectedPropertyValues))]
public void PropertiesWithValuesAreCorrectlyImported(Func<ConnectionInfo, object> propSelector, object expectedValue)
{
var connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
var connection = connectionTreeModel
.GetRecursiveChildList()
.OfType<ContainerInfo>()
.First(node => node.Name == "Group1")
.Children
.First();
Assert.That(propSelector(connection), Is.EqualTo(expectedValue));
}
[TestCaseSource(nameof(NullPropertyValues))]
public void PropertiesWithoutValuesAreIgnored(Func<ConnectionInfo, object> propSelector)
{
var connectionTreeModel = _deserializer.Deserialize(Resources.test_rdcman_v2_7_schema3_empty_values);
var importedConnection = connectionTreeModel
.GetRecursiveChildList()
.OfType<ContainerInfo>()
.First(node => node.Name == "Group1")
.Children
.First();
Assert.That(propSelector(importedConnection), Is.EqualTo(propSelector(new ConnectionInfo())));
}
[TestCaseSource(nameof(NullPropertyValues))]
public void NonExistantPropertiesAreIgnored(Func<ConnectionInfo, object> propSelector)
{
var connectionTreeModel = _deserializer.Deserialize(Resources.test_rdcman_v2_7_schema3_null_values);
var importedConnection = connectionTreeModel
.GetRecursiveChildList()
.OfType<ContainerInfo>()
.First(node => node.Name == "Group1")
.Children
.First();
Assert.That(propSelector(importedConnection), Is.EqualTo(propSelector(new ConnectionInfo())));
}
[Test]
public void ExceptionThrownOnBadSchemaVersion()
{
var badFileContents = Resources.test_rdcman_v2_2_badschemaversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnUnsupportedVersion()
{
var badFileContents = Resources.test_rdcman_badVersionNumber;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnNoVersion()
{
var badFileContents = Resources.test_rdcman_noversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
private static IEnumerable<TestCaseData> ExpectedPropertyValues()
{
return new[]
{
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Name), ExpectedName).SetName(nameof(ConnectionInfo.Name)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Hostname), ExpectedHostname).SetName(nameof(ConnectionInfo.Hostname)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Description), ExpectedDescription).SetName(nameof(ConnectionInfo.Description)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Username), ExpectedUsername).SetName(nameof(ConnectionInfo.Username)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Domain), ExpectedDomain).SetName(nameof(ConnectionInfo.Domain)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Protocol), ProtocolType.RDP).SetName(nameof(ConnectionInfo.Protocol)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.UseConsoleSession), ExpectedUseConsoleSession).SetName(nameof(ConnectionInfo.UseConsoleSession)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Port), ExpectedPort).SetName(nameof(ConnectionInfo.Port)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayUsageMethod), ExpectedGatewayUsageMethod).SetName(nameof(ConnectionInfo.RDGatewayUsageMethod)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayHostname), ExpectedGatewayHostname).SetName(nameof(ConnectionInfo.RDGatewayHostname)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayUsername), ExpectedGatewayUsername).SetName(nameof(ConnectionInfo.RDGatewayUsername)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayDomain), ExpectedGatewayDomain).SetName(nameof(ConnectionInfo.RDGatewayDomain)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Resolution), ExpectedRdpResolution).SetName(nameof(ConnectionInfo.Resolution)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Colors), ExpectedRdpColorDepth).SetName(nameof(ConnectionInfo.Colors)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectSound), ExpectedAudioRedirection).SetName(nameof(ConnectionInfo.RedirectSound)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectKeys), ExpectedKeyRedirection).SetName(nameof(ConnectionInfo.RedirectKeys)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDPAuthenticationLevel), ExpectedAuthLevel).SetName(nameof(ConnectionInfo.RDPAuthenticationLevel)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectSmartCards), ExpectedSmartcardRedirection).SetName(nameof(ConnectionInfo.RedirectSmartCards)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectPrinters), ExpectedPrinterRedirection).SetName(nameof(ConnectionInfo.RedirectPrinters)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectPorts), ExpectedPortRedirection).SetName(nameof(ConnectionInfo.RedirectPorts)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectDiskDrives), ExpectedDriveRedirection).SetName(nameof(ConnectionInfo.RedirectDiskDrives)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDPStartProgram), ExpectedStartProgram).SetName(nameof(ConnectionInfo.RDPStartProgram)),
};
}
private static IEnumerable<TestCaseData> NullPropertyValues()
{
return new[]
{
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Name)).SetName(nameof(ConnectionInfo.Name)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.ExternalAddressProvider)).SetName(nameof(ConnectionInfo.ExternalAddressProvider)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.ExternalCredentialProvider)).SetName(nameof(ConnectionInfo.ExternalCredentialProvider)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.UserViaAPI)).SetName(nameof(ConnectionInfo.UserViaAPI)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Hostname)).SetName(nameof(ConnectionInfo.Hostname)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Description)).SetName(nameof(ConnectionInfo.Description)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Username)).SetName(nameof(ConnectionInfo.Username)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Domain)).SetName(nameof(ConnectionInfo.Domain)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Protocol)).SetName(nameof(ConnectionInfo.Protocol)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.UseConsoleSession)).SetName(nameof(ConnectionInfo.UseConsoleSession)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Port)).SetName(nameof(ConnectionInfo.Port)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayUsageMethod)).SetName(nameof(ConnectionInfo.RDGatewayUsageMethod)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayHostname)).SetName(nameof(ConnectionInfo.RDGatewayHostname)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayUsername)).SetName(nameof(ConnectionInfo.RDGatewayUsername)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayDomain)).SetName(nameof(ConnectionInfo.RDGatewayDomain)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayExternalCredentialProvider)).SetName(nameof(ConnectionInfo.RDGatewayExternalCredentialProvider)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDGatewayUserViaAPI)).SetName(nameof(ConnectionInfo.RDGatewayUserViaAPI)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Resolution)).SetName(nameof(ConnectionInfo.Resolution)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.Colors)).SetName(nameof(ConnectionInfo.Colors)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectSound)).SetName(nameof(ConnectionInfo.RedirectSound)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectKeys)).SetName(nameof(ConnectionInfo.RedirectKeys)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RDPAuthenticationLevel)).SetName(nameof(ConnectionInfo.RDPAuthenticationLevel)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectSmartCards)).SetName(nameof(ConnectionInfo.RedirectSmartCards)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectPrinters)).SetName(nameof(ConnectionInfo.RedirectPrinters)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectPorts)).SetName(nameof(ConnectionInfo.RedirectPorts)),
new TestCaseData((Func<ConnectionInfo,object>)(con => con.RedirectDiskDrives)).SetName(nameof(ConnectionInfo.RedirectDiskDrives)),
};
}
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Name)).SetName(nameof(ConnectionInfo.Name)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.ExternalAddressProvider)).SetName(
nameof(ConnectionInfo.ExternalAddressProvider)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.ExternalCredentialProvider)).SetName(
nameof(ConnectionInfo.ExternalCredentialProvider)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.UserViaAPI)).SetName(
nameof(ConnectionInfo.UserViaAPI)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Hostname)).SetName(
nameof(ConnectionInfo.Hostname)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Description)).SetName(
nameof(ConnectionInfo.Description)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Username)).SetName(
nameof(ConnectionInfo.Username)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Domain)).SetName(nameof(ConnectionInfo.Domain)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Protocol)).SetName(
nameof(ConnectionInfo.Protocol)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.UseConsoleSession)).SetName(
nameof(ConnectionInfo.UseConsoleSession)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Port)).SetName(nameof(ConnectionInfo.Port)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayUsageMethod)).SetName(
nameof(ConnectionInfo.RDGatewayUsageMethod)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayHostname)).SetName(
nameof(ConnectionInfo.RDGatewayHostname)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayUsername)).SetName(
nameof(ConnectionInfo.RDGatewayUsername)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayDomain)).SetName(
nameof(ConnectionInfo.RDGatewayDomain)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayExternalCredentialProvider)).SetName(
nameof(ConnectionInfo.RDGatewayExternalCredentialProvider)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDGatewayUserViaAPI)).SetName(
nameof(ConnectionInfo.RDGatewayUserViaAPI)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Resolution)).SetName(
nameof(ConnectionInfo.Resolution)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.Colors)).SetName(nameof(ConnectionInfo.Colors)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectSound)).SetName(
nameof(ConnectionInfo.RedirectSound)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectKeys)).SetName(
nameof(ConnectionInfo.RedirectKeys)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RDPAuthenticationLevel)).SetName(
nameof(ConnectionInfo.RDPAuthenticationLevel)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectSmartCards)).SetName(
nameof(ConnectionInfo.RedirectSmartCards)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectPrinters)).SetName(
nameof(ConnectionInfo.RedirectPrinters)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectPorts)).SetName(
nameof(ConnectionInfo.RedirectPorts)),
new TestCaseData((Func<ConnectionInfo, object>)(con => con.RedirectDiskDrives)).SetName(
nameof(ConnectionInfo.RedirectDiskDrives))
};
}
}

View File

@@ -8,329 +8,329 @@ using mRemoteNG.Tree;
using mRemoteNGTests.Properties;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.MiscSerializers
namespace mRemoteNGTests.Config.Serializers.MiscSerializers;
public class RemoteDesktopConnectionManagerDeserializerTests
{
public class RemoteDesktopConnectionManagerDeserializerTests
private string _connectionFileContents;
private RemoteDesktopConnectionManagerDeserializer _deserializer;
private ConnectionTreeModel _connectionTreeModel;
private const string ExpectedName = "server1_displayname";
private const string ExpectedHostname = "server1";
private const string ExpectedDescription = "Comment text here";
private const string ExpectedUsername = "myusername1";
private const string ExpectedDomain = "mydomain";
private const string ExpectedPassword = "passwordHere!";
private const bool ExpectedUseConsoleSession = true;
private const int ExpectedPort = 9933;
private const RDGatewayUsageMethod ExpectedGatewayUsageMethod = RDGatewayUsageMethod.Always;
private const string ExpectedGatewayHostname = "gatewayserverhost.innerdomain.net";
private const string ExpectedGatewayUsername = "gatewayusername";
private const string ExpectedGatewayDomain = "innerdomain";
private const string ExpectedGatewayPassword = "gatewayPassword123";
private const RDPResolutions ExpectedRdpResolution = RDPResolutions.FitToWindow;
private const RDPColors ExpectedRdpColorDepth = RDPColors.Colors24Bit;
private const RDPSounds ExpectedAudioRedirection = RDPSounds.DoNotPlay;
private const bool ExpectedKeyRedirection = true;
private const bool ExpectedSmartcardRedirection = true;
private const RDPDiskDrives ExpectedDriveRedirection = RDPDiskDrives.Local;
private const bool ExpectedPortRedirection = true;
private const bool ExpectedPrinterRedirection = true;
private const AuthenticationLevel ExpectedAuthLevel = AuthenticationLevel.AuthRequired;
private const string ExpectedStartProgram = "alternate shell";
[OneTimeSetUp]
public void OnetimeSetup()
{
private string _connectionFileContents;
private RemoteDesktopConnectionManagerDeserializer _deserializer;
private ConnectionTreeModel _connectionTreeModel;
private const string ExpectedName = "server1_displayname";
private const string ExpectedHostname = "server1";
private const string ExpectedDescription = "Comment text here";
private const string ExpectedUsername = "myusername1";
private const string ExpectedDomain = "mydomain";
private const string ExpectedPassword = "passwordHere!";
private const bool ExpectedUseConsoleSession = true;
private const int ExpectedPort = 9933;
private const RDGatewayUsageMethod ExpectedGatewayUsageMethod = RDGatewayUsageMethod.Always;
private const string ExpectedGatewayHostname = "gatewayserverhost.innerdomain.net";
private const string ExpectedGatewayUsername = "gatewayusername";
private const string ExpectedGatewayDomain = "innerdomain";
private const string ExpectedGatewayPassword = "gatewayPassword123";
private const RDPResolutions ExpectedRdpResolution = RDPResolutions.FitToWindow;
private const RDPColors ExpectedRdpColorDepth = RDPColors.Colors24Bit;
private const RDPSounds ExpectedAudioRedirection = RDPSounds.DoNotPlay;
private const bool ExpectedKeyRedirection = true;
private const bool ExpectedSmartcardRedirection = true;
private const RDPDiskDrives ExpectedDriveRedirection = RDPDiskDrives.Local;
private const bool ExpectedPortRedirection = true;
private const bool ExpectedPrinterRedirection = true;
private const AuthenticationLevel ExpectedAuthLevel = AuthenticationLevel.AuthRequired;
private const string ExpectedStartProgram = "alternate shell";
_connectionFileContents = Resources.test_rdcman_v2_2_schema1;
_deserializer = new RemoteDesktopConnectionManagerDeserializer();
_connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
}
[OneTimeSetUp]
public void OnetimeSetup()
{
_connectionFileContents = Resources.test_rdcman_v2_2_schema1;
_deserializer = new RemoteDesktopConnectionManagerDeserializer();
_connectionTreeModel = _deserializer.Deserialize(_connectionFileContents);
}
[Test]
public void ConnectionTreeModelHasARootNode()
{
var numberOfRootNodes = _connectionTreeModel.RootNodes.Count;
Assert.That(numberOfRootNodes, Is.GreaterThan(0));
}
[Test]
public void ConnectionTreeModelHasARootNode()
{
var numberOfRootNodes = _connectionTreeModel.RootNodes.Count;
Assert.That(numberOfRootNodes, Is.GreaterThan(0));
}
[Test]
public void RootNodeHasContents()
{
var rootNodeContents = _connectionTreeModel.RootNodes.First().Children;
Assert.That(rootNodeContents, Is.Not.Empty);
}
[Test]
public void RootNodeHasContents()
{
var rootNodeContents = _connectionTreeModel.RootNodes.First().Children;
Assert.That(rootNodeContents, Is.Not.Empty);
}
[Test]
public void AllSubRootFoldersImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var rootNodeContents =
importedRdcmanRootNode.Children.Count(node => node.Name == "Group1" || node.Name == "Group2");
Assert.That(rootNodeContents, Is.EqualTo(2));
}
[Test]
public void AllSubRootFoldersImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var rootNodeContents = importedRdcmanRootNode.Children.Count(node => node.Name == "Group1" || node.Name == "Group2");
Assert.That(rootNodeContents, Is.EqualTo(2));
}
[Test]
public void ConnectionDisplayNameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Name, Is.EqualTo(ExpectedName));
}
[Test]
public void ConnectionDisplayNameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Name, Is.EqualTo(ExpectedName));
}
[Test]
public void ConnectionHostnameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Hostname, Is.EqualTo(ExpectedHostname));
}
[Test]
public void ConnectionHostnameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Hostname, Is.EqualTo(ExpectedHostname));
}
[Test]
public void ConnectionDescriptionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Description, Is.EqualTo(ExpectedDescription));
}
[Test]
public void ConnectionDescriptionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Description, Is.EqualTo(ExpectedDescription));
}
[Test]
public void ConnectionUsernameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Username, Is.EqualTo(ExpectedUsername));
}
[Test]
public void ConnectionUsernameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Username, Is.EqualTo(ExpectedUsername));
}
[Test]
public void ConnectionDomainImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Domain, Is.EqualTo(ExpectedDomain));
}
[Test]
public void ConnectionDomainImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Domain, Is.EqualTo(ExpectedDomain));
}
// Since password is encrypted with a machine key, cant test decryption on another machine
//[Test]
//public void ConnectionPasswordImported()
//{
// var rootNode = _connectionTreeModel.RootNodes.First();
// var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
// var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
// var connection = group1.Children.First();
// Assert.That(connection.Password, Is.EqualTo(ExpectedPassword));
//}
// Since password is encrypted with a machine key, cant test decryption on another machine
//[Test]
//public void ConnectionPasswordImported()
//{
// var rootNode = _connectionTreeModel.RootNodes.First();
// var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
// var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
// var connection = group1.Children.First();
// Assert.That(connection.Password, Is.EqualTo(ExpectedPassword));
//}
[Test]
public void ConnectionProtocolSetToRdp()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Protocol, Is.EqualTo(ProtocolType.RDP));
}
[Test]
public void ConnectionProtocolSetToRdp()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Protocol, Is.EqualTo(ProtocolType.RDP));
}
[Test]
public void ConnectionUseConsoleSessionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.UseConsoleSession, Is.EqualTo(ExpectedUseConsoleSession));
}
[Test]
public void ConnectionUseConsoleSessionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.UseConsoleSession, Is.EqualTo(ExpectedUseConsoleSession));
}
[Test]
public void ConnectionPortImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Port, Is.EqualTo(ExpectedPort));
}
[Test]
public void ConnectionPortImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Port, Is.EqualTo(ExpectedPort));
}
[Test]
public void ConnectionGatewayUsageMethodImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayUsageMethod, Is.EqualTo(ExpectedGatewayUsageMethod));
}
[Test]
public void ConnectionGatewayUsageMethodImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayUsageMethod, Is.EqualTo(ExpectedGatewayUsageMethod));
}
[Test]
public void ConnectionGatewayHostnameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayHostname, Is.EqualTo(ExpectedGatewayHostname));
}
[Test]
public void ConnectionGatewayHostnameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayHostname, Is.EqualTo(ExpectedGatewayHostname));
}
[Test]
public void ConnectionGatewayUsernameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayUsername, Is.EqualTo(ExpectedGatewayUsername));
}
[Test]
public void ConnectionGatewayUsernameImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayUsername, Is.EqualTo(ExpectedGatewayUsername));
}
// Since password is encrypted with a machine key, cant test decryption on another machine
//[Test]
//public void ConnectionGatewayPasswordImported()
//{
// var rootNode = _connectionTreeModel.RootNodes.First();
// var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
// var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
// var connection = group1.Children.First();
// Assert.That(connection.RDGatewayPassword, Is.EqualTo(ExpectedGatewayPassword));
//}
// Since password is encrypted with a machine key, cant test decryption on another machine
//[Test]
//public void ConnectionGatewayPasswordImported()
//{
// var rootNode = _connectionTreeModel.RootNodes.First();
// var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
// var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
// var connection = group1.Children.First();
// Assert.That(connection.RDGatewayPassword, Is.EqualTo(ExpectedGatewayPassword));
//}
[Test]
public void ConnectionGatewayDomainImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayDomain, Is.EqualTo(ExpectedGatewayDomain));
}
[Test]
public void ConnectionGatewayDomainImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDGatewayDomain, Is.EqualTo(ExpectedGatewayDomain));
}
[Test]
public void ConnectionResolutionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Resolution, Is.EqualTo(ExpectedRdpResolution));
}
[Test]
public void ConnectionResolutionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Resolution, Is.EqualTo(ExpectedRdpResolution));
}
[Test]
public void ConnectionColorDepthImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Colors, Is.EqualTo(ExpectedRdpColorDepth));
}
[Test]
public void ConnectionColorDepthImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.Colors, Is.EqualTo(ExpectedRdpColorDepth));
}
[Test]
public void ConnectionAudioRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectSound, Is.EqualTo(ExpectedAudioRedirection));
}
[Test]
public void ConnectionAudioRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectSound, Is.EqualTo(ExpectedAudioRedirection));
}
[Test]
public void ConnectionKeyRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectKeys, Is.EqualTo(ExpectedKeyRedirection));
}
[Test]
public void ConnectionKeyRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectKeys, Is.EqualTo(ExpectedKeyRedirection));
}
[Test]
public void ConnectionDriveRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectDiskDrives, Is.EqualTo(ExpectedDriveRedirection));
}
[Test]
public void ConnectionDriveRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectDiskDrives, Is.EqualTo(ExpectedDriveRedirection));
}
[Test]
public void ConnectionPortRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectPorts, Is.EqualTo(ExpectedPortRedirection));
}
[Test]
public void ConnectionPortRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectPorts, Is.EqualTo(ExpectedPortRedirection));
}
[Test]
public void ConnectionPrinterRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectPrinters, Is.EqualTo(ExpectedPrinterRedirection));
}
[Test]
public void ConnectionPrinterRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectPrinters, Is.EqualTo(ExpectedPrinterRedirection));
}
[Test]
public void ConnectionSmartcardRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectSmartCards, Is.EqualTo(ExpectedSmartcardRedirection));
}
[Test]
public void ConnectionSmartcardRedirectionImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RedirectSmartCards, Is.EqualTo(ExpectedSmartcardRedirection));
}
[Test]
public void ConnectionauthenticationLevelImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDPAuthenticationLevel, Is.EqualTo(ExpectedAuthLevel));
}
[Test]
public void ConnectionauthenticationLevelImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDPAuthenticationLevel, Is.EqualTo(ExpectedAuthLevel));
}
[Test]
public void ExceptionThrownOnBadSchemaVersion()
{
var badFileContents = Resources.test_rdcman_v2_2_badschemaversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnBadSchemaVersion()
{
var badFileContents = Resources.test_rdcman_v2_2_badschemaversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnUnsupportedVersion()
{
var badFileContents = Resources.test_rdcman_badVersionNumber;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnUnsupportedVersion()
{
var badFileContents = Resources.test_rdcman_badVersionNumber;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnNoVersion()
{
var badFileContents = Resources.test_rdcman_noversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void ExceptionThrownOnNoVersion()
{
var badFileContents = Resources.test_rdcman_noversion;
Assert.That(() => _deserializer.Deserialize(badFileContents), Throws.TypeOf<FileFormatException>());
}
[Test]
public void StartProgramImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDPStartProgram, Is.EqualTo(ExpectedStartProgram));
}
[Test]
public void StartProgramImported()
{
var rootNode = _connectionTreeModel.RootNodes.First();
var importedRdcmanRootNode = rootNode.Children.OfType<ContainerInfo>().First();
var group1 = importedRdcmanRootNode.Children.OfType<ContainerInfo>().First(node => node.Name == "Group1");
var connection = group1.Children.First();
Assert.That(connection.RDPStartProgram, Is.EqualTo(ExpectedStartProgram));
}
}

View File

@@ -4,25 +4,24 @@ using mRemoteNG.Config.Serializers.Versioning;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.Versioning
namespace mRemoteNGTests.Config.Serializers.Versioning;
public class SqlVersion22To23UpgraderTests
{
public class SqlVersion22To23UpgraderTests
private SqlVersion22To23Upgrader _versionUpgrader;
[SetUp]
public void Setup()
{
private SqlVersion22To23Upgrader _versionUpgrader;
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion22To23Upgrader(sqlConnector);
}
[SetUp]
public void Setup()
{
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion22To23Upgrader(sqlConnector);
}
[Test]
public void CanUpgradeIfVersionIs22()
{
var currentVersion = new Version(2, 2);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
[Test]
public void CanUpgradeIfVersionIs22()
{
var currentVersion = new Version(2, 2);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
}

View File

@@ -4,25 +4,24 @@ using mRemoteNG.Config.Serializers.Versioning;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.Versioning
namespace mRemoteNGTests.Config.Serializers.Versioning;
public class SqlVersion23To24UpgraderTests
{
public class SqlVersion23To24UpgraderTests
private SqlVersion23To24Upgrader _versionUpgrader;
[SetUp]
public void Setup()
{
private SqlVersion23To24Upgrader _versionUpgrader;
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion23To24Upgrader(sqlConnector);
}
[SetUp]
public void Setup()
{
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion23To24Upgrader(sqlConnector);
}
[Test]
public void CanUpgradeIfVersionIs23()
{
var currentVersion = new Version(2, 3);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
[Test]
public void CanUpgradeIfVersionIs23()
{
var currentVersion = new Version(2, 3);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
}

View File

@@ -4,25 +4,24 @@ using mRemoteNG.Config.Serializers.Versioning;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.Versioning
namespace mRemoteNGTests.Config.Serializers.Versioning;
public class SqlVersion24To25UpgraderTests
{
public class SqlVersion24To25UpgraderTests
private SqlVersion24To25Upgrader _versionUpgrader;
[SetUp]
public void Setup()
{
private SqlVersion24To25Upgrader _versionUpgrader;
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion24To25Upgrader(sqlConnector);
}
[SetUp]
public void Setup()
{
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion24To25Upgrader(sqlConnector);
}
[Test]
public void CanUpgradeIfVersionIs24()
{
var currentVersion = new Version(2, 4);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
[Test]
public void CanUpgradeIfVersionIs24()
{
var currentVersion = new Version(2, 4);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
}

View File

@@ -4,25 +4,24 @@ using mRemoteNG.Config.Serializers.Versioning;
using NSubstitute;
using NUnit.Framework;
namespace mRemoteNGTests.Config.Serializers.Versioning
namespace mRemoteNGTests.Config.Serializers.Versioning;
public class SqlVersion25To26UpgraderTests
{
public class SqlVersion25To26UpgraderTests
private SqlVersion25To26Upgrader _versionUpgrader;
[SetUp]
public void Setup()
{
private SqlVersion25To26Upgrader _versionUpgrader;
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion25To26Upgrader(sqlConnector);
}
[SetUp]
public void Setup()
{
var sqlConnector = Substitute.For<MSSqlDatabaseConnector>("", "", "", "");
_versionUpgrader = new SqlVersion25To26Upgrader(sqlConnector);
}
[Test]
public void CanUpgradeIfVersionIs25()
{
var currentVersion = new Version(2, 5);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
[Test]
public void CanUpgradeIfVersionIs25()
{
var currentVersion = new Version(2, 5);
var canUpgrade = _versionUpgrader.CanUpgrade(currentVersion);
Assert.That(canUpgrade, Is.True);
}
}

View File

@@ -4,32 +4,31 @@ using mRemoteNG.Config.Settings;
using NUnit.Framework;
using WeifenLuo.WinFormsUI.Docking;
namespace mRemoteNGTests.Config.Settings
namespace mRemoteNGTests.Config.Settings;
public class DockPanelSerializerTests
{
public class DockPanelSerializerTests
private DockPanelLayoutSerializer _dockPanelLayoutSerializer;
private DockPanel _dockPanel;
[SetUp]
public void Setup()
{
private DockPanelLayoutSerializer _dockPanelLayoutSerializer;
private DockPanel _dockPanel;
_dockPanelLayoutSerializer = new DockPanelLayoutSerializer();
_dockPanel = new DockPanel();
}
[SetUp]
public void Setup()
{
_dockPanelLayoutSerializer = new DockPanelLayoutSerializer();
_dockPanel = new DockPanel();
}
[Test]
public void SerializerProducesValidDockPanelXml()
{
var serializedData = _dockPanelLayoutSerializer.Serialize(_dockPanel);
var serializedDataAsXDoc = XDocument.Parse(serializedData);
Assert.That(serializedDataAsXDoc.Root?.Name.ToString(), Is.EqualTo("DockPanel"));
}
[Test]
public void SerializerProducesValidDockPanelXml()
{
var serializedData = _dockPanelLayoutSerializer.Serialize(_dockPanel);
var serializedDataAsXDoc = XDocument.Parse(serializedData);
Assert.That(serializedDataAsXDoc.Root?.Name.ToString(), Is.EqualTo("DockPanel"));
}
[Test]
public void CantProvideNullDockPanel()
{
Assert.Throws<ArgumentNullException>(() => _dockPanelLayoutSerializer.Serialize(null));
}
[Test]
public void CantProvideNullDockPanel()
{
Assert.Throws<ArgumentNullException>(() => _dockPanelLayoutSerializer.Serialize(null));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,40 +3,39 @@ using mRemoteNG.Connection;
using NUnit.Framework;
namespace mRemoteNGTests.Connection
namespace mRemoteNGTests.Connection;
public class ConnectionInfoComparerTests
{
public class ConnectionInfoComparerTests
private ConnectionInfo _con1;
private ConnectionInfo _con2;
[OneTimeSetUp]
public void OnetimeSetup()
{
private ConnectionInfo _con1;
private ConnectionInfo _con2;
_con1 = new ConnectionInfo { Name = "a" };
_con2 = new ConnectionInfo { Name = "b" };
}
[OneTimeSetUp]
public void OnetimeSetup()
[Test]
public void SortAscendingOnName()
{
var comparer = new ConnectionInfoComparer<string>(node => node.Name)
{
_con1 = new ConnectionInfo { Name = "a" };
_con2 = new ConnectionInfo { Name = "b" };
}
SortDirection = ListSortDirection.Ascending
};
var compareReturn = comparer.Compare(_con1, _con2);
Assert.That(compareReturn, Is.Negative);
}
[Test]
public void SortAscendingOnName()
[Test]
public void SortDescendingOnName()
{
var comparer = new ConnectionInfoComparer<string>(node => node.Name)
{
var comparer = new ConnectionInfoComparer<string>(node => node.Name)
{
SortDirection = ListSortDirection.Ascending
};
var compareReturn = comparer.Compare(_con1, _con2);
Assert.That(compareReturn, Is.Negative);
}
[Test]
public void SortDescendingOnName()
{
var comparer = new ConnectionInfoComparer<string>(node => node.Name)
{
SortDirection = ListSortDirection.Descending
};
var compareReturn = comparer.Compare(_con1, _con2);
Assert.That(compareReturn, Is.Positive);
}
SortDirection = ListSortDirection.Descending
};
var compareReturn = comparer.Compare(_con1, _con2);
Assert.That(compareReturn, Is.Positive);
}
}

View File

@@ -6,148 +6,145 @@ using mRemoteNG.Container;
using mRemoteNG.Tree.Root;
using NUnit.Framework;
namespace mRemoteNGTests.Connection
namespace mRemoteNGTests.Connection;
[TestFixture]
public class ConnectionInfoInheritanceTests
{
[TestFixture]
public class ConnectionInfoInheritanceTests
private readonly PropertyInfo[] _inheritanceProperties = typeof(ConnectionInfoInheritance).GetProperties();
[Test]
public void TurnOffInheritanceCompletely()
{
private readonly PropertyInfo[] _inheritanceProperties = typeof(ConnectionInfoInheritance).GetProperties();
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo()) { Username = true };
inheritance.TurnOffInheritanceCompletely();
Assert.That(AllInheritancePropertiesAreFalse(inheritance), Is.True);
}
[Test]
public void TurnOnInheritanceCompletely()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
inheritance.TurnOnInheritanceCompletely();
Assert.That(AllInheritancePropertiesAreTrue(inheritance), Is.True);
}
[Test]
public void TurnOffInheritanceCompletely()
[Test]
public void InheritanceIsDisabledWhenAttachedToARootNode()
{
var inheritance = new ConnectionInfoInheritance(new RootNodeInfo(RootNodeType.Connection));
Assert.That(inheritance.InheritanceActive, Is.False);
}
[Test]
public void InheritanceIsDisabledWhenAttachedToAPuttyRootNode()
{
var inheritance = new ConnectionInfoInheritance(new RootNodeInfo(RootNodeType.PuttySessions));
Assert.That(inheritance.InheritanceActive, Is.False);
}
[Test]
public void InheritanceIsDisabledWhenAttachedToAPuttyNode()
{
var inheritance = new ConnectionInfoInheritance(new RootPuttySessionsNodeInfo());
Assert.That(inheritance.InheritanceActive, Is.False);
}
[Test]
public void InheritanceIsDisabledWhenAttachedToANodeDirectlyUnderTheRootNode()
{
var con = new ConnectionInfo();
new RootNodeInfo(RootNodeType.Connection).AddChild(con);
Assert.That(con.Inheritance.InheritanceActive, Is.False);
}
[Test]
public void InheritanceIsEnabledWhenAttachedToNormalConnectionInfo()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
Assert.That(inheritance.InheritanceActive, Is.True);
}
[Test]
public void InheritanceIsEnabledWhenAttachedToNormalContainerInfo()
{
var inheritance = new ConnectionInfoInheritance(new ContainerInfo());
Assert.That(inheritance.InheritanceActive, Is.True);
}
[Test]
public void GetPropertiesReturnsListOfSettableProperties()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
var hasIconProperty =
inheritance.GetProperties().Contains(typeof(ConnectionInfoInheritance).GetProperty("Icon"));
Assert.That(hasIconProperty, Is.True);
}
[Test]
public void GetPropertiesExludesPropertiesThatShouldNotBeSet()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
var hasEverythingInheritedProperty = inheritance.GetProperties()
.Contains(typeof(ConnectionInfoInheritance).GetProperty("EverythingInherited"));
Assert.That(hasEverythingInheritedProperty, Is.False);
}
[Test]
public void AlwaysReturnInheritedValueIfRequested()
{
var expectedSetting = false;
var container = new ContainerInfo { AutomaticResize = expectedSetting };
var con1 = new ConnectionInfo
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo()) {Username = true};
inheritance.TurnOffInheritanceCompletely();
Assert.That(AllInheritancePropertiesAreFalse(inheritance), Is.True);
}
AutomaticResize = true,
Inheritance = { AutomaticResize = true }
};
container.AddChild(con1);
[Test]
public void TurnOnInheritanceCompletely()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
inheritance.TurnOnInheritanceCompletely();
Assert.That(AllInheritancePropertiesAreTrue(inheritance), Is.True);
}
Assert.That(con1.AutomaticResize, Is.EqualTo(expectedSetting));
}
[Test]
public void InheritanceIsDisabledWhenAttachedToARootNode()
{
var inheritance = new ConnectionInfoInheritance(new RootNodeInfo(RootNodeType.Connection));
Assert.That(inheritance.InheritanceActive, Is.False);
}
private bool AllInheritancePropertiesAreTrue(ConnectionInfoInheritance inheritance)
{
var allPropertiesTrue = true;
foreach (var property in _inheritanceProperties)
if (PropertyIsBoolean(property) && PropertyIsChangedWhenSettingInheritAll(property) &&
BooleanPropertyIsSetToFalse(property, inheritance))
allPropertiesTrue = false;
return allPropertiesTrue;
}
[Test]
public void InheritanceIsDisabledWhenAttachedToAPuttyRootNode()
{
var inheritance = new ConnectionInfoInheritance(new RootNodeInfo(RootNodeType.PuttySessions));
Assert.That(inheritance.InheritanceActive, Is.False);
}
private bool AllInheritancePropertiesAreFalse(ConnectionInfoInheritance inheritance)
{
var allPropertiesFalse = true;
foreach (var property in _inheritanceProperties)
if (PropertyIsBoolean(property) && PropertyIsChangedWhenSettingInheritAll(property) &&
BooleanPropertyIsSetToTrue(property, inheritance))
allPropertiesFalse = false;
return allPropertiesFalse;
}
[Test]
public void InheritanceIsDisabledWhenAttachedToAPuttyNode()
{
var inheritance = new ConnectionInfoInheritance(new RootPuttySessionsNodeInfo());
Assert.That(inheritance.InheritanceActive, Is.False);
}
private bool PropertyIsChangedWhenSettingInheritAll(PropertyInfo property)
{
var propertiesIgnoredByInheritAll = new ArrayList { "IsDefault" };
return propertiesIgnoredByInheritAll.Contains(property);
}
[Test]
public void InheritanceIsDisabledWhenAttachedToANodeDirectlyUnderTheRootNode()
{
var con = new ConnectionInfo();
new RootNodeInfo(RootNodeType.Connection).AddChild(con);
Assert.That(con.Inheritance.InheritanceActive, Is.False);
}
private bool PropertyIsBoolean(PropertyInfo property)
{
return property.PropertyType.Name == typeof(bool).Name;
}
[Test]
public void InheritanceIsEnabledWhenAttachedToNormalConnectionInfo()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
Assert.That(inheritance.InheritanceActive, Is.True);
}
private bool BooleanPropertyIsSetToFalse(PropertyInfo property, ConnectionInfoInheritance inheritance)
{
return (bool)property.GetValue(inheritance) == false;
}
[Test]
public void InheritanceIsEnabledWhenAttachedToNormalContainerInfo()
{
var inheritance = new ConnectionInfoInheritance(new ContainerInfo());
Assert.That(inheritance.InheritanceActive, Is.True);
}
[Test]
public void GetPropertiesReturnsListOfSettableProperties()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
var hasIconProperty = inheritance.GetProperties().Contains(typeof(ConnectionInfoInheritance).GetProperty("Icon"));
Assert.That(hasIconProperty, Is.True);
}
[Test]
public void GetPropertiesExludesPropertiesThatShouldNotBeSet()
{
var inheritance = new ConnectionInfoInheritance(new ConnectionInfo());
var hasEverythingInheritedProperty = inheritance.GetProperties().Contains(typeof(ConnectionInfoInheritance).GetProperty("EverythingInherited"));
Assert.That(hasEverythingInheritedProperty, Is.False);
}
[Test]
public void AlwaysReturnInheritedValueIfRequested()
{
var expectedSetting = false;
var container = new ContainerInfo { AutomaticResize = expectedSetting };
var con1 = new ConnectionInfo
{
AutomaticResize = true,
Inheritance = {AutomaticResize = true}
};
container.AddChild(con1);
Assert.That(con1.AutomaticResize, Is.EqualTo(expectedSetting));
}
private bool AllInheritancePropertiesAreTrue(ConnectionInfoInheritance inheritance)
{
var allPropertiesTrue = true;
foreach (var property in _inheritanceProperties)
{
if (PropertyIsBoolean(property) && PropertyIsChangedWhenSettingInheritAll(property) &&
BooleanPropertyIsSetToFalse(property, inheritance))
allPropertiesTrue = false;
}
return allPropertiesTrue;
}
private bool AllInheritancePropertiesAreFalse(ConnectionInfoInheritance inheritance)
{
var allPropertiesFalse = true;
foreach (var property in _inheritanceProperties)
{
if (PropertyIsBoolean(property) && PropertyIsChangedWhenSettingInheritAll(property) &&
BooleanPropertyIsSetToTrue(property, inheritance))
allPropertiesFalse = false;
}
return allPropertiesFalse;
}
private bool PropertyIsChangedWhenSettingInheritAll(PropertyInfo property)
{
var propertiesIgnoredByInheritAll = new ArrayList {"IsDefault"};
return propertiesIgnoredByInheritAll.Contains(property);
}
private bool PropertyIsBoolean(PropertyInfo property)
{
return (property.PropertyType.Name == typeof(bool).Name);
}
private bool BooleanPropertyIsSetToFalse(PropertyInfo property, ConnectionInfoInheritance inheritance)
{
return (bool)property.GetValue(inheritance) == false;
}
private bool BooleanPropertyIsSetToTrue(PropertyInfo property, ConnectionInfoInheritance inheritance)
{
return (bool)property.GetValue(inheritance);
}
private bool BooleanPropertyIsSetToTrue(PropertyInfo property, ConnectionInfoInheritance inheritance)
{
return (bool)property.GetValue(inheritance);
}
}

View File

@@ -7,51 +7,50 @@ using mRemoteNG.UI.Window;
using NUnit.Framework;
using WeifenLuo.WinFormsUI.Docking;
namespace mRemoteNGTests.Connection.Protocol
namespace mRemoteNGTests.Connection.Protocol;
public class IntegratedProgramTests
{
public class IntegratedProgramTests
{
private readonly ExternalTool _extTool = new ExternalTool
{
DisplayName = "notepad",
FileName = @"%windir%\system32\notepad.exe",
Arguments = "",
TryIntegrate = true
};
private readonly ExternalTool _extTool = new()
{
DisplayName = "notepad",
FileName = @"%windir%\system32\notepad.exe",
Arguments = "",
TryIntegrate = true
};
[Test]
public void CanStartExternalApp()
{
SetExternalToolList(_extTool);
var sut = new IntegratedProgram();
sut.InterfaceControl = BuildInterfaceControl("notepad", sut);
sut.Initialize();
var appStarted = sut.Connect();
sut.Disconnect();
Assert.That(appStarted);
}
[Test]
public void ConnectingToExternalAppThatDoesntExistDoesNothing()
{
SetExternalToolList(_extTool);
var sut = new IntegratedProgram();
sut.InterfaceControl = BuildInterfaceControl("doesntExist", sut);
var appInitialized = sut.Initialize();
Assert.That(appInitialized, Is.False);
}
[Test]
public void CanStartExternalApp()
{
SetExternalToolList(_extTool);
var sut = new IntegratedProgram();
sut.InterfaceControl = BuildInterfaceControl("notepad", sut);
sut.Initialize();
var appStarted = sut.Connect();
sut.Disconnect();
Assert.That(appStarted);
}
private void SetExternalToolList(ExternalTool externalTool)
{
Runtime.ExternalToolsService.ExternalTools = new FullyObservableCollection<ExternalTool> {externalTool};
}
[Test]
public void ConnectingToExternalAppThatDoesntExistDoesNothing()
{
SetExternalToolList(_extTool);
var sut = new IntegratedProgram();
sut.InterfaceControl = BuildInterfaceControl("doesntExist", sut);
var appInitialized = sut.Initialize();
Assert.That(appInitialized, Is.False);
}
private InterfaceControl BuildInterfaceControl(string extAppName, ProtocolBase sut)
{
var connectionWindow = new ConnectionWindow(new DockContent());
var connectionInfo = new ConnectionInfo {ExtApp = extAppName, Protocol = ProtocolType.IntApp};
return new InterfaceControl(connectionWindow, sut, connectionInfo);
}
}
private void SetExternalToolList(ExternalTool externalTool)
{
Runtime.ExternalToolsService.ExternalTools = new FullyObservableCollection<ExternalTool> { externalTool };
}
private InterfaceControl BuildInterfaceControl(string extAppName, ProtocolBase sut)
{
var connectionWindow = new ConnectionWindow(new DockContent());
var connectionInfo = new ConnectionInfo { ExtApp = extAppName, Protocol = ProtocolType.IntApp };
return new InterfaceControl(connectionWindow, sut, connectionInfo);
}
}

View File

@@ -7,212 +7,211 @@ using mRemoteNG.Connection.Protocol.VNC;
using NUnit.Framework;
namespace mRemoteNGTests.Connection.Protocol
namespace mRemoteNGTests.Connection.Protocol;
public class ProtocolListTests
{
public class ProtocolListTests
private ProtocolList _protocolList;
private ProtocolBase _protocol1;
private ProtocolBase _protocol2;
private ProtocolBase _protocol3;
[SetUp]
public void Setup()
{
private ProtocolList _protocolList;
private ProtocolBase _protocol1;
private ProtocolBase _protocol2;
private ProtocolBase _protocol3;
_protocolList = new ProtocolList();
_protocol1 = new ProtocolTelnet();
_protocol2 = new ProtocolSSH2();
_protocol3 = new ProtocolVNC();
}
[TearDown]
public void Teardown()
{
_protocolList = null;
_protocol1 = null;
_protocol2 = null;
_protocol3 = null;
}
[SetUp]
public void Setup()
{
_protocolList = new ProtocolList();
_protocol1 = new ProtocolTelnet();
_protocol2 = new ProtocolSSH2();
_protocol3 = new ProtocolVNC();
}
[Test]
public void EmptyWhenInitialized()
{
Assert.That(_protocolList.Count == 0);
}
[TearDown]
public void Teardown()
{
_protocolList = null;
_protocol1 = null;
_protocol2 = null;
_protocol3 = null;
}
[Test]
public void AddAddsObjectToList()
{
_protocolList.Add(_protocol1);
Assert.That(_protocolList[0] == _protocol1);
}
[Test]
public void EmptyWhenInitialized()
{
Assert.That(_protocolList.Count == 0);
}
[Test]
public void AddRangeAddsAllObjects()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList, Is.EquivalentTo(protArray));
}
[Test]
public void AddAddsObjectToList()
{
_protocolList.Add(_protocol1);
Assert.That(_protocolList[0] == _protocol1);
}
[Test]
public void CountUpdatesToReflectCurrentList()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList.Count == protArray.Length);
}
[Test]
public void AddRangeAddsAllObjects()
{
var protArray = new[] {_protocol1, _protocol2, _protocol3};
_protocolList.AddRange(protArray);
Assert.That(_protocolList, Is.EquivalentTo(protArray));
}
[Test]
public void RemoveRemovesObjectFromList()
{
_protocolList.Add(_protocol1);
_protocolList.Remove(_protocol1);
Assert.That(_protocolList.Count == 0);
}
[Test]
public void CountUpdatesToReflectCurrentList()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList.Count == protArray.Length);
}
[Test]
public void ClearResetsList()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
_protocolList.Clear();
Assert.That(_protocolList.Count == 0);
}
[Test]
public void RemoveRemovesObjectFromList()
{
_protocolList.Add(_protocol1);
_protocolList.Remove(_protocol1);
Assert.That(_protocolList.Count == 0);
}
[Test]
public void IntIndexerReturnsCorrectObject()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList[1], Is.EqualTo(protArray[1]));
}
[Test]
public void ClearResetsList()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
_protocolList.Clear();
Assert.That(_protocolList.Count == 0);
}
[Test]
public void ObjectIndexerReturnsCorrectObject()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList[_protocol3], Is.EqualTo(_protocol3));
}
[Test]
public void IntIndexerReturnsCorrectObject()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList[1], Is.EqualTo(protArray[1]));
}
[Test]
public void IndexerSafelyHandlesUnknownObjects()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList["unacceptablevalue"], Is.EqualTo(null));
}
[Test]
public void ObjectIndexerReturnsCorrectObject()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList[_protocol3], Is.EqualTo(_protocol3));
}
[Test]
public void RemovingNonexistantObjectFromListDoesNothing()
{
Assert.DoesNotThrow(() => _protocolList.Remove(_protocol1));
}
[Test]
public void IndexerSafelyHandlesUnknownObjects()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
_protocolList.AddRange(protArray);
Assert.That(_protocolList["unacceptablevalue"], Is.EqualTo(null));
}
[Test]
public void AddRaisesCollectionChangedEvent()
{
var eventWasCalled = false;
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Add(_protocol1);
Assert.That(eventWasCalled);
}
[Test]
public void RemovingNonexistantObjectFromListDoesNothing()
{
Assert.DoesNotThrow(()=> _protocolList.Remove(_protocol1));
}
[Test]
public void AddCollectionChangedEventContainsAddedObject()
{
IList nodeListFromEvent = new ArrayList();
_protocolList.CollectionChanged += (sender, args) => nodeListFromEvent = args.NewItems;
_protocolList.Add(_protocol1);
Assert.That(nodeListFromEvent, Is.EquivalentTo(new[] { _protocol1 }));
}
[Test]
public void AddRaisesCollectionChangedEvent()
{
var eventWasCalled = false;
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Add(_protocol1);
Assert.That(eventWasCalled);
}
[Test]
public void AddRangeCollectionChangedEventContainsAddedObjects()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
IList nodeListFromEvent = new ArrayList();
_protocolList.CollectionChanged += (sender, args) => nodeListFromEvent = args.NewItems;
_protocolList.AddRange(protArray);
Assert.That(nodeListFromEvent, Is.EquivalentTo(protArray));
}
[Test]
public void AddCollectionChangedEventContainsAddedObject()
{
IList nodeListFromEvent = new ArrayList();
_protocolList.CollectionChanged += (sender, args) => nodeListFromEvent = args.NewItems;
_protocolList.Add(_protocol1);
Assert.That(nodeListFromEvent, Is.EquivalentTo(new[] {_protocol1}));
}
[Test]
public void RemoveCollectionChangedEventContainsRemovedObject()
{
IList nodeListFromEvent = new ArrayList();
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => nodeListFromEvent = args.OldItems;
_protocolList.Remove(_protocol1);
Assert.That(nodeListFromEvent, Is.EquivalentTo(new[] { _protocol1 }));
}
[Test]
public void AddRangeCollectionChangedEventContainsAddedObjects()
{
var protArray = new[] { _protocol1, _protocol2, _protocol3 };
IList nodeListFromEvent = new ArrayList();
_protocolList.CollectionChanged += (sender, args) => nodeListFromEvent = args.NewItems;
_protocolList.AddRange(protArray);
Assert.That(nodeListFromEvent, Is.EquivalentTo(protArray));
}
[Test]
public void AttemptingToRemoveNonexistantObjectDoesNotRaiseCollectionChangedEvent()
{
var eventWasCalled = false;
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Remove(_protocol1);
Assert.That(eventWasCalled == false);
}
[Test]
public void RemoveCollectionChangedEventContainsRemovedObject()
{
IList nodeListFromEvent = new ArrayList();
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => nodeListFromEvent = args.OldItems;
_protocolList.Remove(_protocol1);
Assert.That(nodeListFromEvent, Is.EquivalentTo(new[] { _protocol1 }));
}
[Test]
public void ClearRaisesCollectionChangedEvent()
{
var eventWasCalled = false;
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Clear();
Assert.That(eventWasCalled);
}
[Test]
public void AttemptingToRemoveNonexistantObjectDoesNotRaiseCollectionChangedEvent()
{
var eventWasCalled = false;
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Remove(_protocol1);
Assert.That(eventWasCalled == false);
}
[Test]
public void ClearDoesntRaiseCollectionChangedEventWhenNoObjectsRemoved()
{
var eventWasCalled = false;
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Clear();
Assert.That(eventWasCalled == false);
}
[Test]
public void ClearRaisesCollectionChangedEvent()
{
var eventWasCalled = false;
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Clear();
Assert.That(eventWasCalled);
}
[Test]
public void AddCollectionChangedEventHasCorrectAction()
{
var collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.Add(_protocol1);
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Add));
}
[Test]
public void ClearDoesntRaiseCollectionChangedEventWhenNoObjectsRemoved()
{
var eventWasCalled = false;
_protocolList.CollectionChanged += (sender, args) => eventWasCalled = true;
_protocolList.Clear();
Assert.That(eventWasCalled == false);
}
[Test]
public void AddRangeCollectionChangedEventHasCorrectAction()
{
var collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.AddRange(new[] { _protocol1 });
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Add));
}
[Test]
public void AddCollectionChangedEventHasCorrectAction()
{
NotifyCollectionChangedAction collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.Add(_protocol1);
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Add));
}
[Test]
public void RemoveCollectionChangedEventHasCorrectAction()
{
var collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.Remove(_protocol1);
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Remove));
}
[Test]
public void AddRangeCollectionChangedEventHasCorrectAction()
{
NotifyCollectionChangedAction collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.AddRange(new []{_protocol1});
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Add));
}
[Test]
public void RemoveCollectionChangedEventHasCorrectAction()
{
NotifyCollectionChangedAction collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.Remove(_protocol1);
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Remove));
}
[Test]
public void ClearCollectionChangedEventHasCorrectAction()
{
NotifyCollectionChangedAction collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.Clear();
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Reset));
}
[Test]
public void ClearCollectionChangedEventHasCorrectAction()
{
var collectionChangedAction = NotifyCollectionChangedAction.Move;
_protocolList.Add(_protocol1);
_protocolList.CollectionChanged += (sender, args) => collectionChangedAction = args.Action;
_protocolList.Clear();
Assert.That(collectionChangedAction, Is.EqualTo(NotifyCollectionChangedAction.Reset));
}
}