public async Task RestorableMongodb36Tests()
        {
            DatabaseRestoreResource databaseRestoreResource1 = new DatabaseRestoreResource()
            {
                DatabaseName    = "database1",
                CollectionNames = new List <string>()
                {
                    "collection1", "collection2", "collection3"
                }
            };

            DatabaseRestoreResource databaseRestoreResource2 = new DatabaseRestoreResource()
            {
                DatabaseName    = "databaseA",
                CollectionNames = new List <string>()
            };

            List <DatabaseRestoreResource> resources = new List <DatabaseRestoreResource>()
            {
                databaseRestoreResource1,
                databaseRestoreResource2
            };

            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler);
                await RestorableMongodbTestHelper(cosmosDBManagementClient, sourceDatabaseAccountInstanceId36, resources);
            }
        }
Exemplo n.º 2
0
        private async Task RestoreDatabaseAccountFeedTestHelperAsync(
            CosmosDBManagementClient cosmosDBManagementClient,
            string sourceDatabaseAccountName,
            string sourceApiType,
            int expectedRestorableLocationCount)
        {
            DatabaseAccountGetResults sourceDatabaseAccount = await CreateDatabaseAccountIfNotExists(cosmosDBManagementClient, sourceDatabaseAccountName, location, sourceApiType);

            List <RestorableDatabaseAccountGetResult> restorableAccountsFromGlobalFeed = (await cosmosDBManagementClient.RestorableDatabaseAccounts.ListByLocationAsync(location)).ToList();

            //List<RestorableDatabaseAccountGetResult> restorableAccounts = (await cosmosDBManagementClient.RestorableDatabaseAccounts.ListByLocationAsync(westus2)).ToList();
            RestorableDatabaseAccountGetResult restorableDatabaseAccount = restorableAccountsFromGlobalFeed.
                                                                           Single(account => account.Name.Equals(sourceDatabaseAccount.InstanceId, StringComparison.OrdinalIgnoreCase));

            ValidateRestorableDatabaseAccount(restorableDatabaseAccount, sourceDatabaseAccount, sourceApiType, expectedRestorableLocationCount);

            List <RestorableDatabaseAccountGetResult> restorableAccountsFromRegionalFeed =
                (await cosmosDBManagementClient.RestorableDatabaseAccounts.ListByLocationAsync(location)).ToList();

            restorableDatabaseAccount = restorableAccountsFromRegionalFeed.
                                        Single(account => account.Name.Equals(sourceDatabaseAccount.InstanceId, StringComparison.OrdinalIgnoreCase));

            ValidateRestorableDatabaseAccount(restorableDatabaseAccount, sourceDatabaseAccount, sourceApiType, expectedRestorableLocationCount);

            restorableDatabaseAccount =
                await cosmosDBManagementClient.RestorableDatabaseAccounts.GetByLocationAsync(location, sourceDatabaseAccount.InstanceId);

            ValidateRestorableDatabaseAccount(restorableDatabaseAccount, sourceDatabaseAccount, sourceApiType, expectedRestorableLocationCount);
        }
Exemplo n.º 3
0
        private TableGetResults CreateTableResources(CosmosDBManagementClient cosmosDBManagementClient, string databaseAccountName, string tableName)
        {
            TableGetResults tableGetResult = null;

            try
            {
                tableGetResult = cosmosDBManagementClient.TableResources.GetTable(this.fixture.ResourceGroupName, databaseAccountName, tableName);
            }
            catch (Exception) { }

            if (tableGetResult == null)
            {
                TableCreateUpdateParameters collectionCreateParams = new TableCreateUpdateParameters()
                {
                    Resource = new TableResource
                    {
                        Id = tableName
                    },
                    Options = new CreateUpdateOptions()
                    {
                        Throughput = 30000
                    }
                };

                tableGetResult = cosmosDBManagementClient.TableResources.CreateUpdateTable(
                    this.fixture.ResourceGroupName,
                    databaseAccountName,
                    tableName,
                    collectionCreateParams);
            }

            return(tableGetResult);
        }
Exemplo n.º 4
0
        public static CosmosDBManagementClient GetCosmosDBClient(MockContext context, RecordedDelegatingHandler handler)
        {
            handler.IsPassThrough = true;
            CosmosDBManagementClient client = context.GetServiceClient <CosmosDBManagementClient>(handlers: handler);

            return(client);
        }
        protected async Task initNewRecord()
        {
            Subscription sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            ResourceGroupsOperations = sub.GetResourceGroups();
            CosmosDBManagementClient = GetCosmosDBManagementClient();
        }
Exemplo n.º 6
0
        private MongoDBCollectionGetResults CreateMongoDBResources(CosmosDBManagementClient cosmosDBManagementClient, string databaseAccountName, string databaseName, string collectionName)
        {
            MongoDBDatabaseGetResults databaseGetResults = null;

            try
            {
                databaseGetResults = cosmosDBManagementClient.MongoDBResources.GetMongoDBDatabase(this.fixture.ResourceGroupName, databaseAccountName, databaseName);
            }
            catch (Exception) { }

            if (databaseGetResults == null)
            {
                MongoDBDatabaseCreateUpdateParameters mongoDBDatabaseCreateUpdateParameters = new MongoDBDatabaseCreateUpdateParameters
                {
                    Resource = new MongoDBDatabaseResource {
                        Id = databaseName
                    },
                    Options = new CreateUpdateOptions()
                };

                databaseGetResults = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBDatabase(
                    this.fixture.ResourceGroupName,
                    databaseAccountName,
                    databaseName,
                    mongoDBDatabaseCreateUpdateParameters);
            }

            MongoDBCollectionGetResults collectionGetResult = null;

            try
            {
                collectionGetResult = cosmosDBManagementClient.MongoDBResources.GetMongoDBCollection(this.fixture.ResourceGroupName, databaseAccountName, databaseName, collectionName);
            }
            catch (Exception) { }
            if (collectionGetResult == null)
            {
                Dictionary <string, string> dict = new Dictionary <string, string>();
                dict.Add("partitionKey", PartitionKind.Hash.ToString());
                MongoDBCollectionCreateUpdateParameters collectionCreateParams = new MongoDBCollectionCreateUpdateParameters()
                {
                    Resource = new MongoDBCollectionResource
                    {
                        Id       = collectionName,
                        ShardKey = dict
                    },
                    Options = new CreateUpdateOptions()
                    {
                        Throughput = 30000
                    }
                };
                collectionGetResult = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBCollection(
                    this.fixture.ResourceGroupName,
                    databaseAccountName,
                    databaseName,
                    collectionName,
                    collectionCreateParams);
            }

            return(collectionGetResult);
        }
        public void Init(MockContext context)
        {
            this.accounts = new Dictionary <AccountType, string>();

            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            handler1.IsPassThrough        = true;
            this.ResourceManagementClient = context.GetServiceClient <ResourceManagementClient>(handlers: handler1);

            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            handler2.IsPassThrough        = true;
            this.CosmosDBManagementClient = context.GetServiceClient <CosmosDBManagementClient>(handlers: handler2);

            // Create a resource group for testing.
            const string testPrefix = "CosmosDBDotNetSDKTestsRG";

            this.ResourceGroupName = TestUtilities.GenerateName(testPrefix);

            var resourceGroupDefinition = new ResourceGroup
            {
                Location = Location
            };

            ResourceManagementClient.ResourceGroups.CreateOrUpdate(this.ResourceGroupName, resourceGroupDefinition);
        }
Exemplo n.º 8
0
 protected void InitializeClients()
 {
     SubscriptionId            = TestEnvironment.SubscriptionId;
     ResourcesManagementClient = GetResourceManagementClient();
     ResourceGroupsOperations  = ResourcesManagementClient.ResourceGroups;
     CosmosDBManagementClient  = GetCosmosDBManagementClient();
 }
        private async Task RestorableMongodbTestHelper(
            CosmosDBManagementClient cosmosDBManagementClient,
            string sourceAccountInstanceId,
            List <DatabaseRestoreResource> resources = null)
        {
            List <RestorableMongodbDatabaseGetResult> restorableMongodbDatabases =
                (await cosmosDBManagementClient.RestorableMongodbDatabases.ListAsync(location, sourceAccountInstanceId)).ToList();

            Assert.Equal(resources.Count, restorableMongodbDatabases.Count());

            DatabaseRestoreResource resource = resources.Single(x => x.DatabaseName == "database1");

            RestorableMongodbDatabaseGetResult restorableMongodbDatabase = restorableMongodbDatabases.Single(db => db.Resource.OwnerId == resource.DatabaseName);

            string dbRid = restorableMongodbDatabase.Resource.OwnerResourceId;

            List <RestorableMongodbCollectionGetResult> restorableMongodbContainers =
                (await cosmosDBManagementClient.RestorableMongodbCollections.ListAsync(location, sourceAccountInstanceId, dbRid)).ToList();

            Assert.Equal(resource.CollectionNames.Count, restorableMongodbContainers.Count());

            List <DatabaseRestoreResource> restorableMongodbResources =
                (await cosmosDBManagementClient.RestorableMongodbResources.ListAsync(location, sourceAccountInstanceId, location, restoreTimestamp.ToString())).ToList();

            ValidateDatabaseRestoreResource(resources, restorableMongodbResources);
        }
Exemplo n.º 10
0
 protected void SetupManagementClients(MockContext context)
 {
     ResourceManagementClient = GetResourceManagementClient(context);
     CosmosDBManagementClient = GetCosmosDBManagementClient(context);
     _helper.SetupManagementClients(
         ResourceManagementClient,
         CosmosDBManagementClient);
 }
Exemplo n.º 11
0
        private SqlContainerGetResults CreateSQLResources(CosmosDBManagementClient cosmosDBManagementClient, string databaseAccountName, string databaseName, string containerName)
        {
            SqlDatabaseGetResults databaseGetResults = null;

            try
            {
                databaseGetResults = cosmosDBManagementClient.SqlResources.GetSqlDatabase(this.fixture.ResourceGroupName, databaseAccountName, databaseName);
            }
            catch (Exception) { }

            if (databaseGetResults == null)
            {
                SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters = new SqlDatabaseCreateUpdateParameters
                {
                    Resource = new SqlDatabaseResource {
                        Id = databaseName
                    },
                    Options = new CreateUpdateOptions()
                };

                databaseGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlDatabase(
                    this.fixture.ResourceGroupName,
                    databaseAccountName,
                    databaseName,
                    sqlDatabaseCreateUpdateParameters);
            }

            SqlContainerGetResults collectionGetResult = null;

            try
            {
                collectionGetResult = cosmosDBManagementClient.SqlResources.GetSqlContainer(this.fixture.ResourceGroupName, databaseAccountName, databaseName, containerName);
            }
            catch (Exception) { }

            if (collectionGetResult == null)
            {
                SqlContainerCreateUpdateParameters collectionCreateParams = new SqlContainerCreateUpdateParameters()
                {
                    Resource = new SqlContainerResource(containerName, partitionKey: new ContainerPartitionKey(new List <String>()
                    {
                        "/id"
                    })),
                    Options = new CreateUpdateOptions()
                    {
                        Throughput = 30000
                    }
                };
                collectionGetResult = cosmosDBManagementClient.SqlResources.CreateUpdateSqlContainer(
                    this.fixture.ResourceGroupName,
                    databaseAccountName,
                    databaseName,
                    containerName,
                    collectionCreateParams);
            }

            return(collectionGetResult);
        }
        public async Task RestoreDatabaseAccountTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);

                DatabaseAccountGetResults databaseAccount = await cosmosDBManagementClient.DatabaseAccounts.GetAsync(resourceGroupName, "pitr-sql-stage-source");

                DateTime restoreTs = DateTime.Parse(restoreTimestamp);
                string   restoredatabaseAccountName = TestUtilities.GenerateName(prefix: "restoredaccountname");

                List <RestorableDatabaseAccountGetResult> restorableAccounts        = (await cosmosDBManagementClient.RestorableDatabaseAccounts.ListAsync()).ToList();
                RestorableDatabaseAccountGetResult        restorableDatabaseAccount = restorableAccounts.
                                                                                      SingleOrDefault(account => account.Name.Equals(databaseAccount.InstanceId, StringComparison.OrdinalIgnoreCase));

                List <Location> locations = new List <Location>
                {
                    new Location(locationName: westus2)
                };

                RestoreReqeustDatabaseAccountCreateUpdateProperties databaseAccountCreateUpdateProperties = new RestoreReqeustDatabaseAccountCreateUpdateProperties
                {
                    Locations         = locations,
                    RestoreParameters = new RestoreParameters()
                    {
                        RestoreMode           = "PointInTime",
                        RestoreTimestampInUtc = restoreTs,
                        RestoreSource         = restorableDatabaseAccount.Id
                    }
                };

                DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                {
                    Location = westus2,
                    Tags     = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    },
                    Kind       = "GlobalDocumentDB",
                    Properties = databaseAccountCreateUpdateProperties
                };

                DatabaseAccountGetResults restoredDatabaseAccount =
                    (await cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(
                         resourceGroupName, restoredatabaseAccountName, databaseAccountCreateUpdateParameters)).Body;

                Assert.NotNull(restoredDatabaseAccount);
                Assert.NotNull(restoredDatabaseAccount.RestoreParameters);
                Assert.Equal(restoredDatabaseAccount.RestoreParameters.RestoreSource.ToLower(), restorableDatabaseAccount.Id.ToLower());
                Assert.True(restoredDatabaseAccount.BackupPolicy is ContinuousModeBackupPolicy);
            }
        }
        protected async Task InitializeClients()
        {
            SubscriptionId            = TestEnvironment.SubscriptionId;
            ResourcesManagementClient = GetResourceManagementClient();
            Subscription sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            ResourceGroupsOperations = sub.GetResourceGroups();
            CosmosDBManagementClient = GetCosmosDBManagementClient();
        }
 public CosmosDBMgmtClient(
     string subscriptionId,
     RestClient restClient
     )
 {
     _cosmosDBManagementClient = new CosmosDBManagementClient(restClient)
     {
         SubscriptionId = subscriptionId
     };
 }
Exemplo n.º 15
0
        private static async Task <DatabaseAccountGetResults> CreateDatabaseAccountIfNotExists(
            CosmosDBManagementClient cosmosDBManagementClient,
            string databaseAccountName,
            string armLocation,
            string kind)
        {
            bool            isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;
            String          databaseKind         = null;
            List <Location> locations            = null;

            if (kind == ApiType.Sql)
            {
                databaseKind = DatabaseAccountKind.GlobalDocumentDB;
                locations    = new List <Location> {
                    new Location {
                        LocationName = "westus"
                    }, new Location {
                        LocationName = "eastus"
                    }, new Location {
                        LocationName = "eastus2"
                    }
                };
            }
            else if (kind == ApiType.MongoDB)
            {
                databaseKind = DatabaseAccountKind.MongoDB;
                locations    = new List <Location> {
                    new Location {
                        LocationName = "westus"
                    }, new Location {
                        LocationName = "eastus"
                    }
                };
            }

            DatabaseAccountGetResults databaseAccount = null;

            if (!isDatabaseNameExists)
            {
                DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                {
                    Location     = armLocation,
                    Kind         = databaseKind,
                    Locations    = locations,
                    BackupPolicy = new ContinuousModeBackupPolicy()
                };

                databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.Equal(databaseAccount.Name, databaseAccountName);
            }
            databaseAccount = await cosmosDBManagementClient.DatabaseAccounts.GetAsync(resourceGroupName, databaseAccountName);

            return(databaseAccount);
        }
Exemplo n.º 16
0
        public async void CheckCosmosNameExistsTest()
        {
            Env.Load("../../../../../.env");


            var client = new CosmosDBManagementClient(new AzureIdentityCredentialAdapter());

            client.SubscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");

            var name = "cosmos" + Guid.NewGuid().ToString("n").Substring(0, 8);

            var results = await client.DatabaseAccounts.CheckNameExistsAsync(name);

            Assert.False(results);
        }
Exemplo n.º 17
0
        public async Task RestoreDatabaseAccountFeedTests()
        {
            RecordedDelegatingHandler handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler);

                await RestoreDatabaseAccountFeedTestHelperAsync(cosmosDBManagementClient, "pitr-sql-stage-source", ApiType.Sql, 1);
                await RestoreDatabaseAccountFeedTestHelperAsync(cosmosDBManagementClient, "pitr-mongo32-stage-source", ApiType.MongoDB, 1);
                await RestoreDatabaseAccountFeedTestHelperAsync(cosmosDBManagementClient, "pitr-mongo36-stage-source", ApiType.MongoDB, 1);
            }
        }
Exemplo n.º 18
0
        public void RetrieveMongoCollectionContinuousBackupInfoTest()
        {
            using (var context = MockContext.Start(this.GetType()))
            {
                fixture.Init(context);
                CosmosDBManagementClient cosmosDBManagementClient = this.fixture.CosmosDBManagementClient;
                var    resourceGroupName   = this.fixture.ResourceGroupName;
                var    databaseAccountName = this.fixture.GetDatabaseAccountName(TestFixture.AccountType.Mongo36);
                string location            = this.fixture.Location;
                var    databaseName        = TestUtilities.GenerateName("database");
                var    collectionName      = TestUtilities.GenerateName("collection");
                ContinuousBackupRestoreLocation restoreLocation = new ContinuousBackupRestoreLocation(location);

                this.CreateMongoDBResources(cosmosDBManagementClient, databaseAccountName, databaseName, collectionName);

                var result = cosmosDBManagementClient.DatabaseAccounts.Get(this.fixture.ResourceGroupName, databaseAccountName);

                DateTime?oldTime = result.SystemData.CreatedAt;
                Assert.NotNull(oldTime);
                BackupInformation backupInformation = cosmosDBManagementClient.MongoDBResources.RetrieveContinuousBackupInformation(
                    resourceGroupName,
                    databaseAccountName,
                    databaseName,
                    collectionName,
                    restoreLocation);

                Assert.NotNull(backupInformation);
                Assert.NotNull(backupInformation.ContinuousBackupInformation);
                Assert.True(DateTime.Parse(backupInformation.ContinuousBackupInformation.LatestRestorableTimestamp) > oldTime);

                oldTime = DateTime.Parse(backupInformation.ContinuousBackupInformation.LatestRestorableTimestamp);
                BackupInformation mongobackupInformation = cosmosDBManagementClient.MongoDBResources.RetrieveContinuousBackupInformation(
                    resourceGroupName,
                    databaseAccountName,
                    databaseName,
                    collectionName,
                    restoreLocation);

                Assert.NotNull(mongobackupInformation);
                Assert.NotNull(mongobackupInformation.ContinuousBackupInformation);
                Assert.True(DateTime.Parse(mongobackupInformation.ContinuousBackupInformation.LatestRestorableTimestamp) > oldTime);
            }
        }
Exemplo n.º 19
0
        public void RetrieveSqlContainerContinuousBackupInfoTest()
        {
            using (var context = MockContext.Start(this.GetType()))
            {
                fixture.Init(context);
                CosmosDBManagementClient cosmosDBManagementClient = this.fixture.CosmosDBManagementClient;
                var    resourceGroupName   = this.fixture.ResourceGroupName;
                var    databaseAccountName = this.fixture.GetDatabaseAccountName(TestFixture.AccountType.PitrSql);
                string location            = this.fixture.Location;
                var    databaseName        = TestUtilities.GenerateName("database");
                var    containerName       = TestUtilities.GenerateName("container");
                ContinuousBackupRestoreLocation restoreLocation = new ContinuousBackupRestoreLocation(location);

                var result = this.CreateSQLResources(cosmosDBManagementClient, databaseAccountName, databaseName, containerName);

                DateTime          oldTime           = DateTimeOffset.FromUnixTimeSeconds((int)result.Resource._ts).DateTime.AddSeconds(-1);
                BackupInformation backupInformation = cosmosDBManagementClient.SqlResources.RetrieveContinuousBackupInformation(
                    resourceGroupName,
                    databaseAccountName,
                    databaseName,
                    containerName,
                    restoreLocation);

                Assert.NotNull(backupInformation);
                Assert.NotNull(backupInformation.ContinuousBackupInformation);
                Assert.True(DateTime.Parse(backupInformation.ContinuousBackupInformation.LatestRestorableTimestamp) > oldTime);

                oldTime = DateTime.Parse(backupInformation.ContinuousBackupInformation.LatestRestorableTimestamp);
                BackupInformation sqlbackupInformation = cosmosDBManagementClient.SqlResources.RetrieveContinuousBackupInformation(
                    resourceGroupName,
                    databaseAccountName,
                    databaseName,
                    containerName,
                    restoreLocation);

                Assert.NotNull(sqlbackupInformation);
                Assert.NotNull(sqlbackupInformation.ContinuousBackupInformation);
                Assert.True(DateTime.Parse(sqlbackupInformation.ContinuousBackupInformation.LatestRestorableTimestamp) >= oldTime);
            }
        }
Exemplo n.º 20
0
        public void ListOperationsTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBMgmtClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);

                // Get operations
                var operations = cosmosDBMgmtClient.Operations.List();

                // Verify operations are returned
                Assert.NotNull(operations);
                Assert.NotEmpty(operations);
            }
        }
Exemplo n.º 21
0
        public void CreateCosmosDBTest()
        {
            Env.Load("../../../.env");


            var client = new CosmosDBManagementClient(new DefaultAzureMgmtCredential());

            client.SubscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");

            var name = Environment.GetEnvironmentVariable("COSMOSDB_NAME") + Guid.NewGuid().ToString("n").Substring(0, 8);

            var parameters = new DatabaseAccountCreateUpdateParameters
            {
                Location  = Environment.GetEnvironmentVariable("AZURE_REGION"),
                Locations = new List <Location> {
                    new Location(locationName: Environment.GetEnvironmentVariable("AZURE_REGION"))
                }
            };

            var results = client.DatabaseAccounts.CreateOrUpdate(Environment.GetEnvironmentVariable("AZURE_RESOURCE_GROUP"), name, parameters);

            Assert.Equal(results.Name, name);
        }
Exemplo n.º 22
0
        private DatabaseAccountGetResults CreateDatabaseAccount(CosmosDBManagementClient cosmosDBManagementClient, string databaseAccountName, string kind = DatabaseAccountKind.GlobalDocumentDB)
        {
            DatabaseAccountGetResults databaseAccount;

            try
            {
                DatabaseAccountGetResults databaseAccountGetResult = cosmosDBManagementClient.DatabaseAccounts.Get(this.fixture.ResourceGroupName, databaseAccountName);
                if (databaseAccountGetResult != null)
                {
                    return(databaseAccountGetResult);
                }
            }
            catch (Exception) { }

            bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;

            if (!isDatabaseNameExists)
            {
                DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters1 = new DatabaseAccountCreateUpdateParameters
                {
                    Location  = this.fixture.Location,
                    Kind      = kind,
                    Locations = new List <Location> {
                        new Location {
                            LocationName = this.fixture.Location
                        }
                    },
                    BackupPolicy = new ContinuousModeBackupPolicy(),
                };

                databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(this.fixture.ResourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters1).GetAwaiter().GetResult().Body;
                Assert.Equal(databaseAccount.Name, databaseAccountName);
            }
            databaseAccount = cosmosDBManagementClient.DatabaseAccounts.Get(this.fixture.ResourceGroupName, databaseAccountName);

            return(databaseAccount);
        }
        public PSRestoreParameters GetRestoreParameters(CosmosDBManagementClient cosmosDBManagementClient)
        {
            if (string.IsNullOrEmpty(SourceRestorableDatabaseAccountId) && !string.IsNullOrEmpty(SourceDatabaseAccountName))
            {
                List <RestorableDatabaseAccountGetResult> restorableDatabaseAccounts = cosmosDBManagementClient.RestorableDatabaseAccounts.ListWithHttpMessagesAsync().GetAwaiter().GetResult().Body.ToList();
                List <RestorableDatabaseAccountGetResult> accountsWithMatchingName   = restorableDatabaseAccounts.Where(databaseAccount => databaseAccount.AccountName.Equals(SourceDatabaseAccountName, StringComparison.OrdinalIgnoreCase)).ToList();
                if (accountsWithMatchingName.Count > 0)
                {
                    foreach (RestorableDatabaseAccountGetResult restorableAccount in accountsWithMatchingName)
                    {
                        if (restorableAccount.CreationTime.HasValue &&
                            restorableAccount.CreationTime < RestoreTimestampInUtc)
                        {
                            if (!restorableAccount.DeletionTime.HasValue || restorableAccount.DeletionTime < RestoreTimestampInUtc)
                            {
                                SourceRestorableDatabaseAccountId = restorableAccount.Id;
                                break;
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(SourceRestorableDatabaseAccountId))
            {
                return(null);
            }

            PSRestoreParameters restoreParameters = new PSRestoreParameters()
            {
                RestoreSource         = SourceRestorableDatabaseAccountId,
                RestoreTimestampInUtc = RestoreTimestampInUtc.DateTime,
                DatabasesToRestore    = DatabasesToRestore
            };

            return(restoreParameters);
        }
Exemplo n.º 24
0
        public void MongoCRUDTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);
                ResourceManagementClient resourcesClient          = CosmosDBTestUtilities.GetResourceManagementClient(context, handler2);

                string resourceGroupName   = "CosmosDBResourceGroup3668";
                string databaseAccountName = "db001";

                bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;

                DatabaseAccountGetResults databaseAccount = null;
                if (!isDatabaseNameExists)
                {
                    List <Location> locations = new List <Location>();
                    locations.Add(new Location(locationName: "East US"));
                    DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                    {
                        Location  = "EAST US",
                        Kind      = "MongoDB",
                        Locations = locations
                    };

                    databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body;
                }

                string databaseName  = "databaseName3668";
                string databaseName2 = "databaseName23668";
                MongoDBDatabaseCreateUpdateParameters mongoDBDatabaseCreateUpdateParameters = new MongoDBDatabaseCreateUpdateParameters
                {
                    Resource = new MongoDBDatabaseResource {
                        Id = databaseName
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "foo", "bar" }
                    }
                };

                MongoDBDatabaseGetResults mongoDBDatabaseGetResults = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, mongoDBDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.Equal(databaseName, mongoDBDatabaseGetResults.Name);
                Assert.NotNull(mongoDBDatabaseGetResults);
                Assert.Equal("Microsoft.DocumentDB/databaseAccounts/mongodbDatabases", mongoDBDatabaseGetResults.Type);

                MongoDBDatabaseGetResults mongoDBDatabaseGetResults1 = cosmosDBManagementClient.MongoDBResources.GetMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBDatabaseGetResults1);
                Assert.Equal(databaseName, mongoDBDatabaseGetResults1.Name);
                Assert.Equal("Microsoft.DocumentDB/databaseAccounts/mongodbDatabases", mongoDBDatabaseGetResults1.Type);


                VerifyEqualMongoDBDatabases(mongoDBDatabaseGetResults, mongoDBDatabaseGetResults1);

                MongoDBDatabaseCreateUpdateParameters mongoDBDatabaseCreateUpdateParameters2 = new MongoDBDatabaseCreateUpdateParameters
                {
                    Resource = new MongoDBDatabaseResource {
                        Id = databaseName2
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "Throughput", "700" }
                    }
                };

                MongoDBDatabaseGetResults mongoDBDatabaseGetResults2 = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2, mongoDBDatabaseCreateUpdateParameters2).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBDatabaseGetResults2);
                Assert.Equal(databaseName2, mongoDBDatabaseGetResults2.Name);
                Assert.Equal("Microsoft.DocumentDB/databaseAccounts/mongodbDatabases", mongoDBDatabaseGetResults2.Type);

                IEnumerable <MongoDBDatabaseGetResults> mongoDBDatabases = cosmosDBManagementClient.MongoDBResources.ListMongoDBDatabasesWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBDatabases);

                ThroughputSettingsGetResults throughputSettingsGetResults = cosmosDBManagementClient.MongoDBResources.GetMongoDBDatabaseThroughputWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2).GetAwaiter().GetResult().Body;
                Assert.NotNull(throughputSettingsGetResults);
                Assert.NotNull(throughputSettingsGetResults.Name);
                Assert.Equal("Microsoft.DocumentDB/databaseAccounts/mongodbDatabases/throughputSettings", throughputSettingsGetResults.Type);

                string collectionName = "collectionName3668";

                MongoDBCollectionCreateUpdateParameters mongoDBCollectionCreateUpdateParameters = new MongoDBCollectionCreateUpdateParameters
                {
                    Resource = new MongoDBCollectionResource
                    {
                        Id = collectionName,
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "foo", "bar" },
                    }
                };

                MongoDBCollectionGetResults mongoDBCollectionGetResults = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBCollectionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, collectionName, mongoDBCollectionCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBCollectionGetResults);

                IEnumerable <MongoDBCollectionGetResults> mongoDBCollections = cosmosDBManagementClient.MongoDBResources.ListMongoDBCollectionsWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBCollections);

                foreach (MongoDBCollectionGetResults mongoDBCollection in mongoDBCollections)
                {
                    cosmosDBManagementClient.MongoDBResources.DeleteMongoDBCollectionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, mongoDBCollection.Name);
                }

                foreach (MongoDBDatabaseGetResults mongoDBDatabase in mongoDBDatabases)
                {
                    cosmosDBManagementClient.MongoDBResources.DeleteMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, mongoDBDatabase.Name);
                }
            }
        }
        public void MongoCRUDTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);

                bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;

                DatabaseAccountGetResults databaseAccount = null;
                if (!isDatabaseNameExists)
                {
                    DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                    {
                        Location   = location,
                        Kind       = DatabaseAccountKind.MongoDB,
                        Properties = new DefaultRequestDatabaseAccountCreateUpdateProperties
                        {
                            Locations = new List <Location>
                            {
                                { new Location(locationName: location) }
                            }
                        }
                    };

                    databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body;
                    Assert.Equal(databaseAccount.Name, databaseAccountName);
                }

                MongoDBDatabaseCreateUpdateParameters mongoDBDatabaseCreateUpdateParameters = new MongoDBDatabaseCreateUpdateParameters
                {
                    Resource = new MongoDBDatabaseResource {
                        Id = databaseName
                    },
                    Options = new CreateUpdateOptions()
                };

                MongoDBDatabaseGetResults mongoDBDatabaseGetResults = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, mongoDBDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.Equal(databaseName, mongoDBDatabaseGetResults.Name);
                Assert.NotNull(mongoDBDatabaseGetResults);

                MongoDBDatabaseGetResults mongoDBDatabaseGetResults1 = cosmosDBManagementClient.MongoDBResources.GetMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBDatabaseGetResults1);
                Assert.Equal(databaseName, mongoDBDatabaseGetResults1.Name);

                VerifyEqualMongoDBDatabases(mongoDBDatabaseGetResults, mongoDBDatabaseGetResults1);

                MongoDBDatabaseCreateUpdateParameters mongoDBDatabaseCreateUpdateParameters2 = new MongoDBDatabaseCreateUpdateParameters
                {
                    Resource = new MongoDBDatabaseResource {
                        Id = databaseName2
                    },
                    Options = new CreateUpdateOptions
                    {
                        Throughput = sampleThroughput
                    }
                };

                MongoDBDatabaseGetResults mongoDBDatabaseGetResults2 = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2, mongoDBDatabaseCreateUpdateParameters2).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBDatabaseGetResults2);
                Assert.Equal(databaseName2, mongoDBDatabaseGetResults2.Name);

                IEnumerable <MongoDBDatabaseGetResults> mongoDBDatabases = cosmosDBManagementClient.MongoDBResources.ListMongoDBDatabasesWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBDatabases);

                ThroughputSettingsGetResults throughputSettingsGetResults = cosmosDBManagementClient.MongoDBResources.GetMongoDBDatabaseThroughputWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2).GetAwaiter().GetResult().Body;
                Assert.NotNull(throughputSettingsGetResults);
                Assert.NotNull(throughputSettingsGetResults.Name);
                Assert.Equal(throughputSettingsGetResults.Resource.Throughput, sampleThroughput);
                Assert.Equal(mongoDatabaseThroughputType, throughputSettingsGetResults.Type);

                MongoDBCollectionCreateUpdateParameters mongoDBCollectionCreateUpdateParameters = new MongoDBCollectionCreateUpdateParameters
                {
                    Resource = new MongoDBCollectionResource
                    {
                        Id = collectionName,
                    },
                    Options = new CreateUpdateOptions()
                };

                MongoDBCollectionGetResults mongoDBCollectionGetResults = cosmosDBManagementClient.MongoDBResources.CreateUpdateMongoDBCollectionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, collectionName, mongoDBCollectionCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBCollectionGetResults);
                VerfiyMongoCollectionCreation(mongoDBCollectionGetResults, mongoDBCollectionCreateUpdateParameters);

                IEnumerable <MongoDBCollectionGetResults> mongoDBCollections = cosmosDBManagementClient.MongoDBResources.ListMongoDBCollectionsWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(mongoDBCollections);

                foreach (MongoDBCollectionGetResults mongoDBCollection in mongoDBCollections)
                {
                    cosmosDBManagementClient.MongoDBResources.DeleteMongoDBCollectionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, mongoDBCollection.Name);
                }

                foreach (MongoDBDatabaseGetResults mongoDBDatabase in mongoDBDatabases)
                {
                    cosmosDBManagementClient.MongoDBResources.DeleteMongoDBDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, mongoDBDatabase.Name);
                }
            }
        }
        public void SqlCRUDTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);

                bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;

                DatabaseAccountGetResults databaseAccount = null;
                if (!isDatabaseNameExists)
                {
                    DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                    {
                        Location  = location,
                        Kind      = DatabaseAccountKind.GlobalDocumentDB,
                        Locations = new List <Location>()
                        {
                            { new Location(locationName: location) }
                        }
                    };

                    databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body;
                    Assert.Equal(databaseAccount.Name, databaseAccountName);
                }

                SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters = new SqlDatabaseCreateUpdateParameters
                {
                    Resource = new SqlDatabaseResource {
                        Id = databaseName
                    },
                    Options = new CreateUpdateOptions()
                };

                SqlDatabaseGetResults sqlDatabaseGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, sqlDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabaseGetResults);
                Assert.Equal(databaseName, sqlDatabaseGetResults.Name);

                SqlDatabaseGetResults sqlDatabaseGetResults2 = cosmosDBManagementClient.SqlResources.GetSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabaseGetResults2);
                Assert.Equal(databaseName, sqlDatabaseGetResults2.Name);

                VerifyEqualSqlDatabases(sqlDatabaseGetResults, sqlDatabaseGetResults2);

                SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters2 = new SqlDatabaseCreateUpdateParameters
                {
                    Location = location,
                    Tags     = tags,
                    Resource = new SqlDatabaseResource {
                        Id = databaseName2
                    },
                    Options = new CreateUpdateOptions
                    {
                        Throughput = sampleThroughput
                    }
                };

                SqlDatabaseGetResults sqlDatabaseGetResults3 = cosmosDBManagementClient.SqlResources.CreateUpdateSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2, sqlDatabaseCreateUpdateParameters2).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabaseGetResults3);
                Assert.Equal(databaseName2, sqlDatabaseGetResults3.Name);

                IEnumerable <SqlDatabaseGetResults> sqlDatabases = cosmosDBManagementClient.SqlResources.ListSqlDatabasesWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabases);

                ThroughputSettingsGetResults throughputSettingsGetResults = cosmosDBManagementClient.SqlResources.GetSqlDatabaseThroughputWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2).GetAwaiter().GetResult().Body;
                Assert.NotNull(throughputSettingsGetResults);
                Assert.NotNull(throughputSettingsGetResults.Name);
                Assert.Equal(sqlThroughputType, throughputSettingsGetResults.Type);

                SqlContainerCreateUpdateParameters sqlContainerCreateUpdateParameters = new SqlContainerCreateUpdateParameters
                {
                    Resource = new SqlContainerResource {
                        Id           = containerName,
                        PartitionKey = new ContainerPartitionKey
                        {
                            Kind  = "Hash",
                            Paths = new List <string> {
                                "/address/zipCode"
                            }
                        },
                        IndexingPolicy = new IndexingPolicy
                        {
                            Automatic     = true,
                            IndexingMode  = IndexingMode.Consistent,
                            IncludedPaths = new List <IncludedPath>
                            {
                                new IncludedPath {
                                    Path = "/*"
                                }
                            },
                            ExcludedPaths = new List <ExcludedPath>
                            {
                                new ExcludedPath {
                                    Path = "/pathToNotIndex/*"
                                }
                            },
                            CompositeIndexes = new List <IList <CompositePath> >
                            {
                                new List <CompositePath>
                                {
                                    new CompositePath {
                                        Path = "/orderByPath1", Order = CompositePathSortOrder.Ascending
                                    },
                                    new CompositePath {
                                        Path = "/orderByPath2", Order = CompositePathSortOrder.Descending
                                    }
                                },
                                new List <CompositePath>
                                {
                                    new CompositePath {
                                        Path = "/orderByPath3", Order = CompositePathSortOrder.Ascending
                                    },
                                    new CompositePath {
                                        Path = "/orderByPath4", Order = CompositePathSortOrder.Descending
                                    }
                                }
                            }
                        }
                    },
                    Options = new CreateUpdateOptions
                    {
                        Throughput = sampleThroughput
                    }
                };

                SqlContainerGetResults sqlContainerGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlContainerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlContainerCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlContainerGetResults);

                IEnumerable <SqlContainerGetResults> sqlContainers = cosmosDBManagementClient.SqlResources.ListSqlContainersWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlContainers);

                SqlStoredProcedureCreateUpdateParameters sqlStoredProcedureCreateUpdateParameters = new SqlStoredProcedureCreateUpdateParameters
                {
                    Resource = new SqlStoredProcedureResource
                    {
                        Id   = storedProcedureName,
                        Body = "function () { var context = getContext(); " +
                               "var response = context.getResponse();" +
                               "response.setBody('Hello, World');" +
                               "}"
                    },
                    Options = new CreateUpdateOptions()
                };

                SqlStoredProcedureGetResults sqlStoredProcedureGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlStoredProcedureWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, storedProcedureName, sqlStoredProcedureCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlStoredProcedureGetResults);
                Assert.Equal(sqlStoredProcedureGetResults.Resource.Body, sqlStoredProcedureGetResults.Resource.Body);

                IEnumerable <SqlStoredProcedureGetResults> sqlStoredProcedures = cosmosDBManagementClient.SqlResources.ListSqlStoredProceduresWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlStoredProcedures);

                foreach (SqlStoredProcedureGetResults sqlStoredProcedure in sqlStoredProcedures)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlStoredProcedureWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlStoredProcedure.Name);
                }

                SqlUserDefinedFunctionCreateUpdateParameters sqlUserDefinedFunctionCreateUpdateParameters = new SqlUserDefinedFunctionCreateUpdateParameters
                {
                    Resource = new SqlUserDefinedFunctionResource
                    {
                        Id   = userDefinedFunctionName,
                        Body = "function () { var context = getContext(); " +
                               "var response = context.getResponse();" +
                               "response.setBody('Hello, World');" +
                               "}"
                    },
                    Options = new CreateUpdateOptions()
                };

                SqlUserDefinedFunctionGetResults sqlUserDefinedFunctionGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlUserDefinedFunctionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, userDefinedFunctionName, sqlUserDefinedFunctionCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlUserDefinedFunctionGetResults);
                Assert.Equal(sqlUserDefinedFunctionGetResults.Resource.Body, sqlUserDefinedFunctionGetResults.Resource.Body);


                IEnumerable <SqlUserDefinedFunctionGetResults> sqlUserDefinedFunctions = cosmosDBManagementClient.SqlResources.ListSqlUserDefinedFunctionsWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlUserDefinedFunctions);

                foreach (SqlUserDefinedFunctionGetResults sqlUserDefinedFunction in sqlUserDefinedFunctions)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlUserDefinedFunctionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlUserDefinedFunction.Name);
                }

                SqlTriggerCreateUpdateParameters sqlTriggerCreateUpdateParameters = new SqlTriggerCreateUpdateParameters
                {
                    Resource = new SqlTriggerResource
                    {
                        Id = triggerName,
                        TriggerOperation = "All",
                        TriggerType      = "Pre",
                        Body             = "function () { var context = getContext(); " +
                                           "var response = context.getResponse();" +
                                           "response.setBody('Hello, World');" +
                                           "}"
                    },
                    Options = new CreateUpdateOptions()
                };

                SqlTriggerGetResults sqlTriggerGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlTriggerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, triggerName, sqlTriggerCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlTriggerGetResults);
                Assert.Equal(sqlTriggerGetResults.Resource.TriggerType, sqlTriggerCreateUpdateParameters.Resource.TriggerType);
                Assert.Equal(sqlTriggerGetResults.Resource.TriggerOperation, sqlTriggerCreateUpdateParameters.Resource.TriggerOperation);
                Assert.Equal(sqlTriggerGetResults.Resource.Body, sqlTriggerCreateUpdateParameters.Resource.Body);

                IEnumerable <SqlTriggerGetResults> sqlTriggers = cosmosDBManagementClient.SqlResources.ListSqlTriggersWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlTriggers);

                foreach (SqlTriggerGetResults sqlTrigger in sqlTriggers)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlTriggerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlTrigger.Name);
                }

                foreach (SqlContainerGetResults sqlContainer in sqlContainers)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlContainerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, sqlContainer.Name);
                }

                foreach (SqlDatabaseGetResults sqlDatabase in sqlDatabases)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, sqlDatabase.Name);
                }
            }
        }
        public void SqlCRUDTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);
                ResourceManagementClient resourcesClient          = CosmosDBTestUtilities.GetResourceManagementClient(context, handler2);

                string resourceGroupName   = "CosmosDBResourceGroup822"; // Using a pre-existing ResourceGroup and DatabaseAccount, because Database Account provisioning takes some time
                string databaseAccountName = "db9934";

                bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;

                DatabaseAccountGetResults databaseAccount = null;
                if (!isDatabaseNameExists)
                {
                    List <Location> locations = new List <Location>();
                    locations.Add(new Location(locationName: "East US"));
                    DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                    {
                        Location  = "EAST US",
                        Kind      = "GlobalDocumentDB",
                        Locations = locations
                    };

                    databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body;
                }

                string databaseName  = "databaseName822";
                string databaseName2 = "databaseName2822";
                SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters = new SqlDatabaseCreateUpdateParameters
                {
                    Resource = new SqlDatabaseResource {
                        Id = databaseName
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "foo", "bar" }
                    }
                };

                SqlDatabaseGetResults sqlDatabaseGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, sqlDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabaseGetResults);
                Assert.Equal(databaseName, sqlDatabaseGetResults.Name);

                SqlDatabaseGetResults sqlDatabaseGetResults2 = cosmosDBManagementClient.SqlResources.GetSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabaseGetResults2);
                Assert.Equal(databaseName, sqlDatabaseGetResults2.Name);

                VerifyEqualSqlDatabases(sqlDatabaseGetResults, sqlDatabaseGetResults2);

                SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters2 = new SqlDatabaseCreateUpdateParameters
                {
                    Location = "EAST US",
                    Tags     = new Dictionary <string, string>
                    {
                        { "key3", "value3" },
                        { "key4", "value4" }
                    },
                    Resource = new SqlDatabaseResource {
                        Id = databaseName2
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "Throughput", "700" }
                    }
                };

                SqlDatabaseGetResults sqlDatabaseGetResults3 = cosmosDBManagementClient.SqlResources.CreateUpdateSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2, sqlDatabaseCreateUpdateParameters2).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabaseGetResults3);
                Assert.Equal(databaseName2, sqlDatabaseGetResults3.Name);

                IEnumerable <SqlDatabaseGetResults> sqlDatabases = cosmosDBManagementClient.SqlResources.ListSqlDatabasesWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlDatabases);

                ThroughputSettingsGetResults throughputSettingsGetResults = cosmosDBManagementClient.SqlResources.GetSqlDatabaseThroughputWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2).GetAwaiter().GetResult().Body;
                Assert.NotNull(throughputSettingsGetResults);
                Assert.NotNull(throughputSettingsGetResults.Name);
                Assert.Equal("Microsoft.DocumentDB/databaseAccounts/sqlDatabases/throughputSettings", throughputSettingsGetResults.Type);

                string containerName = "containerName822";

                SqlContainerCreateUpdateParameters sqlContainerCreateUpdateParameters = new SqlContainerCreateUpdateParameters
                {
                    Resource = new SqlContainerResource {
                        Id           = containerName,
                        PartitionKey = new ContainerPartitionKey
                        {
                            Kind  = "Hash",
                            Paths = new List <string> {
                                "/address/zipCode"
                            }
                        }
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "Throughput", "700" }
                    }
                };

                SqlContainerGetResults sqlContainerGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlContainerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlContainerCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlContainerGetResults);

                IEnumerable <SqlContainerGetResults> sqlContainers = cosmosDBManagementClient.SqlResources.ListSqlContainersWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlContainers);

                string storedProcedureName = "storedProcedureName822";

                SqlStoredProcedureCreateUpdateParameters sqlStoredProcedureCreateUpdateParameters = new SqlStoredProcedureCreateUpdateParameters
                {
                    Resource = new SqlStoredProcedureResource
                    {
                        Id   = storedProcedureName,
                        Body = "function () { var context = getContext(); " +
                               "var response = context.getResponse();" +
                               "response.setBody('Hello, World');" +
                               "}"
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "foo", "bar" }
                    }
                };

                SqlStoredProcedureGetResults sqlStoredProcedureGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlStoredProcedureWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, storedProcedureName, sqlStoredProcedureCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlStoredProcedureGetResults);

                IEnumerable <SqlStoredProcedureGetResults> sqlStoredProcedures = cosmosDBManagementClient.SqlResources.ListSqlStoredProceduresWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlStoredProcedures);

                foreach (SqlStoredProcedureGetResults sqlStoredProcedure in sqlStoredProcedures)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlStoredProcedureWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlStoredProcedure.Name);
                }

                string userDefinedFunctionName = "userDefinedFunctionName822";

                SqlUserDefinedFunctionCreateUpdateParameters sqlUserDefinedFunctionCreateUpdateParameters = new SqlUserDefinedFunctionCreateUpdateParameters
                {
                    Resource = new SqlUserDefinedFunctionResource
                    {
                        Id   = userDefinedFunctionName,
                        Body = "function () { var context = getContext(); " +
                               "var response = context.getResponse();" +
                               "response.setBody('Hello, World');" +
                               "}"
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "foo", "bar" }
                    }
                };

                SqlUserDefinedFunctionGetResults sqlUserDefinedFunctionGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlUserDefinedFunctionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, userDefinedFunctionName, sqlUserDefinedFunctionCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlStoredProcedureGetResults);

                IEnumerable <SqlUserDefinedFunctionGetResults> sqlUserDefinedFunctions = cosmosDBManagementClient.SqlResources.ListSqlUserDefinedFunctionsWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlUserDefinedFunctions);

                foreach (SqlUserDefinedFunctionGetResults sqlUserDefinedFunction in sqlUserDefinedFunctions)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlUserDefinedFunctionWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlUserDefinedFunction.Name);
                }

                string triggerName = "triggerName822";

                SqlTriggerCreateUpdateParameters sqlTriggerCreateUpdateParameters = new SqlTriggerCreateUpdateParameters
                {
                    Resource = new SqlTriggerResource
                    {
                        Id = triggerName,
                        TriggerOperation = "All",
                        TriggerType      = "Pre",
                        Body             = "function () { var context = getContext(); " +
                                           "var response = context.getResponse();" +
                                           "response.setBody('Hello, World');" +
                                           "}"
                    },
                    Options = new Dictionary <string, string>()
                    {
                        { "foo", "bar" }
                    }
                };

                SqlTriggerGetResults sqlTriggerGetResults = cosmosDBManagementClient.SqlResources.CreateUpdateSqlTriggerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, triggerName, sqlTriggerCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlTriggerGetResults);

                IEnumerable <SqlTriggerGetResults> sqlTriggers = cosmosDBManagementClient.SqlResources.ListSqlTriggersWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName).GetAwaiter().GetResult().Body;
                Assert.NotNull(sqlTriggers);

                foreach (SqlTriggerGetResults sqlTrigger in sqlTriggers)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlTriggerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlTrigger.Name);
                }

                foreach (SqlContainerGetResults sqlContainer in sqlContainers)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlContainerWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, sqlContainer.Name);
                }

                foreach (SqlDatabaseGetResults sqlDatabase in sqlDatabases)
                {
                    cosmosDBManagementClient.SqlResources.DeleteSqlDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, sqlDatabase.Name);
                }
            }
        }
        public void DatabaseAccountCRUDTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);
                ResourceManagementClient resourcesClient          = CosmosDBTestUtilities.GetResourceManagementClient(context, handler2);

                string resourceGroupName   = CosmosDBTestUtilities.CreateResourceGroup(resourcesClient);
                string databaseAccountName = TestUtilities.GenerateName(prefix: "accountname");

                List <Location> locations = new List <Location>();
                locations.Add(new Location(locationName: location));
                DefaultRequestDatabaseAccountCreateUpdateProperties databaseAccountCreateUpdateProperties = new DefaultRequestDatabaseAccountCreateUpdateProperties
                {
                    ConsistencyPolicy = new ConsistencyPolicy
                    {
                        DefaultConsistencyLevel = DefaultConsistencyLevel.BoundedStaleness,
                        MaxStalenessPrefix      = 300,
                        MaxIntervalInSeconds    = 1000
                    },
                    Locations = locations,
                    IpRules   = new List <IpAddressOrRange>
                    {
                        new IpAddressOrRange("23.43.230.120")
                    },
                    IsVirtualNetworkFilterEnabled = true,
                    EnableAutomaticFailover       = false,
                    EnableMultipleWriteLocations  = true,
                    EnableCassandraConnector      = true,
                    ConnectorOffer = "Small",
                    DisableKeyBasedMetadataWriteAccess = false
                };

                DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                {
                    Location = location,
                    Tags     = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    },
                    Kind       = "MongoDB",
                    Properties = databaseAccountCreateUpdateProperties
                };

                DatabaseAccountGetResults databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body;

                VerifyCosmosDBAccount(databaseAccount, databaseAccountCreateUpdateParameters);
                Assert.Equal(databaseAccountName, databaseAccount.Name);

                DatabaseAccountGetResults readDatabaseAccount = cosmosDBManagementClient.DatabaseAccounts.GetWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                VerifyCosmosDBAccount(readDatabaseAccount, databaseAccountCreateUpdateParameters);
                Assert.Equal(databaseAccountName, readDatabaseAccount.Name);

                DatabaseAccountUpdateParameters databaseAccountUpdateParameters = new DatabaseAccountUpdateParameters
                {
                    Location = location,
                    Tags     = new Dictionary <string, string>
                    {
                        { "key3", "value3" },
                        { "key4", "value4" }
                    },
                    ConsistencyPolicy = new ConsistencyPolicy
                    {
                        DefaultConsistencyLevel = DefaultConsistencyLevel.Session,
                        MaxStalenessPrefix      = 1300,
                        MaxIntervalInSeconds    = 12000
                    },
                    Locations = locations,
                    IpRules   = new List <IpAddressOrRange>
                    {
                        new IpAddressOrRange("23.43.230.120")
                    },
                    IsVirtualNetworkFilterEnabled = false,
                    EnableAutomaticFailover       = true,
                    EnableCassandraConnector      = true,
                    ConnectorOffer = "Small",
                    DisableKeyBasedMetadataWriteAccess = true
                };

                DatabaseAccountGetResults updatedDatabaseAccount = cosmosDBManagementClient.DatabaseAccounts.UpdateWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseAccountUpdateParameters).GetAwaiter().GetResult().Body;

                VerifyCosmosDBAccount(updatedDatabaseAccount, databaseAccountUpdateParameters);
                Assert.Equal(databaseAccountName, databaseAccount.Name);

                IEnumerable <DatabaseAccountGetResults> databaseAccounts = cosmosDBManagementClient.DatabaseAccounts.ListWithHttpMessagesAsync().GetAwaiter().GetResult().Body;
                Assert.NotNull(databaseAccounts);

                IEnumerable <DatabaseAccountGetResults> databaseAccountsByResourceGroupName = cosmosDBManagementClient.DatabaseAccounts.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName).GetAwaiter().GetResult().Body;
                Assert.NotNull(databaseAccountsByResourceGroupName);

                DatabaseAccountListKeysResult databaseAccountListKeysResult = cosmosDBManagementClient.DatabaseAccounts.ListKeysWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;

                Assert.NotNull(databaseAccountListKeysResult.PrimaryMasterKey);
                Assert.NotNull(databaseAccountListKeysResult.SecondaryMasterKey);
                Assert.NotNull(databaseAccountListKeysResult.PrimaryReadonlyMasterKey);
                Assert.NotNull(databaseAccountListKeysResult.SecondaryReadonlyMasterKey);

                DatabaseAccountListConnectionStringsResult databaseAccountListConnectionStringsResult = cosmosDBManagementClient.DatabaseAccounts.ListConnectionStringsWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(databaseAccountListConnectionStringsResult);

                DatabaseAccountListReadOnlyKeysResult databaseAccountGetReadOnlyKeysResult = cosmosDBManagementClient.DatabaseAccounts.GetReadOnlyKeysWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(databaseAccountGetReadOnlyKeysResult);

                DatabaseAccountListReadOnlyKeysResult databaseAccountListReadOnlyKeysResult = cosmosDBManagementClient.DatabaseAccounts.ListReadOnlyKeysWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(databaseAccountListReadOnlyKeysResult);

                cosmosDBManagementClient.DatabaseAccounts.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, databaseAccountName, new DatabaseAccountRegenerateKeyParameters {
                    KeyKind = "primary"
                });
                cosmosDBManagementClient.DatabaseAccounts.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, databaseAccountName, new DatabaseAccountRegenerateKeyParameters {
                    KeyKind = "secondary"
                });
                cosmosDBManagementClient.DatabaseAccounts.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, databaseAccountName, new DatabaseAccountRegenerateKeyParameters {
                    KeyKind = "primaryReadonly"
                });
                cosmosDBManagementClient.DatabaseAccounts.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, databaseAccountName, new DatabaseAccountRegenerateKeyParameters {
                    KeyKind = "secondaryReadonly"
                });

                DatabaseAccountListKeysResult databaseAccountListRegeneratedKeysResult = cosmosDBManagementClient.DatabaseAccounts.ListKeysWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;

                cosmosDBManagementClient.DatabaseAccounts.DeleteWithHttpMessagesAsync(resourceGroupName, databaseAccountName);
            }
        }
        public async Task SqlCRUDTests()
        {
            CosmosDBManagementClient  cosmosDBManagementClient = GetCosmosDBManagementClient();
            DatabaseAccountGetResults databaseAccount          = null;

            var locations = new List <Location>()
            {
                { new Location(id: default(string), locationName: location, documentEndpoint: default(string), provisioningState: default(string), failoverPriority: default(int?), isZoneRedundant: default(bool?)) }
            };
            DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters(locations)
            {
                Location = location,
                Kind     = DatabaseAccountKind.GlobalDocumentDB,
            };

            databaseAccount = await WaitForCompletionAsync(await cosmosDBManagementClient.DatabaseAccounts.StartCreateOrUpdateAsync(resourceGroupName, databaseAccountName, databaseAccountCreateUpdateParameters));

            Assert.AreEqual(databaseAccount.Name, databaseAccountName);

            Response isDatabaseNameExists = await cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsAsync(databaseAccountName);

            Assert.AreEqual(200, isDatabaseNameExists.Status);

            //Create sql database
            SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters = new SqlDatabaseCreateUpdateParameters(new SqlDatabaseResource(databaseName), new CreateUpdateOptions());
            SqlDatabaseGetResults             sqlDatabaseGetResults             = await WaitForCompletionAsync(await cosmosDBManagementClient.SqlResources.StartCreateUpdateSqlDatabaseAsync(resourceGroupName, databaseAccountName, databaseName, sqlDatabaseCreateUpdateParameters));

            Assert.NotNull(sqlDatabaseGetResults);
            Assert.AreEqual(databaseName, sqlDatabaseGetResults.Name);

            SqlDatabaseGetResults sqlDatabaseGetResults2 = (await cosmosDBManagementClient.SqlResources.GetSqlDatabaseAsync(resourceGroupName, databaseAccountName, databaseName)).Value;

            Assert.NotNull(sqlDatabaseGetResults2);
            Assert.AreEqual(databaseName, sqlDatabaseGetResults2.Name);
            VerifyEqualSqlDatabases(sqlDatabaseGetResults, sqlDatabaseGetResults2);

            SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters2 = new SqlDatabaseCreateUpdateParameters(id: default(string), name: default(string), type: default(string), location: location, tags: tags, resource: new SqlDatabaseResource(databaseName2), options: new CreateUpdateOptions {
                Throughput = sampleThroughput
            });
            SqlDatabaseGetResults sqlDatabaseGetResults3 = await WaitForCompletionAsync(await cosmosDBManagementClient.SqlResources.StartCreateUpdateSqlDatabaseAsync(resourceGroupName, databaseAccountName, databaseName2, sqlDatabaseCreateUpdateParameters2));

            Assert.NotNull(sqlDatabaseGetResults3);
            Assert.AreEqual(databaseName2, sqlDatabaseGetResults3.Name);

            IAsyncEnumerable <SqlDatabaseGetResults> sqlDatabases = cosmosDBManagementClient.SqlResources.ListSqlDatabasesAsync(resourceGroupName, databaseAccountName);

            Assert.NotNull(sqlDatabases);

            ThroughputSettingsGetResults throughputSettingsGetResults = (await cosmosDBManagementClient.SqlResources.GetSqlDatabaseThroughputAsync(resourceGroupName, databaseAccountName, databaseName2)).Value;

            Assert.NotNull(throughputSettingsGetResults);
            Assert.NotNull(throughputSettingsGetResults.Name);
            Assert.AreEqual(sqlThroughputType, throughputSettingsGetResults.Type);

            //Create sql container
            SqlContainerCreateUpdateParameters sqlContainerCreateUpdateParameters = new SqlContainerCreateUpdateParameters(
                resource: new SqlContainerResource(containerName)
            {
                PartitionKey = new ContainerPartitionKey(new List <string> {
                    "/address/zipCode"
                }, null, null)
                {
                    Kind = new PartitionKind("Hash")
                },
                IndexingPolicy = new IndexingPolicy(true, IndexingMode.Consistent,
                                                    new List <IncludedPath>
                {
                    new IncludedPath {
                        Path = "/*"
                    }
                },
                                                    new List <ExcludedPath>
                {
                    new ExcludedPath {
                        Path = "/pathToNotIndex/*"
                    }
                },
                                                    new List <IList <CompositePath> >
                {
                    new List <CompositePath>
                    {
                        new CompositePath {
                            Path = "/orderByPath1", Order = CompositePathSortOrder.Ascending
                        },
                        new CompositePath {
                            Path = "/orderByPath2", Order = CompositePathSortOrder.Descending
                        }
                    },
                    new List <CompositePath>
                    {
                        new CompositePath {
                            Path = "/orderByPath3", Order = CompositePathSortOrder.Ascending
                        },
                        new CompositePath {
                            Path = "/orderByPath4", Order = CompositePathSortOrder.Descending
                        }
                    }
                },
                                                    new List <SpatialSpec>
                {
                    new SpatialSpec
                    (
                        "/*",
                        new List <SpatialType>
                    {
                        new SpatialType("Point")
                    }
                    ),
                }
                                                    )
            },
                options: new CreateUpdateOptions
            {
                Throughput = sampleThroughput
            }
                );
            SqlContainerGetResults sqlContainerGetResults = await WaitForCompletionAsync(await cosmosDBManagementClient.SqlResources.StartCreateUpdateSqlContainerAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlContainerCreateUpdateParameters));

            Assert.NotNull(sqlContainerGetResults);
            VerifySqlContainerCreation(sqlContainerGetResults, sqlContainerCreateUpdateParameters);

            IAsyncEnumerable <SqlContainerGetResults> sqlContainers = cosmosDBManagementClient.SqlResources.ListSqlContainersAsync(resourceGroupName, databaseAccountName, databaseName);

            Assert.NotNull(sqlContainers);

            //Create stored procedure
            SqlStoredProcedureCreateUpdateParameters sqlStoredProcedureCreateUpdateParameters = new SqlStoredProcedureCreateUpdateParameters(
                new SqlStoredProcedureResource(storedProcedureName)
            {
                Body = "function () { var context = getContext(); " +
                       "var response = context.getResponse();" +
                       "response.setBody('Hello, World');" +
                       "}"
            },
                new CreateUpdateOptions()
                );

            SqlStoredProcedureGetResults sqlStoredProcedureGetResults = await WaitForCompletionAsync(await cosmosDBManagementClient.SqlResources.StartCreateUpdateSqlStoredProcedureAsync(resourceGroupName, databaseAccountName, databaseName, containerName, storedProcedureName, sqlStoredProcedureCreateUpdateParameters));

            Assert.NotNull(sqlStoredProcedureGetResults);
            Assert.AreEqual(sqlStoredProcedureGetResults.Resource.Body, sqlStoredProcedureGetResults.Resource.Body);

            IAsyncEnumerable <SqlStoredProcedureGetResults> sqlStoredProcedures = cosmosDBManagementClient.SqlResources.ListSqlStoredProceduresAsync(resourceGroupName, databaseAccountName, databaseName, containerName);

            Assert.NotNull(sqlStoredProcedures);

            //Create defined function
            SqlUserDefinedFunctionCreateUpdateParameters sqlUserDefinedFunctionCreateUpdateParameters = new SqlUserDefinedFunctionCreateUpdateParameters(
                resource: new SqlUserDefinedFunctionResource(userDefinedFunctionName)
            {
                Body = "function () { var context = getContext(); " +
                       "var response = context.getResponse();" +
                       "response.setBody('Hello, World');" +
                       "}"
            },
                options: new CreateUpdateOptions()
                );

            SqlUserDefinedFunctionGetResults sqlUserDefinedFunctionGetResults = await WaitForCompletionAsync(await cosmosDBManagementClient.SqlResources.StartCreateUpdateSqlUserDefinedFunctionAsync(resourceGroupName, databaseAccountName, databaseName, containerName, userDefinedFunctionName, sqlUserDefinedFunctionCreateUpdateParameters));

            Assert.NotNull(sqlUserDefinedFunctionGetResults);
            Assert.AreEqual(sqlUserDefinedFunctionGetResults.Resource.Body, sqlUserDefinedFunctionGetResults.Resource.Body);


            IAsyncEnumerable <SqlUserDefinedFunctionGetResults> sqlUserDefinedFunctions = cosmosDBManagementClient.SqlResources.ListSqlUserDefinedFunctionsAsync(resourceGroupName, databaseAccountName, databaseName, containerName);

            Assert.NotNull(sqlUserDefinedFunctions);


            //Create trigger
            SqlTriggerCreateUpdateParameters sqlTriggerCreateUpdateParameters = new SqlTriggerCreateUpdateParameters(
                resource: new SqlTriggerResource(triggerName)
            {
                TriggerOperation = "All",
                TriggerType      = "Pre",
                Body             = "function () { var context = getContext(); " +
                                   "var response = context.getResponse();" +
                                   "response.setBody('Hello, World');" +
                                   "}"
            },
                options: new CreateUpdateOptions()
                );

            SqlTriggerGetResults sqlTriggerGetResults = await WaitForCompletionAsync(await cosmosDBManagementClient.SqlResources.StartCreateUpdateSqlTriggerAsync(resourceGroupName, databaseAccountName, databaseName, containerName, triggerName, sqlTriggerCreateUpdateParameters));

            Assert.NotNull(sqlTriggerGetResults);
            Assert.AreEqual(sqlTriggerGetResults.Resource.TriggerType, sqlTriggerCreateUpdateParameters.Resource.TriggerType);
            Assert.AreEqual(sqlTriggerGetResults.Resource.TriggerOperation, sqlTriggerCreateUpdateParameters.Resource.TriggerOperation);
            Assert.AreEqual(sqlTriggerGetResults.Resource.Body, sqlTriggerCreateUpdateParameters.Resource.Body);

            IAsyncEnumerable <SqlTriggerGetResults> sqlTriggers = cosmosDBManagementClient.SqlResources.ListSqlTriggersAsync(resourceGroupName, databaseAccountName, databaseName, containerName);

            Assert.NotNull(sqlTriggers);

            //Delete operations
            await foreach (SqlStoredProcedureGetResults sqlStoredProcedure in sqlStoredProcedures)
            {
                await cosmosDBManagementClient.SqlResources.StartDeleteSqlStoredProcedureAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlStoredProcedure.Name);
            }

            await foreach (SqlUserDefinedFunctionGetResults sqlUserDefinedFunction in sqlUserDefinedFunctions)
            {
                await cosmosDBManagementClient.SqlResources.StartDeleteSqlStoredProcedureAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlUserDefinedFunction.Name);
            }

            await foreach (SqlTriggerGetResults sqlTrigger in sqlTriggers)
            {
                await cosmosDBManagementClient.SqlResources.StartDeleteSqlTriggerAsync(resourceGroupName, databaseAccountName, databaseName, containerName, sqlTrigger.Name);
            }
            await foreach (SqlContainerGetResults sqlContainer in sqlContainers)
            {
                await cosmosDBManagementClient.SqlResources.StartDeleteSqlContainerAsync(resourceGroupName, databaseAccountName, databaseName, sqlContainer.Name);
            }

            await foreach (SqlDatabaseGetResults sqlDatabase in sqlDatabases)
            {
                await cosmosDBManagementClient.SqlResources.StartDeleteSqlDatabaseAsync(resourceGroupName, databaseAccountName, sqlDatabase.Name);
            }
        }
Exemplo n.º 30
0
        public async Task RestoreDatabaseAccountTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);
                ResourceManagementClient resourcesClient          = CosmosDBTestUtilities.GetResourceManagementClient(context, handler1);
                string restoredatabaseAccountName = TestUtilities.GenerateName(prefix: "restoredaccountname");

                DatabaseAccountGetResults databaseAccount = null;
                bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(sourceDatabaseAccountName).GetAwaiter().GetResult().Body;
                if (!isDatabaseNameExists)
                {
                    DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters1 = new DatabaseAccountCreateUpdateParameters
                    {
                        Location  = location,
                        Kind      = DatabaseAccountKind.GlobalDocumentDB,
                        Locations = new List <Location> {
                            new Location {
                                LocationName = location
                            }
                        },
                        BackupPolicy = new ContinuousModeBackupPolicy(),
                    };

                    databaseAccount = cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, sourceDatabaseAccountName, databaseAccountCreateUpdateParameters1).GetAwaiter().GetResult().Body;
                    Assert.Equal(databaseAccount.Name, sourceDatabaseAccountName);
                }
                databaseAccount = await cosmosDBManagementClient.DatabaseAccounts.GetAsync(resourceGroupName, sourceDatabaseAccountName);

                DateTime restoreTs = DateTime.UtcNow;

                List <RestorableDatabaseAccountGetResult> restorableAccounts        = (await cosmosDBManagementClient.RestorableDatabaseAccounts.ListByLocationAsync(location)).ToList();
                RestorableDatabaseAccountGetResult        restorableDatabaseAccount = restorableAccounts.
                                                                                      SingleOrDefault(account => account.AccountName.Equals(databaseAccount.Name, StringComparison.OrdinalIgnoreCase));

                DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters
                {
                    Location = location,
                    Tags     = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    },
                    Kind      = "GlobalDocumentDB",
                    Locations = new List <Location>
                    {
                        new Location(locationName: location)
                    },
                    CreateMode        = CreateMode.Restore,
                    RestoreParameters = new RestoreParameters()
                    {
                        RestoreMode           = "PointInTime",
                        RestoreTimestampInUtc = restoreTs,
                        RestoreSource         = restorableDatabaseAccount.Id
                    }
                };

                DatabaseAccountGetResults restoredDatabaseAccount = (await cosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, restoredatabaseAccountName, databaseAccountCreateUpdateParameters)).Body;
                Assert.NotNull(restoredDatabaseAccount);
                Assert.NotNull(restoredDatabaseAccount.RestoreParameters);
                Assert.Equal(restoredDatabaseAccount.RestoreParameters.RestoreSource.ToLower(), restorableDatabaseAccount.Id.ToLower());
                Assert.True(restoredDatabaseAccount.BackupPolicy is ContinuousModeBackupPolicy);
            }
        }