/// <summary>
 /// Imports the Azure Manifest to the given <paramref name="powershell"/> instance.
 /// </summary>
 /// <param name="powershell">An instance of the <see cref="PowerShell"/> object.</param>
 public static void ImportAzureModule(System.Management.Automation.PowerShell powershell)
 {
     // Import the test manifest file
     powershell.InvokeBatchScript(
         string.Format(@"Import-Module .\{0}", SqlDatabaseTestManifest));
     Assert.IsTrue(powershell.Streams.Error.Count == 0);
 }
        /// <summary>
        /// Creates the $credential object in the given <paramref name="powershell"/> instance with
        /// the given user name and password.
        /// </summary>
        /// <param name="powershell">An instance of the <see cref="PowerShell"/> object.</param>
        public static void CreateTestCredential(System.Management.Automation.PowerShell powershell, string username, string password)
        {
            password = password.Replace("$", "`$");

            // Create the test credential
            powershell.InvokeBatchScript(
                string.Format(@"$user = ""{0}""", username),
                string.Format(@"$pass = ""{0}"" | ConvertTo-SecureString -asPlainText -Force", password),
                @"$credential = New-Object System.Management.Automation.PSCredential($user, $pass)");
            Assert.IsTrue(powershell.Streams.Error.Count == 0);
        }
        /// <summary>
        /// Removes all existing db which name starting with PremiumTest on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void RemoveTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.RemoveTestPremiumDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-11: Remove database requests
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase $context | " +
                        @"? {$_.Name.contains(""NewAzureSqlPremiumDatabaseTests"")} " +
                        @"| Remove-AzureSqlDatabase -Context $context -Force");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();
            }
        }
        /// <summary>
        /// Common helper method for other tests to create a context.
        /// </summary>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void CreateServerContextSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.NewAzureSqlDatabaseServerContextWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-2: Create context with both ManageUrl and ServerName overriden
                        case 0:
                            // GetAccessToken call
                            DatabaseTestHelper.ValidateGetAccessTokenRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        case 1:
                            // Get server call
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        case 2:
                            // $metadata call
                            Assert.IsTrue(
                                actual.RequestUri.AbsoluteUri.EndsWith("$metadata"),
                                "Incorrect Uri specified for $metadata");
                            DatabaseTestHelper.ValidateHeadersForServiceRequest(
                                expected.RequestInfo,
                                actual);
                            Assert.AreEqual(
                                expected.RequestInfo.Headers[DataServiceConstants.AccessTokenHeader],
                                actual.Headers[DataServiceConstants.AccessTokenHeader],
                                "AccessToken header does not match");
                            Assert.AreEqual(
                                expected.RequestInfo.Cookies[DataServiceConstants.AccessCookie],
                                actual.Cookies[DataServiceConstants.AccessCookie],
                                "AccessCookie does not match");
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            UnitTestHelper.ImportSqlDatabaseModule(powershell);
            UnitTestHelper.CreateTestCredential(powershell);

            Collection<PSObject> serverContext;
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    serverContext = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{1} = New-AzureSqlDatabaseServerContext " +
                            @"-ServerName testserver " +
                            @"-ManageUrl {0} " +
                            @"-Credential $credential",
                            MockHttpServer.DefaultServerPrefixUri.AbsoluteUri,
                            contextVariable),
                        contextVariable);
                }
            }

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject contextPsObject = serverContext.Single();
            Assert.IsTrue(
                contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                "Expecting a ServerDataServiceSqlAuth object");
        }
        /// <summary>
        /// Common helper method for other tests to create a context for ESA server.
        /// </summary>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void CreateServerContextSqlAuthV12(
            System.Management.Automation.PowerShell powershell,
            string manageUrl,
            string username,
            string password,
            string contextVariable)
        {
            UnitTestHelper.ImportAzureModule(powershell);
            UnitTestHelper.CreateTestCredential(
                powershell,
                username,
                password);

            // Tell the sql auth factory to create a v22 context (skip checking sql version using select query).
            //
            SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v12;
            
            Collection<PSObject> serverContext;
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                serverContext = powershell.InvokeBatchScript(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        @"{1} = New-AzureSqlDatabaseServerContext " +
                        @"-ManageUrl {0} " +
                        @"-Credential $credential ",
                        manageUrl,
                        contextVariable),
                    contextVariable);
            }

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject contextPsObject = serverContext.Single();
            Assert.IsTrue(
                contextPsObject.BaseObject is TSqlConnectionContext,
                "Expecting a TSqlConnectionContext object");
        }
        /// <summary>
        /// Create continuous copy of testdb1 to partnersrv.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        /// <param name="copyVariable">The variable name that holds the copy object.</param>
        /// <param name="databaseName">The name of the database to copy.</param>
        public static void StartDatabaseContinuousCopyWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable,
            string copyVariable,
            string databaseName)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.StartAzureSqlDatabaseContinuousCopyWithSqlAuth." + databaseName);
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-1: Start database copy request
                        case 0:
                        case 1:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> databaseCopy;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    databaseCopy = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{0} = Start-AzureSqlDatabaseCopy " +
                            @"-Context $context " +
                            @"-DatabaseName {1} " +
                            @"-PartnerServer partnersrv " +
                            @"-ContinuousCopy",
                            copyVariable,
                            databaseName),
                        copyVariable);
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    databaseCopy.Single().BaseObject is Services.Server.DatabaseCopy,
                    "Expecting a Database Copy object");
                Services.Server.DatabaseCopy databaseCopyObj =
                    (Services.Server.DatabaseCopy)databaseCopy.Single().BaseObject;
                Assert.AreEqual(
                    "testserver",
                    databaseCopyObj.SourceServerName,
                    "Unexpected source server name");
                Assert.AreEqual(
                    databaseName,
                    databaseCopyObj.SourceDatabaseName,
                    "Unexpected source database name");
                Assert.AreEqual(
                    "partnersrv",
                    databaseCopyObj.DestinationServerName,
                    "Unexpected destination server name");
                Assert.AreEqual(
                    databaseName,
                    databaseCopyObj.DestinationDatabaseName,
                    "Unexpected destination database name");
                Assert.IsTrue(
                    databaseCopyObj.IsContinuous,
                    "Expected copy to be continuous");
            }
        }
        /// <summary>
        /// Wait for Continuous Copy operation to become catchup.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        /// <param name="dbCopyVariable">The variable name that holds the db copy object.</param>
        public static void WaitContinuousCopyCatchup(
            System.Management.Automation.PowerShell powershell,
            string contextVariable,
            string dbCopyVariable)
        {
            if (DatabaseTestHelper.CommonServiceBaseUri == null)
            {
                // Don't need to wait during playback
                return;
            }

            HttpSession testSession = new HttpSession();
            testSession.Messages = new HttpMessageCollection();
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    for (int i = 0; i < 20; i++)
                    {
                        Collection<PSObject> databaseCopy = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"{0} | Get-AzureSqlDatabaseCopy " +
                                @"-Context $context",
                                dbCopyVariable));
                        Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                        Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                        powershell.Streams.ClearStreams();

                        Assert.IsTrue(
                            databaseCopy.First().BaseObject is Services.Server.DatabaseCopy,
                            "Expecting a Database Copy object");
                        Services.Server.DatabaseCopy databaseCopyObj =
                            (Services.Server.DatabaseCopy)databaseCopy.Single().BaseObject;
                        if (databaseCopyObj.ReplicationStateDescription == "CATCH_UP")
                        {
                            break;
                        }

                        Thread.Sleep(TimeSpan.FromSeconds(1));
                    }
                }
            }
        }
        /// <summary>
        /// Helper function to create premium database in the powershell environment provided.
        /// </summary>
        /// <param name="powershell">The powershell environment</param>
        /// <param name="testSession">The test session</param>
        private static void TestCreatePremiumDatabase(System.Management.Automation.PowerShell powershell, HttpSession testSession)
        {
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> premiumDB_P1, PremiumDB_P2;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                        @" -Context $context" +
                        @" -ServiceObjectiveName ""P1""");

                    powershell.InvokeBatchScript(
                        @"$P2 = Get-AzureSqlDatabaseServiceObjective " +
                        @"-Context $context" +
                        @" -ServiceObjectiveName ""P2""");

                    premiumDB_P1 = powershell.InvokeBatchScript(
                        @"$premiumDB_P1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P1 " +
                        @"-Edition Premium " +
                        @"-ServiceObjective $P1 ");
                    premiumDB_P1 = powershell.InvokeBatchScript("$PremiumDB_P1");

                    powershell.InvokeBatchScript(
                        @"$PremiumDB_P2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Premium " +
                        @"-ServiceObjective $P2 " +
                        @"-MaxSizeGB 10 " +
                        @"-Force");
                    PremiumDB_P2 = powershell.InvokeBatchScript("$PremiumDB_P2");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    premiumDB_P1.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database databaseP1 =
                    (Services.Server.Database)premiumDB_P1.Single().BaseObject;
                Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P1", databaseP1.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P1");

                Assert.IsTrue(
                    PremiumDB_P2.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database databaseP2 =
                    (Services.Server.Database)PremiumDB_P2.Single().BaseObject;
                Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P2", databaseP2.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P2");

                Assert.AreEqual(
                    "Japanese_CI_AS",
                    databaseP2.CollationName,
                    "Expected collation to be Japanese_CI_AS");
                Assert.AreEqual("Premium", databaseP2.Edition, "Expected edition to be Premium");
                Assert.AreEqual(10, databaseP2.MaxSizeGB, "Expected max size to be 10 GB");
            }
        }
        /// <summary>
        /// Helper function to create the test databases.
        /// </summary>
        public static void CreateTestDatabasesWithCertAuth(System.Management.Automation.PowerShell powershell)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithCertAuth");

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2, database3;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Standard " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                    database3 = powershell.InvokeBatchScript(
                        @"$testdb3 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb3 " +
                        @"-MaxSizeBytes 104857600 " +
                        @"-Force",
                        @"$testdb3");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                database = database2.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Standard", 250, 268435456000L, "Japanese_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                database = database3.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Standard", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);
            }
        }
        /// <summary>
        /// Helper function to remove the test databases.
        /// </summary>
        public static void RemoveTestDatabasesWithCertAuth(System.Management.Automation.PowerShell powershell)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.RemoveTestDatabasesWithCertAuth");

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb1 " +
                        @"-Force");
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb2 " +
                        @"-Force");
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb3 " +
                        @"-Force");
                }

                powershell.Streams.ClearStreams();
            }
        }
        /// <summary>
        /// Create $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void CreateTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-2: Create testdb1
                        // Request 3-5: Create testdb2
                        // Request 6-8: Create testdb3
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2, database3;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Web " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                    database3 = powershell.InvokeBatchScript(
                        @"$testdb3 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb3 " +
                        @"-MaxSizeBytes 104857600 " +
                        @"-Force",
                        @"$testdb3");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                database = database2.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                database = database3.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Web", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

            }
        }
        /// <summary>
        /// Create $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void CreateTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-2: Create testdb1
                        // Request 3-5: Create testdb2
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Web " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    database1.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database database1Obj =
                    (Services.Server.Database)database1.Single().BaseObject;
                Assert.AreEqual("testdb1", database1Obj.Name, "Expected db name to be testdb1");

                Assert.IsTrue(
                    database2.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database database2Obj =
                    (Services.Server.Database)database2.Single().BaseObject;
                Assert.AreEqual("testdb2", database2Obj.Name, "Expected db name to be testdb2");
                Assert.AreEqual(
                    "Japanese_CI_AS",
                    database2Obj.CollationName,
                    "Expected collation to be Japanese_CI_AS");
                Assert.AreEqual("Web", database2Obj.Edition, "Expected edition to be Web");
                Assert.AreEqual(5, database2Obj.MaxSizeGB, "Expected max size to be 5 GB");
            }
        }
 /// <summary>
 /// Imports the Azure Manifest to the given <paramref name="powershell"/> instance.
 /// </summary>
 /// <param name="powershell">An instance of the <see cref="PowerShell"/> object.</param>
 public static void ImportAzureModule(System.Management.Automation.PowerShell powershell)
 {
     // Import the test manifest file
     powershell.InvokeBatchScript(@"Import-Module ..\..\..\..\Package\Debug\ServiceManagement\Azure\Azure.psd1");
     Assert.IsTrue(powershell.Streams.Error.Count == 0);
 }
        /// <summary>
        /// Helper method for wait for all copy to terminate.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void WaitForCopyTermination(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            if (DatabaseTestHelper.CommonServiceBaseUri == null)
            {
                // Don't need to wait during playback
                return;
            }

            HttpSession testSession = new HttpSession();
            testSession.Messages = new HttpMessageCollection();
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);

            Collection<PSObject> databaseCopies = null;
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    for (int i = 0; i < 20; i++)
                    {
                        databaseCopies = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"Get-AzureSqlDatabaseCopy " +
                                @"-Context {0}",
                                contextVariable));
                        if (databaseCopies.Count == 0)
                        {
                            break;
                        }

                        Thread.Sleep(TimeSpan.FromSeconds(1));
                    }
                }
            }

            Assert.AreEqual(0, databaseCopies.Count, "Expecting 0 Database Copy objects");
        }
        /// <summary>
        /// Create a new database in the given server context along with a continuous copy at the specified partner server
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        /// <param name="databaseVariable">The variable name that holds the database object.</param>
        /// <param name="databaseName">The name of the database to create and to copy.</param>
        /// <param name="partnerServer">The name of the partner server where the continuous copy goes to</param>
        public static void CreateDatabaseWithCopy(
            System.Management.Automation.PowerShell powershell,
            string contextVariable,
            string databaseVariable,
            string databaseName,
            string partnerServer)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateDatabaseWithCopy");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-1: Create database with copy
                        case 0:
                        case 1:
                        // Request 2-3: Get database copy
                        case 2:
                        case 3:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database, databaseCopy;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    database = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{0} = New-AzureSqlDatabaseWithCopy " +
                            @"-Context {1} " +
                            @"-DatabaseName {2} " +
                            @"-PartnerServer {3} " +
                            @"-Collation Japanese_CI_AS " +
                            @"-Edition Web " +
                            @"-MaxSizeGB 5 " +
                            @"-MaxLagInMinutes 15 " +
                            @"-Force",
                            databaseVariable,
                            contextVariable,
                            databaseName,
                            partnerServer),
                        databaseVariable);
                    databaseCopy = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"Get-AzureSqlDatabaseCopy " +
                            @"-Context {0} " +
                            @"-DatabaseName {1} " +
                            @"-PartnerServer {2}",
                            contextVariable,
                            databaseName,
                            partnerServer)
                        );
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Validate Database object returned
                Assert.IsTrue(
                    database.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database databaseObj =
                    (Services.Server.Database)database.Single().BaseObject;
                Assert.AreEqual(databaseName, databaseObj.Name, "Expected database name to match");
                Assert.AreEqual("Japanese_CI_AS", databaseObj.CollationName, "Expected collation to be Japanese_CI_AS");
                Assert.AreEqual("Web", databaseObj.Edition, "Expected edition to be Web");
                Assert.AreEqual(5, databaseObj.MaxSizeGB, "Expected max size to be 5 GB");

                // Validate DatabaseCopy object returned
                Assert.IsTrue(
                    databaseCopy.First().BaseObject is Services.Server.DatabaseCopy,
                    "Expected a DatabaseCopy object");
                Services.Server.DatabaseCopy databaseCopyObj =
                    (Services.Server.DatabaseCopy)databaseCopy.First().BaseObject;
                Assert.AreEqual("testserver", databaseCopyObj.SourceServerName, "Expected source server name to be testserver");
                Assert.AreEqual(
                    databaseName,
                    databaseCopyObj.SourceDatabaseName,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Expected source database name to be {0}",
                        databaseName)
                    );
                Assert.AreEqual(
                    partnerServer,
                    databaseCopyObj.DestinationServerName,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Expected destination server name to be {0}",
                        partnerServer)
                    );
                Assert.AreEqual(
                    databaseName,
                    databaseCopyObj.DestinationDatabaseName,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Expected destination database name to be {0}",
                        databaseName)
                    );
                Assert.IsTrue(databaseCopyObj.IsContinuous, "Expected copy to be continuous");
                Assert.AreEqual(15, databaseCopyObj.MaximumLag, "Expected maximum lag to be 15 minutes");
                Assert.AreEqual("CATCH_UP", databaseCopyObj.ReplicationStateDescription, "Expected replication state to be CATCH_UP");
            }
        }