示例#1
0
        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);
                }
            }
        }
示例#2
0
 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"));
     }
 }
示例#3
0
        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);
        }
示例#4
0
        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);
            }
        }
示例#5
0
        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);
            }
        }
示例#6
0
        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);
                }
            }
        }
示例#7
0
        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"));
            }
        }
示例#8
0
        private void StopClick(object sender, EventArgs e)
        {
            Button obj = (Button)sender;

            WaitLabel();
            SqlLocalDbApi.StopInstance(obj.Parent.Name);
            RefreshInstances();
        }
示例#9
0
        private void Initialize(string instanceName, string databaseName)
        {
            this.databaseName = databaseName;
            this.instanceName = instanceName;

            var existing = SqlLocalDbApi.GetInstanceInfo(instanceName);

            if (existing.Exists)
            {
                if (existing.IsRunning)
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
                SqlLocalDbApi.DeleteInstance(instanceName);
            }


            ISqlLocalDbProvider provider = new SqlLocalDbProvider();

            this.instance = provider.GetOrCreateInstance(instanceName);

            instance.Start();


            var connectionStringBuilder = instance.CreateConnectionStringBuilder();

            using (var conn = new SqlConnection(connectionStringBuilder.ConnectionString))
            {
                var serverConnection = new ServerConnection(conn);

                // By default, LocalDB stores database files in the user's home folder. Messy for temporary test databases.
                // Store them in the user's temp folder instead.
                var testDatabasesDirectory = Path.Combine(Path.GetTempPath(), "TestDatabases");

                if (!Directory.Exists(testDatabasesDirectory))
                {
                    Directory.CreateDirectory(testDatabasesDirectory);
                }

                // Generate a unique name for our mdf file to avoid clashing with other ongoing test runs.
                var databaseFileNameRoot = string.Format("{0}_{1}_{2}", databaseName, DateTime.Now.ToString("yyyyMMdd_HHmmss"), Guid.NewGuid().ToString("N"));

                var mdfFileName = databaseFileNameRoot + ".mdf";
                var ldfFileName = databaseFileNameRoot + "_log.ldf";

                this.mdfFilePath = Path.Combine(testDatabasesDirectory, mdfFileName);
                this.ldfFilePath = Path.Combine(testDatabasesDirectory, ldfFileName);

                var sql = string.Format("CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')", databaseName, this.mdfFilePath);

                Console.WriteLine(string.Format("Creating database {0} at {1}", databaseName, this.mdfFilePath));
                serverConnection.ExecuteNonQuery(sql);
            }

            connectionStringBuilder.InitialCatalog = this.databaseName;
            this.connectionString = connectionStringBuilder.ConnectionString;
        }
示例#10
0
        public void Delete()
        {
            if (!Exists)
            {
                return;
            }

            SqlLocalDbApi.StopInstance(_databaseName);
            SqlLocalDbApi.DeleteInstance(_databaseName, true);
        }
示例#11
0
        public void SqlLocalDbInstance_CreateConnection_If_Instance_Is_Started_And_Returned_ConnectionStringBuilder_Is_Null()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            string instanceName = Guid.NewGuid().ToString();

            SqlLocalDbApi.CreateInstance(instanceName);

            try
            {
                var mock = new Mock <SqlLocalDbInstance>(instanceName)
                {
                    CallBase = true,
                };

                mock.Setup((p) => p.CreateConnectionStringBuilder())
                .Returns(null as SqlConnectionStringBuilder);

                SqlLocalDbInstance target = mock.Object;
                target.Start();

                try
                {
                    // Act
                    SqlConnection result = target.CreateConnection();

                    try
                    {
                        // Assert
                        Assert.IsNotNull(result, "CreateConnection() returned null.");
                        Assert.AreEqual(ConnectionState.Closed, result.State, "SqlConnection.State is incorrect.");
                        Assert.AreEqual(string.Empty, result.ConnectionString, "SqlConnection.ConnectionString is incorrect.");
                    }
                    finally
                    {
                        if (result != null)
                        {
                            result.Dispose();
                        }
                    }
                }
                finally
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
            }
            finally
            {
                SqlLocalDbApi.DeleteInstance(instanceName);
            }
        }
示例#12
0
        public void Methods_Validate_Parameters()
        {
            // Arrange
            TimeSpan timeout = TimeSpan.Zero.Add(TimeSpan.FromTicks(-1));

            using (var actual = new SqlLocalDbApi(_loggerFactory))
            {
                // Act and Assert
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.CreateInstance(null, "version"));
                Assert.Throws <ArgumentNullException>("version", () => actual.CreateInstance("instanceName", null));
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.DeleteInstance(null));
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.GetInstanceInfo(null));
                Assert.Throws <ArgumentNullException>("version", () => actual.GetVersionInfo(null));
                Assert.Throws <ArgumentNullException>("ownerSid", () => actual.ShareInstance(null, "instanceName", "sharedInstanceName"));
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.ShareInstance("ownerSid", null, "sharedInstanceName"));
                Assert.Throws <ArgumentNullException>("sharedInstanceName", () => actual.ShareInstance("ownerSid", "instanceName", null));
                Assert.Throws <ArgumentException>("instanceName", () => actual.ShareInstance("sid", string.Empty, "sharedInstanceName"));
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.StartInstance(null));
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.StopInstance(null, TimeSpan.Zero));
                Assert.Throws <ArgumentOutOfRangeException>("timeout", () => actual.StopInstance("instanceName", timeout)).ActualValue.ShouldBe(timeout);
                Assert.Throws <ArgumentNullException>("instanceName", () => actual.UnshareInstance(null));
            }
        }
示例#13
0
        private void CreateLocalDb()
        {
            string connection    = System.Configuration.ConfigurationManager.ConnectionStrings["BVCareManager.Properties.Settings.BVCareManagerConnectionString"].ConnectionString;
            string localDbstring = @"(LocalDB)\";

            int pFrom = connection.IndexOf(localDbstring) + localDbstring.Length;
            int pTo   = connection.LastIndexOf(";AttachDbFilename");

            string resultLocalDb = connection.Substring(pFrom, pTo - pFrom);

            #region SqlLocalDb Handle
            var localDb = new SqlLocalDbApi();

            ISqlLocalDbInstanceInfo localDbInstance = localDb.GetInstanceInfo(resultLocalDb);
            string localDbVersion = localDbInstance.LocalDbVersion.ToString().Substring(0, 2);

            if (localDbVersion == "0.")
            {
                try
                {
                    localDb.CreateInstance(resultLocalDb, "12.0");
                }
                catch
                {
                    MessageBox.Show("Phiên bản SQL Server LocalDB hiện tại không phù hợp. Hãy cài đặt phiên bản 12.0 (SQL Server 2014 Express LocalDb)");
                    Environment.Exit(1);
                }
            }
            else if (localDbVersion != "0." && localDbVersion != "12")
            {
                localDb.StopInstance(resultLocalDb);
                localDb.DeleteInstance(resultLocalDb);

                try
                {
                    localDb.CreateInstance(resultLocalDb, "12.0");
                }
                catch
                {
                    MessageBox.Show("Phiên bản SQL Server LocalDB hiện tại không phù hợp. Hãy cài đặt phiên bản 12.0 (SQL Server 2014 Express LocalDb)");
                    Environment.Exit(1);
                }
            }


            localDb.StartInstance(resultLocalDb);
            #endregion
        }
示例#14
0
 /// <summary>
 /// Create an instance of SQL Server LocalDB
 /// </summary>
 /// <param name="instanceName">instance name</param>
 /// <param name="version">version of SQL Serer LocalDB</param>
 /// <param name="isRecreate">If an instance of the same name exists, destroy it before creating it</param>
 public static void CreateInstance(string instanceName, string version, bool isRecreate)
 {
     if (SqlLocalDbApi.GetInstanceNames().Contains(instanceName))
     {
         if (isRecreate)
         {
             // For details of options, see API Reference : https://msdn.microsoft.com/ja-JP/library/hh234692.aspx
             SqlLocalDbApi.StopInstance(instanceName, StopInstanceOptions.KillProcess, new TimeSpan(0, 0, 30));
             SqlLocalDbApi.DeleteInstance(instanceName, true);
         }
         else
         {
             return;
         }
     }
     SqlLocalDbApi.CreateInstance(instanceName, version);
 }
示例#15
0
        public void SqlLocalDbInstance_Unshare_If_Instance_Is_Started()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();
            Helpers.EnsureUserIsAdmin();

            string instanceName = Guid.NewGuid().ToString();

            SqlLocalDbApi.CreateInstance(instanceName);

            try
            {
                SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName);
                target.Start();

                try
                {
                    string sharedName = Guid.NewGuid().ToString();
                    target.Share(sharedName);

                    ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName);

                    Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
                    Assert.IsTrue(info.IsShared, "ISqlLocalDbInstanceInfo.IsShared is incorrect.");
                    Assert.AreEqual(sharedName, info.SharedName, "ISqlLocalDbInstanceInfo.SharedName is incorrect.");

                    // Act
                    target.Unshare();

                    // Assert
                    info = SqlLocalDbApi.GetInstanceInfo(instanceName);

                    Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
                    Assert.IsFalse(info.IsShared, "ISqlLocalDbInstanceInfo.IsShared is incorrect.");
                    Assert.AreEqual(string.Empty, info.SharedName, "ISqlLocalDbInstanceInfo.SharedName is incorrect.");
                }
                finally
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
            }
            finally
            {
                SqlLocalDbApi.DeleteInstance(instanceName);
            }
        }
        public void Manager_Shares_And_Unshares_Instance()
        {
            // Act
            string instanceName = Guid.NewGuid().ToString();
            string sharedName   = Guid.NewGuid().ToString();

            using (var api = new SqlLocalDbApi(_loggerFactory))
            {
                api.CreateInstance(instanceName);

                try
                {
                    api.StartInstance(instanceName);

                    try
                    {
                        var instance = api.GetInstanceInfo(instanceName);

                        var manager = new SqlLocalDbInstanceManager(instance, api);

                        // Act
                        manager.Share(sharedName);

                        // Assert
                        instance.IsShared.ShouldBeTrue();

                        // Act
                        manager.Unshare();

                        // Assert
                        instance.IsShared.ShouldBeFalse();
                    }
                    catch (Exception)
                    {
                        api.StopInstance(instanceName);
                        throw;
                    }
                }
                catch (Exception)
                {
                    api.DeleteInstance(instanceName, deleteFiles: true);
                    throw;
                }
            }
        }
示例#17
0
        public void SqlLocalDbInstance_Stop_Stops_Instance()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            string instanceName = Guid.NewGuid().ToString();

            SqlLocalDbApi.CreateInstance(instanceName);

            try
            {
                SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName);
                target.Start();

                ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName);
                Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
                Assert.IsTrue(info.IsRunning, "The SQL LocalDB instance was not started.");

                Assert.IsTrue(target.IsRunning, "SqlLocalDbInstance.IsRunning is incorrect.");
                Assert.AreNotEqual(string.Empty, target.NamedPipe, "SqlLocalDbInstance.NamedPipe is incorrect.");

                // Act
                target.Stop();

                try
                {
                    // Assert
                    info = SqlLocalDbApi.GetInstanceInfo(instanceName);
                    Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
                    Assert.IsFalse(info.IsRunning, "ISqlLocalDbInstanceInfo.IsRunning is incorrect.");

                    Assert.IsFalse(target.IsRunning, "SqlLocalDbInstance.IsRunning is incorrect.");
                    Assert.AreEqual(string.Empty, target.NamedPipe, "SqlLocalDbInstance.NamedPipe is incorrect.");
                }
                finally
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
            }
            finally
            {
                SqlLocalDbApi.DeleteInstance(instanceName);
            }
        }
示例#18
0
        public void SqlLocalDbInstance_CreateConnection_If_Instance_Is_Started()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            string instanceName = Guid.NewGuid().ToString();

            SqlLocalDbApi.CreateInstance(instanceName);

            try
            {
                SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName);
                target.Start();

                try
                {
                    // Act
                    SqlConnection result = target.CreateConnection();

                    try
                    {
                        // Assert
                        Assert.IsNotNull(result, "CreateConnection() returned null.");
                        Assert.AreEqual(ConnectionState.Closed, result.State, "SqlConnection.State is incorrect.");
                        StringAssert.Contains(result.ConnectionString, target.NamedPipe, "SqlConnection.ConnectionString is incorrect.");
                    }
                    finally
                    {
                        if (result != null)
                        {
                            result.Dispose();
                        }
                    }
                }
                finally
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
            }
            finally
            {
                SqlLocalDbApi.DeleteInstance(instanceName);
            }
        }
示例#19
0
        /// <summary>
        /// Create an instance of SQL Server LocalDB
        /// </summary>
        /// <param name="instanceName">instance name</param>
        /// <param name="version">version of SQL Serer LocalDB</param>
        /// <param name="isRecreate">If an instance of the same name exists, destroy it before creating it</param>
        public static void CreateInstance(string instanceName, string version, bool isRecreate)
        {
            var localDb = new SqlLocalDbApi();

            if (localDb.GetInstanceNames().Contains(instanceName))
            {
                if (isRecreate)
                {
                    // For details of options, see API Reference : https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/sql-server-express-localdb-reference-instance-apis
                    localDb.StopInstance(instanceName, StopInstanceOptions.KillProcess, new TimeSpan(0, 0, 30));
                    localDb.DeleteInstance(instanceName, true);
                }
                else
                {
                    return;
                }
            }
            localDb.CreateInstance(instanceName, version);
        }
示例#20
0
        /// <summary>
        /// Initializes the database.
        /// </summary>
        /// <param name="connection"></param>
        public static INDbUnitTest Initialize(SqlConnection connection)
        {
            if (SqlLocalDbApi.GetInstanceInfo(InstanceName).Exists)
            {
                SqlLocalDbApi.StopInstance(InstanceName, TimeSpan.FromSeconds(10));
                SqlLocalDbApi.DeleteInstance(InstanceName, true);
            }

            SqlLocalDbApi.CreateInstance(InstanceName);

            var database = new SqlDbUnitTest(connection);

            database.Scripts.AddSingle($"{TestContext.CurrentContext.TestDirectory}\\Scripts\\InitSchema.sql");
            database.Scripts.AddWithWildcard($"{TestContext.CurrentContext.TestDirectory}\\Scripts", "InitTable_*.sql");
            database.ExecuteScripts();
            database.ReadXmlSchema(Resource.AsStream("Wikibus.xsd"));

            return(database);
        }
示例#21
0
        private void CleanupLocalDbDatabase()
        {
            SqlLocalDbApi.AutomaticallyDeleteInstanceFiles = true;
            SqlLocalDbApi.StopOptions = StopInstanceOptions.KillProcess;

            var localDbProvider     = new SqlLocalDbProvider();
            var localDbInstanceInfo = localDbProvider.GetInstances().FirstOrDefault(instance => instance.Name == DatabaseName);

            if (localDbInstanceInfo != null)
            {
                var localDbInstance = localDbProvider.GetInstance(DatabaseName);
                if (!localDbInstance.IsRunning)
                {
                    localDbInstance.Start();
                }
                this.CleanupMsSqlDatabase(localDbInstance.CreateConnectionStringBuilder().ConnectionString);
                SqlLocalDbApi.StopInstance(DatabaseName, TimeSpan.FromSeconds(20.0));
                SqlLocalDbApi.DeleteInstance(DatabaseName);
            }
        }
示例#22
0
        /// <summary>
        /// Stops the SQL Server LocalDB instance.
        /// </summary>
        /// <exception cref="SqlLocalDbException">
        /// The LocalDB instance could not be stopped.
        /// </exception>
        public void Stop()
        {
            try
            {
                SqlLocalDbApi.StopInstance(_instanceName);
                _namedPipe = string.Empty;
            }
            catch (SqlLocalDbException e)
            {
                string message = SRHelper.Format(
                    SR.SqlLocalDbInstance_StopFailedFormat,
                    _instanceName);

                Logger.Error(Logger.TraceEvent.StopInstance, message);

                throw new SqlLocalDbException(
                          message,
                          e.ErrorCode,
                          e.InstanceName,
                          e);
            }
        }
示例#23
0
        public void SqlLocalDbInstance_Unshare_Throws_If_An_Error_Occurs()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            string instanceName = Guid.NewGuid().ToString();

            SqlLocalDbApi.CreateInstance(instanceName);

            try
            {
                SqlLocalDbInstance target = new SqlLocalDbInstance(instanceName);
                target.Start();

                try
                {
                    // Act
                    SqlLocalDbException error = ErrorAssert.Throws <SqlLocalDbException>(
                        () => target.Unshare());

                    // Assert
                    Assert.AreEqual(SqlLocalDbErrors.InstanceNotShared, error.ErrorCode, "SqlLocalDbException.ErrorCode is incorrect.");
                    Assert.AreEqual(instanceName, error.InstanceName, "SqlLocalDbException.InstanceName is incorrect.");

                    throw error;
                }
                finally
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
            }
            finally
            {
                SqlLocalDbApi.DeleteInstance(instanceName);
            }
        }
示例#24
0
 /// <summary>
 /// Stops the specified instance of SQL Server LocalDB.
 /// </summary>
 /// <param name="instanceName">
 /// The name of the LocalDB instance to stop.
 /// </param>
 /// <param name="timeout">
 /// The amount of time to give the LocalDB instance to stop.
 /// If the value is <see cref="TimeSpan.Zero"/>, the method will
 /// return immediately and not wait for the instance to stop.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="instanceName"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="ArgumentOutOfRangeException">
 /// <paramref name="timeout"/> is less than <see cref="TimeSpan.Zero"/>.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// SQL Server LocalDB is not installed on the local machine.
 /// </exception>
 /// <exception cref="SqlLocalDbException">
 /// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be stopped.
 /// </exception>
 /// <remarks>
 /// The <paramref name="timeout"/> parameter is rounded to the nearest second.
 /// </remarks>
 public virtual void StopInstance(string instanceName, TimeSpan timeout)
 {
     SqlLocalDbApi.StopInstance(instanceName, timeout);
 }
示例#25
0
        public async Task Can_Manage_SqlLocalDB_Instances()
        {
            // Arrange
            using (var actual = new SqlLocalDbApi(_loggerFactory))
            {
                string instanceName = Guid.NewGuid().ToString();

                // Act
                ISqlLocalDbInstanceInfo instance = actual.GetInstanceInfo(instanceName);

                // Assert
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeFalse();
                instance.IsRunning.ShouldBeFalse();

                // Act and Assert
                actual.InstanceExists(instanceName).ShouldBeFalse();

                // Act
                instance = actual.CreateInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeTrue();
                instance.IsRunning.ShouldBeFalse();

                // Act
                string namedPipe = actual.StartInstance(instanceName);

                // Assert
                namedPipe.ShouldNotBeNullOrWhiteSpace();

                var builder = new SqlConnectionStringBuilder()
                {
                    DataSource = namedPipe
                };

                using (var connection = new SqlConnection(builder.ConnectionString))
                {
                    await connection.OpenAsync();
                }

                // Act
                instance = actual.GetInstanceInfo(instanceName);

                // Assert
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeTrue();
                instance.IsRunning.ShouldBeTrue();

                // Act and Assert
                actual.InstanceExists(instanceName).ShouldBeTrue();

                // Act
                actual.StopInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeTrue();
                instance.IsRunning.ShouldBeFalse();

                // Act
                actual.DeleteInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeFalse();
                instance.IsRunning.ShouldBeFalse();

                // Act and Assert
                actual.InstanceExists(instanceName).ShouldBeFalse();

                // Act (no Assert)
                actual.DeleteInstanceFiles(instanceName);
            }
        }
示例#26
0
        public void Can_Manage_SqlLocalDB_Instances()
        {
            // Arrange
            using (var actual = new SqlLocalDbApi(_loggerFactory))
            {
                string instanceName = Guid.NewGuid().ToString();

                // Act
                ISqlLocalDbInstanceInfo instance = actual.GetInstanceInfo(instanceName);

                // Assert
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeFalse();
                instance.IsRunning.ShouldBeFalse();

                // Act and Assert
                actual.InstanceExists(instanceName).ShouldBeFalse();

                // Act
                actual.CreateInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeTrue();
                instance.IsRunning.ShouldBeFalse();

                // Act
                actual.StartInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeTrue();
                instance.IsRunning.ShouldBeTrue();

                // Act and Assert
                actual.InstanceExists(instanceName).ShouldBeTrue();

                // Act
                actual.StopInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeTrue();
                instance.IsRunning.ShouldBeFalse();

                // Act
                actual.DeleteInstance(instanceName);

                // Assert
                instance = actual.GetInstanceInfo(instanceName);
                instance.ShouldNotBeNull();
                instance.Name.ShouldBe(instanceName);
                instance.Exists.ShouldBeFalse();
                instance.IsRunning.ShouldBeFalse();

                // Act and Assert
                actual.InstanceExists(instanceName).ShouldBeFalse();

                // Act (no Assert)
                actual.DeleteInstanceFiles(instanceName);
            }
        }