/// <summary> /// Initializes a new instance of the <see cref="TemporarySqlLocalDbInstance"/> class. /// </summary> /// <param name="instanceName">The name of the temporary SQL LocalDB instance.</param> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use to create the temporary instance.</param> /// <param name="deleteFiles">Whether to delete the file(s) associated with the SQL LocalDB instance when deleted.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="instanceName"/> or <paramref name="provider"/> is <see langword="null"/>. /// </exception> public TemporarySqlLocalDbInstance(string instanceName, ISqlLocalDbProvider provider, bool deleteFiles) { if (instanceName == null) { throw new ArgumentNullException(nameof(instanceName)); } if (provider == null) { throw new ArgumentNullException(nameof(provider)); } _instance = provider.CreateInstance(instanceName); _deleteFiles = deleteFiles; try { _instance.Start(); } catch (Exception) { SqlLocalDbInstance.Delete(_instance, throwIfNotFound: true, deleteFiles: _deleteFiles); throw; } }
public void TemporarySqlLocalDbInstance_Dispose_Does_Not_Throw_If_Instance_Cannot_Be_Stopped_Due_To_Sql_LocalDb_Error() { // Arrange string instanceName = "MyTempInstance" + Guid.NewGuid().ToString(); var mock = new Mock <SqlLocalDbProvider>() { CallBase = true, }; // Set up the CreateInstance() method to create an SQL LocalDB // instance but that then throws an exception when stopped. mock.Setup((p) => p.CreateInstance(instanceName)) .Returns( () => { SqlLocalDbApi.CreateInstance(instanceName); return(new SqlLocalDbInstanceThatCannotBeStopped(instanceName)); }) .Verifiable(); ISqlLocalDbProvider provider = mock.Object; // Act using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instanceName, provider)) { } // Assert mock.Verify(); // Tidy up as the stop intentionally failed, meaning delete would also have failed SqlLocalDbApi.StopInstance(instanceName); SqlLocalDbApi.DeleteInstance(instanceName); }
//public override void SetUp() //{ // try // { // base.SetUp(); // // Start a Local DB instance. // _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting"); // _SqlLocalDbInstance.Start(); // } // catch (Exception e) // { // Console.WriteLine(e.ToString()); // throw; // } //} private void PrepareTestData() { _SqlLocalDbProvider = new SqlLocalDbProvider(); _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting"); _SqlLocalDbInstance.Start(); // Get the SQL to create a couple of differen tables string tableOneName; string createTableSql1 = GetCreateTestTableSql(out tableOneName); TestEntityName = tableOneName; string table2Name; string createTableSql2 = GetCreateTestTableSql(out table2Name); TestEntityName2 = table2Name; // create a foreign key column between them. var alterTableAddForeignKey = string.Format("ALTER TABLE {0} ADD {1}Id UNIQUEIDENTIFIER CONSTRAINT {0}_{1} REFERENCES {1}", tableOneName, table2Name); // CreateTestEntity(); // Create table in LocalDB using (SqlConnection connection = _SqlLocalDbInstance.CreateConnection()) { connection.Open(); // create the first table var command = connection.CreateCommand(); command.CommandType = CommandType.Text; Console.WriteLine("Executing local db command " + createTableSql1); command.CommandText = createTableSql1; var result = command.ExecuteNonQuery(); Assert.AreEqual(result, -1); // create the second table command.CommandText = createTableSql2; result = command.ExecuteNonQuery(); Assert.AreEqual(result, -1); // create a column in the first table that is a foreign key so it references the second table command.CommandText = alterTableAddForeignKey; result = command.ExecuteNonQuery(); Assert.AreEqual(result, -1); } // Create first table in Crm ExecuteCrmNonQuery(createTableSql1, -1); // Create second table in Crm ExecuteCrmNonQuery(createTableSql2, -1); // create a column in the first table that is a foreign key so it references the second table ExecuteCrmNonQuery(alterTableAddForeignKey, -1); }
/// <summary> /// Tests that the instances reported by the specified <see cref="ISqlLocalDbProvider"/> are valid. /// </summary> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to test the instances for.</param> private static void TestInstances(ISqlLocalDbProvider provider) { IList <ISqlLocalDbInstanceInfo> instances = provider.GetInstances(); Assert.IsNotNull(instances, "GetInstances() returned null."); CollectionAssert.AllItemsAreNotNull(instances.ToArray(), "GetInstances() returned a null item."); bool usingSqlServer2012 = NativeMethods.NativeApiVersion == new Version(11, 0); string[] defaultInstanceNamesForSqlServer2012 = new string[] { "v12.0", }; foreach (ISqlLocalDbInstanceInfo instanceInfo in instances) { Assert.IsNotNull(instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is null.", instanceInfo.Name); if (usingSqlServer2012 && defaultInstanceNamesForSqlServer2012.Contains(instanceInfo.Name, StringComparer.Ordinal)) { // The SQL LocalDB 2012 Instance API reports the name as 'v12.0' instead of 'MSSQLLocalDB', // which then if queried states that it does not exist (because it doesn't actually exist) // under that name. In this case, skip this instance from being tested. We could fudge this // in the wrapper itself, but that's probably not the best idea as the default instance name // may change again in SQL Server 2016. continue; } Assert.AreNotEqual(string.Empty, instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is incorrect.", instanceInfo.Name); Assert.IsFalse(instanceInfo.ConfigurationCorrupt, "ISqlLocalDbInstanceInfo.ConfigurationCorrupt is incorrect for instance '{0}'.", instanceInfo.Name); // The automatic instance may not yet exist on a clean machine if (!instanceInfo.IsAutomatic) { Assert.IsTrue(instanceInfo.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect for instance '{0}'.", instanceInfo.Name); } Assert.IsNotNull(instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is null for instance '{0}'.", instanceInfo.Name); Assert.AreNotEqual(string.Empty, instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is incorrect for instance '{0}'.", instanceInfo.Name); // These values are only populated if the instance exists if (instanceInfo.Exists) { Assert.IsNotNull(instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is null for instance '{0}'.", instanceInfo.Name); Assert.AreNotEqual(string.Empty, instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is incorrect for instance '{0}'.", instanceInfo.Name); } } }
public void TemporarySqlLocalDbInstance_Constructor_Throws_If_Provider_Is_Null() { // Arrange string instanceName = Guid.NewGuid().ToString(); ISqlLocalDbProvider provider = null; // Act and Assert throw ErrorAssert.Throws <ArgumentNullException>( () => { using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instanceName, provider)) { } }, "provider"); }
public void TemporarySqlLocalDbInstance_Constructor_Throws_If_InstanceName_Is_Null() { // Arrange string instanceName = null; ISqlLocalDbProvider provider = Mock.Of <ISqlLocalDbProvider>(); // Act and Assert throw ErrorAssert.Throws <ArgumentNullException>( () => { using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instanceName, provider)) { } }, "instanceName"); }
/// <summary> /// Tests that the versions reported by the specified <see cref="ISqlLocalDbProvider"/> are valid. /// </summary> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to test the versions for.</param> private static void TestVersions(ISqlLocalDbProvider provider) { IList <ISqlLocalDbVersionInfo> versions = provider.GetVersions(); Assert.IsNotNull(versions, "GetVersions() returned null."); CollectionAssert.AllItemsAreNotNull(versions.ToArray(), "GetVersions() returned a null item."); foreach (ISqlLocalDbVersionInfo version in versions) { Assert.IsNotNull(version.Name, "ISqlLocalDbVersionInfo.Name is null."); Assert.AreNotEqual(string.Empty, version.Name, "ISqlLocalDbVersionInfo.Name is incorrect."); Assert.IsTrue(version.Exists, "ISqlLocalDbVersionInfo.Exists is incorrect for version '{0}'.", version.Name); Assert.IsNotNull(version.Version, "ISqlLocalDbVersionInfo.Version is null for version '{0}'.", version.Name); Assert.AreNotEqual(string.Empty, version.Version, "ISqlLocalDbVersionInfo.Version is incorrect for version '{0}'.", version.Name); } }
/// <summary> /// Gets an SQL Local DB instance with the specified name if it exists, otherwise a new instance with the specified name is created. /// </summary> /// <param name="value">The <see cref="ISqlLocalDbProvider"/> to use to get or create the instance.</param> /// <param name="instanceName">The name of the SQL Server LocalDB instance to get or create.</param> /// <returns> /// An SQL Local DB instance with the name specified by <paramref name="instanceName"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="value"/> or <paramref name="instanceName"/> is <see langword="null"/>. /// </exception> /// <exception cref="InvalidOperationException"> /// <paramref name="value"/> returns <see langword="null"/> when queried for instances. /// </exception> public static ISqlLocalDbInstance GetOrCreateInstance(this ISqlLocalDbProvider value, string instanceName) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (instanceName == null) { throw new ArgumentNullException(nameof(instanceName)); } bool instanceExists = false; if (SqlLocalDbApi.IsDefaultInstanceName(instanceName)) { // The default instance is always listed, even if it does not exist, // so need to query that separately to verify whether to get or create. instanceExists = SqlLocalDbApi.GetInstanceInfo(instanceName).Exists; } else { // This approach is used otherwise for testability IList <ISqlLocalDbInstanceInfo> instances = value.GetInstances(); if (instances != null) { // Instance names in SQL Local DB are case-insensitive instanceExists = instances .Where((p) => p != null) .Where((p) => string.Equals(p.Name, instanceName, StringComparison.OrdinalIgnoreCase)) .Any(); } } if (instanceExists) { return(value.GetInstance(instanceName)); } else { return(value.CreateInstance(instanceName)); } }
public void TemporarySqlLocalDbInstance_Constructor_Attempts_To_Delete_Instance_If_Instance_Cannot_Be_Started() { // Arrange string instanceName = "MyTempInstance" + Guid.NewGuid().ToString(); var mock = new Mock <SqlLocalDbProvider>() { CallBase = true, }; // Set up the CreateInstance() method to create an SQL LocalDB // instance but that then throws an exception when started. mock.Setup((p) => p.CreateInstance(instanceName)) .Returns( () => { SqlLocalDbApi.CreateInstance(instanceName); return(new SqlLocalDbInstanceThatCannotBeStarted(instanceName)); }) .Verifiable(); ISqlLocalDbProvider provider = mock.Object; bool deleteFiles = false; // Act InvalidOperationException error = ErrorAssert.Throws <InvalidOperationException>( () => { using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instanceName, provider, deleteFiles)) { } }); mock.Verify(); ISqlLocalDbInstanceInfo instanceInfo = SqlLocalDbApi.GetInstanceInfo(instanceName); Assert.IsFalse(instanceInfo.Exists, "The temporary instance was not deleted."); throw error; }
/// <summary> /// Tests that the versions reported by the specified <see cref="ISqlLocalDbProvider"/> are valid. /// </summary> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to test the versions for.</param> private static void TestVersions(ISqlLocalDbProvider provider) { IList<ISqlLocalDbVersionInfo> versions = provider.GetVersions(); Assert.IsNotNull(versions, "GetVersions() returned null."); CollectionAssert.AllItemsAreNotNull(versions.ToArray(), "GetVersions() returned a null item."); foreach (ISqlLocalDbVersionInfo version in versions) { Assert.IsNotNull(version.Name, "ISqlLocalDbVersionInfo.Name is null."); Assert.AreNotEqual(string.Empty, version.Name, "ISqlLocalDbVersionInfo.Name is incorrect."); Assert.IsTrue(version.Exists, "ISqlLocalDbVersionInfo.Exists is incorrect for version '{0}'.", version.Name); Assert.IsNotNull(version.Version, "ISqlLocalDbVersionInfo.Version is null for version '{0}'.", version.Name); Assert.AreNotEqual(string.Empty, version.Version, "ISqlLocalDbVersionInfo.Version is incorrect for version '{0}'.", version.Name); } }
/// <summary> /// Tests the lifecycle of SQL LocalDB instances. /// </summary> /// <param name="localDB">The <see cref="ISqlLocalDbApi"/> to use.</param> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use.</param> private static void TestInstanceLifecycle(ISqlLocalDbApi localDB, ISqlLocalDbProvider provider) { string instanceName = Guid.NewGuid().ToString(); string sharedInstanceName = string.Empty; ISqlLocalDbInstance instance = provider.CreateInstance(instanceName); instance.Start(); try { bool currentUserIsAdmin = Helpers.IsCurrentUserAdmin(); if (currentUserIsAdmin) { sharedInstanceName = Guid.NewGuid().ToString(); instance.Share(sharedInstanceName); // Restart the instance so it listens on the new shared name's pipe instance.Restart(); } try { ISqlLocalDbInstanceInfo info = provider.GetInstances() .Where((p) => string.Equals(p.Name, instanceName, StringComparison.Ordinal)) .FirstOrDefault(); Assert.IsNotNull(info, "GetInstances() did not return the created instance."); Assert.AreEqual(sharedInstanceName, info.SharedName, "ISqlLocalDbInstanceInfo.SharedName is incorrect."); using (SqlConnection connection = instance.CreateConnection()) { Assert.IsNotNull(connection, "CreateConnection() returned null."); TestConnection(connection); } if (currentUserIsAdmin) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = string.Format(CultureInfo.InvariantCulture, "(localdb)\\.\\{0}", sharedInstanceName); builder.IntegratedSecurity = true; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { TestConnection(connection); } } } finally { if (currentUserIsAdmin) { instance.Unshare(); } } } finally { instance.Stop(); localDB.DeleteInstance(instance.Name); } }
/// <summary> /// Tests the lifecycle of SQL LocalDB instances. /// </summary> /// <param name="localDB">The <see cref="ISqlLocalDbApi"/> to use.</param> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use.</param> private static void TestInstanceLifecycle(ISqlLocalDbApi localDB, ISqlLocalDbProvider provider) { string instanceName = Guid.NewGuid().ToString(); string sharedInstanceName = string.Empty; ISqlLocalDbInstance instance = provider.CreateInstance(instanceName); instance.Start(); try { bool currentUserIsAdmin = Helpers.IsCurrentUserAdmin(); if (currentUserIsAdmin) { sharedInstanceName = Guid.NewGuid().ToString(); instance.Share(sharedInstanceName); // Restart the instance so it listens on the new shared name's pipe instance.Restart(); } try { ISqlLocalDbInstanceInfo info = provider.GetInstances() .Where((p) => string.Equals(p.Name, instanceName, StringComparison.Ordinal)) .FirstOrDefault(); Assert.IsNotNull(info, "GetInstances() did not return the created instance."); Assert.AreEqual(sharedInstanceName, info.SharedName, "ISqlLocalDbInstanceInfo.SharedName is incorrect."); using (SqlConnection connection = instance.CreateConnection()) { Assert.IsNotNull(connection, "CreateConnection() returned null."); TestConnection(connection); } if (currentUserIsAdmin) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder() { DataSource = $@"(localdb)\.\{sharedInstanceName}", IntegratedSecurity = true }; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { TestConnection(connection); } } } finally { if (currentUserIsAdmin) { instance.Unshare(); } } } finally { instance.Stop(); localDB.DeleteInstance(instance.Name); } }
/// <summary> /// Initializes a new instance of the <see cref="TemporarySqlLocalDbInstance"/> class. /// </summary> /// <param name="instanceName">The name of the temporary SQL LocalDB instance.</param> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use to create the temporary instance.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="instanceName"/> or <paramref name="provider"/> is <see langword="null"/>. /// </exception> public TemporarySqlLocalDbInstance(string instanceName, ISqlLocalDbProvider provider) : this(instanceName, provider, SqlLocalDbApi.AutomaticallyDeleteInstanceFiles) { }
/// <summary> /// Gets the default SQL Local DB instance. /// </summary> /// <param name="value">The <see cref="ISqlLocalDbProvider"/> to use to get the default instance.</param> /// <returns> /// The default SQL Local DB instance. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="value"/> is <see langword="null"/>. /// </exception> public static ISqlLocalDbInstance GetDefaultInstance(this ISqlLocalDbProvider value) => value.GetOrCreateInstance(SqlLocalDbApi.DefaultInstanceName);
/// <summary> /// Tests that the instances reported by the specified <see cref="ISqlLocalDbProvider"/> are valid. /// </summary> /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to test the instances for.</param> private static void TestInstances(ISqlLocalDbProvider provider) { IList<ISqlLocalDbInstanceInfo> instances = provider.GetInstances(); Assert.IsNotNull(instances, "GetInstances() returned null."); CollectionAssert.AllItemsAreNotNull(instances.ToArray(), "GetInstances() returned a null item."); bool usingSqlServer2012 = NativeMethods.NativeApiVersion == new Version(11, 0); string[] defaultInstanceNamesForSqlServer2012 = new string[] { "v12.0", }; foreach (ISqlLocalDbInstanceInfo instanceInfo in instances) { Assert.IsNotNull(instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is null.", instanceInfo.Name); if (usingSqlServer2012 && defaultInstanceNamesForSqlServer2012.Contains(instanceInfo.Name, StringComparer.Ordinal)) { // The SQL LocalDB 2012 Instance API reports the name as 'v12.0' instead of 'MSSQLLocalDB', // which then if queried states that it does not exist (because it doesn't actually exist) // under that name. In this case, skip this instance from being tested. We could fudge this // in the wrapper itself, but that's probably not the best idea as the default instance name // may change again in SQL Server 2016. continue; } Assert.AreNotEqual(string.Empty, instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is incorrect.", instanceInfo.Name); Assert.IsFalse(instanceInfo.ConfigurationCorrupt, "ISqlLocalDbInstanceInfo.ConfigurationCorrupt is incorrect for instance '{0}'.", instanceInfo.Name); // The automatic instance may not yet exist on a clean machine if (!instanceInfo.IsAutomatic) { Assert.IsTrue(instanceInfo.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect for instance '{0}'.", instanceInfo.Name); } Assert.IsNotNull(instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is null for instance '{0}'.", instanceInfo.Name); Assert.AreNotEqual(string.Empty, instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is incorrect for instance '{0}'.", instanceInfo.Name); // These values are only populated if the instance exists if (instanceInfo.Exists) { Assert.IsNotNull(instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is null for instance '{0}'.", instanceInfo.Name); Assert.AreNotEqual(string.Empty, instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is incorrect for instance '{0}'.", instanceInfo.Name); } } }