Esempio n. 1
0
        public void FailoverElasticPool()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Server server = context.CreateServer(resourceGroup);

                // Create elastic pool
                string epName = SqlManagementTestUtilities.GenerateName();
                var    ep     = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, new ElasticPool()
                {
                    Location = server.Location
                });
                Assert.NotNull(ep);

                // Create database in elastic pool
                string dbName  = SqlManagementTestUtilities.GenerateName();
                var    dbInput = new Database()
                {
                    Location      = server.Location,
                    ElasticPoolId = ep.Id
                };
                var db = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput);
                Assert.NotNull(db);

                // Failover elastic pool
                sqlClient.ElasticPools.Failover(
                    resourceGroup.Name,
                    server.Name,
                    epName);
            }
        }
        public void TestCreateLedgerDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server        server        = context.CreateServer(resourceGroup);

                // Create database with IsLedgerOn
                string   databaseName = SqlManagementTestUtilities.GenerateName();
                Database ledgerDb     = sqlClient.Databases.CreateOrUpdate(
                    resourceGroup.Name,
                    server.Name,
                    databaseName,
                    new Database()
                {
                    Location   = server.Location,
                    IsLedgerOn = true
                });

                // Get the created database and validate IsLedgerOn parameter is set
                Database databaseResponse = sqlClient.Databases.Get(resourceGroup.Name, server.Name, databaseName);
                Assert.True(databaseResponse.IsLedgerOn);
            }
        }
Esempio n. 3
0
        public void TestShortTermRetentionPolicyOnPremium()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Valid Retention Days for Basic DB is 1 to 35 days.
                int defaultRetentionDays = 7;

                // Valid Differential Backup Interval Hours is 12 or 24.
                int defaultDiffBackupIntervalHours = 12;

                // Create a DTU - Premium DB.
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Database            database      = sqlClient.Databases.CreateOrUpdate(
                    resourceGroup.Name, server.Name, SqlManagementTestUtilities.GenerateName(),
                    new Database
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P1)
                });

                // Test GET operation can get default retention days and diffbackupinterval value.
                BackupShortTermRetentionPolicy policyDefault = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(defaultRetentionDays, policyDefault.RetentionDays);
                Assert.Equal(defaultDiffBackupIntervalHours, policyDefault.DiffBackupIntervalInHours);

                // Attempt to set retention period to 36 days (invalid); Attemp to set the differential backup interval to 24 hours (valid); Verify the operation fails on updating the policy.
                BackupShortTermRetentionPolicy parameters1 = new BackupShortTermRetentionPolicy(retentionDays: 36, diffBackupIntervalInHours: 24);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters1);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                BackupShortTermRetentionPolicy policy = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(defaultRetentionDays, policy.RetentionDays);
                Assert.Equal(defaultDiffBackupIntervalHours, policy.DiffBackupIntervalInHours);

                // Attempt to set retention period to 35 days (valid); Attemp to set the differential backup interval to 20 hours (invalid); Verify the operation fails on updating the policy.
                BackupShortTermRetentionPolicy parameters2 = new BackupShortTermRetentionPolicy(retentionDays: 35, diffBackupIntervalInHours: 20);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters2);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                BackupShortTermRetentionPolicy policy2 = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(defaultRetentionDays, policy2.RetentionDays);
                Assert.Equal(defaultDiffBackupIntervalHours, policy2.DiffBackupIntervalInHours);

                // Increase retention period to 35 days (valid); Increase differential backup interval to 24 hours (valid); Verify the operation success.
                BackupShortTermRetentionPolicy parameters3 = new BackupShortTermRetentionPolicy(retentionDays: 35, diffBackupIntervalInHours: 24);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters3);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                BackupShortTermRetentionPolicy policy3 = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(parameters3.RetentionDays, policy3.RetentionDays);
                Assert.Equal(parameters3.DiffBackupIntervalInHours, policy3.DiffBackupIntervalInHours);

                // Decrease retention period to 7 days again; Decrease differential backup interval to 12 hours again (valid); Verify the operation success.
                BackupShortTermRetentionPolicy parameters4 = new BackupShortTermRetentionPolicy(retentionDays: 7, diffBackupIntervalInHours: 12);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters4);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                BackupShortTermRetentionPolicy policy4 = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(parameters4.RetentionDays, policy4.RetentionDays);
                Assert.Equal(parameters4.DiffBackupIntervalInHours, policy4.DiffBackupIntervalInHours);
            }
        }
        public static void ValidateManagedInstance(
            ManagedInstance actual,
            IDictionary <string, string> tags = null,
            string instancePoolId             = null,
            bool shouldCheckState             = false)
        {
            Assert.NotNull(actual);

            if (shouldCheckState)
            {
                Assert.Equal("Succeeded", actual.ProvisioningState);
            }

            if (tags != null)
            {
                // Remove our default tag before validation
                actual.Tags.Remove(ManagedInstanceTestUtilities.Tags.First().Key);
                SqlManagementTestUtilities.AssertCollection(tags, actual.Tags);
            }


            if (instancePoolId != null)
            {
                Assert.Equal(actual.InstancePoolId, instancePoolId);
            }
        }
        public static void ValidateServer(Server actual, string name, string login, string version, Dictionary <string, string> tags, string location, string publicNetworkAccess = null, string minimalTlsVersion = null, string restrictOutboundNetworkAccess = null)
        {
            Assert.NotNull(actual);
            Assert.Equal(name, actual.Name);
            Assert.Equal(login, actual.AdministratorLogin);
            Assert.Equal(version, actual.Version);
            SqlManagementTestUtilities.AssertCollection(tags, actual.Tags);

            // Location is being returned two different ways across different APIs.
            Assert.Equal(location.ToLower().Replace(" ", ""), actual.Location.ToLower().Replace(" ", ""));

            if (publicNetworkAccess != null)
            {
                Assert.Equal(publicNetworkAccess, actual.PublicNetworkAccess);
            }

            if (minimalTlsVersion != null)
            {
                Assert.Equal(minimalTlsVersion, actual.MinimalTlsVersion);
            }

            if (restrictOutboundNetworkAccess != null)
            {
                Assert.Equal(restrictOutboundNetworkAccess, actual.RestrictOutboundNetworkAccess);
            }
        }
Esempio n. 6
0
        public void FailoverReadableSecondaryDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Server server = context.CreateServer(resourceGroup);

                // Create database
                string dbName  = SqlManagementTestUtilities.GenerateName();
                var    dbInput = new Database()
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P1)
                };
                var db = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput);
                Assert.NotNull(db);

                // Failover database
                sqlClient.Databases.Failover(
                    resourceGroup.Name,
                    server.Name,
                    dbName,
                    "ReadableSecondary");
            }
        }
Esempio n. 7
0
        public void TestCreateAndUpdateFirewallRule()
        {
            string testPrefix = "firewallrulecrudtest-";

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

                // Create Firewall Rule and Validate
                //
                string firewallRuleName = SqlManagementTestUtilities.GenerateName(testPrefix);

                FirewallRule toCreate = new FirewallRule()
                {
                    StartIpAddress = "0.0.0.0",
                    EndIpAddress   = "0.0.0.0"
                };
                var fr1 = sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, firewallRuleName, toCreate);
                SqlManagementTestUtilities.ValidateFirewallRule(toCreate, fr1, firewallRuleName);

                // Update Firewall Rule and Validate
                toCreate = new FirewallRule()
                {
                    StartIpAddress = "1.1.1.1",
                    EndIpAddress   = "255.255.255.255"
                };
                fr1 = sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, firewallRuleName, toCreate);
                SqlManagementTestUtilities.ValidateFirewallRule(toCreate, fr1, firewallRuleName);
            }
        }
Esempio n. 8
0
        public void TestAllScenariosPrivateEndpointConnection()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                sqlClient     = context.GetClient <SqlManagementClient>();
                networkClient = context.GetClient <NetworkManagementClient>();

                var            location                = TestEnvironmentUtilities.DefaultEuapPrimaryLocationId;
                ResourceGroup  resourceGroup           = context.CreateResourceGroup(location);
                Server         server                  = context.CreateServer(resourceGroup, location);
                VirtualNetwork vnet                    = CreateVirtualNetwork(resourceGroup, location);
                IList <PrivateEndpointConnection> pecs = CreatePrivateEndpoints(resourceGroup, location, server, vnet, n: 2);

                PrivateEndpointConnection pec1 = pecs[0];
                pec1.PrivateLinkServiceConnectionState.Status = "Approved";
                sqlClient.PrivateEndpointConnections.CreateOrUpdate(resourceGroup.Name, server.Name, pec1.Name, pec1);
                PrivateEndpointConnection pec1r = sqlClient.PrivateEndpointConnections.Get(resourceGroup.Name, server.Name, pec1.Name);
                SqlManagementTestUtilities.ValidatePrivateEndpointConnection(pec1, pec1r);

                PrivateEndpointConnection pec2 = pecs[1];
                pec2.PrivateLinkServiceConnectionState.Status = "Rejected";
                sqlClient.PrivateEndpointConnections.CreateOrUpdate(resourceGroup.Name, server.Name, pec2.Name, pec2);
                PrivateEndpointConnection pec2r = sqlClient.PrivateEndpointConnections.Get(resourceGroup.Name, server.Name, pec2.Name);
                SqlManagementTestUtilities.ValidatePrivateEndpointConnection(pec2, pec2r);

                sqlClient.PrivateEndpointConnections.Delete(resourceGroup.Name, server.Name, pec1.Name);
                Assert.Throws <Microsoft.Rest.Azure.CloudException>(() => sqlClient.PrivateEndpointConnections.Get(resourceGroup.Name, server.Name, pec1.Name));

                sqlClient.PrivateEndpointConnections.Delete(resourceGroup.Name, server.Name, pec2.Name);
                Assert.Throws <Microsoft.Rest.Azure.CloudException>(() => sqlClient.PrivateEndpointConnections.Get(resourceGroup.Name, server.Name, pec2.Name));
            }
        }
Esempio n. 9
0
        public void TestShortTermRetentionPolicyOnBasic()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                int basicRetention = 7;

                // Create a Basic DB so it defaults to 7 days retention.
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Database            database      = sqlClient.Databases.CreateOrUpdate(
                    resourceGroup.Name, server.Name, SqlManagementTestUtilities.GenerateName(),
                    new Database
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.Basic)
                });

                // Attempt to increase retention period to 8 days and verfiy that the operation fails.
                BackupShortTermRetentionPolicy parameters = new BackupShortTermRetentionPolicy(retentionDays: 8);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                BackupShortTermRetentionPolicy policy = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(basicRetention, policy.RetentionDays);

                // Attempt to dncrease retention period to 3 days and verify operation failure.
                parameters = new BackupShortTermRetentionPolicy(retentionDays: 3);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                policy = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(basicRetention, policy.RetentionDays);
            }
        }
Esempio n. 10
0
        public void TestShortTermRetentionPolicyOnPremium()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Create a Premium DB so it defaults to 35 days retention.
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Database            database      = sqlClient.Databases.CreateOrUpdate(
                    resourceGroup.Name, server.Name, SqlManagementTestUtilities.GenerateName(),
                    new Database
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P1)
                });

                // Decrease retention period to 8 days and verfiy that it was updated.
                BackupShortTermRetentionPolicy parameters = new BackupShortTermRetentionPolicy(retentionDays: 8);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                BackupShortTermRetentionPolicy policy = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(parameters.RetentionDays, policy.RetentionDays);

                // Increase retention period to 35 days again and verfiy that it was updated.
                parameters = new BackupShortTermRetentionPolicy(retentionDays: 35);
                sqlClient.BackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, database.Name, parameters);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                policy = sqlClient.BackupShortTermRetentionPolicies.Get(resourceGroup.Name, server.Name, database.Name);
                Assert.Equal(parameters.RetentionDays, policy.RetentionDays);
            }
        }
Esempio n. 11
0
        public async void TestCreateUpdateGetManagedInstanceVulnerabilityAssessments()
        {
            SqlManagementClient sqlClient = m_testFixture.Context.GetClient <SqlManagementClient>();

            // Verify Policy is empty to begin with
            ManagedInstanceVulnerabilityAssessment policyThatWasReceived = sqlClient.ManagedInstanceVulnerabilityAssessments.Get(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name);

            Assert.Null(policyThatWasReceived.StorageContainerPath);
            Assert.Null(policyThatWasReceived.StorageAccountAccessKey);
            Assert.False(policyThatWasReceived.RecurringScans.IsEnabled);

            // Set policy and then get policy and verify correctness
            ManagedInstanceVulnerabilityAssessment policyThatWasSet = await SetPolicy(m_testFixture.Context, sqlClient, m_testFixture.ResourceGroup, m_testFixture.ManagedInstance);

            policyThatWasReceived = sqlClient.ManagedInstanceVulnerabilityAssessments.Get(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name);
            Assert.Equal(policyThatWasSet.StorageContainerPath, policyThatWasReceived.StorageContainerPath);
            Assert.Null(policyThatWasSet.StorageAccountAccessKey);
            Assert.Equal(policyThatWasSet.RecurringScans.IsEnabled, policyThatWasReceived.RecurringScans.IsEnabled);
            SqlManagementTestUtilities.AssertCollection(policyThatWasSet.RecurringScans.Emails, policyThatWasReceived.RecurringScans.Emails);
            Assert.Equal(policyThatWasSet.RecurringScans.EmailSubscriptionAdmins, policyThatWasReceived.RecurringScans.EmailSubscriptionAdmins);

            // Delete policy and then get policy and verify correctness
            sqlClient.ManagedInstanceVulnerabilityAssessments.Delete(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name);

            // Get policy after deletion
            policyThatWasReceived = sqlClient.ManagedInstanceVulnerabilityAssessments.Get(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name);
            Assert.Null(policyThatWasReceived.StorageContainerPath);
            Assert.Null(policyThatWasReceived.StorageAccountAccessKey);
            Assert.False(policyThatWasReceived.RecurringScans.IsEnabled);
        }
Esempio n. 12
0
        public void TestListElasticPoolActivity()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();

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

                // Create a elastic pool
                //
                string epName  = SqlManagementTestUtilities.GenerateName();
                var    epInput = new ElasticPool()
                {
                    Location       = server.Location,
                    Tags           = tags,
                    DatabaseDtuMax = 5,
                    DatabaseDtuMin = 0
                };
                var returnedEp = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput);
                SqlManagementTestUtilities.ValidateElasticPool(epInput, returnedEp, epName);

                // Get the Elastic Pool Activity List
                var activity = sqlClient.ElasticPoolActivities.ListByElasticPool(resourceGroup.Name, server.Name, epName);

                Assert.Equal(1, activity.Where(a => a.ElasticPoolName == epName).Count());
                Assert.Equal(1, activity.Where(a => a.Operation == "CREATE").Count());
            }
        }
        public async void TestCreateUpdateGetDeleteDatabaseVulnerabilityAssessmentBaselines()
        {
            string testPrefix = "sqlvulnerabilityassessmentbaselinetest-";

            SqlManagementClient sqlClient = m_testFixture.Context.GetClient <SqlManagementClient>();

            // Create managed database
            //
            string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
            var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, new ManagedDatabase()
            {
                Location = m_testFixture.ManagedInstance.Location,
            });

            Assert.NotNull(db1);

            // Set policy
            await SetPolicy(m_testFixture.Context, sqlClient, m_testFixture.ResourceGroup, m_testFixture.ManagedInstance, dbName);

            // Test baseline for database level rule
            ValidateBaselineRule(sqlClient, m_testFixture.ResourceGroup, m_testFixture.ManagedInstance, dbName, isServerLevelRule: true);

            // Test baseline for server level rule
            ValidateBaselineRule(sqlClient, m_testFixture.ResourceGroup, m_testFixture.ManagedInstance, dbName, isServerLevelRule: false);
        }
        public void TestDatabasePointInTimeRestore()
        {
            // 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());

                // Create a new database that is the first database restored to an earlier point in time
                string   db2Name  = SqlManagementTestUtilities.GenerateName();
                Database db2Input = new Database
                {
                    Location           = server.Location,
                    CreateMode         = CreateMode.PointInTimeRestore,
                    RestorePointInTime = db1.EarliestRestoreDate.Value,
                    SourceDatabaseId   = db1.Id
                };
                Database db2 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, db2Name, db2Input);
                Assert.NotNull(db2);
                SqlManagementTestUtilities.ValidateDatabase(db2Input, db2, db2Name);
            }
        }
        public async void TestExportDatabaseVulnerabilityAssessmentScans()
        {
            string testPrefix = "sqlvulnerabilityassessmentexportscantest-";

            SqlManagementClient sqlClient = m_testFixture.Context.GetClient <SqlManagementClient>();

            // Create managed database
            //
            string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
            var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, new ManagedDatabase()
            {
                Location = m_testFixture.ManagedInstance.Location,
            });

            Assert.NotNull(db1);

            // Set policy
            await SetPolicy(m_testFixture.Context, sqlClient, m_testFixture.ResourceGroup, m_testFixture.ManagedInstance, dbName);

            // Run some scans
            string scanId = string.Format("scan1_{0}", testPrefix);

            sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.InitiateScan(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, scanId);
            sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.Export(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, scanId);
        }
        public async void TestShortTermRetentionPolicyOnGeneralPurposeScriptUse()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Valid Retention Days for GeneralPurpose DB is 1 to 35 days.
                int defaultRetentionDays = 7;

                // Create a vCore - GeneralPurpose DB.
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Database            database      = sqlClient.Databases.CreateOrUpdate(
                    resourceGroup.Name, server.Name, SqlManagementTestUtilities.GenerateName(),
                    new Database
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P1)
                });

                // Test Update operation through GET operation.
                var strPolicy = await sqlClient.BackupShortTermRetentionPolicies.GetAsync(resourceGroup.Name.ToString(), server.Name.ToString(), database.Name.ToString());

                strPolicy.RetentionDays = 28;
                await sqlClient.BackupShortTermRetentionPolicies.BeginCreateOrUpdateAsync(resourceGroup.Name.ToString(), server.Name.ToString(), database.Name.ToString(), strPolicy);

                Assert.Equal(28, strPolicy.RetentionDays);
            }
        }
        internal static Task <ManagedDatabase[]> CreateManagedDatabasesAsync(
            SqlManagementClient sqlClient,
            string resourceGroupName,
            ManagedInstance managedInstance,
            string testPrefix,
            int count)
        {
            List <Task <ManagedDatabase> > createDbTasks = new List <Task <ManagedDatabase> >();

            for (int i = 0; i < count; i++)
            {
                string name = SqlManagementTestUtilities.GenerateName();
                createDbTasks.Add(sqlClient.ManagedDatabases.CreateOrUpdateAsync(
                                      resourceGroupName,
                                      managedInstance.Name,
                                      name,
                                      new ManagedDatabase()
                {
                    Location = managedInstance.Location
                }));
            }

            // Wait for all databases to be created.
            return(Task.WhenAll(createDbTasks));
        }
        public void TestCreateAndDropVirtualNetworkRule()
        {
            string testPrefix = "virtualnetworkrulecrudtest-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Basic setup
                var            location        = TestEnvironmentUtilities.DefaultEuapPrimaryLocationId;
                ResourceGroup  resourceGroup   = context.CreateResourceGroup(location);
                VirtualNetwork getVnetResponse = CreateVirtualNetwork(context, resourceGroup, location: location, subnetCount: 1);

                Server server = context.CreateServer(resourceGroup, location);
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // create virtual network rules
                string vnetfirewallRuleName = SqlManagementTestUtilities.GenerateName(testPrefix);

                VirtualNetworkRule rule = new VirtualNetworkRule()
                {
                    VirtualNetworkSubnetId           = getVnetResponse.Subnets[0].Id.ToString(),
                    IgnoreMissingVnetServiceEndpoint = false
                };
                VirtualNetworkRule vfr = sqlClient.VirtualNetworkRules.CreateOrUpdate(resourceGroup.Name, server.Name, vnetfirewallRuleName, rule);
                SqlManagementTestUtilities.ValidateVirtualNetworkRule(rule, vfr, vnetfirewallRuleName);

                // delete virtual network rules
                sqlClient.VirtualNetworkRules.Delete(resourceGroup.Name, server.Name, vfr.Name);
            }
        }
        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);
            }
        }
        public void TestCreateAndUpdateIPv6FirewallRule()
        {
            string testPrefix = "ipv6firewallrulecrudtest-";

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

                // Create IPv6 Firewall Rule and Validate
                string ipv6FirewallRuleName = SqlManagementTestUtilities.GenerateName(testPrefix);

                IPv6FirewallRule toCreate = new IPv6FirewallRule()
                {
                    StartIPv6Address = "0000:0000:0000:0000:0000:ffff:0000:0000",
                    EndIPv6Address   = "0000:0000:0000:0000:0000:ffff:0000:0000"
                };
                var fr1 = sqlClient.IPv6FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, ipv6FirewallRuleName, toCreate);
                SqlManagementTestUtilities.ValidateIPv6FirewallRule(toCreate, fr1, ipv6FirewallRuleName);

                // Update Firewall Rule and Validate
                toCreate = new IPv6FirewallRule()
                {
                    StartIPv6Address = "0000:0000:0000:0000:0000:ffff:0101:0101",
                    EndIPv6Address   = "0000:0000:0000:0000:0000:ffff:ffff:ffff"
                };
                fr1 = sqlClient.IPv6FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, ipv6FirewallRuleName, toCreate);
                SqlManagementTestUtilities.ValidateIPv6FirewallRule(toCreate, fr1, ipv6FirewallRuleName);
            }
        }
        public void TestPauseResumeDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                Server              server        = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();

                // Create data warehouse
                string dbName = SqlManagementTestUtilities.GenerateName();
                var    db1    = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                    Sku      = SqlTestConstants.DefaultDataWarehouseSku()
                });
                Assert.NotNull(db1);

                // Pause
                sqlClient.Databases.Pause(resourceGroup.Name, server.Name, dbName);
                // TODO: Get result and verify that status is now resumed - blocked by https://github.com/Azure/autorest/issues/2295

                // Resume
                sqlClient.Databases.Resume(resourceGroup.Name, server.Name, dbName);
                // TODO: Get result and verify that status is now resumed - blocked by https://github.com/Azure/autorest/issues/2295
            }
        }
        public VirtualNetwork CreateVirtualNetwork(SqlManagementTestContext context, ResourceGroup resourceGroup, string location, int subnetCount = 1)
        {
            NetworkManagementClient networkClient = context.GetClient <NetworkManagementClient>();

            // Create vnet andinitialize subnets
            string vnetName = SqlManagementTestUtilities.GenerateName();

            List <ServiceEndpointPropertiesFormat> SqlPrivateAccess = new List <ServiceEndpointPropertiesFormat>()
            {
                new ServiceEndpointPropertiesFormat("Microsoft.Sql")
            };

            List <Subnet> subnetList = new List <Subnet>();

            for (int i = 0; i < subnetCount; i++)
            {
                string subnetName    = SqlManagementTestUtilities.GenerateName();
                String addressPrefix = "10.0." + (i + 1) + ".0/24";
                Subnet subnet        = new Subnet()
                {
                    Name             = subnetName,
                    AddressPrefix    = addressPrefix,
                    ServiceEndpoints = SqlPrivateAccess,
                };
                subnetList.Add(subnet);
            }

            var vnet = new VirtualNetwork()
            {
                Location = location,

                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16",
                    }
                },
                DhcpOptions = new DhcpOptions()
                {
                    DnsServers = new List <string>()
                    {
                        "10.1.1.1",
                        "10.1.2.4"
                    }
                },
                Subnets = subnetList
            };

            // Put Vnet
            var putVnetResponse = networkClient.VirtualNetworks.CreateOrUpdate(resourceGroup.Name, vnetName, vnet);

            Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

            // Get Vnet
            var getVnetResponse = networkClient.VirtualNetworks.Get(resourceGroup.Name, vnetName);

            return(getVnetResponse);
        }
        public async void TestExecuteGetListDatabaseVulnerabilityAssessmentScans()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string testPrefix = "sqlvulnerabilityassessmentscantest-";

                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Server server = context.CreateServer(resourceGroup);

                // Create database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Turn ON database threat detection as a prerequisite to use VA
                DatabaseSecurityAlertPolicy updatedDatabasePolicy = new DatabaseSecurityAlertPolicy
                {
                    State = SecurityAlertPolicyState.Enabled,
                    EmailAccountAdmins = SecurityAlertPolicyEmailAccountAdmins.Enabled
                };
                sqlClient.DatabaseThreatDetectionPolicies.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, updatedDatabasePolicy);

                // Set policy
                await SetPolicy(context, sqlClient, resourceGroup, server, dbName);

                // Run some scans
                string scanId = string.Format("scantest1_{0}", testPrefix);
                sqlClient.DatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, server.Name, dbName, scanId);

                string scanId1 = string.Format("scantest2_{0}", testPrefix);
                sqlClient.DatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, server.Name, dbName, scanId1);

                // Verify get scan and list scans
                VulnerabilityAssessmentScanRecord scanRecord = sqlClient.DatabaseVulnerabilityAssessmentScans.Get(resourceGroup.Name, server.Name, dbName, scanId);
                Assert.Equal(scanId, scanRecord.ScanId);

                IPage <VulnerabilityAssessmentScanRecord> scanRecords = sqlClient.DatabaseVulnerabilityAssessmentScans.ListByDatabase(resourceGroup.Name, server.Name, dbName);
                Assert.Equal(2, scanRecords.ToList().Count);
                Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId);
                Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId1);

                VulnerabilityAssessmentScanRecord scanId1Record         = sqlClient.DatabaseVulnerabilityAssessmentScans.Get(resourceGroup.Name, server.Name, dbName, scanId1);
                VulnerabilityAssessmentScanRecord scanId1RecordFromList = scanRecords.FirstOrDefault(item => item.ScanId == scanId1);
                Assert.Equal(scanId1Record.ScanId, scanId1RecordFromList.ScanId);
                Assert.Equal(scanId1Record.TriggerType, scanId1RecordFromList.TriggerType);
                Assert.Equal(scanId1Record.State, scanId1RecordFromList.State);
                Assert.Equal(scanId1Record.StartTime, scanId1RecordFromList.StartTime);
                Assert.Equal(scanId1Record.EndTime, scanId1RecordFromList.EndTime);
                Assert.Equal(scanId1Record.Errors, scanId1RecordFromList.Errors);
                Assert.Equal(scanId1Record.StorageContainerPath, scanId1RecordFromList.StorageContainerPath);
                Assert.Equal(scanId1Record.NumberOfFailedSecurityChecks, scanId1RecordFromList.NumberOfFailedSecurityChecks);
            }
        }
        public void TestGetAndListVirtualNetworkRule()
        {
            string testPrefix = "virtualnetworkrulescrudtest-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Basic setup
                var            location        = TestEnvironmentUtilities.DefaultEuapPrimaryLocationId;
                ResourceGroup  resourceGroup   = context.CreateResourceGroup(location);
                VirtualNetwork getVnetResponse = CreateVirtualNetwork(context, resourceGroup, location: location, subnetCount: 2);

                Server server = context.CreateServer(resourceGroup, location);
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // create virtual network rules
                Dictionary <string, VirtualNetworkRule> rules = new Dictionary <string, VirtualNetworkRule>();

                //rule 1
                string vnetfirewallRuleName1 = SqlManagementTestUtilities.GenerateName(testPrefix);

                VirtualNetworkRule rule1 = new VirtualNetworkRule()
                {
                    VirtualNetworkSubnetId           = getVnetResponse.Subnets[0].Id.ToString(),
                    IgnoreMissingVnetServiceEndpoint = false
                };
                sqlClient.VirtualNetworkRules.CreateOrUpdate(resourceGroup.Name, server.Name, vnetfirewallRuleName1, rule1);
                rules.Add(vnetfirewallRuleName1, rule1);

                //rule 2
                string             vnetfirewallRuleName2 = SqlManagementTestUtilities.GenerateName(testPrefix);
                VirtualNetworkRule rule2 = new VirtualNetworkRule()
                {
                    VirtualNetworkSubnetId           = getVnetResponse.Subnets[1].Id.ToString(),
                    IgnoreMissingVnetServiceEndpoint = false
                };
                sqlClient.VirtualNetworkRules.CreateOrUpdate(resourceGroup.Name, server.Name, vnetfirewallRuleName2, rule2);
                rules.Add(vnetfirewallRuleName2, rule2);

                foreach (var rul in rules)
                {
                    VirtualNetworkRule response = sqlClient.VirtualNetworkRules.Get(resourceGroup.Name, server.Name, rul.Key);
                    SqlManagementTestUtilities.ValidateVirtualNetworkRule(rul.Value, response, rul.Key);
                }

                var listResponse = sqlClient.VirtualNetworkRules.ListByServer(resourceGroup.Name, server.Name);
                Assert.Equal(rules.Count(), listResponse.Count());

                foreach (var rul in listResponse)
                {
                    SqlManagementTestUtilities.ValidateVirtualNetworkRule(rules[rul.Name], rul, rul.Name);
                }

                foreach (var rul in rules)
                {
                    SqlManagementTestUtilities.ValidateVirtualNetworkRule(rul.Value, listResponse.Single(r => r.Name == rul.Key), rul.Key);
                }
            }
        }
Esempio n. 25
0
        public ManagedInstance CreateManagedInstance(ResourceGroup resourceGroup, ManagedInstance initialManagedInstance, string name = null)
        {
            SqlManagementClient sqlClient = GetClient <SqlManagementClient>();

            string miName  = name ?? SqlManagementTestUtilities.GenerateName("net-sdk-crud-tests-");
            var    payload = this.GetManagedInstancePayload(initialManagedInstance);

            return(sqlClient.ManagedInstances.CreateOrUpdate(resourceGroup.Name, miName, payload));
        }
        public void TestCreateGetDeleteVirtualCluster()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string resourceGroupName      = "RG_MIPlayground";
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                string managedInstanceName = "sqlcl-vccrudtests-dotnetsdk1";
                string login    = "******";
                string password = "******";
                Dictionary <string, string> tags = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                Microsoft.Azure.Management.Sql.Models.Sku sku = new Microsoft.Azure.Management.Sql.Models.Sku();
                sku.Name   = "MIGP8G4";
                sku.Tier   = "GeneralPurpose";
                sku.Family = "Gen4";

                string subnetId = "/subscriptions/a8c9a924-06c0-4bde-9788-e7b1370969e1/resourceGroups/RG_MIPlayground/providers/Microsoft.Network/virtualNetworks/VNET_MIPlayground/subnets/VCReservedSubnet";
                string location = "eastus";

                //Create server
                var managedInstance = sqlClient.ManagedInstances.CreateOrUpdate(resourceGroupName, managedInstanceName, new ManagedInstance()
                {
                    AdministratorLogin         = login,
                    AdministratorLoginPassword = password,
                    Sku      = sku,
                    SubnetId = subnetId,
                    Tags     = tags,
                    Location = location,
                });
                SqlManagementTestUtilities.ValidateManagedInstance(managedInstance, managedInstanceName, login, tags, location);

                // Get and verify Virtual cluster
                var virtualClusters = sqlClient.VirtualClusters.List();
                Assert.True(virtualClusters.Count() > 0);
                var virtualCluster = virtualClusters.Single(vc => vc.SubnetId == subnetId);
                Assert.Equal(location, virtualCluster.Location, ignoreCase: true);
                string virtualClusterName = virtualCluster.Name;
                virtualCluster = sqlClient.VirtualClusters.ListByResourceGroup(resourceGroupName).Single(vc => vc.SubnetId == subnetId);
                Assert.Equal(location, virtualCluster.Location, ignoreCase: true);
                Assert.Equal(virtualClusterName, virtualCluster.Name);
                virtualCluster = sqlClient.VirtualClusters.Get(resourceGroupName, virtualClusterName);
                Assert.Equal(location, virtualCluster.Location, ignoreCase: true);
                Assert.Equal(virtualClusterName, virtualCluster.Name);
                Assert.Equal(subnetId, virtualCluster.SubnetId);

                // Drop managed server
                sqlClient.ManagedInstances.Delete(resourceGroupName, managedInstanceName);

                // Delete Virtual Cluster
                sqlClient.VirtualClusters.Delete(resourceGroupName, virtualClusterName);
                Assert.Throws <Microsoft.Rest.Azure.CloudException>(() => sqlClient.VirtualClusters.Get(resourceGroupName, virtualClusterName));
            }
        }
        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);
            }
        }
Esempio n. 28
0
        public void TestCreateDropDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup               resourceGroup = context.CreateResourceGroup();
                Server                      server        = context.CreateServer(resourceGroup);
                SqlManagementClient         sqlClient     = context.GetClient <SqlManagementClient>();
                Dictionary <string, string> tags          = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                // Create database only required parameters
                //
                string dbName = SqlManagementTestUtilities.GenerateName();
                var    db1    = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Create a database with all parameters specified
                //
                dbName = SqlManagementTestUtilities.GenerateName();
                var db2Input = new Database()
                {
                    Location     = server.Location,
                    Collation    = SqlTestConstants.DefaultCollation,
                    Sku          = SqlTestConstants.DefaultDatabaseSku(),
                    MaxSizeBytes = 2 * 1024L * 1024L * 1024L,
                    Tags         = tags,
                    CreateMode   = "Default",
                    SampleName   = SampleName.AdventureWorksLT
                };
                var db2 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db2Input);
                Assert.NotNull(db2);
                SqlManagementTestUtilities.ValidateDatabase(db2Input, db2, dbName);

                // Service Objective Name
                //
                dbName = SqlManagementTestUtilities.GenerateName();
                var db4Input = new Database()
                {
                    Location = server.Location,
                    Sku      = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.S0),
                    Tags     = tags,
                };
                var db4 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db4Input);
                Assert.NotNull(db4);
                SqlManagementTestUtilities.ValidateDatabase(db4Input, db4, dbName);

                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db1.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db2.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db4.Name);
            }
        }
        public void TestUpdateEncryptionProtector()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server        server        = sqlClient.Servers.CreateOrUpdate(
                    resourceGroup.Name,
                    serverName: SqlManagementTestUtilities.GenerateName(),
                    parameters: new Server
                {
                    AdministratorLogin         = SqlManagementTestUtilities.DefaultLogin,
                    AdministratorLoginPassword = SqlManagementTestUtilities.DefaultPassword,
                    Location = resourceGroup.Location,
                    Identity = new ResourceIdentity()
                    {
                        Type = IdentityType.SystemAssigned
                    }
                });

                var keyBundle = SqlManagementTestUtilities.CreateKeyVaultKeyWithServerAccess(context, resourceGroup, server);

                // Create server key
                string serverKeyName = SqlManagementTestUtilities.GetServerKeyNameFromKeyBundle(keyBundle);
                string serverKeyUri  = keyBundle.Key.Kid;
                var    serverKey     = sqlClient.ServerKeys.CreateOrUpdate(resourceGroup.Name, server.Name, serverKeyName, new ServerKey()
                {
                    ServerKeyType = "AzureKeyVault",
                    Uri           = serverKeyUri
                });
                SqlManagementTestUtilities.ValidateServerKey(serverKey, serverKeyName, "AzureKeyVault", serverKeyUri);

                // Update to Key Vault
                sqlClient.EncryptionProtectors.CreateOrUpdate(resourceGroup.Name, server.Name, new EncryptionProtector()
                {
                    ServerKeyName = serverKeyName,
                    ServerKeyType = "AzureKeyVault"
                });

                EncryptionProtector encProtector1 = sqlClient.EncryptionProtectors.Get(resourceGroup.Name, server.Name);
                Assert.Equal("AzureKeyVault", encProtector1.ServerKeyType);
                Assert.Equal(serverKeyName, encProtector1.ServerKeyName);

                // Update to Service Managed
                sqlClient.EncryptionProtectors.CreateOrUpdate(resourceGroup.Name, server.Name, new EncryptionProtector()
                {
                    ServerKeyName = "ServiceManaged",
                    ServerKeyType = "ServiceManaged"
                });

                EncryptionProtector encProtector2 = sqlClient.EncryptionProtectors.Get(resourceGroup.Name, server.Name);
                Assert.Equal("ServiceManaged", encProtector2.ServerKeyType);
                Assert.Equal("ServiceManaged", encProtector2.ServerKeyName);
            }
        }
Esempio n. 30
0
        public static void ValidateManagedInstance(ManagedInstance actual, string name, string login, Dictionary <string, string> tags, string location)
        {
            Assert.NotNull(actual);
            Assert.Equal(name, actual.Name);
            Assert.Equal(login, actual.AdministratorLogin);
            SqlManagementTestUtilities.AssertCollection(tags, actual.Tags);

            // Location is being returned two different ways across different APIs.
            Assert.Equal(location.ToLower().Replace(" ", ""), actual.Location.ToLower().Replace(" ", ""));
        }