public void TestFixtureSetUp() { if (!SqlLocalDbApi.IsLocalDBInstalled()) { throw new Exception("LocalDB is not installed!"); } this.databaseName = "SqlServerUserManagerTests_" + Guid.NewGuid().ToString("N"); // Configure dapper to support datetime2 SqlMapper.AddTypeMap(typeof(DateTime), DbType.DateTime2); // Create test instance this.instance = TemporarySqlLocalDbInstance.Create(deleteFiles: true); // Seed test data using (var connection = this.instance.CreateConnection()) { connection.Open(); try { connection.Execute("CREATE DATABASE " + this.databaseName); connection.Execute("USE " + this.databaseName); connection.Execute("CREATE TABLE Users (Id bigint NOT NULL PRIMARY KEY IDENTITY(1,1), UserId VARCHAR(255) NOT NULL, Password VARCHAR(MAX) NOT NULL, FirstName NVARCHAR(255) NOT NULL, LastName NVARCHAR(255) NOT NULL, LastLogin DATETIMEOFFSET)"); connection.Execute("INSERT INTO Users (UserId, Password, FirstName, LastName) VALUES ('azzlack', '10000:gW7zpVeugKl8IFu7TcpPskcgQjy4185eAwBk9fFlZK6JNd1I45tLyCYtJrzWzE+kVCUP7lMSY8o808EjUgfavBzYU/ZtWypcdCdCJ0BMfMcf8Mk+XIYQCQLiFpt9Rjrf5mAY86NuveUtd1yBdPjxX5neMXEtquNYhu9I6iyzcN4=:Lk2ZkpmTDkNtO/tsB/GskMppdAX2bXehP+ED4oLis0AAv3Q1VeI8KL0SxIIWdxjKH0NJKZ6qniRFkfZKZRS2hS4SB8oyB34u/jyUlmv+RZGZSt9nJ9FYJn1percd/yFA7sSQOpkGljJ6OTwdthe0Bw0A/8qlKHbO2y2M5BFgYHY=', 'Ove', 'Andersen')"); } finally { connection.Close(); } } base.TestFixtureSetUp(); }
public void SqlLocalDbInstance_Share_Throws_If_SharedName_Is_Invalid() { // Arrange Helpers.EnsureLocalDBInstalled(); string instanceName = Guid.NewGuid().ToString(); string sharedName = "\\\\"; SqlLocalDbApi.CreateInstance(instanceName); try { SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName); // Act SqlLocalDbException error = ErrorAssert.Throws <SqlLocalDbException>( () => target.Share(sharedName)); // Assert Assert.AreEqual(SqlLocalDbErrors.InvalidInstanceName, error.ErrorCode, "SqlLocalDbException.ErrorCode is incorrect."); Assert.AreEqual(instanceName, error.InstanceName, "SqlLocalDbException.InstanceName is incorrect."); throw error; } finally { SqlLocalDbApi.DeleteInstance(instanceName); } }
public async Task CreateConnection_Creates_A_Sql_Connection() { // Arrange using (var api = new SqlLocalDbApi(_loggerFactory)) { using (TemporarySqlLocalDbInstance temporary = api.CreateTemporaryInstance(deleteFiles: true)) { ISqlLocalDbInstanceManager manager = temporary.Manage(); manager.ShouldNotBeNull(); manager.Name.ShouldBe(temporary.Name); // Act using (SqlConnection actual = manager.CreateConnection()) { // Assert actual.ShouldNotBeNull(); actual.ConnectionString.ShouldNotBeNull(); actual.State.ShouldBe(ConnectionState.Closed); await actual.OpenAsync(); actual.Close(); } } } }
private static void Execute() { var localInfo = SqlLocalDbApi.GetInstanceInfo(AppConfig.Database); if (localInfo.Exists) { SqlLocalDbApi.StopInstance(localInfo.Name); SqlLocalDbApi.DeleteInstance(localInfo.Name, true); } SqlLocalDbApi.CreateInstance(localInfo.Name); using (var memoryStream = new MemoryStream()) { var remote = new DacServices(AppConfig.RemoteConnectionString); remote.ProgressChanged += (sender, args) => Console.WriteLine($"remote {args.Status} {args.Message}"); remote.ExportBacpac(memoryStream, localInfo.Name, DacSchemaModelStorageType.Memory); using (var bacPackage = BacPackage.Load(memoryStream, DacSchemaModelStorageType.Memory)) { var local = new DacServices(AppConfig.LocalConnectionString); local.ProgressChanged += (sender, args) => Console.WriteLine($"local {args.Status} {args.Message}"); local.ImportBacpac(bacPackage, localInfo.Name); } } }
public void SqlLocalDbProvider_As_ISqlLocalDbFactory_GetInstance_Returns_Specified_Instance() { // Arrange Helpers.EnsureLocalDBInstalled(); ISqlLocalDbProvider target = new SqlLocalDbProvider(); string instanceName = Guid.NewGuid().ToString(); // Act SqlLocalDbApi.CreateInstance(instanceName); try { // Assert ISqlLocalDbInstance result = target.GetInstance(instanceName); Assert.IsNotNull(result, "CreateInstance() returned null."); Assert.AreEqual(instanceName, result.Name, "SqlLocalDbInstance.Name is incorrect."); ISqlLocalDbInstanceInfo info = result.GetInstanceInfo(); Assert.IsTrue(info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect."); Assert.IsFalse(info.IsRunning, "ISqlLocalDbInstanceInfo.IsRunning is incorrect."); Assert.IsTrue(Guid.TryParse(result.Name, out Guid unused), "SqlLocalDbInstance.Name is not a valid GUID."); } finally { SqlLocalDbApi.DeleteInstance(instanceName); } }
public void SqlLocalDbInstance_Share_Throws_If_SharedName_Is_Null() { // Arrange Helpers.EnsureLocalDBInstalled(); string instanceName = Guid.NewGuid().ToString(); SqlLocalDbApi.CreateInstance(instanceName); try { SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName); string sharedName = null; // Act and Assert throw ErrorAssert.Throws <ArgumentNullException>( () => target.Share(sharedName), "sharedName"); } finally { SqlLocalDbApi.DeleteInstance(instanceName); } }
public void Can_Get_Instances_From_Names() { // Arrange using (var api = new SqlLocalDbApi(_loggerFactory)) { IReadOnlyList <string> names = api.GetInstanceNames(); foreach (string name in names) { // Act ISqlLocalDbInstanceInfo info = api.GetInstanceInfo(name); // Assert info.ShouldNotBeNull(); } // Arrange string instanceName = Guid.NewGuid().ToString(); // Act bool actual = api.InstanceExists(instanceName); // Assert actual.ShouldBeFalse(); } }
public SqlLocalDb() { _localDb = new SqlLocalDbApi(); _instance = _localDb.GetOrCreateInstance("SSS-LoadTests"); _manager = _instance.Manage(); Initialize().Wait(); }
public void SqlLocalDbInstance_Delete_If_SqlLocalDbApi_AutomaticallyDeleteInstanceFiles_Is_True() { // Arrange Helpers.EnsureLocalDBInstalled(); Helpers.InvokeInNewAppDomain( () => { SqlLocalDbApi.AutomaticallyDeleteInstanceFiles = true; string instanceName = Guid.NewGuid().ToString(); SqlLocalDbApi.CreateInstance(instanceName); Mock <ISqlLocalDbInstance> mock = new Mock <ISqlLocalDbInstance>(); mock.Setup((p) => p.Name).Returns(instanceName); ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName); Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null."); Assert.IsTrue(info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect."); ISqlLocalDbInstance instance = mock.Object; // Act SqlLocalDbInstance.Delete(instance); // Assert info = SqlLocalDbApi.GetInstanceInfo(instanceName); Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null."); Assert.IsFalse(info.Exists, "The SQL LocalDB instance was not deleted."); string path = Path.Combine(SqlLocalDbApi.GetInstancesFolderPath(), instanceName); Assert.IsFalse(Directory.Exists(path), "The instance folder was not deleted."); }); }
public void SqlLocalDbInstance_Constructor_If_Instance_Is_Started() { // Arrange Helpers.EnsureLocalDBInstalled(); string instanceName = Guid.NewGuid().ToString(); try { SqlLocalDbApi.CreateInstance(instanceName); try { string namedPipe = SqlLocalDbApi.StartInstance(instanceName); // Act SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName); // Assert Assert.IsTrue(target.IsRunning, "SqlLocalDbInstance.IsRunning is incorrect."); Assert.AreEqual(instanceName, target.Name, "SqlLocalDbInstance.Name is incorrect."); Assert.AreEqual(namedPipe, target.NamedPipe, "SqlLocalDbInstance.NamedPipe is incorrect."); } finally { SqlLocalDbApi.StopInstance(instanceName); } } finally { SqlLocalDbApi.DeleteInstance(instanceName); } }
public void Can_Test_Whether_Instances_Exist() { // Arrange using (var api = new SqlLocalDbApi(_loggerFactory)) { // Start the default instance to ensure it exists api.StartInstance(api.DefaultInstanceName); try { // Arrange string instanceName = api.DefaultInstanceName; // Act bool actual = api.InstanceExists(instanceName); // Assert actual.ShouldBeTrue(); // Arrange instanceName = Guid.NewGuid().ToString(); // Act actual = api.InstanceExists(instanceName); // Assert actual.ShouldBeFalse(); } finally { api.StopInstance(api.DefaultInstanceName); } } }
/// <summary> /// Shares the LocalDB instance using the specified name. /// </summary> /// <param name="sharedName">The name to use to share the instance.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="sharedName"/> is <see langword="null"/>. /// </exception> /// <exception cref="SqlLocalDbException"> /// The LocalDB instance could not be shared. /// </exception> public virtual void Share(string sharedName) { if (sharedName == null) { throw new ArgumentNullException(nameof(sharedName)); } try { SqlLocalDbApi.ShareInstance(_instanceName, sharedName); } catch (SqlLocalDbException e) { string message = SRHelper.Format( SR.SqlLocalDbInstance_ShareFailedFormat, _instanceName); Logger.Error(Logger.TraceEvent.ShareInstance, message); throw new SqlLocalDbException( message, e.ErrorCode, e.InstanceName, e); } }
/// <summary> /// Deletes the specified <see cref="ISqlLocalDbInstance"/> instance. /// </summary> /// <param name="instance">The LocalDB instance to delete.</param> /// <param name="throwIfNotFound"> /// Whether to throw an exception if the SQL LocalDB instance /// associated with <paramref name="instance"/> cannot be found. /// </param> /// <param name="deleteFiles"> /// Whether to delete the file(s) associated with the SQL LocalDB instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="instance"/> is <see langword="null"/>. /// </exception> /// <exception cref="SqlLocalDbException"> /// The SQL Server LocalDB instance specified by <paramref name="instance"/> could not be deleted. /// </exception> internal static void Delete(ISqlLocalDbInstance instance, bool throwIfNotFound, bool deleteFiles) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } try { SqlLocalDbApi.DeleteInstanceInternal(instance.Name, throwIfNotFound, deleteFiles); } catch (SqlLocalDbException ex) { string message = SRHelper.Format( SR.SqlLocalDbInstance_DeleteFailedFormat, instance.Name); Logger.Error(Logger.TraceEvent.DeleteFailed, message); throw new SqlLocalDbException( message, ex.ErrorCode, ex.InstanceName, ex); } }
public void Can_Delete_User_Instances() { // Arrange using (var actual = new SqlLocalDbApi(_loggerFactory)) { actual.CreateInstance(Guid.NewGuid().ToString()); IReadOnlyList <string> namesBefore = actual.GetInstanceNames(); // Act int deleted = actual.DeleteUserInstances(deleteFiles: true); // Assert deleted.ShouldBeGreaterThanOrEqualTo(1); IReadOnlyList <string> namesAfter = actual.GetInstanceNames(); int instancesDeleted = 0; foreach (string name in namesBefore) { if (!namesAfter.Contains(name)) { instancesDeleted++; } } instancesDeleted.ShouldBeGreaterThanOrEqualTo(1); } }
public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) { replacementsDictionary["$ext_safeprojectname$"] = RootWizard.GlobalDictionary["$ext_safeprojectname$"]; replacementsDictionary["$ext_projectname$"] = RootWizard.GlobalDictionary["$ext_projectname$"]; string localDBInstance = "v11.0"; var localDBInstances = SqlLocalDbApi.GetInstanceNames(); if (localDBInstances.IndexOf("MSSqlLocalDB") >= 0) { localDBInstance = "MSSqlLocalDB"; } else if (localDBInstances.IndexOf("v12.0") >= 0) { localDBInstance = "v12.0"; } else if (localDBInstances.IndexOf("v11.0") >= 0) { localDBInstance = "v11.0"; } else if (localDBInstances.Count > 0) { localDBInstance = localDBInstances[0]; } replacementsDictionary["connectionString=\"Data Source=(LocalDb)\\v11.0;"] = "connectionString=\"Data Source=(LocalDb)\\" + localDBInstance + ";"; }
public void Can_Create_SqlLocalDB_Instances_With_Different_Versions() { // Arrange using (var actual = new SqlLocalDbApi(_loggerFactory)) { foreach (string version in actual.Versions) { // Act ISqlLocalDbVersionInfo versionInfo = actual.GetVersionInfo(version); // Assert versionInfo.ShouldNotBeNull(); versionInfo.Name.ShouldStartWith(version.Split('.').First()); versionInfo.Exists.ShouldBeTrue(); versionInfo.Version.ShouldNotBeNull(); versionInfo.Version.ShouldNotBe(new Version()); string instanceName = Guid.NewGuid().ToString(); // Act ISqlLocalDbInstanceInfo instanceInfo = actual.CreateInstance(instanceName, version); // Assert instanceInfo.ShouldNotBeNull(); instanceInfo.Name.ShouldBe(instanceName); instanceInfo.Exists.ShouldBeTrue(); instanceInfo.IsRunning.ShouldBeFalse(); instanceInfo.LocalDbVersion.ShouldBe(versionInfo.Version); // Act (no Assert) actual.DeleteInstance(instanceName); actual.DeleteInstanceFiles(instanceName); } } }
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 void SqlLocalDbInstance_CreateConnectionStringBuilder_If_Instance_Started() { // Arrange Helpers.EnsureLocalDBInstalled(); string instanceName = Guid.NewGuid().ToString(); SqlLocalDbApi.CreateInstance(instanceName); try { SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName); target.Start(); try { // Act SqlConnectionStringBuilder result = target.CreateConnectionStringBuilder(); // Assert Assert.IsNotNull(result, "CreateConnection() returned null."); StringAssert.Contains(result.ConnectionString, target.NamedPipe, "SqlConnection.ConnectionString is incorrect."); } finally { SqlLocalDbApi.StopInstance(instanceName); } } finally { SqlLocalDbApi.DeleteInstance(instanceName); } }
/// <summary> /// Assets that the specified SQL LocalDB instance name is in the specified state of existence. /// </summary> /// <param name="instanceName">The instance name to assert for.</param> /// <param name="exists">Whether the specified instance name is expected to exist.</param> private static void AssertExistence(string instanceName, bool exists) { ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName); Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null."); Assert.AreEqual(exists, info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect."); }
public void SqlLocalDbInstance_Delete_Deletes_Instance() { // Arrange Helpers.EnsureLocalDBInstalled(); string instanceName = Guid.NewGuid().ToString(); SqlLocalDbApi.CreateInstance(instanceName); Mock <ISqlLocalDbInstance> mock = new Mock <ISqlLocalDbInstance>(); mock.Setup((p) => p.Name).Returns(instanceName); ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName); Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null."); Assert.IsTrue(info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect."); ISqlLocalDbInstance instance = mock.Object; // Act SqlLocalDbInstance.Delete(instance); // Assert info = SqlLocalDbApi.GetInstanceInfo(instanceName); Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null."); Assert.IsFalse(info.Exists, "The SQL LocalDB instance was not deleted."); string path = Path.Combine(SqlLocalDbApi.GetInstancesFolderPath(), instanceName); Assert.IsTrue(Directory.Exists(path), "The instance folder was deleted."); Assert.AreNotEqual(0, Directory.GetFiles(path).Length, "The instance files were deleted."); }
/// <summary> /// Ensures that SQL Server LocalDB is installed on the current machine. /// </summary> /// <remarks> /// Any unit test calling this method is marked as Inconclusive if SQL /// Server LocalDB is not installed on the local machine. /// </remarks> public static void EnsureLocalDBInstalled() { if (!SqlLocalDbApi.IsLocalDBInstalled()) { Assert.Inconclusive("SQL Server LocalDB is not installed on {0}.", Environment.MachineName); } }
public override void TestFixtureSetUp() { if (!SqlLocalDbApi.IsLocalDBInstalled()) { throw new Exception("LocalDB is not installed!"); } this.databaseName = "SqlTokenRepositoryTests" + Guid.NewGuid().ToString("N"); // Configure dapper to support datetime2 SqlMapper.AddTypeMap(typeof(DateTime), DbType.DateTime2); // Create test instance this.instance = TemporarySqlLocalDbInstance.Create(true); // Seed test data using (var connection = this.instance.CreateConnection()) { connection.Open(); connection.Execute($"CREATE DATABASE [{this.databaseName}]"); connection.Execute($"USE [{this.databaseName}]"); connection.Execute("CREATE TABLE AccessTokens (Id bigint NOT NULL PRIMARY KEY IDENTITY(1,1), ClientId VARCHAR(255) NOT NULL, Ticket VARCHAR(MAX) NOT NULL, Token VARCHAR(MAX) NOT NULL, Subject NVARCHAR(255) NOT NULL, RedirectUri VARCHAR(MAX), Scope NVARCHAR(MAX), ValidTo DATETIMEOFFSET, Created DATETIMEOFFSET)"); connection.Execute("CREATE TABLE RefreshTokens (Id bigint NOT NULL PRIMARY KEY IDENTITY(1,1), ClientId VARCHAR(255) NOT NULL, Token VARCHAR(MAX) NOT NULL, Subject NVARCHAR(255) NOT NULL, RedirectUri VARCHAR(MAX), Scope NVARCHAR(MAX), ValidTo DATETIMEOFFSET, Created DATETIMEOFFSET)"); connection.Execute("CREATE TABLE AuthorizationCodes (Id bigint NOT NULL PRIMARY KEY IDENTITY(1,1), ClientId VARCHAR(255) NOT NULL, Ticket VARCHAR(MAX) NOT NULL, Code VARCHAR(MAX) NOT NULL, Subject NVARCHAR(255) NOT NULL, Scope NVARCHAR(MAX), RedirectUri VARCHAR(MAX), ValidTo DATETIMEOFFSET, Created DATETIMEOFFSET)"); } base.TestFixtureSetUp(); }
public void Constructor_Initializes_Instance() { // Arrange var options = new SqlLocalDbOptions() { AutomaticallyDeleteInstanceFiles = true, Language = CultureInfo.GetCultureInfo("de-DE"), NativeApiOverrideVersion = "11.0", StopOptions = StopInstanceOptions.NoWait, StopTimeout = TimeSpan.FromSeconds(30), }; using (var actual = new SqlLocalDbApi(options, _loggerFactory)) { actual.AutomaticallyDeleteInstanceFiles.ShouldBe(options.AutomaticallyDeleteInstanceFiles); actual.DefaultInstanceName.ShouldNotBeNull(); actual.LanguageId.ShouldBeGreaterThan(0); actual.LatestVersion.ShouldNotBeNull(); actual.LoggerFactory.ShouldNotBeNull(); actual.StopOptions.ShouldBe(options.StopOptions); actual.StopTimeout.ShouldBe(options.StopTimeout); actual.Versions.ShouldNotBeNull(); actual.Versions.ShouldNotBeEmpty(); actual.Versions.ShouldBeUnique(); } }
public void SqlLocalDbInstance_Stop_Throws_If_An_Error_Occurs() { // Arrange Helpers.EnsureLocalDBInstalled(); string instanceName = Guid.NewGuid().ToString(); SqlLocalDbApi.CreateInstance(instanceName); SqlLocalDbInstance target; try { target = new SqlLocalDbInstance(instanceName); } finally { SqlLocalDbApi.DeleteInstance(instanceName); } // Act SqlLocalDbException error = ErrorAssert.Throws <SqlLocalDbException>( () => target.Stop()); // Assert Assert.AreEqual(SqlLocalDbErrors.UnknownInstance, error.ErrorCode, "SqlLocalDbException.ErrorCode is incorrect."); Assert.AreEqual(instanceName, error.InstanceName, "SqlLocalDbException.InstanceName is incorrect."); throw error; }
public void Throws_PlatformNotSupportedException() { // Arrange using (var actual = new SqlLocalDbApi(_loggerFactory)) { // Act and Assert Assert.Throws <PlatformNotSupportedException>(() => actual.CreateInstance("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.DeleteInstance("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.DeleteUserInstances()); Assert.Throws <PlatformNotSupportedException>(() => actual.GetDefaultInstance()); Assert.Throws <PlatformNotSupportedException>(() => actual.GetInstanceInfo("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.GetInstanceNames()); Assert.Throws <PlatformNotSupportedException>(() => actual.GetInstances()); Assert.Throws <PlatformNotSupportedException>(() => actual.GetOrCreateInstance("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.GetVersionInfo("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.InstanceExists("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.LatestVersion); Assert.Throws <PlatformNotSupportedException>(() => actual.ShareInstance("name", "sharedName")); Assert.Throws <PlatformNotSupportedException>(() => actual.ShareInstance("sid", "name", "sharedName")); Assert.Throws <PlatformNotSupportedException>(() => actual.StartInstance("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.StartTracing()); Assert.Throws <PlatformNotSupportedException>(() => actual.StopInstance("name")); Assert.Throws <PlatformNotSupportedException>(() => actual.StopTracing()); Assert.Throws <PlatformNotSupportedException>(() => actual.UnshareInstance("name")); } }
public void Throws_InvalidOperationException_If_SQL_LocalDB_Not_Installed() { // Arrange var options = new SqlLocalDbOptions(); var registry = Mock.Of <Interop.IRegistry>(); using (var actual = new SqlLocalDbApi(options, registry, _loggerFactory)) { // Act and Assert Assert.Throws <InvalidOperationException>(() => actual.CreateInstance("name")); Assert.Throws <InvalidOperationException>(() => actual.DeleteInstance("name")); Assert.Throws <InvalidOperationException>(() => actual.DeleteUserInstances()); Assert.Throws <InvalidOperationException>(() => actual.GetDefaultInstance()); Assert.Throws <InvalidOperationException>(() => actual.GetInstanceInfo("name")); Assert.Throws <InvalidOperationException>(() => actual.GetInstanceNames()); Assert.Throws <InvalidOperationException>(() => actual.GetInstances()); Assert.Throws <InvalidOperationException>(() => actual.GetOrCreateInstance("name")); Assert.Throws <InvalidOperationException>(() => actual.GetVersionInfo("name")); Assert.Throws <InvalidOperationException>(() => actual.InstanceExists("name")); Assert.Throws <InvalidOperationException>(() => actual.LatestVersion); Assert.Throws <InvalidOperationException>(() => actual.ShareInstance("name", "sharedName")); Assert.Throws <InvalidOperationException>(() => actual.StartInstance("name")); Assert.Throws <InvalidOperationException>(() => actual.StartTracing()); Assert.Throws <InvalidOperationException>(() => actual.StopInstance("name")); Assert.Throws <InvalidOperationException>(() => actual.StopTracing()); Assert.Throws <InvalidOperationException>(() => actual.UnshareInstance("name")); } }
public void Dispose() { this.sqlLocalDbApi?.Dispose(); this.sqlLocalDbApi = null; this.dbInstance = null; this.manager = null; }
public void DeleteInstanceInternal_Returns_False_If_ThrownIfNotFound_Is_False_And_Instance_Does_Not_Exist() { // Arrange using var actual = new SqlLocalDbApi(_loggerFactory); // Act and Assert actual.DeleteInstanceInternal("NotARealInstance", throwIfNotFound: false).ShouldBeFalse(); }
private void StartClick(object sender, EventArgs e) { Button obj = (Button)sender; WaitLabel(); SqlLocalDbApi.StartInstance(obj.Parent.Name); RefreshInstances(); }
public DacpacDbFixture() { Console.WriteLine("Running fixture constructor..."); _localDb = new SqlLocalDbApi(); DateTime nowUtc = DateTime.UtcNow; LocalDbInstanceName = $"{nowUtc.ToString("yyyyMMddHHmmssFFFFFFF")}"; //something mostly unique _instance = _localDb.GetOrCreateInstance(LocalDbInstanceName); _manager = _instance.Manage(); if (!_instance.IsRunning) { _manager.Start(); } var packagePath = "SimpleDb.dacpac"; var deployOptions = new DacDeployOptions { CreateNewDatabase = true, GenerateSmartDefaults = true, }; deployOptions.SqlCommandVariableValues["LoginName"] = DatabaseUserName; deployOptions.SqlCommandVariableValues["Password"] = DatabasePassword; SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(); csb.DataSource = _manager.NamedPipe; csb.IntegratedSecurity = true; var databaseName = "SimpleDbUnitTest"; var debugConnectionString = csb.ConnectionString; var dacServices = new DacServices(debugConnectionString); using (var package = DacPackage.Load(packagePath)) { dacServices.Deploy(package, databaseName, true, deployOptions); } csb.InitialCatalog = databaseName; //csb.UserID = DatabaseUserName; //csb.Password = DatabasePassword; //csb.IntegratedSecurity = false; ConnectionString = csb.ConnectionString; EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(); string nameOfConnectionString = "SimpleDbModel"; //NOTE: HACK: this must match the name of my Entity Framework model (the .edmx guy) string providerName = "System.Data.SqlClient"; ecsb.Provider = providerName; ecsb.ProviderConnectionString = csb.ConnectionString; ecsb.Metadata = $"res://*/{nameOfConnectionString}.csdl|res://*/{nameOfConnectionString}.ssdl|res://*/{nameOfConnectionString}.msl"; EfConnectionString = ecsb.ConnectionString; NumberOfTimesDacpacWasApplied++; Debug.WriteLine($">> The DACPAC has been applied {NumberOfTimesDacpacWasApplied} times"); Console.WriteLine($">> The DACPAC has been applied {NumberOfTimesDacpacWasApplied} times"); }