public static void ValidateManagedDatabaseEx(ManagedDatabase expected, ManagedDatabase actual)
        {
            Assert.Equal(expected.Name, actual.Name);
            Assert.NotNull(actual.CreationDate);
            Assert.NotNull(actual.Id);
            Assert.NotNull(actual.Type);

            // Old 2014-04-01 apis return en-us location friendly name, e.g. "Japan East",
            // newer apis return locaion id e.g. "japaneast". This makes comparison
            // logic annoying until we have a newer api-version for database.
            //Assert.Equal(expected.Location, actual.Location);

            if (!string.IsNullOrEmpty(expected.Collation))
            {
                Assert.Equal(expected.Collation, actual.Collation);
            }
            else
            {
                Assert.NotNull(actual.Collation);
            }

            if (expected.Location != null)
            {
                Assert.Equal(expected.Location, actual.Location);
            }
            else
            {
                Assert.NotNull(actual.Location);
            }
        }
        public void TestRecoverInstanceDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // Use exising CI/database, otherwise 10 hours are needed for waiting new created database is replicated in paired cluster.
                // In worst case, more than 1 day is needed for waiting
                string resourceGroup       = "restore-rg";
                string managedInstanceName = "restorerunnermanagedserverwus";
                var    managedInstance     = sqlClient.ManagedInstances.Get(resourceGroup, managedInstanceName);

                // List recoveralbe database
                var listResponse = sqlClient.RecoverableManagedDatabases.ListByInstance(resourceGroup, managedInstance.Name);

                // Get more than 1 database
                Assert.True(listResponse.Count() > 0);
                RecoverableManagedDatabase sourceManagedDb = listResponse.First();
                String targetDbName = SqlManagementTestUtilities.GenerateName();
                var    targetInput  = new ManagedDatabase()
                {
                    Location              = managedInstance.Location,
                    CreateMode            = "Recovery",
                    RecoverableDatabaseId = sourceManagedDb.Id
                };

                // Issue recovery request
                var targetDb = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup, managedInstanceName, targetDbName,
                                                                         targetInput);

                Assert.NotNull(targetDb);
                SqlManagementTestUtilities.ValidateManagedDatabase(targetInput, targetDb, targetDbName);
                sqlClient.ManagedDatabases.Delete(resourceGroup, managedInstance.Name, targetDb.Name);
            }
        }
Пример #3
0
        public async Task Get()
        {
            #region Snippet:Managing_Sql_GetAManagedDatabases
            ManagedDatabaseCollection managedDatabaseCollection = managedInstance.GetManagedDatabases();

            ManagedDatabase managedDatabase = await managedDatabaseCollection.GetAsync("myManagedDatabase");

            Console.WriteLine(managedDatabase.Data.Name);
            #endregion
        }
Пример #4
0
        public async Task DeleteManagedDatabases()
        {
            #region Snippet:Managing_Sql_DeleteAManagedDatabases
            ManagedDatabaseCollection managedDatabaseCollection = managedInstance.GetManagedDatabases();

            ManagedDatabase managedDatabase = await managedDatabaseCollection.GetAsync("myManagedInstance");

            await managedDatabase.DeleteAsync(true);

            #endregion
        }
Пример #5
0
        public void TestManagedInstanceLongTermRetentionResourceGroupBasedCrud()
        {
            // MANUAL TEST INSTRUCTIONS
            // PlayBack Mode:
            //     Make sure information below matches what is gets recorded in Session Records
            // Record Mode:
            //     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
            //     OR
            //     Use existing instance/database that already has LTR backups
            //
            string locationName        = "southeastasia";
            string resourceGroupName   = "sdk-test-rg";
            string managedInstanceName = "sdk-test-mi";
            string databaseName        = "test";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                //ManagedDatabase database = sqlClient.ManagedDatabases.Get(resourceGroupName, managedInstanceName, databaseName);

                // Get the backups under the location, server, and database. Assert there is at least one backup for each call.
                //
                IPage <ManagedInstanceLongTermRetentionBackup> backups = sqlClient.LongTermRetentionManagedInstanceBackups.ListByResourceGroupLocation(resourceGroupName, locationName);
                Assert.True(backups.Count() >= 1);
                backups = sqlClient.LongTermRetentionManagedInstanceBackups.ListByResourceGroupInstance(resourceGroupName, locationName, managedInstanceName);
                Assert.True(backups.Count() >= 1);
                backups = sqlClient.LongTermRetentionManagedInstanceBackups.ListByResourceGroupDatabase(resourceGroupName, locationName, managedInstanceName, databaseName);
                Assert.True(backups.Count() >= 1);

                // Get a specific backup using the previous call
                //
                ManagedInstanceLongTermRetentionBackup backup = sqlClient.LongTermRetentionManagedInstanceBackups.GetByResourceGroup(resourceGroupName, locationName, managedInstanceName, databaseName, backups.First().Name);
                Assert.NotNull(backup);

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

                // Delete the backup.
                //
                sqlClient.LongTermRetentionManagedInstanceBackups.DeleteByResourceGroupWithHttpMessagesAsync(resourceGroupName, locationName, managedInstanceName, databaseName, backup.Name);
            }
        }
Пример #6
0
        public void TestGetAndListManagedDatabase()
        {
            string testPrefix = "sqlcrudtest-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // Update with values from a current MI on the region
                //
                string resourceGroup       = "testclrg";
                string managedInstanceName = "tdstage-haimb-dont-delete-3";

                // Get MI
                var managedInstance = sqlClient.ManagedInstances.Get(resourceGroup, managedInstanceName);

                // Create some small databases to run the get/List tests on.
                ManagedDatabase[] mngdDatabases = SqlManagementTestUtilities.CreateManagedDatabasesAsync(
                    sqlClient, resourceGroup, managedInstance, testPrefix, 4).Result;

                // Organize into a dictionary for better lookup later
                IDictionary <string, ManagedDatabase> inputs = mngdDatabases.ToDictionary(
                    keySelector: d => d.Name,
                    elementSelector: d => d);

                // Get each database and compare to the results of create database
                //
                foreach (var db in inputs)
                {
                    var response = sqlClient.ManagedDatabases.Get(resourceGroup, managedInstance.Name, db.Key);
                    SqlManagementTestUtilities.ValidateManagedDatabaseEx(db.Value, response);
                }

                // List all databases
                //
                var listResponse = sqlClient.ManagedDatabases.ListByInstance(resourceGroup, managedInstance.Name);

                // Check that all created Managed Databases are created
                foreach (var db in inputs.Keys)
                {
                    var actualDbList = listResponse.Where(d => d.Name.Equals(db));
                    Assert.True(actualDbList.Count() == 1);
                    ManagedDatabase actualDb = actualDbList.FirstOrDefault();
                    SqlManagementTestUtilities.ValidateManagedDatabase(inputs[db], actualDb, db);
                }

                foreach (var db in inputs.Keys)
                {
                    sqlClient.ManagedDatabases.Delete(resourceGroup, managedInstance.Name, db);
                }
            }
        }
Пример #7
0
        public async Task CreateOrUpdate()
        {
            #region Snippet:Managing_Sql_CreateAManagedDatabases
            ManagedDatabaseCollection managedDatabaseCollection = managedInstance.GetManagedDatabases();

            ManagedDatabaseData data = new ManagedDatabaseData(AzureLocation.WestUS2)
            {
            };
            string databaseName       = "myDatabase";
            var    managedDatabaseLro = await managedDatabaseCollection.CreateOrUpdateAsync(true, databaseName, data);

            ManagedDatabase managedDatabase = managedDatabaseLro.Value;
            #endregion
        }
Пример #8
0
        public void TestCreateDropManagedDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // Update with values from a current MI on the region
                //
                string resourceGroup       = "testclrg";
                string managedInstanceName = "tdstage-haimb-dont-delete-3";

                //Get MI
                var managedInstance = sqlClient.ManagedInstances.Get(resourceGroup, managedInstanceName);

                Dictionary <string, string> tags = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                // Create database only required parameters
                //
                string mdbName = SqlManagementTestUtilities.GenerateName();
                var    mdb1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup, managedInstance.Name, mdbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(mdb1);

                // Create a database with all parameters specified
                //
                mdbName = SqlManagementTestUtilities.GenerateName();
                var mdb2Input = new ManagedDatabase()
                {
                    Location   = managedInstance.Location,
                    Collation  = SqlTestConstants.DefaultCollation,
                    Tags       = tags,
                    CreateMode = "Default"
                };
                var mdb2 = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup, managedInstance.Name, mdbName, mdb2Input);
                Assert.NotNull(mdb2);
                SqlManagementTestUtilities.ValidateManagedDatabase(mdb2Input, mdb2, mdbName);

                sqlClient.ManagedDatabases.Delete(resourceGroup, managedInstance.Name, mdb1.Name);
                sqlClient.ManagedDatabases.Delete(resourceGroup, managedInstance.Name, mdb2.Name);
            }
        }
Пример #9
0
        public async Task GetIfExists()
        {
            #region Snippet:Managing_Sql_GetAManagedDatabasesIfExists
            ManagedDatabaseCollection managedDatabaseCollection = managedInstance.GetManagedDatabases();

            ManagedDatabase managedDatabase = await managedDatabaseCollection.GetIfExistsAsync("foo");

            if (managedInstance != null)
            {
                Console.WriteLine(managedDatabase.Data.Name);
            }

            if (await managedDatabaseCollection.ExistsAsync("bar"))
            {
                Console.WriteLine("Virtual network 'bar' exists.");
            }
            #endregion
        }
Пример #10
0
        public void TestManagedInstanceLongTermRetentionPolicies()
        {
            // MANUAL TEST INSTRUCTIONS
            // PlayBack Mode:
            //     Make sure information below matches what is gets recorded in Session Records
            //
            string locationName        = "southeastasia";
            string resourceGroupName   = "sdk-test-rg";
            string managedInstanceName = "sdk-test-mi";
            string defaultPolicy       = "PT0S";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                ManagedDatabase     database  = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroupName, managedInstanceName, SqlManagementTestUtilities.GenerateName(), new ManagedDatabase {
                    Location = locationName
                });

                // Get the policy and verify it is the default policy
                //
                ManagedInstanceLongTermRetentionPolicy policy = sqlClient.ManagedInstanceLongTermRetentionPolicies.Get(resourceGroupName, managedInstanceName, database.Name);
                Assert.Equal(defaultPolicy, policy.WeeklyRetention);
                Assert.Equal(defaultPolicy, policy.MonthlyRetention);
                Assert.Equal(defaultPolicy, policy.YearlyRetention);
                Assert.Equal(0, policy.WeekOfYear);

                // Set the retention policy to two weeks for the weekly retention policy
                //
                ManagedInstanceLongTermRetentionPolicy parameters = new ManagedInstanceLongTermRetentionPolicy(weeklyRetention: "P2W");
                sqlClient.ManagedInstanceLongTermRetentionPolicies.CreateOrUpdate(resourceGroupName, managedInstanceName, database.Name, parameters);

                // Get the policy and verify the weekly policy is two weeks but all the rest stayed the same
                //
                policy = sqlClient.ManagedInstanceLongTermRetentionPolicies.Get(resourceGroupName, managedInstanceName, database.Name);
                Assert.Equal(parameters.WeeklyRetention, policy.WeeklyRetention);
                Assert.Equal(defaultPolicy, policy.MonthlyRetention);
                Assert.Equal(defaultPolicy, policy.YearlyRetention);
                Assert.Equal(0, policy.WeekOfYear);
            }
        }
Пример #11
0
        public void TestCrudInstanceFailoverGroup()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // Names of pre-existing ManagedInstances
                string sourceManagedInstanceName = "mi-primary-wcus";
                string targetManagedInstanceName = "mi-tooling-cus";
                string sourceResourceGroup       = ManagedInstanceTestUtilities.ResourceGroupName;
                string targetResourceGroup       = ManagedInstanceTestUtilities.ResourceGroupName;

                // Create server
                var sourceManagedInstance = sqlClient.ManagedInstances.Get(sourceResourceGroup, sourceManagedInstanceName);

                // Create second server
                var targetManagedInstance = sqlClient.ManagedInstances.Get(targetResourceGroup, targetManagedInstanceName);

                // Create database only required parameters
                string mdbName = "database1";
                var    mdb1    = sqlClient.ManagedDatabases.CreateOrUpdate(sourceResourceGroup, sourceManagedInstance.Name, mdbName, new ManagedDatabase()
                {
                    Location = sourceManagedInstance.Location,
                });
                Assert.NotNull(mdb1);

                // Create a failover group
                string instanceFailoverGroupName = SqlManagementTestUtilities.GenerateName();
                var    fgInput = new InstanceFailoverGroup()
                {
                    ReadOnlyEndpoint = new InstanceFailoverGroupReadOnlyEndpoint()
                    {
                        FailoverPolicy = ReadOnlyEndpointFailoverPolicy.Disabled,
                    },
                    ReadWriteEndpoint = new InstanceFailoverGroupReadWriteEndpoint()
                    {
                        FailoverPolicy = ReadWriteEndpointFailoverPolicy.Manual,
                    },
                    PartnerRegions = new List <PartnerRegionInfo>()
                    {
                        new PartnerRegionInfo()
                        {
                            Location = targetManagedInstance.Location
                        },
                    },
                    ManagedInstancePairs = new List <ManagedInstancePairInfo>()
                    {
                        new ManagedInstancePairInfo()
                        {
                            PrimaryManagedInstanceId = sourceManagedInstance.Id, PartnerManagedInstanceId = targetManagedInstance.Id
                        },
                    },
                };
                var instanceFailoverGroup = sqlClient.InstanceFailoverGroups.CreateOrUpdate(sourceResourceGroup, sourceManagedInstance.Location, instanceFailoverGroupName, fgInput);
                SqlManagementTestUtilities.ValidateInstanceFailoverGroup(fgInput, instanceFailoverGroup, instanceFailoverGroupName);

                var pePrimaryDatabase = sqlClient.ManagedDatabases.Get(sourceResourceGroup, sourceManagedInstance.Name, mdbName);

                // A brief wait may be needed until the secondary for the pre-existing database is created
                ManagedDatabase peSecondaryDatabase = new ManagedDatabase();

                SqlManagementTestUtilities.ExecuteWithRetry(() =>
                {
                    peSecondaryDatabase = sqlClient.ManagedDatabases.Get(targetResourceGroup, targetManagedInstance.Name, mdbName);
                },
                                                            TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(5),
                                                            (CloudException e) =>
                {
                    return(e.Response.StatusCode == HttpStatusCode.NotFound);
                });

                // Update a few settings
                var fgSetInput = new InstanceFailoverGroup()
                {
                    ReadOnlyEndpoint = new InstanceFailoverGroupReadOnlyEndpoint
                    {
                        FailoverPolicy = ReadOnlyEndpointFailoverPolicy.Enabled
                    },
                    ReadWriteEndpoint = new InstanceFailoverGroupReadWriteEndpoint
                    {
                        FailoverPolicy = ReadWriteEndpointFailoverPolicy.Automatic,
                        FailoverWithDataLossGracePeriodMinutes = 120
                    },
                    PartnerRegions = new List <PartnerRegionInfo>()
                    {
                        new PartnerRegionInfo()
                        {
                            Location = instanceFailoverGroup.PartnerRegions.FirstOrDefault().Location
                        },
                    },
                    ManagedInstancePairs = new List <ManagedInstancePairInfo>()
                    {
                        new ManagedInstancePairInfo()
                        {
                            PrimaryManagedInstanceId = instanceFailoverGroup.ManagedInstancePairs.FirstOrDefault().PrimaryManagedInstanceId,
                            PartnerManagedInstanceId = instanceFailoverGroup.ManagedInstancePairs.FirstOrDefault().PartnerManagedInstanceId
                        },
                    },
                };

                var instanceFailoverGroupUpdated2 = sqlClient.InstanceFailoverGroups.CreateOrUpdate(sourceResourceGroup, sourceManagedInstance.Location, instanceFailoverGroupName, fgSetInput);

                // Set expectations and verify update
                fgInput.ReadWriteEndpoint = fgSetInput.ReadWriteEndpoint;
                fgInput.ReadOnlyEndpoint  = fgSetInput.ReadOnlyEndpoint;
                SqlManagementTestUtilities.ValidateInstanceFailoverGroup(fgInput, instanceFailoverGroupUpdated2, instanceFailoverGroupName);

                // Failover failover group
                sqlClient.InstanceFailoverGroups.Failover(targetResourceGroup, targetManagedInstance.Location, instanceFailoverGroupName);
                instanceFailoverGroup = sqlClient.InstanceFailoverGroups.Get(targetResourceGroup, targetManagedInstance.Location, instanceFailoverGroupName);

                // Get failover group on the new secondary server and verify its replication role
                Assert.Equal(sourceManagedInstance.Id, instanceFailoverGroup.ManagedInstancePairs.FirstOrDefault().PartnerManagedInstanceId);
                Assert.Equal(targetManagedInstance.Id, instanceFailoverGroup.ManagedInstancePairs.FirstOrDefault().PrimaryManagedInstanceId);

                // Delete failover group
                sqlClient.InstanceFailoverGroups.Delete(targetResourceGroup, targetManagedInstance.Location, instanceFailoverGroupName);
                Assert.Throws <Microsoft.Rest.Azure.CloudException>(() => sqlClient.InstanceFailoverGroups.Get(sourceResourceGroup, sourceManagedInstance.Location, instanceFailoverGroupName));

                //Delete the managed database
                sqlClient.ManagedDatabases.Delete(sourceResourceGroup, sourceManagedInstance.Name, mdbName);
                sqlClient.ManagedDatabases.Delete(targetResourceGroup, targetManagedInstance.Name, mdbName);
            }
        }
 /// <summary>
 /// Creates a new database or updates an existing database.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the resource. You can obtain
 /// this value from the Azure Resource Manager API or the portal.
 /// </param>
 /// <param name='managedInstanceName'>
 /// The name of the managed instance.
 /// </param>
 /// <param name='databaseName'>
 /// The name of the database.
 /// </param>
 /// <param name='parameters'>
 /// The requested database resource state.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <ManagedDatabase> BeginCreateOrUpdateAsync(this IManagedDatabasesOperations operations, string resourceGroupName, string managedInstanceName, string databaseName, ManagedDatabase parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, managedInstanceName, databaseName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates a new database or updates an existing database.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the resource. You can obtain
 /// this value from the Azure Resource Manager API or the portal.
 /// </param>
 /// <param name='managedInstanceName'>
 /// The name of the managed instance.
 /// </param>
 /// <param name='databaseName'>
 /// The name of the database.
 /// </param>
 /// <param name='parameters'>
 /// The requested database resource state.
 /// </param>
 public static ManagedDatabase BeginCreateOrUpdate(this IManagedDatabasesOperations operations, string resourceGroupName, string managedInstanceName, string databaseName, ManagedDatabase parameters)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, managedInstanceName, databaseName, parameters).GetAwaiter().GetResult());
 }
        public virtual ManagedDatabasesCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string managedInstanceName, string databaseName, ManagedDatabase parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (managedInstanceName == null)
            {
                throw new ArgumentNullException(nameof(managedInstanceName));
            }
            if (databaseName == null)
            {
                throw new ArgumentNullException(nameof(databaseName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var scope = _clientDiagnostics.CreateScope("ManagedDatabasesOperations.StartCreateOrUpdate");
            scope.Start();
            try
            {
                var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, managedInstanceName, databaseName, parameters, cancellationToken);
                return(new ManagedDatabasesCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, managedInstanceName, databaseName, parameters).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }