/// <summary>
        /// Tests that the instances reported by the specified <see cref="ISqlLocalDbProvider"/> are valid.
        /// </summary>
        /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to test the instances for.</param>
        private static void TestInstances(ISqlLocalDbProvider provider)
        {
            IList <ISqlLocalDbInstanceInfo> instances = provider.GetInstances();

            Assert.IsNotNull(instances, "GetInstances() returned null.");
            CollectionAssert.AllItemsAreNotNull(instances.ToArray(), "GetInstances() returned a null item.");

            bool usingSqlServer2012 = NativeMethods.NativeApiVersion == new Version(11, 0);

            string[] defaultInstanceNamesForSqlServer2012 = new string[]
            {
                "v12.0",
            };

            foreach (ISqlLocalDbInstanceInfo instanceInfo in instances)
            {
                Assert.IsNotNull(instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is null.", instanceInfo.Name);

                if (usingSqlServer2012 && defaultInstanceNamesForSqlServer2012.Contains(instanceInfo.Name, StringComparer.Ordinal))
                {
                    // The SQL LocalDB 2012 Instance API reports the name as 'v12.0' instead of 'MSSQLLocalDB',
                    // which then if queried states that it does not exist (because it doesn't actually exist)
                    // under that name.  In this case, skip this instance from being tested. We could fudge this
                    // in the wrapper itself, but that's probably not the best idea as the default instance name
                    // may change again in SQL Server 2016.
                    continue;
                }

                Assert.AreNotEqual(string.Empty, instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is incorrect.", instanceInfo.Name);
                Assert.IsFalse(instanceInfo.ConfigurationCorrupt, "ISqlLocalDbInstanceInfo.ConfigurationCorrupt is incorrect for instance '{0}'.", instanceInfo.Name);

                // The automatic instance may not yet exist on a clean machine
                if (!instanceInfo.IsAutomatic)
                {
                    Assert.IsTrue(instanceInfo.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect for instance '{0}'.", instanceInfo.Name);
                }

                Assert.IsNotNull(instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is null for instance '{0}'.", instanceInfo.Name);
                Assert.AreNotEqual(string.Empty, instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is incorrect for instance '{0}'.", instanceInfo.Name);

                // These values are only populated if the instance exists
                if (instanceInfo.Exists)
                {
                    Assert.IsNotNull(instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is null for instance '{0}'.", instanceInfo.Name);
                    Assert.AreNotEqual(string.Empty, instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is incorrect for instance '{0}'.", instanceInfo.Name);
                }
            }
        }
Example #2
0
        /// <summary>
        /// Gets an SQL Local DB instance with the specified name if it exists, otherwise a new instance with the specified name is created.
        /// </summary>
        /// <param name="value">The <see cref="ISqlLocalDbProvider"/> to use to get or create the instance.</param>
        /// <param name="instanceName">The name of the SQL Server LocalDB instance to get or create.</param>
        /// <returns>
        /// An SQL Local DB instance with the name specified by <paramref name="instanceName"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="value"/> or <paramref name="instanceName"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// <paramref name="value"/> returns <see langword="null"/> when queried for instances.
        /// </exception>
        public static ISqlLocalDbInstance GetOrCreateInstance(this ISqlLocalDbProvider value, string instanceName)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            bool instanceExists = false;

            if (SqlLocalDbApi.IsDefaultInstanceName(instanceName))
            {
                // The default instance is always listed, even if it does not exist,
                // so need to query that separately to verify whether to get or create.
                instanceExists = SqlLocalDbApi.GetInstanceInfo(instanceName).Exists;
            }
            else
            {
                // This approach is used otherwise for testability
                IList <ISqlLocalDbInstanceInfo> instances = value.GetInstances();

                if (instances != null)
                {
                    // Instance names in SQL Local DB are case-insensitive
                    instanceExists = instances
                                     .Where((p) => p != null)
                                     .Where((p) => string.Equals(p.Name, instanceName, StringComparison.OrdinalIgnoreCase))
                                     .Any();
                }
            }

            if (instanceExists)
            {
                return(value.GetInstance(instanceName));
            }
            else
            {
                return(value.CreateInstance(instanceName));
            }
        }
        /// <summary>
        /// Tests that the instances reported by the specified <see cref="ISqlLocalDbProvider"/> are valid.
        /// </summary>
        /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to test the instances for.</param>
        private static void TestInstances(ISqlLocalDbProvider provider)
        {
            IList<ISqlLocalDbInstanceInfo> instances = provider.GetInstances();

            Assert.IsNotNull(instances, "GetInstances() returned null.");
            CollectionAssert.AllItemsAreNotNull(instances.ToArray(), "GetInstances() returned a null item.");

            bool usingSqlServer2012 = NativeMethods.NativeApiVersion == new Version(11, 0);

            string[] defaultInstanceNamesForSqlServer2012 = new string[]
            {
                "v12.0",
            };

            foreach (ISqlLocalDbInstanceInfo instanceInfo in instances)
            {
                Assert.IsNotNull(instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is null.", instanceInfo.Name);

                if (usingSqlServer2012 && defaultInstanceNamesForSqlServer2012.Contains(instanceInfo.Name, StringComparer.Ordinal))
                {
                    // The SQL LocalDB 2012 Instance API reports the name as 'v12.0' instead of 'MSSQLLocalDB',
                    // which then if queried states that it does not exist (because it doesn't actually exist)
                    // under that name.  In this case, skip this instance from being tested. We could fudge this
                    // in the wrapper itself, but that's probably not the best idea as the default instance name
                    // may change again in SQL Server 2016.
                    continue;
                }

                Assert.AreNotEqual(string.Empty, instanceInfo.Name, "ISqlLocalDbInstanceInfo.Name is incorrect.", instanceInfo.Name);
                Assert.IsFalse(instanceInfo.ConfigurationCorrupt, "ISqlLocalDbInstanceInfo.ConfigurationCorrupt is incorrect for instance '{0}'.", instanceInfo.Name);

                // The automatic instance may not yet exist on a clean machine
                if (!instanceInfo.IsAutomatic)
                {
                    Assert.IsTrue(instanceInfo.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect for instance '{0}'.", instanceInfo.Name);
                }

                Assert.IsNotNull(instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is null for instance '{0}'.", instanceInfo.Name);
                Assert.AreNotEqual(string.Empty, instanceInfo.LocalDbVersion, "ISqlLocalDbInstanceInfo.LocalDbVersion is incorrect for instance '{0}'.", instanceInfo.Name);

                // These values are only populated if the instance exists
                if (instanceInfo.Exists)
                {
                    Assert.IsNotNull(instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is null for instance '{0}'.", instanceInfo.Name);
                    Assert.AreNotEqual(string.Empty, instanceInfo.OwnerSid, "ISqlLocalDbInstanceInfo.OwnerSid is incorrect for instance '{0}'.", instanceInfo.Name);
                }
            }
        }
        /// <summary>
        /// Tests the lifecycle of SQL LocalDB instances.
        /// </summary>
        /// <param name="localDB">The <see cref="ISqlLocalDbApi"/> to use.</param>
        /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use.</param>
        private static void TestInstanceLifecycle(ISqlLocalDbApi localDB, ISqlLocalDbProvider provider)
        {
            string instanceName = Guid.NewGuid().ToString();
            string sharedInstanceName = string.Empty;

            ISqlLocalDbInstance instance = provider.CreateInstance(instanceName);

            instance.Start();

            try
            {
                bool currentUserIsAdmin = Helpers.IsCurrentUserAdmin();

                if (currentUserIsAdmin)
                {
                    sharedInstanceName = Guid.NewGuid().ToString();
                    instance.Share(sharedInstanceName);

                    // Restart the instance so it listens on the new shared name's pipe
                    instance.Restart();
                }

                try
                {
                    ISqlLocalDbInstanceInfo info = provider.GetInstances()
                        .Where((p) => string.Equals(p.Name, instanceName, StringComparison.Ordinal))
                        .FirstOrDefault();

                    Assert.IsNotNull(info, "GetInstances() did not return the created instance.");
                    Assert.AreEqual(sharedInstanceName, info.SharedName, "ISqlLocalDbInstanceInfo.SharedName is incorrect.");

                    using (SqlConnection connection = instance.CreateConnection())
                    {
                        Assert.IsNotNull(connection, "CreateConnection() returned null.");
                        TestConnection(connection);
                    }

                    if (currentUserIsAdmin)
                    {
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                        builder.DataSource = string.Format(CultureInfo.InvariantCulture, "(localdb)\\.\\{0}", sharedInstanceName);
                        builder.IntegratedSecurity = true;

                        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                        {
                            TestConnection(connection);
                        }
                    }
                }
                finally
                {
                    if (currentUserIsAdmin)
                    {
                        instance.Unshare();
                    }
                }
            }
            finally
            {
                instance.Stop();
                localDB.DeleteInstance(instance.Name);
            }
        }
        /// <summary>
        /// Tests the lifecycle of SQL LocalDB instances.
        /// </summary>
        /// <param name="localDB">The <see cref="ISqlLocalDbApi"/> to use.</param>
        /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use.</param>
        private static void TestInstanceLifecycle(ISqlLocalDbApi localDB, ISqlLocalDbProvider provider)
        {
            string instanceName       = Guid.NewGuid().ToString();
            string sharedInstanceName = string.Empty;

            ISqlLocalDbInstance instance = provider.CreateInstance(instanceName);

            instance.Start();

            try
            {
                bool currentUserIsAdmin = Helpers.IsCurrentUserAdmin();

                if (currentUserIsAdmin)
                {
                    sharedInstanceName = Guid.NewGuid().ToString();
                    instance.Share(sharedInstanceName);

                    // Restart the instance so it listens on the new shared name's pipe
                    instance.Restart();
                }

                try
                {
                    ISqlLocalDbInstanceInfo info = provider.GetInstances()
                                                   .Where((p) => string.Equals(p.Name, instanceName, StringComparison.Ordinal))
                                                   .FirstOrDefault();

                    Assert.IsNotNull(info, "GetInstances() did not return the created instance.");
                    Assert.AreEqual(sharedInstanceName, info.SharedName, "ISqlLocalDbInstanceInfo.SharedName is incorrect.");

                    using (SqlConnection connection = instance.CreateConnection())
                    {
                        Assert.IsNotNull(connection, "CreateConnection() returned null.");
                        TestConnection(connection);
                    }

                    if (currentUserIsAdmin)
                    {
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
                        {
                            DataSource         = $@"(localdb)\.\{sharedInstanceName}",
                            IntegratedSecurity = true
                        };

                        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                        {
                            TestConnection(connection);
                        }
                    }
                }
                finally
                {
                    if (currentUserIsAdmin)
                    {
                        instance.Unshare();
                    }
                }
            }
            finally
            {
                instance.Stop();
                localDB.DeleteInstance(instance.Name);
            }
        }