public async Task TestCancelDatabaseOperation()
        {
            string testPrefix = "sqldblistcanceloperation-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup               resourceGroup = context.CreateResourceGroup("West Europe");
                Server                      server        = context.CreateServer(resourceGroup, "westeurope");
                SqlManagementClient         sqlClient     = context.GetClient <SqlManagementClient>();
                Dictionary <string, string> tags          = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                // Create database only required parameters
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.S0),
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Start updateslo operation
                //
                var dbUpdateResponse = sqlClient.Databases.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P2),
                    Location = server.Location,
                });
                TestUtilities.Wait(TimeSpan.FromSeconds(3));

                // Get the updateslo operation
                //
                AzureOperationResponse <IPage <DatabaseOperation> > response = sqlClient.DatabaseOperations.ListByDatabaseWithHttpMessagesAsync(
                    resourceGroup.Name, server.Name, dbName).Result;
                Assert.Equal(response.Response.StatusCode, HttpStatusCode.OK);
                IList <DatabaseOperation> responseObject = response.Body.ToList();
                Assert.Equal(responseObject.Count(), 1);

                // Cancel the database updateslo operation
                //
                string requestId = responseObject[0].Name;
                sqlClient.DatabaseOperations.Cancel(resourceGroup.Name, server.Name, dbName, Guid.Parse(requestId));

                CloudException ex = await Assert.ThrowsAsync <CloudException>(() => sqlClient.GetPutOrPatchOperationResultAsync(dbUpdateResponse.Result, new Dictionary <string, List <string> >(), CancellationToken.None));

                Assert.Contains("Long running operation failed with status 'Canceled'", ex.Message);

                // Make sure the database is not updated due to cancel operation
                //
                var dbGetResponse = sqlClient.Databases.Get(resourceGroup.Name, server.Name, dbName);
                Assert.Equal(dbGetResponse.ServiceLevelObjective, ServiceObjectiveName.S0);
            }
        }
        public void TestDatabaseRestore()
        {
            // Warning: This test takes around 20 minutes to run in record mode.

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();

                Database db1 = CreateDatabaseAndWaitUntilBackupCreated(
                    sqlClient,
                    resourceGroup,
                    server,
                    dbName: SqlManagementTestUtilities.GenerateName());

                // Delete the original database
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db1.Name);

                // Wait until the final backup is created and the restorable dropped database exists.
                // This could be up to 10 minutes after the database is deleted, and the database must already
                // have a backup (which was accomplished by the previous wait period). Let's wait up to 15
                // just to give it a little more room.
                IEnumerable <RestorableDroppedDatabase> droppedDatabases;
                DateTime startTime = DateTime.UtcNow;
                TimeSpan timeout   = TimeSpan.FromMinutes(15);
                do
                {
                    droppedDatabases = sqlClient.RestorableDroppedDatabases.ListByServer(resourceGroup.Name, server.Name);

                    if (droppedDatabases.Any())
                    {
                        // Dropped database now exists. Exit polling loop.
                        break;
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(30));
                    }
                } while (DateTime.UtcNow < startTime + timeout);

                // Assert that we found a restorable db before timeout ended.
                Assert.True(droppedDatabases.Any(), "No dropped databases were found after waiting for " + timeout);

                // The original database should now exist as a restorable dropped database
                var droppedDatabase = droppedDatabases.Single();
                Assert.StartsWith(db1.Name, droppedDatabase.Name);

                // Restore the deleted database using restorable dropped database id
                //   In new DB API (Version 2017), if use restorable dropped database id, need to specify the RestorableDroppedDatabaseId,
                //       which include the source database id and deletion time
                var db3Name  = SqlManagementTestUtilities.GenerateName();
                var db3Input = new Database
                {
                    Location   = server.Location,
                    CreateMode = CreateMode.Restore,
                    RestorableDroppedDatabaseId = droppedDatabase.Id,
                    RestorePointInTime          = droppedDatabase.EarliestRestoreDate // optional param for Restore
                };
                var db3Response = sqlClient.Databases.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, db3Name, db3Input);

                // Concurrently (to make test faster) also restore the deleted database using its original id
                // and deletion date
                var db4Name  = SqlManagementTestUtilities.GenerateName();
                var db4Input = new Database
                {
                    Location                   = server.Location,
                    CreateMode                 = CreateMode.Restore,
                    SourceDatabaseId           = db1.Id,
                    SourceDatabaseDeletionDate = droppedDatabase.DeletionDate,
                    RestorePointInTime         = droppedDatabase.EarliestRestoreDate // optional param for Restore
                };
                var db4Response = sqlClient.Databases.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, db4Name, db4Input);

                // Wait for completion
                sqlClient.GetPutOrPatchOperationResultAsync(db3Response.Result, new Dictionary <string, List <string> >(), CancellationToken.None).Wait();
                sqlClient.GetPutOrPatchOperationResultAsync(db4Response.Result, new Dictionary <string, List <string> >(), CancellationToken.None).Wait();
            }
        }
        public async Task TestCancelUpdateElasticPoolOperation()
        {
            /* *
             * In this test we only test the cancel operation on resize pool from Premium to Premium
             *    since currently we only support Cancel pool resize operation on Premium <-> Premium
             * */
            string testPrefix = "sqlelasticpoollistcanceloperation-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup               resourceGroup = context.CreateResourceGroup("West Europe");
                Server                      server        = context.CreateServer(resourceGroup, "westeurope");
                SqlManagementClient         sqlClient     = context.GetClient <SqlManagementClient>();
                Dictionary <string, string> tags          = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                // Create a premium elastic pool with required parameters
                string epName  = SqlManagementTestUtilities.GenerateName();
                var    epInput = new ElasticPool()
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ElasticPoolEdition.Premium + "Pool"),
                    Tags     = tags,
                };
                var elasticPool = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput);
                SqlManagementTestUtilities.ValidateElasticPool(epInput, elasticPool, epName);
                Assert.NotNull(elasticPool);

                // Update elastic pool to Premium with 250 DTU
                var epUpdateReponse = sqlClient.ElasticPools.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, epName, new ElasticPool()
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ElasticPoolEdition.Premium + "Pool")
                    {
                        Capacity = 250,
                    },
                    Tags = tags
                });

                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(15));
                }

                // Get the pool update operation for new added properties on elastic pool operations: ETA, Operation Description and IsCancellable
                //   Expected they have null value since not been updated by operation progress
                AzureOperationResponse <IPage <ElasticPoolOperation> > response = sqlClient.ElasticPoolOperations.ListByElasticPoolWithHttpMessagesAsync(resourceGroup.Name, server.Name, epName).Result;
                Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
                IList <ElasticPoolOperation> responseObject = response.Body.ToList();
                Assert.Single(responseObject);
                Assert.NotNull(responseObject[0].PercentComplete);
                Assert.NotNull(responseObject[0].EstimatedCompletionTime);
                Assert.NotNull(responseObject[0].Description);
                Assert.NotNull(responseObject[0].IsCancellable);

                // Cancel the elastic pool update operation
                string requestId = responseObject[0].Name;
                sqlClient.ElasticPoolOperations.Cancel(resourceGroup.Name, server.Name, epName, Guid.Parse(requestId));
                CloudException ex = await Assert.ThrowsAsync <CloudException>(() => sqlClient.GetPutOrPatchOperationResultAsync(epUpdateReponse.Result, new Dictionary <string, List <string> >(), CancellationToken.None));

                Assert.Contains("OperationCancelled", ex.Body.Code);

                // Make sure the elastic pool is not updated due to cancel operation
                var epGetResponse = sqlClient.ElasticPools.Get(resourceGroup.Name, server.Name, epName);
                Assert.Equal(125, epGetResponse.Dtu);
                Assert.Equal(DatabaseEdition.Premium, epGetResponse.Edition);
            }
        }
Exemple #4
0
        public void TestLongTermRetentionV2Crud()
        {
            // MANUAL INSTRUCTIONS
            // Create a server and database and fill in the appropriate information below
            // Set the weekly retention on the database so that the first backup gets picked up
            // Wait about 18 hours until it gets properly copied and you see the backup when run get backups
            //
            string locationName      = "";
            string resourceGroupName = "";
            string serverName        = "";
            string databaseName      = "";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                Database            database  = sqlClient.Databases.Get(resourceGroupName, serverName, databaseName);

                // Set the retention policy to two weeks for the weekly retention policy
                //
                Microsoft.Azure.Management.Sql.Models.BackupLongTermRetentionPolicy parameters = new Microsoft.Azure.Management.Sql.Models.BackupLongTermRetentionPolicy(weeklyRetention: "P2W");
                var policyResult = sqlClient.BackupLongTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, databaseName, parameters).Result;
                sqlClient.GetPutOrPatchOperationResultAsync(policyResult, new Dictionary <string, List <string> >(), CancellationToken.None).Wait();

                // Get the policy and verify the weekly policy is two weeks
                //
                Microsoft.Azure.Management.Sql.Models.BackupLongTermRetentionPolicy policy = sqlClient.BackupLongTermRetentionPolicies.Get(resourceGroupName, serverName, databaseName);
                Assert.Equal(parameters.WeeklyRetention, policy.WeeklyRetention);

                // Get the backups under the location, server, and database. Assert there is at least one backup for each call.
                //
                IPage <LongTermRetentionBackup> backups = sqlClient.LongTermRetentionBackups.ListByLocation(locationName);
                Assert.True(backups.Count() >= 1);
                backups = sqlClient.LongTermRetentionBackups.ListByServer(locationName, serverName);
                Assert.True(backups.Count() >= 1);
                backups = sqlClient.LongTermRetentionBackups.ListByDatabase(locationName, serverName, databaseName);
                Assert.True(backups.Count() >= 1);

                // Get a specific backup using the previous call
                //
                LongTermRetentionBackup backup = sqlClient.LongTermRetentionBackups.Get(locationName, serverName, databaseName, backups.First().Name);
                Assert.NotNull(backup);

                // Restore the backup
                //
                Database restoredDatabase = sqlClient.Databases.CreateOrUpdate(
                    resourceGroupName, serverName, databaseName: SqlManagementTestUtilities.GenerateName(),
                    parameters: new Database
                {
                    Location   = locationName,
                    CreateMode = CreateMode.RestoreLongTermRetentionBackup,
                    LongTermRetentionBackupResourceId = backup.Id
                });

                // Delete the backup.
                //
                var deleteResult = sqlClient.LongTermRetentionBackups.BeginDeleteWithHttpMessagesAsync(locationName, serverName, databaseName, backup.Name).Result;
                sqlClient.GetPutOrPatchOperationResultAsync(deleteResult, new Dictionary <string, List <string> >(), CancellationToken.None).Wait();

                // Verify the backup is gone.
                //
                try
                {
                    sqlClient.LongTermRetentionBackups.Get(locationName, serverName, databaseName, backup.Name);
                }
                catch (CloudException e)
                {
                    Assert.Contains(string.Format("'{0}' was not found.", backup.Name), e.Message);
                }

                // Set the retention policy back to one week for the weekly retention policy
                //
                parameters   = new Microsoft.Azure.Management.Sql.Models.BackupLongTermRetentionPolicy(weeklyRetention: "P1W");
                policyResult = sqlClient.BackupLongTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, databaseName, parameters).Result;
                sqlClient.GetPutOrPatchOperationResultAsync(policyResult, new Dictionary <string, List <string> >(), CancellationToken.None).Wait();

                // Get the policy and verify the weekly policy is two weeks
                //
                policy = sqlClient.BackupLongTermRetentionPolicies.Get(resourceGroupName, serverName, databaseName);
                Assert.Equal(parameters.WeeklyRetention, policy.WeeklyRetention);
            }
        }