Пример #1
0
        /// <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);
            }
        }