/// <summary> /// creates a mongo db workflows class. /// </summary> /// <param name="account"> cosmos db account, prefereably with MONGO DB API (mongo db) set as the default expirience. </param> /// <param name="name"> name of the account. </param> /// <returns> an instance of MongoDBWorkflows</returns> public MongoDBWorkflows GenerateMongoDBWF(ICosmosDBAccount account, string name) { MongoDBWorkflows wf = new MongoDBWorkflows(account); mongodbWorkflows.Add(name, wf); return(wf); }
public async Task GetOrCreateAsync(string resourceGroup, string cosmosDbName, string primaryRegion, IEnumerable <string> replicaRegions, string accountRegion = null) { var resourceGroupRegion = accountRegion != null ? accountRegion : primaryRegion; _cosmosDBAccount = await _azure.CosmosDBAccounts.GetByResourceGroupAsync(resourceGroup, cosmosDbName); if (_cosmosDBAccount == null) { if (!await _azure.ResourceGroups.ContainAsync(resourceGroup)) { await _azure.ResourceGroups.Define(resourceGroup).WithRegion(resourceGroupRegion).CreateAsync(); } var create = _azure.CosmosDBAccounts.Define(cosmosDbName) .WithRegion(primaryRegion) .WithExistingResourceGroup(resourceGroup) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithStrongConsistency() .WithReadReplication(Region.Create(primaryRegion)); foreach (var secondary in replicaRegions) { create.WithReadReplication(Region.Create(secondary)); } _cosmosDBAccount = await create.CreateAsync(); } }
/// <summary> /// creates a graph workflows class. /// </summary> /// <param name="account"> cosmos db account, prefereably with GRAPH API (graph database) set as the default expirience. </param> /// <param name="name"> name of the account. </param> /// <returns> an instance of GraphWorkflows</returns> public GraphWorkflows GenerateGraphWF(ICosmosDBAccount account, string name) { GraphWorkflows wf = new GraphWorkflows(account); graphWorkflows.Add(name, wf); return(wf); }
/// <summary> /// creates a table workflows class. /// </summary> /// <param name="account"> cosmos db account, prefereably with TABLE API (table store) set as the default expirience. </param> /// <param name="name"> name of the account. </param> /// <returns> an instance of TableWorkflows</returns> public TableWorkflows GenerateTableWF(ICosmosDBAccount account, string name) { TableWorkflows wf = new TableWorkflows(account); tableWorkflows.Add(name, wf); return(wf); }
/// <summary> /// creates a doc db workflows class. /// </summary> /// <param name="account"> cosmos db account, prefereably with SQL API (doc db) set as the default expirience. </param> /// <param name="name"> name of the account. </param> /// <returns> an instance of DocumentDBWorkflows</returns> public DocumentDBWorkflows GenerateDocDBWF(ICosmosDBAccount account, string name) { DocumentDBWorkflows wf = new DocumentDBWorkflows(account); docdbWorkflows.Add(name, wf); return(wf); }
/** * Azure CosmosDB sample - * - Create a CosmosDB configured with MongoDB kind. * - Get the mongodb connection string * - Delete the CosmosDB. */ public static void RunSample(IAzure azure) { string cosmosDBName = SdkContext.RandomResourceName("docDb", 10); string rgName = SdkContext.RandomResourceName("rgNEMV", 24); try { //============================================================ // Create a CosmosDB. Console.WriteLine("Creating a CosmosDB..."); ICosmosDBAccount cosmosDBAccount = azure.CosmosDBAccounts.Define(cosmosDBName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithKind(DatabaseAccountKind.MongoDB) .WithEventualConsistency() .WithWriteReplication(Region.USEast) .WithReadReplication(Region.USCentral) .Create(); Console.WriteLine("Created CosmosDB"); Utilities.Print(cosmosDBAccount); //============================================================ // Get credentials for the CosmosDB. Console.WriteLine("Get credentials for the CosmosDB"); DatabaseAccountListKeysResultInner databaseAccountListKeysResult = cosmosDBAccount.ListKeys(); string masterKey = databaseAccountListKeysResult.PrimaryMasterKey; string endPoint = cosmosDBAccount.DocumentEndpoint; Console.WriteLine("Get the MongoDB connection string"); DatabaseAccountListConnectionStringsResultInner databaseAccountListConnectionStringsResult = cosmosDBAccount.ListConnectionStrings(); Console.WriteLine("MongoDB connection string: " + databaseAccountListConnectionStringsResult.ConnectionStrings[0].ConnectionString); //============================================================ // Delete CosmosDB Console.WriteLine("Deleting the CosmosDB"); azure.CosmosDBAccounts.DeleteById(cosmosDBAccount.Id); Console.WriteLine("Deleted the CosmosDB"); } finally { try { Utilities.Log("Deleting resource group: " + rgName); azure.ResourceGroups.DeleteByName(rgName); Utilities.Log("Deleted resource group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception e) { Utilities.Log(e.StackTrace); } } }
/// <summary> /// Create a TableUtils class for use with CosmosDB Table API operations/resources /// </summary> /// <param name="account"> a valid cosmos db account. </param> public TableUtils(ICosmosDBAccount account) : base(account) { this.connectionString = FormConnectionString(account); CloudStorageAccount storageAccount = CreateStorageAccountTB(); this.tableClient = CreateClientTB(storageAccount); }
private async Task <string> GenerateDbKeyAsync(string key, ICosmosDBAccount account, CancellationToken token) { await account.RegenerateKeyAsync(key, token); var keys = await account.ListKeysAsync(); if (string.Compare(key, KeyKind.Primary.Value, true) == 0) { return(keys.PrimaryMasterKey); } if (string.Compare(key, KeyKind.PrimaryReadonly.Value, true) == 0) { return(keys.PrimaryReadonlyMasterKey); } if (string.Compare(key, KeyKind.Secondary.Value, true) == 0) { return(keys.SecondaryMasterKey); } if (string.Compare(key, KeyKind.SecondaryReadonly.Value, true) == 0) { return(keys.SecondaryReadonlyMasterKey); } return(null); }
public void CosmosDBCRUD() { using (var context = FluentMockContext.Start(GetType().FullName)) { var dbName = TestUtilities.GenerateName("db"); var saName = TestUtilities.GenerateName("dbsa"); var rgName = TestUtilities.GenerateName("ddbRg"); var manager = TestHelper.CreateCosmosDB(); var resourceManager = TestHelper.CreateResourceManager(); ICosmosDBAccount databaseAccount = null; try { databaseAccount = manager.CosmosDBAccounts.Define(dbName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithSessionConsistency() .WithDefaultWriteReplication() .WithReadReplication(Region.USCentral, true) .WithIpRangeFilter("") .WithMultipleWriteLocationsEnabled(true) .Create(); Assert.Equal(databaseAccount.Name, dbName.ToLower()); Assert.Equal(DatabaseAccountKind.GlobalDocumentDB.Value, databaseAccount.Kind); Assert.Equal(2, databaseAccount.WritableReplications.Count); Assert.Equal(2, databaseAccount.ReadableReplications.Count); Assert.True(databaseAccount.ReadableReplications.First(l => l.LocationName.ToLower().Replace(" ", "") == Region.USCentral.ToString()).IsZoneRedundant); Assert.Equal(DefaultConsistencyLevel.Session, databaseAccount.DefaultConsistencyLevel); Assert.True(databaseAccount.MultipleWriteLocationsEnabled); databaseAccount = databaseAccount.Update() .WithoutAllReplications() .WithWriteReplication(Region.USWest) .WithReadReplication(Region.USEast) .Apply(); Assert.Equal(Region.USEast.ToString(), databaseAccount.WritableReplications.First(l => l.FailoverPriority == 1).LocationName.ToLower().Replace(" ", "")); databaseAccount = databaseAccount.Update() .WithEventualConsistency() .WithTag("tag2", "value2") .WithTag("tag3", "value3") .WithoutTag("tag1") .Apply(); Assert.Equal(DefaultConsistencyLevel.Eventual, databaseAccount.DefaultConsistencyLevel); Assert.True(databaseAccount.Tags.ContainsKey("tag2")); Assert.True(!databaseAccount.Tags.ContainsKey("tag1")); } finally { try { resourceManager.ResourceGroups.BeginDeleteByName(rgName); } catch { } } } }
public void CosmosDBBugfix() { using (var context = FluentMockContext.Start(GetType().FullName)) { var dbName = TestUtilities.GenerateName("db"); var saName = TestUtilities.GenerateName("dbsa"); var rgName = TestUtilities.GenerateName("ddbRg"); var manager = TestHelper.CreateCosmosDB(); var resourceManager = TestHelper.CreateResourceManager(); ICosmosDBAccount databaseAccount = null; var azure = TestHelper.CreateRollupClient(); try { databaseAccount = manager.CosmosDBAccounts.Define(dbName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithSessionConsistency() .WithWriteReplication(Region.USWest) .WithReadReplication(Region.USCentral) .WithIpRangeFilter("") .Create(); // BUGFIX var vn = azure.Networks.Define(dbName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithAddressSpace("192.168.0.0/16") .DefineSubnet("subnet1") .WithAddressPrefix("192.168.1.0/24") .WithAccessFromService(ServiceEndpointType.MicrosoftAzureCosmosDB) .Attach() .DefineSubnet("subnet2") .WithAddressPrefix("192.168.2.0/24") .WithAccessFromService(ServiceEndpointType.MicrosoftAzureCosmosDB) .Attach() .Create(); databaseAccount.Update().WithVirtualNetworkRule(vn.Id, "Subnet1").Apply(); databaseAccount.Update().WithVirtualNetworkRule(vn.Id, "Subnet1").Apply(); databaseAccount.Update().WithVirtualNetworkRule(vn.Id, "Subnet1").Apply(); // END of BUGFIX Assert.True(databaseAccount.VirtualNetoworkFilterEnabled); } finally { try { resourceManager.ResourceGroups.BeginDeleteByName(rgName); } catch { } } } }
public void CosmosDBCRUD() { using (var context = FluentMockContext.Start(GetType().FullName)) { var dbName = TestUtilities.GenerateName("db"); var saName = TestUtilities.GenerateName("dbsa"); var rgName = TestUtilities.GenerateName("ddbRg"); var manager = TestHelper.CreateCosmosDB(); var resourceManager = TestHelper.CreateResourceManager(); ICosmosDBAccount databaseAccount = null; try { databaseAccount = manager.CosmosDBAccounts.Define(dbName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithSessionConsistency() .WithWriteReplication(Region.USWest) .WithReadReplication(Region.USCentral) .WithIpRangeFilter("") .Create(); Assert.Equal(databaseAccount.Name, dbName.ToLower()); Assert.Equal(DatabaseAccountKind.GlobalDocumentDB, databaseAccount.Kind); Assert.Equal(1, databaseAccount.WritableReplications.Count); Assert.Equal(2, databaseAccount.ReadableReplications.Count); Assert.Equal(DefaultConsistencyLevel.Session, databaseAccount.DefaultConsistencyLevel); databaseAccount = databaseAccount.Update() .WithReadReplication(Region.AsiaSouthEast) .WithoutReadReplication(Region.USEast) .WithoutReadReplication(Region.USCentral) .Apply(); databaseAccount = databaseAccount.Update() .WithEventualConsistency() .WithTag("tag2", "value2") .WithTag("tag3", "value3") .WithoutTag("tag1") .Apply(); Assert.Equal(DefaultConsistencyLevel.Eventual, databaseAccount.DefaultConsistencyLevel); Assert.True(databaseAccount.Tags.ContainsKey("tag2")); Assert.True(!databaseAccount.Tags.ContainsKey("tag1")); } finally { try { resourceManager.ResourceGroups.BeginDeleteByName(rgName); } catch { } } } }
/// <summary> /// run a resource level operation. /// </summary> /// <param name="manager"> an instance of resource manager. </param> /// <param name="op"> the menu choice which denotes the operation to be completed. </param> public void InteractResource(ResourceManager manager, int op) { try { string accountName = GeneralUtils.PromptInput("Please enter the name of the database account that contains the resources you want to interact with"); char lookUp = manager.CheckForExistingWorkFlow(accountName); if (lookUp != 'n') { switch (lookUp) { case 'd': manager.RunDoc(manager.docdbWorkflows[accountName], op); break; case 'm': manager.RunMongo(manager.mongodbWorkflows[accountName], op); break; case 'g': manager.RunGraph(manager.graphWorkflows[accountName], op); break; case 't': manager.RunTable(manager.tableWorkflows[accountName], op); break; } } else { string model = manager.accountWorkflow.acctUtil.databaseAccountInformation[accountName][4]; Task <ICosmosDBAccount> accountTask = manager.accountWorkflow.acctUtil.SelectAccountByName(accountName); ICosmosDBAccount account = accountTask.Result; switch (model) { case "DocumentDB": DocumentDBWorkflows doc = manager.GenerateDocDBWF(account, accountName); manager.RunDoc(doc, op); break; case "MongoDB": MongoDBWorkflows mongo = manager.GenerateMongoDBWF(account, accountName); manager.RunMongo(mongo, op); break; case "Graph": GraphWorkflows graph = manager.GenerateGraphWF(account, accountName); manager.RunGraph(graph, op); break; case "Table": TableWorkflows table = manager.GenerateTableWF(account, accountName); manager.RunTable(table, op); break; } } } catch (Exception e) { Console.WriteLine("Something went wrong while trying to process the request..."); Console.WriteLine(e.Message); } }
/// <summary> /// Deletes a database account and prompts for necesary inputs. /// </summary> public void DeleteDatabaseAccountWF() { string name = GeneralUtils.PromptInput("Please enter the name of a database account"); Task <ICosmosDBAccount> accountTask = this.acctUtil.SelectAccountByName(name); ICosmosDBAccount account = accountTask.Result; this.acctUtil.DeleteDatabaseAccount(account); acctUtil.RemoveDatabaseAccountInformation(name); Console.WriteLine("The database account {0} was removed. This change may not be reflected in the portal for several minutes.", name); Console.WriteLine("Please wait a minute for this to operation to go through before moving on to the next operation, otherwise azure will not process the request."); }
/// <summary> /// creates a graph client. /// </summary> /// <param name="account"> a valid cosmos db account with graph as the default expirience. </param> /// <returns> document client suitable for use with the graph api. </returns> public DocumentClient CreateClientTB(ICosmosDBAccount account) { string authkey = account.ListKeys().PrimaryMasterKey; Uri endpoint = new Uri(account.DocumentEndpoint); return(new DocumentClient(endpoint, authkey, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp })); }
/// <summary> /// get the freshly created cosmosDB from azure. The template deployment deployed the cosmos. /// Get the connection string to the cosmos and write into function.json, for the output of the function app /// </summary> public static void CreateCosmosDB() { spin.setMessage("Creating a Cosmos DB..."); spin.Start(); //ICosmosDBAccount cosmosDBAccount = await azure.CosmosDBAccounts.Define(cosmosDBName) // .WithRegion(Region.EuropeWest) // .WithExistingResourceGroup(rgName) // .WithKind(DatabaseAccountKind.MongoDB) // .WithEventualConsistency() // .WithWriteReplication(Region.EuropeWest) // .WithReadReplication(Region.EuropeWest) // .CreateAsync(); ICosmosDBAccount cosmosDBAccount = azure.CosmosDBAccounts.GetByResourceGroup(rgName, cosmosDBName); spin.Stop(); Console.WriteLine("CosmosDB Successfully created : " + cosmosDBAccount.Name); spin.setMessage("Getting credentials for CosmosDB..."); spin.Start(); var databaseAccountListKeysResult = cosmosDBAccount.ListKeys(); string masterKey = databaseAccountListKeysResult.PrimaryMasterKey; string endPoint = cosmosDBAccount.DocumentEndpoint; string primaryConnectionString = "AccountEndpoint=" + endPoint + ";AccountKey=" + masterKey + ";"; endPointCosmosDB = endPoint; accountKeyCosmosDB = masterKey; //Console.WriteLine("Get the MongoDB connection string"); //var databaseAccountListConnectionStringsResult = cosmosDBAccount.ListConnectionStrings(); //Console.WriteLine("MongoDB connection string: " //+ databaseAccountListConnectionStringsResult.ConnectionStrings[0].ConnectionString); //string primaryConnectionString = databaseAccountListConnectionStringsResult.ConnectionStrings[0].ConnectionString; spin.Stop(); Console.WriteLine($"CosmosDb {cosmosDBName} with the connection string {primaryConnectionString}"); dynamic jsonFunction = JObject.Parse(File.ReadAllText("..\\..\\FunctionAppCore\\IoTHubTrigger\\function.json")); dynamic bindings = jsonFunction["bindings"]; bindings[1]["databaseName"] = cosmosDBName; //bindings[1]["connection"] = primaryConnectionString; jsonFunction["bindings"] = bindings; string jsonUpdated = JsonConvert.SerializeObject(jsonFunction, Formatting.Indented); File.WriteAllText(@"..\..\FunctionAppCore\IoTHubTrigger\function.json", jsonUpdated); }
/// <summary> /// Creates a dictionary of cosmos db account level information. /// </summary> /// <param name="account"> an existing cosmos db account. </param> /// <returns> a dictionary of account level attributes used for operations against the account and its resources. </returns> public Dictionary <string, string> GetAccountConnectionInformation(ICosmosDBAccount account) { DatabaseAccountListKeysResultInner databaseAccountListKeysResult = account.ListKeys(); return(new Dictionary <string, string> { { "Endpoint", account.DocumentEndpoint }, { "Primary Key", databaseAccountListKeysResult.PrimaryMasterKey }, { "Secondary Key", databaseAccountListKeysResult.SecondaryMasterKey }, { "Primary Read-only Key", databaseAccountListKeysResult.PrimaryReadonlyMasterKey }, { "Secondary Read-only Key", databaseAccountListKeysResult.SecondaryReadonlyMasterKey } }); }
/// <summary> /// Creates a mongoDB connection string for an account. /// </summary> /// <param name="account"> a Cosmos DB account object </param> /// <returns> the connection string of the resource or null. </returns> public string FormConnectionStringTB(ICosmosDBAccount account) { try { string userName = account.Name; string password = account.ListKeys().PrimaryMasterKey; string host = account.DocumentEndpoint.Split('/')[2].Split(':')[0]; return(String.Format("mongodb://{0}:{1}@{2}:10255/?ssl=true&replicaSet=globaldb", userName, password, host)); } catch (Exception e) { Console.WriteLine("Something went wrong while trying to create a MongoDB connection string."); Console.WriteLine(e.Message); return(null); } }
/// <summary> /// Deletes a cosmos db account. /// </summary> /// <param name="cosmosDbAccount"> a valid/existing cosmos db account. </param> public async void DeleteDatabaseAccount(ICosmosDBAccount cosmosDbAccount) { try { string name = cosmosDbAccount.Name; string id = cosmosDbAccount.Id; Console.WriteLine("Deleting the database account [{0}]. This process can take several minutes...", cosmosDbAccount.Name); await this.azure.CosmosDBAccounts.DeleteByIdAsync(cosmosDbAccount.Id); } catch (Exception e) { Console.WriteLine("Azure encountered an error, but it is likely that your account was still deleted. Please confirm through portal."); Console.WriteLine(e.Message); } }
public static void LaunchGremlinConsole(ICosmosDBAccount account, string pathToGremlinBAT, string pathToRemoteSecureYAML, string databaseName, string collectionName) { ModifyRemoteSecureYAML(account, pathToRemoteSecureYAML, databaseName, collectionName); Console.WriteLine("Check: " + pathToRemoteSecureYAML); Process gremlinConsole = new Process(); gremlinConsole.StartInfo = new ProcessStartInfo(pathToGremlinBAT) { UseShellExecute = false, WorkingDirectory = pathToGremlinBAT.Substring(0, (pathToGremlinBAT.Length - 15)) }; Console.WriteLine("**IMPORTANT** Once the Gremlin Console has loaded please run the following command > :remote connect tinkerpop.server conf/remote-secure.yaml"); Console.WriteLine("**IMPORTANT** To exit the Gremlin Console, use the command > :x "); gremlinConsole.Start(); gremlinConsole.WaitForExit(); }
/// <summary> /// Creates a connection string used to access the table storage account /// </summary> /// <param name="account"> valid cosmos db account. </param> /// <returns> connection string or null if error</returns> public string FormConnectionString(ICosmosDBAccount account) { try { string name = account.Name; string key = account.ListKeys().PrimaryMasterKey; string endpoint = "https://" + name + ".table.cosmosdb.azure.com:443/"; return(String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};TableEndpoint={2};", name, key, endpoint)); } catch (Exception e) { Console.WriteLine("Something went wrong while trying to create a Storage account connection string."); Console.WriteLine(e.Message); return(null); } }
/// <summary> /// Initialize the document client, return null if there is an exception /// </summary> /// <param name="account"> A cosmos db account that the client will connect to. </param> /// <returns> A valid document client or null. </returns> public DocumentClient CreateClientTB(ICosmosDBAccount account) { DocumentClient client; try { client = new DocumentClient(new Uri(account.DocumentEndpoint), account.ListKeys().PrimaryMasterKey); return(client); } catch (Exception e) { Console.WriteLine("Something went wrong while creating the document client. Make sure you have provided the correct account."); Console.WriteLine(e.Message); return(null); } }
/// <summary> /// Lists database account information and prompts for necesary inputs. /// </summary> public void ListDatabaseAccountInformationWF() { string name = GeneralUtils.PromptInput("Please enter the name of a database account"); Task <ICosmosDBAccount> accountTask = this.acctUtil.SelectAccountByName(name); ICosmosDBAccount account = accountTask.Result; Dictionary <string, string> accountConnectionInformation = this.acctUtil.GetAccountConnectionInformation(account); string[] headers = { "Account Connection Information" }; List <string[]> lines = GeneralUtils.CreateMenuHeader(headers); foreach (string connectionItem in accountConnectionInformation.Keys) { lines.Add(new string[] { connectionItem + " : " + accountConnectionInformation[connectionItem] }); } Console.WriteLine(GeneralUtils.PadElementsInLines(lines)); }
/// <summary> /// Adds database account information to the master dicionary for database account management. /// </summary> /// <param name="account"> a vlaid cosmos db account. </param> /// <returns> array containing account resource group and account name. </returns> public string[] AddDatabaseAccountInformation(ICosmosDBAccount account) { string name = account.Name; string resourceGroupName = account.ResourceGroupName; string dbModel; if (account.Tags.Keys.Contains("defaultExperience")) { dbModel = account.Tags["defaultExperience"]; } else { dbModel = "DocumentDB"; } this.databaseAccountInformation.Add(name, new string[] { account.Id, resourceGroupName, account.Type, account.RegionName, dbModel }); return(new string[] { resourceGroupName, name }); }
public static void ModifyRemoteSecureYAML(ICosmosDBAccount account, string pathToRemoteSecureYAML, string databaseName, string collectionName) { string host = @"hosts: [" + account.Name + @".graphs.azure.com]"; string port = @"port: 443"; string userName = @"username: /dbs/" + databaseName + @"/colls/" + collectionName; string password = @"password: "******"serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0, config: { serializeResultToString: true }}"; string[] lines = File.ReadLines(pathToRemoteSecureYAML).ToArray(); lines[26] = host; lines[27] = port; lines[28] = userName; lines[29] = password; lines[32] = serializer; Console.WriteLine("Modifying remote-secure.yaml"); File.WriteAllLines(pathToRemoteSecureYAML, lines); Console.Write("Finished"); }
/// <summary> /// Creates a cosmos db account. All params with default values will be autogenerated if no value is provided. /// </summary> /// <param name="resourceName"> name of the resource to create. </param> /// <param name="provisioningRegion"> region in which to provision the resource. </param> /// <param name="resourceGroupName"> name of resource group to assign the resource to. </param> /// <param name="databaseModel"> the api of the new cosmos db resource (SQL, mongo, table, graph...). </param> /// <returns> new cosmos db account </returns> public async Task <ICosmosDBAccount> CreateCosmosDBAccount(string resourceName = null, string provisioningRegion = null, string resourceGroupName = null, string databaseModel = null) { string rName = resourceName ?? SdkContext.RandomResourceName("docDb", 10); Region pRegion = YieldRegion(provisioningRegion); string dbModel = databaseModel ?? DatabaseAccountKind.GlobalDocumentDB; try { Console.WriteLine("Creating the database account [{0}]. This process can take several minutes...", rName); if (resourceGroupName == null) { string rgName = SdkContext.RandomResourceName("docDbToolBox", 10); ICosmosDBAccount cosmosDBAccount = await this.azure.CosmosDBAccounts. Define(rName) .WithRegion(pRegion) .WithNewResourceGroup(rgName) .WithKind(dbModel) .WithSessionConsistency() .WithWriteReplication(pRegion) .CreateAsync(); return(cosmosDBAccount); } else { ICosmosDBAccount cosmosDBAccount = await this.azure.CosmosDBAccounts.Define(rName) .WithRegion(pRegion) .WithExistingResourceGroup(resourceGroupName) .WithKind(dbModel) .WithSessionConsistency() .WithWriteReplication(pRegion) .CreateAsync(); return(cosmosDBAccount); } } catch (Exception e) { Console.WriteLine("Something went wrong... creating a default resource"); Console.WriteLine(e.Message); return(await CreateCosmosDBAccount()); } }
private Container ConnectToCosmosDBContainer(ICosmosDBAccount cosmosDB, string cosmosDBDatabase, string cosmosDBContainer) { try { var client = new CosmosClientBuilder( cosmosDB.DocumentEndpoint, cosmosDB.ListKeys().PrimaryMasterKey) .Build(); return(client .GetDatabase(cosmosDBDatabase) .GetContainer(cosmosDBContainer)); } catch (Exception e) { this.logger.LogCritical( e, "Couldn't retrieve Cosmos DB container {cosmosDBContainer}", cosmosDBContainer); throw; } }
public void CanCreateCassandraCosmosDB() { using (var context = FluentMockContext.Start(GetType().FullName)) { var dbName = TestUtilities.GenerateName("db"); var rgName = TestUtilities.GenerateName("dbRg"); var manager = TestHelper.CreateCosmosDB(); var resourceManager = TestHelper.CreateResourceManager(); ICosmosDBAccount databaseAccount = null; var azure = TestHelper.CreateRollupClient(); try { databaseAccount = manager.CosmosDBAccounts.Define(dbName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithDataModelCassandra() .WithStrongConsistency() .WithCassandraConnector(ConnectorOffer.Small) .Create(); Assert.True(databaseAccount.CassandraConnectorEnabled); Assert.Equal(ConnectorOffer.Small, databaseAccount.CassandraConnectorOffer); databaseAccount = databaseAccount.Update() .WithoutCassandraConnector() .Apply(); Assert.False(databaseAccount.CassandraConnectorEnabled); } finally { try { resourceManager.ResourceGroups.BeginDeleteByName(rgName); } catch { } } } }
/** * Azure App Service basic sample for managing web apps. * - Create a Cosmos DB with credentials stored in a Key Vault * - Create a web app which interacts with the Cosmos DB by first * reading the secrets from the Key Vault. * * The source code of the web app is located at Asset/documentdb-dotnet-todo-app */ public static void RunSample(IAzure azure) { Region region = Region.USWest; string appName = SdkContext.RandomResourceName("webapp-", 20); string rgName = SdkContext.RandomResourceName("rg1NEMV_", 24); string vaultName = SdkContext.RandomResourceName("vault", 20); string cosmosName = SdkContext.RandomResourceName("cosmosdb", 20); string appUrl = appName + ".azurewebsites.net"; try { //============================================================ // Create a CosmosDB Utilities.Log("Creating a CosmosDB..."); ICosmosDBAccount cosmosDBAccount = azure.CosmosDBAccounts.Define(cosmosName) .WithRegion(region) .WithNewResourceGroup(rgName) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithEventualConsistency() .WithWriteReplication(Region.USEast) .WithReadReplication(Region.USCentral) .Create(); Utilities.Log("Created CosmosDB"); Utilities.Log(cosmosDBAccount); //============================================================ // Create a key vault var servicePrincipalInfo = ParseAuthFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); IVault vault = azure.Vaults .Define(vaultName) .WithRegion(region) .WithNewResourceGroup(rgName) .DefineAccessPolicy() .ForServicePrincipal(servicePrincipalInfo.ClientId) .AllowSecretAllPermissions() .Attach() .Create(); SdkContext.DelayProvider.Delay(10000); //============================================================ // Store Cosmos DB credentials in Key Vault IKeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async(authority, resource, scope) => { var context = new AuthenticationContext(authority, TokenCache.DefaultShared); var result = await context.AcquireTokenAsync(resource, new ClientCredential(servicePrincipalInfo.ClientId, servicePrincipalInfo.ClientSecret)); return(result.AccessToken); }), ((KeyVaultManagementClient)azure.Vaults.Manager.Inner).HttpClient); keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-uri", cosmosDBAccount.DocumentEndpoint).GetAwaiter().GetResult(); keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-key", cosmosDBAccount.ListKeys().PrimaryMasterKey).GetAwaiter().GetResult(); keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-database", "tododb").GetAwaiter().GetResult(); //============================================================ // Create a web app with a new app service plan Utilities.Log("Creating web app " + appName + " in resource group " + rgName + "..."); IWebApp app = azure.WebApps .Define(appName) .WithRegion(region) .WithExistingResourceGroup(rgName) .WithNewWindowsPlan(PricingTier.StandardS1) .WithNetFrameworkVersion(NetFrameworkVersion.V4_6) .WithAppSetting("AZURE_KEYVAULT_URI", vault.VaultUri) .WithSystemAssignedManagedServiceIdentity() .Create(); Utilities.Log("Created web app " + app.Name); Utilities.Log(app); //============================================================ // Update vault to allow the web app to access vault.Update() .DefineAccessPolicy() .ForObjectId(app.SystemAssignedManagedServiceIdentityPrincipalId) .AllowSecretAllPermissions() .Attach() .Apply(); //============================================================ // Deploy to web app through local Git Utilities.Log("Deploying a local asp.net application to " + appName + " through Git..."); var profile = app.GetPublishingProfile(); Utilities.DeployByGit(profile, "documentdb-dotnet-todo-app"); Utilities.Log("Deployment to web app " + app.Name + " completed"); Utilities.Print(app); // warm up Utilities.Log("Warming up " + appUrl + "..."); Utilities.CheckAddress("http://" + appUrl); SdkContext.DelayProvider.Delay(5000); Utilities.Log("CURLing " + appUrl + "..."); Utilities.Log(Utilities.CheckAddress("http://" + appUrl)); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.DeleteByName(rgName); Utilities.Log("Deleted Resource Group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { Utilities.Log(g); } } }
public InteractiveQueryTerminal(ICosmosDBAccount account = null, DocumentClient documentClient = null, CloudTableClient tableClient = null, MongoClient mongoClient = null) { this.shellType = account.Tags["defaultExpirience"] ?? "Global DocumentDB"; }
/** * Azure CosmosDB sample - * - Create a CosmosDB configured with IP range filter * - Delete the CosmosDB. */ public static void RunSample(IAzure azure) { string cosmosDBName = SdkContext.RandomResourceName("docDb", 10); string rgName = SdkContext.RandomResourceName("rgNEMV", 24); try { //============================================================ // Create a CosmosDB. Console.WriteLine("Creating a CosmosDB..."); ICosmosDBAccount cosmosDBAccount = azure.CosmosDBAccounts.Define(cosmosDBName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithSessionConsistency() .WithWriteReplication(Region.USEast) .WithReadReplication(Region.USCentral) .WithIpRangeFilter("13.91.6.132,13.91.6.1/24") .Create(); Console.WriteLine("Created CosmosDB"); Utilities.Print(cosmosDBAccount); //============================================================ // Get credentials for the CosmosDB. Console.WriteLine("Get credentials for the CosmosDB"); var databaseAccountListKeysResult = cosmosDBAccount.ListKeys(); string masterKey = databaseAccountListKeysResult.PrimaryMasterKey; string endPoint = cosmosDBAccount.DocumentEndpoint; //============================================================ // Connect to CosmosDB and add a collection Console.WriteLine("Connecting and adding collection"); //CreateDBAndAddCollection(masterKey, endPoint); //============================================================ // Delete CosmosDB Console.WriteLine("Deleting the CosmosDB"); // work around CosmosDB service issue returning 404 CloudException on delete operation try { azure.CosmosDBAccounts.DeleteById(cosmosDBAccount.Id); } catch (CloudException) { } Console.WriteLine("Deleted the CosmosDB"); } finally { try { Utilities.Log("Deleting resource group: " + rgName); azure.ResourceGroups.BeginDeleteByName(rgName); Utilities.Log("Deleted resource group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception e) { Utilities.Log(e.StackTrace); } } }