Exemple #1
0
        public void SqlLocalDbProvider_CreateInstance_Specifies_No_Version_If_Default_Instance_Name_Specified_2014_2016()
        {
            // Arrange
            string instanceName = "MSSQLLocalDB";
            string version      = "1.2.3.4";

            Mock <ISqlLocalDbInstanceInfo> mockInfo = new Mock <ISqlLocalDbInstanceInfo>();

            mockInfo
            .SetupSequence((p) => p.Exists)
            .Returns(false)
            .Returns(true);

            Mock <ISqlLocalDbApi> mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.CreateInstance(instanceName, string.Empty))
            .Verifiable();

            mock.Setup((p) => p.GetInstanceInfo(instanceName))
            .Returns(mockInfo.Object)
            .Verifiable();

            ISqlLocalDbApi localDB = mock.Object;

            SqlLocalDbProvider target = new SqlLocalDbProvider(localDB)
            {
                Version = version,
            };

            // Act
            target.CreateInstance(instanceName);

            // Assert
            mock.Verify();
        }
Exemple #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlLocalDbInstance"/> class.
        /// </summary>
        /// <param name="instanceName">The name of the SQL Server LocalDB instance.</param>
        /// <param name="localDB">The <see cref="ISqlLocalDbApi"/> instance to use.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instanceName"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The LocalDB instance specified by <paramref name="instanceName"/> does not exist.
        /// </exception>
        /// <exception cref="SqlLocalDbException">
        /// The LocalDB instance specified by <paramref name="instanceName"/> could not be obtained.
        /// </exception>
        internal SqlLocalDbInstance(string instanceName, ISqlLocalDbApi localDB)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            Debug.Assert(localDB != null, "localDB cannot be  null.");

            ISqlLocalDbInstanceInfo info = localDB.GetInstanceInfo(instanceName);

            if (info == null || !info.Exists)
            {
                string message = SRHelper.Format(
                    SR.SqlLocalDbInstance_InstanceNotFoundFormat,
                    instanceName);

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

                throw new InvalidOperationException(message);
            }

            _instanceName = instanceName;
            _namedPipe    = info.NamedPipe;
        }
Exemple #3
0
        /// <summary>
        /// Creates a new DB instance with the given instance name.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="instanceName"></param>
        /// <returns></returns>
        ISqlLocalDbInstanceInfo GetOrCreateLocalDbInstance(ISqlLocalDbApi api, string instanceName)
        {
            // get existing instance
            var i = GetLocalDbInstance(api, instanceName);

            if (i != null)
            {
                if (i.IsRunning == false)
                {
                    var m = i.Manage();
                    m.Start();
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }

                return(i);
            }

            // retry get and create with synchronous region
            using (new Mutex(true, typeof(SqlDeploymentInstallLocalDbAction).FullName))
                using (new Mutex(true, typeof(SqlDeploymentInstallLocalDbAction).FullName + "::" + instanceName))
                {
                    i = GetLocalDbInstance(api, instanceName) ?? CreateLocalDbInstance(api, instanceName);
                    if (i.IsRunning == false)
                    {
                        var m = i.Manage();
                        m.Start();
                        Thread.Sleep(TimeSpan.FromSeconds(5));
                    }

                    return(i);
                }
        }
        public void TemporaryInstance_Deletes_Instance_If_Start_Fails()
        {
            // Arrange
            var mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.LatestVersion)
            .Returns("v99.9");

            mock.Setup((p) => p.CreateInstance(It.IsAny <string>(), "v99.9"))
            .Verifiable();

            mock.Setup((p) => p.StartInstance(It.IsAny <string>()))
            .Throws <PlatformNotSupportedException>();

            mock.Setup((p) => p.DeleteInstance(It.IsAny <string>()))
            .Verifiable();

            ISqlLocalDbApi api = mock.Object;

            using (TemporarySqlLocalDbInstance target = api.CreateTemporaryInstance())
            {
                // Act and Assert
                Assert.Throws <PlatformNotSupportedException>(() => target.GetInstanceInfo());
            }

            mock.Verify();
        }
        public void TemporaryInstance_Ignores_Exception_If_Stop_Fails(int errorCode)
        {
            // Arrange
            var mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.LatestVersion)
            .Returns("v99.9");

            mock.Setup((p) => p.CreateInstance(It.IsAny <string>(), "v99.9"))
            .Verifiable();

            mock.Setup((p) => p.StartInstance(It.IsAny <string>()))
            .Verifiable();

            mock.Setup((p) => p.StopInstance(It.IsAny <string>(), null))
            .Throws(new SqlLocalDbException("Error", errorCode))
            .Verifiable();

            mock.Setup((p) => p.DeleteInstance(It.IsAny <string>()))
            .Verifiable();

            ISqlLocalDbApi api = mock.Object;

            // Act
            using (TemporarySqlLocalDbInstance target = api.CreateTemporaryInstance())
            {
                target.GetInstanceInfo();
            }

            // Assert
            mock.Verify();
        }
Exemple #6
0
        private static void AddTodoContext(IServiceProvider serviceProvider, DbContextOptionsBuilder options)
        {
            // Check that SQL Server LocalDB is installed
            ISqlLocalDbApi localDB = serviceProvider.GetRequiredService <ISqlLocalDbApi>();

            if (!localDB.IsLocalDBInstalled())
            {
                throw new NotSupportedException("SQL LocalDB is not installed.");
            }

            // Get the configured SQL LocalDB instance to store the TODO items in, creating it if it does not exist
            IConfiguration          config   = serviceProvider.GetRequiredService <IConfiguration>();
            ISqlLocalDbInstanceInfo instance = localDB.GetOrCreateInstance(config["SqlLocalDbInstance"]);

            // Ensure that the SQL LocalDB instance is running and start it if not already running
            if (!instance.IsRunning)
            {
                instance.Manage().Start();
            }

            // Get the SQL connection string to use to connect to the LocalDB instance
            string connectionString = instance.GetConnectionString();

            options.UseSqlServer(connectionString);
        }
        public static void Share_Throws_If_SqlLocalDbEception_Is_Thrown()
        {
            // Act
            var innerException = new SqlLocalDbException(
                "It broke",
                123,
                "Name");

            var mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.ShareInstance(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Throws(innerException);

            ISqlLocalDbInstanceInfo instance = CreateInstance();
            ISqlLocalDbApi          api      = mock.Object;

            var target = new SqlLocalDbInstanceManager(instance, api);

            var exception = Assert.Throws <SqlLocalDbException>(() => target.Share("SharedName"));

            exception.ErrorCode.ShouldBe(123);
            exception.InstanceName.ShouldBe("Name");
            exception.Message.ShouldBe("Failed to share SQL LocalDB instance 'Name'.");
            exception.InnerException.ShouldBeSameAs(innerException);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlLocalDbInstance"/> class.
        /// </summary>
        /// <param name="instanceName">The name of the SQL Server LocalDB instance.</param>
        /// <param name="localDB">The <see cref="ISqlLocalDbApi"/> instance to use.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instanceName"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The LocalDB instance specified by <paramref name="instanceName"/> does not exist.
        /// </exception>
        /// <exception cref="SqlLocalDbException">
        /// The LocalDB instance specified by <paramref name="instanceName"/> could not be obtained.
        /// </exception>
        internal SqlLocalDbInstance(string instanceName, ISqlLocalDbApi localDB)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            Debug.Assert(localDB != null, "localDB cannot be  null.");

            ISqlLocalDbInstanceInfo info = localDB.GetInstanceInfo(instanceName);

            if (info == null || !info.Exists)
            {
                string message = SRHelper.Format(
                    SR.SqlLocalDbInstance_InstanceNotFoundFormat,
                    instanceName);

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

                throw new InvalidOperationException(message);
            }

            _instanceName = instanceName;
            _namedPipe = info.NamedPipe;
        }
        public void Use_With_Dependency_Injection()
        {
            // Register with SQL LocalDB services
            var services = new ServiceCollection()
                           .AddLogging((builder) => builder.AddXUnit(OutputHelper))
                           .AddSqlLocalDB();

            IServiceProvider serviceProvider = services.BuildServiceProvider();

            using (IServiceScope scope = serviceProvider.CreateScope())
            {
                ISqlLocalDbApi             localDB  = scope.ServiceProvider.GetService <ISqlLocalDbApi>();
                ISqlLocalDbInstanceInfo    instance = localDB.GetDefaultInstance();
                ISqlLocalDbInstanceManager manager  = instance.Manage();

                if (!instance.IsRunning)
                {
                    manager.Start();
                }

                using (SqlConnection connection = instance.CreateConnection())
                {
                    connection.Open();

                    // Use the SQL connection...
                }
            }
        }
Exemple #10
0
        public void GetVersions_Throws_If_Api_Is_Null()
        {
            // Arrange
            ISqlLocalDbApi api = null;

            // Act and Assert
            Assert.Throws <ArgumentNullException>("api", () => api.GetVersions());
        }
Exemple #11
0
        public void CreateTemporaryInstance_Throws_If_Api_Is_Null()
        {
            // Arrange
            ISqlLocalDbApi api = null;

            // Act and Assert
            Assert.Throws <ArgumentNullException>("api", () => api.CreateTemporaryInstance());
        }
Exemple #12
0
        public void GetOrCreateInstance_Throws_If_Api_Is_Null()
        {
            // Arrange
            ISqlLocalDbApi api          = null;
            string         instanceName = "SomeName";

            // Act and Assert
            Assert.Throws <ArgumentNullException>("api", () => api.GetOrCreateInstance(instanceName));
        }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlLocalDbProvider"/> class.
        /// </summary>
        /// <param name="localDB">The instance of <see cref="ISqlLocalDbApi"/> to use.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="localDB"/> is <see langword="null"/>.
        /// </exception>
        public SqlLocalDbProvider(ISqlLocalDbApi localDB)
        {
            if (localDB == null)
            {
                throw new ArgumentNullException(nameof(localDB));
            }

            _localDB = localDB;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlLocalDbProvider"/> class.
        /// </summary>
        /// <param name="localDB">The instance of <see cref="ISqlLocalDbApi"/> to use.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="localDB"/> is <see langword="null"/>.
        /// </exception>
        public SqlLocalDbProvider(ISqlLocalDbApi localDB)
        {
            if (localDB == null)
            {
                throw new ArgumentNullException(nameof(localDB));
            }

            _localDB = localDB;
        }
        public void GetOrCreateInstance_Throws_If_InstanceName_Is_Null()
        {
            // Arrange
            ISqlLocalDbApi api          = Mock.Of <ISqlLocalDbApi>();
            string?        instanceName = null;

            // Act and Assert
            Assert.Throws <ArgumentNullException>("instanceName", () => api.GetOrCreateInstance(instanceName !));
        }
Exemple #16
0
        /// <summary>
        /// Gets the default SQL Local DB instance.
        /// </summary>
        /// <param name="api">The <see cref="ISqlLocalDbApi"/> to use to get the default instance.</param>
        /// <returns>
        /// The default SQL Local DB instance.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="api"/> is <see langword="null"/>.
        /// </exception>
        public static ISqlLocalDbInstanceInfo GetDefaultInstance(this ISqlLocalDbApi api)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }

            return(api.GetOrCreateInstance(api.DefaultInstanceName));
        }
Exemple #17
0
        /// <summary>
        /// Creates a new local instance, either by finding an existing instance, or generating a temporary instance.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="instanceName"></param>
        /// <returns></returns>
        ISqlLocalDbInstanceInfo CreateLocalDbInstance(ISqlLocalDbApi api, string instanceName)
        {
            if (api.GetOrCreateInstance(instanceName) is ISqlLocalDbInstanceInfo info && info.Exists)
            {
                return(info);
            }

            throw new InvalidOperationException("Unable to create instance.");
        }
Exemple #18
0
        public void SqlLocalDbInstance_Constructor_Throws_If_LocalDb_Returns_Null()
        {
            // Arrange
            string         instanceName = Guid.NewGuid().ToString();
            ISqlLocalDbApi localDB      = Mock.Of <ISqlLocalDbApi>();

            // Act and Assert
            throw ErrorAssert.Throws <InvalidOperationException>(
                      () => new SqlLocalDbInstance(instanceName, localDB));
        }
Exemple #19
0
        public void SqlLocalDbProvider_Constructor_Throws_If_LocalDB_Is_Null()
        {
            // Arrange
            ISqlLocalDbApi localDB = null;

            // Act and Assert
            throw ErrorAssert.Throws <ArgumentNullException>(
                      () => new SqlLocalDbProvider(localDB),
                      "localDB");
        }
Exemple #20
0
        public void SqlLocalDbProvider_Constructor_Uses_Specified_LocalDB_Instance()
        {
            // Arrange
            ISqlLocalDbApi localDB = Mock.Of <ISqlLocalDbApi>();

            // Act
            SqlLocalDbProvider target = new SqlLocalDbProvider(localDB);

            // Assert
            Assert.AreSame(localDB, target.LocalDB, "SqlLocalDbProvider.LocalDB is incorrect.");
        }
Exemple #21
0
        public void SqlLocalDbProvider_CreateInstance_Throws_If_No_Instance_Info_From_Api()
        {
            // Arrange
            ISqlLocalDbApi localDB = Mock.Of <ISqlLocalDbApi>();

            SqlLocalDbProvider target       = new SqlLocalDbProvider(localDB);
            string             instanceName = Guid.NewGuid().ToString();

            // Act and Assert
            throw ErrorAssert.Throws <InvalidOperationException>(
                      () => target.CreateInstance(instanceName));
        }
        public static IServiceCollection AddSqlLocalDbInstance(this IServiceCollection services, Action <TOptions> setupAction = null)
        {
            if (setupAction != null)
            {
                services.Configure(setupAction);
            }

            services.AddSingleton <ISqlLocalDbInstanceInfo>(provider =>
            {
                var options = provider.GetService <IOptions <TOptions> >() ?? new OptionsWrapper <TOptions>(provider.GetRequiredService <TOptions>());

                ISqlLocalDbApi localDB = provider.GetRequiredService <ISqlLocalDbApi>();

                if (!localDB.IsLocalDBInstalled())
                {
                    throw new NotSupportedException("SQL LocalDB is not installed.");
                }

                // Get the configured SQL LocalDB instance to store the TODO items in, creating it if it does not exist

                ISqlLocalDbInstanceInfo instance = localDB.GetOrCreateInstance(options?.Value?.InstanceName ?? "SqlLocalDb-DefaultDb");

                // Ensure that the SQL LocalDB instance is running and start it if not already running
                if (!instance.IsRunning)
                {
                    instance.Manage().Start();
                }

                // Get the SQL connection string to use to connect to the LocalDB instance
                //string connectionString = instance.GetConnectionString();
                return(instance);
            });

            services.AddSingleton <Server>(provider =>
            {
                var options = provider.GetService <IOptions <TOptions> >() ?? new OptionsWrapper <TOptions>(provider.GetRequiredService <TOptions>());

                var instance      = provider.GetRequiredService <ISqlLocalDbInstanceInfo>();
                string connString = instance.GetConnectionString();
                //var conn = new SqlConnection(connString);
                var builder            = instance.CreateConnectionStringBuilder();
                builder.InitialCatalog = options?.Value.DatabaseName ?? "";
                var conn = new SqlConnection(builder.ConnectionString);

                var server = new Server(new ServerConnection(conn));
                return(server);
            });


            return(services);
        }
        public void Unshare_Unshares_Instance()
        {
            // Act
            var mock = new Mock <ISqlLocalDbApi>();
            ISqlLocalDbInstanceInfo instance = CreateInstance();
            ISqlLocalDbApi          api      = mock.Object;

            var target = new SqlLocalDbInstanceManager(instance, api);

            // Act
            target.Unshare();

            // Assert
            mock.Verify((p) => p.UnshareInstance("Name"), Times.Once());
        }
        public void Stop_Stops_Instance()
        {
            // Act
            var mock = new Mock <ISqlLocalDbApi>();
            ISqlLocalDbInstanceInfo instance = CreateInstance();
            ISqlLocalDbApi          api      = mock.Object;

            var target = new SqlLocalDbInstanceManager(instance, api);

            // Act
            target.Stop();

            // Assert
            mock.Verify((p) => p.StopInstance("Name", null), Times.Once());
        }
Exemple #25
0
        /// <summary>
        /// Gets the instance with the existing name.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="instanceName"></param>
        /// <returns></returns>
        ISqlLocalDbInstanceInfo GetLocalDbInstance(ISqlLocalDbApi api, string instanceName)
        {
            try
            {
                if (api.GetInstanceInfo(instanceName) is ISqlLocalDbInstanceInfo info && info.Exists)
                {
                    return(info);
                }
            }
            catch (InvalidOperationException)
            {
                // ignore
            }

            return(null);
        }
        public static void Share_Shares_Instance()
        {
            // Act
            string sharedName = Guid.NewGuid().ToString();

            var mock = new Mock <ISqlLocalDbApi>();
            ISqlLocalDbInstanceInfo instance = CreateInstance();
            ISqlLocalDbApi          api      = mock.Object;

            var target = new SqlLocalDbInstanceManager(instance, api);

            // Act
            target.Share(sharedName);

            // Assert
            mock.Verify((p) => p.ShareInstance(It.IsNotNull <string>(), "Name", sharedName), Times.Once());
        }
Exemple #27
0
        public SqlServerTests()
        {
            _localDb = new SqlLocalDbApiWrapper();
            ISqlLocalDbProvider provider = new SqlLocalDbProvider();
            string instanceName          = Guid.NewGuid().ToString();

            _instance = provider.CreateInstance(instanceName);

            _instance.Start();

            _connection = _instance.CreateConnection();
            _connection.Open();

            _database = new Database(_connection);

            _database.Execute("create database [SqlServerTests]");
        }
Exemple #28
0
        /// <summary>
        /// Shares the specified SQL Server LocalDB instance with other users of the computer,
        /// using the specified shared name for the current Windows user.
        /// </summary>
        /// <param name="api">The <see cref="ISqlLocalDbApi"/> to use to share the instance.</param>
        /// <param name="instanceName">The private name for the LocalDB instance to share.</param>
        /// <param name="sharedInstanceName">The shared name for the LocalDB instance to share.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="api"/>, <paramref name="instanceName"/> or <paramref name="sharedInstanceName"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="PlatformNotSupportedException">
        /// The method is called from a non-Windows operating system.
        /// </exception>
        public static void ShareInstance(this ISqlLocalDbApi api, string instanceName, string sharedInstanceName)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }

            SqlLocalDbApi.EnsurePlatformSupported();

            string ownerSid;

            using (var identity = WindowsIdentity.GetCurrent())
            {
                ownerSid = identity.User.Value;
            }

            api.ShareInstance(ownerSid, instanceName, sharedInstanceName);
        }
        public static void ShareInstance_Uses_SID_For_Current_User()
        {
            // Arrange
            string instanceName       = "SomeName";
            string sharedInstanceName = "SomeSharedName";

            var mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.ShareInstance(It.IsNotNull <string>(), instanceName, sharedInstanceName))
            .Verifiable();

            ISqlLocalDbApi api = mock.Object;

            // Act
            api.ShareInstance(instanceName, sharedInstanceName);

            // Assert
            mock.Verify();
        }
        public void GetOrCreateInstance_Returns_The_Default_Instance_If_It_Exists(string instanceName)
        {
            // Arrange
            var mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.DefaultInstanceName)
            .Returns("Blah");

            mock.Setup((p) => p.GetInstanceInfo(instanceName))
            .Returns(CreateInstanceInfo(exists: true));

            ISqlLocalDbApi api = mock.Object;

            // Act
            ISqlLocalDbInstanceInfo actual = api.GetOrCreateInstance(instanceName);

            // Assert
            actual.ShouldNotBeNull();
            actual.Exists.ShouldBeTrue();
        }
Exemple #31
0
        /// <summary>
        /// Returns information about the installed SQL Server LocalDB version(s).
        /// </summary>
        /// <param name="api">The <see cref="ISqlLocalDbApi"/> to use to enumerate the installed versions.</param>
        /// <returns>
        /// An <see cref="IReadOnlyList{ISqlLocalDbVersionInfo}"/> containing information
        /// about the SQL Server LocalDB version(s) installed on the current machine.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="api"/> is <see langword="null"/>.
        /// </exception>
        public static IReadOnlyList <ISqlLocalDbVersionInfo> GetVersions(this ISqlLocalDbApi api)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }

            IReadOnlyList <string> versionNames = api.Versions;
            var versions = new List <ISqlLocalDbVersionInfo>(versionNames?.Count ?? 0);

            if (versionNames != null)
            {
                foreach (string version in versionNames)
                {
                    ISqlLocalDbVersionInfo info = api.GetVersionInfo(version);
                    versions.Add(info);
                }
            }

            return(versions);
        }
        public static void TemporaryInstance_Ignores_Exception_If_Delete_Fails(int errorCode)
        {
            // Arrange
            if (!SqlLocalDbApi.IsWindows)
            {
                // HACK Theories dont seem to work correctly with subclasses now
                // so cannot make a derived class for a "Windows-only" theory.
                return;
            }

            // Arrange
            var mock = new Mock <ISqlLocalDbApi>();

            mock.Setup((p) => p.LatestVersion)
            .Returns("v99.9");

            mock.Setup((p) => p.CreateInstance(It.IsAny <string>(), "v99.9"))
            .Verifiable();

            mock.Setup((p) => p.StartInstance(It.IsAny <string>()))
            .Verifiable();

            mock.Setup((p) => p.StopInstance(It.IsAny <string>(), null))
            .Verifiable();

            mock.Setup((p) => p.DeleteInstance(It.IsAny <string>()))
            .Throws(new SqlLocalDbException("Error", errorCode))
            .Verifiable();

            ISqlLocalDbApi api = mock.Object;

            // Act
            using (TemporarySqlLocalDbInstance target = api.CreateTemporaryInstance())
            {
                target.GetInstanceInfo();
            }

            // Assert
            mock.Verify();
        }
        /// <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>
 /// Initializes a new instance of the <see cref="SqlLocalDbProvider"/> class.
 /// </summary>
 public SqlLocalDbProvider()
 {
     _localDB = SqlLocalDbApiWrapper.Instance;
 }