public static async Task <Permission> GetOrCreatePermission(this DocumentClient client, string databaseId, string collectionId, string resourceLink, string userId, PermissionMode permissionMode, int durationInSeconds, TraceWriter log) { var permissionId = string.Empty; try { Database database = null; DocumentCollection documentCollection = null; if (!string.IsNullOrEmpty(collectionId)) { await client.EnsureCollection(databaseId, collectionId, log); log?.Info($" ... getting collection ({collectionId}) in database ({databaseId})"); var collectionResponse = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId)); documentCollection = collectionResponse?.Resource ?? throw new Exception($"Could not find Document Collection in Database {databaseId} with CollectionId: {collectionId}"); } else if (!string.IsNullOrEmpty(databaseId)) { await client.EnsureDatabase(databaseId, log); log?.Info($" ... collectionId == null, getting database ({databaseId})"); var databaseResponse = await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseId)); database = databaseResponse?.Resource ?? throw new Exception($"Could not find Database {databaseId}"); } else { throw new Exception($"databaseId and collectionId must be provided"); } var link = resourceLink ?? documentCollection?.SelfLink; //?? throw new Exception($"Could not get selfLink for Document Collection in Database {databaseId} with CollectionId: {collectionId}"); var userTup = await client.GetOrCreateUser(databaseId, userId, log); var user = userTup.user; Permission permission; permissionId = GetUserPermissionId(databaseId, collectionId, user.Id, permissionMode); // if the user was newly created, go ahead and create the permission if (userTup.created && !string.IsNullOrEmpty(user?.Id)) { permission = await client.CreateNewPermission(databaseId, link, user, permissionId, permissionMode, durationInSeconds, log); } else // else look for an existing permission with the id { var permissionUri = UriFactory.CreatePermissionUri(databaseId, user.Id, permissionId); try { log?.Info($" ... getting permission ({permissionId}) at uri: {permissionUri}"); var permissionResponse = await client.ReadPermissionAsync(permissionUri, PermissionRequestOptions(durationInSeconds)); permission = permissionResponse?.Resource; if (permission != null) { log?.Info($" ... found existing permission ({permission.Id})"); } } catch (DocumentClientException dcx) { dcx.Print(log); switch (dcx.StatusCode) { case HttpStatusCode.NotFound: log?.Info($" ... could not find permission ({permissionId}) at uri: {permissionUri} - creating..."); permission = await client.CreateNewPermission(databaseId, link, user, permissionId, permissionMode, durationInSeconds, log); break; default: throw; } } } return(permission); } catch (Exception ex) { var resourceComponent = string.IsNullOrEmpty(resourceLink) ? "" : $" Resource: {resourceLink} "; log?.Error($"Error creating new new {permissionMode.ToString().ToUpper()} Permission [Database: {databaseId} Collection: {collectionId}{resourceComponent} User: {userId} Permission: {permissionId}", ex); throw; } }
public async static Task Run() { Debugger.Break(); var endpoint = ConfigurationManager.AppSettings["CosmosDbEndpoint"]; var masterKey = ConfigurationManager.AppSettings["CosmosDbMasterKey"]; using (var client = new DocumentClient(new Uri(endpoint), masterKey)) { _graph = client .CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri("MyGraphDb")) .ToList() .FirstOrDefault(g => g.Id == "DemoGraph"); await ClearGraph(client); // --- Terminal 1 --- // V: Terminal 1 await CreateTerminal(client, "Terminal 1", "NY"); // V: Gates in terminal 1 await CreateGate(client, "Gate T1-1", "NY", "Continental"); await CreateGate(client, "Gate T1-2", "NY", "Continental"); await CreateGate(client, "Gate T1-3", "NY", "Continental"); // V: Restaurants in terminal 2 await CreateRestaurant(client, "Wendys", "NY", 0.4m, 9.5m); await CreateRestaurant(client, "McDonalds", "NY", 0.3m, 8.15m); await CreateRestaurant(client, "Chipotle", "NY", 0.6m, 12.5m); // E: TerminalToGate (cyan) await CreateTerminalToGate(client, "Terminal 1", "Gate T1-1", 3); await CreateTerminalToGate(client, "Terminal 1", "Gate T1-2", 5); await CreateTerminalToGate(client, "Terminal 1", "Gate T1-3", 7); // E: TerminalToRestaurant (purple) await CreateTerminalToRestaurant(client, "Terminal 1", "Wendys", 5); await CreateTerminalToRestaurant(client, "Terminal 1", "McDonalds", 7); await CreateTerminalToRestaurant(client, "Terminal 1", "Chipotle", 10); // E: GateToNextGate / GateToPrevGate (cyan dashed) await CreateGateToGate(client, "Gate T1-1", "Gate T1-2", 2); await CreateGateToGate(client, "Gate T1-2", "Gate T1-3", 2); // E: GateToRestaurant (purple dashed) await CreateGateToRestaurant(client, "Gate T1-1", "Wendys", 2); await CreateGateToRestaurant(client, "Gate T1-1", "McDonalds", 4); await CreateGateToRestaurant(client, "Gate T1-1", "Chipotle", 6); await CreateGateToRestaurant(client, "Gate T1-2", "Wendys", 2); await CreateGateToRestaurant(client, "Gate T1-2", "McDonalds", 4); await CreateGateToRestaurant(client, "Gate T1-2", "Chipotle", 6); await CreateGateToRestaurant(client, "Gate T1-3", "Wendys", 6); await CreateGateToRestaurant(client, "Gate T1-3", "McDonalds", 4); await CreateGateToRestaurant(client, "Gate T1-3", "Chipotle", 2); // --- Terminal 2 --- // V: Terminal 2 await CreateTerminal(client, "Terminal 2", "NY"); // V: Gates in terminal 2 await CreateGate(client, "Gate T2-1", "NY", "Delta"); await CreateGate(client, "Gate T2-2", "NY", "Delta"); await CreateGate(client, "Gate T2-3", "NY", "Delta"); // V: Restaurants in terminal 2 await CreateRestaurant(client, "Jack in the Box", "NY", 0.3m, 3.15m); await CreateRestaurant(client, "Kentucky Fried Chicken", "NY", 0.4m, 7.5m); await CreateRestaurant(client, "Burger King", "NY", 0.2m, 7.15m); // E: TerminalToGate await CreateTerminalToGate(client, "Terminal 2", "Gate T2-1", 3); await CreateTerminalToGate(client, "Terminal 2", "Gate T2-2", 5); await CreateTerminalToGate(client, "Terminal 2", "Gate T2-3", 7); // E: TerminalToRestaurant await CreateTerminalToRestaurant(client, "Terminal 2", "Jack in the Box", 5); await CreateTerminalToRestaurant(client, "Terminal 2", "Kentucky Fried Chicken", 7); await CreateTerminalToRestaurant(client, "Terminal 2", "Burger King", 10); // E: GateToNextGate / GateToPrevGate await CreateGateToGate(client, "Gate T2-1", "Gate T2-2", 2); await CreateGateToGate(client, "Gate T2-2", "Gate T2-3", 2); // E: GateToRestaurant await CreateGateToRestaurant(client, "Gate T2-1", "Jack in the Box", 2); await CreateGateToRestaurant(client, "Gate T2-1", "Kentucky Fried Chicken", 4); await CreateGateToRestaurant(client, "Gate T2-1", "Burger King", 6); await CreateGateToRestaurant(client, "Gate T2-2", "Jack in the Box", 2); await CreateGateToRestaurant(client, "Gate T2-2", "Kentucky Fried Chicken", 4); await CreateGateToRestaurant(client, "Gate T2-2", "Burger King", 6); await CreateGateToRestaurant(client, "Gate T2-3", "Jack in the Box", 6); await CreateGateToRestaurant(client, "Gate T2-3", "Kentucky Fried Chicken", 4); await CreateGateToRestaurant(client, "Gate T2-3", "Burger King", 2); // --- Terminal to Terminal --- // E: TerminalToNextTerminal / TerminalToPrevTerminal await CreateTerminalToTerminal(client, "Terminal 1", "Terminal 2", 10); } }
static async Task Main(string[] args) { string primaryKey; try { Console.WriteLine("Downloading the primary key from https://localhost:8081/_explorer/quickstart.html…"); var html = await new HttpClient().GetStringAsync("https://localhost:8081/_explorer/quickstart.html"); primaryKey = Regex.Match(html, "Primary Key</p>\\s+<input .* value=\"(?<primaryKey>.*)\"").Groups["primaryKey"].Value; Console.WriteLine("The primary key has been downloaded."); } catch { Console.WriteLine("Failed to download the primary key. Make sure to install and run the Cosmos emulator."); Console.WriteLine("The primary key gets downloaded from https://localhost:8081/_explorer/quickstart.html"); return; } var client = new DocumentClient(new Uri("https://localhost:8081"), primaryKey); await client.CreateDatabaseIfNotExistsAsync(new Database { Id = nameof(cosmos_net_sdk) }); await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(nameof(cosmos_net_sdk)), new DocumentCollection { Id = nameof(cosmos_net_sdk) }); await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(nameof(cosmos_net_sdk), nameof(cosmos_net_sdk)), new { Id = Guid.NewGuid(), FirstName = "Tomas", LastName = "Hubelbauer", }); // TODO: Find a better way to recreate the UDF each time, `Replace…` seem to be too complex for now try { await client.DeleteUserDefinedFunctionAsync(UriFactory.CreateUserDefinedFunctionUri(nameof(cosmos_net_sdk), nameof(cosmos_net_sdk), "test")); } catch (System.Exception) { Console.WriteLine("UDF didn't exist yet"); } await client.CreateUserDefinedFunctionAsync(UriFactory.CreateDocumentCollectionUri(nameof(cosmos_net_sdk), nameof(cosmos_net_sdk)), new UserDefinedFunction { Id = "test", Body = "function test() { return 'test'; }", }); var results = client.CreateDocumentQuery <dynamic>( UriFactory.CreateDocumentCollectionUri(nameof(cosmos_net_sdk), nameof(cosmos_net_sdk)), $"SELECT {{ firstName: collection.FirstName, lastName: collection.LastName, id: collection.Id, test: udf.test() }} FROM {nameof(cosmos_net_sdk)} collection"); foreach (var result in results) { Console.WriteLine(result); } }
private async Task UsingBulkUpdate() { var option = new FeedOptions { EnableCrossPartitionQuery = true }; this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey); DocumentCollection dataCollection = client.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri("database"), option) .Where(c => c.Id == "collection").AsEnumerable().FirstOrDefault(); long numberOfDocumentsToGenerate = 3; int numberOfBatches = 1; long numberOfDocumentsPerBatch = (long)Math.Floor(((double)numberOfDocumentsToGenerate) / numberOfBatches); // Set retry options high for initialization (default values). client.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds = 30; client.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 9; var docs = client.CreateDocumentQuery(dataCollection.SelfLink); var listIds = new List <string>(); foreach (var document in docs) { listIds.Add(document.GetPropertyValue <string>("id")); } IBulkExecutor bulkExecutor = new BulkExecutor(client, dataCollection); await bulkExecutor.InitializeAsync(); // Set retries to 0 to pass control to bulk executor. client.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds = 0; client.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 0; double totalRequestUnitsConsumed = 0; double totalTimeTakenSec = 0; var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; BulkUpdateResponse bulkUpdateResponse = null; long totalNumberOfDocumentsUpdated = 0; totalRequestUnitsConsumed = 0; totalTimeTakenSec = 0; tokenSource = new CancellationTokenSource(); token = tokenSource.Token; // Generate update operations. List <UpdateOperation> updateOperations = new List <UpdateOperation>(); // Set the name field. updateOperations.Add(new SetUpdateOperation <string>("isDeleted", "true")); for (int i = 0; i < numberOfBatches; i++) { // Generate update items. List <UpdateItem> updateItemsInBatch = new List <UpdateItem>(); for (int j = 0; j < numberOfDocumentsPerBatch; j++) { string partitionKeyValue = "12345"; string id = listIds[0]; listIds.RemoveAt(0); updateItemsInBatch.Add(new UpdateItem(id, partitionKeyValue, updateOperations)); } // Invoke bulk update API. var tasks = new List <Task>(); tasks.Add(Task.Run(async() => { do { try { bulkUpdateResponse = await bulkExecutor.BulkUpdateAsync( updateItems: updateItemsInBatch, maxConcurrencyPerPartitionKeyRange: null, cancellationToken: token); } catch (DocumentClientException de) { Trace.TraceError("Document client exception: {0}", de); break; } catch (Exception e) { Trace.TraceError("Exception: {0}", e); break; } } while (bulkUpdateResponse.NumberOfDocumentsUpdated < updateItemsInBatch.Count); totalNumberOfDocumentsUpdated += bulkUpdateResponse.NumberOfDocumentsUpdated; totalRequestUnitsConsumed += bulkUpdateResponse.TotalRequestUnitsConsumed; totalTimeTakenSec += bulkUpdateResponse.TotalTimeTaken.TotalSeconds; }, token)); await Task.WhenAll(tasks); } Console.WriteLine(String.Format("Updated {0} docs @ {1} update/s, {2} RU/s in {3} sec", totalNumberOfDocumentsUpdated, Math.Round(totalNumberOfDocumentsUpdated / totalTimeTakenSec), Math.Round(totalRequestUnitsConsumed / totalTimeTakenSec), totalTimeTakenSec)); Console.WriteLine(String.Format("Average RU consumption per document update: {0}", (totalRequestUnitsConsumed / totalNumberOfDocumentsUpdated))); Console.WriteLine("TotalRUsConsumed: " + totalRequestUnitsConsumed); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, [CosmosDB( databaseName: "QuestionsData", collectionName: "QuestionsData", ConnectionStringSetting = "QuestionsDBConnection")] DocumentClient questionsTable, [CosmosDB( databaseName: "Appointment", collectionName: "AppointmentForUsers", ConnectionStringSetting = "AppointmentDBConnection")] DocumentClient appointmentsTable, [CosmosDB( databaseName: "UserInformation", collectionName: "UserInformation", ConnectionStringSetting = "UserInformationDBConnection")] DocumentClient usersTable, ILogger log) { log.LogInformation("Create questions tables."); await questionsTable.CreateDatabaseIfNotExistsAsync(new Database() { Id = "QuestionsData" }); await questionsTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("QuestionsData"), new DocumentCollection() { Id = "QuestionsData", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/Source" } }, UniqueKeyPolicy = new UniqueKeyPolicy() { UniqueKeys = new Collection <UniqueKey>() { new UniqueKey() { Paths = new Collection <string>() { "/Token" } } } } }); await questionsTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("QuestionsData"), new DocumentCollection() { Id = "leases", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/id" } } }); log.LogInformation("Create appointment tables."); await questionsTable.CreateDatabaseIfNotExistsAsync(new Database() { Id = "Appointment" }); await questionsTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Appointment"), new DocumentCollection() { Id = "AppointmentForUsers", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/id" } }, UniqueKeyPolicy = new UniqueKeyPolicy() { UniqueKeys = new Collection <UniqueKey>() { new UniqueKey() { Paths = new Collection <string>() { "/Token" } } } } }); await questionsTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Appointment"), new DocumentCollection() { Id = "leases", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/id" } } }); log.LogInformation("Create users tables."); await questionsTable.CreateDatabaseIfNotExistsAsync(new Database() { Id = "UserInformation" }); await questionsTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("UserInformation"), new DocumentCollection() { Id = "UserInformation", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/Source" } }, UniqueKeyPolicy = new UniqueKeyPolicy() { UniqueKeys = new Collection <UniqueKey>() { new UniqueKey() { Paths = new Collection <string>() { "/Token" } } } } }); await questionsTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("UserInformation"), new DocumentCollection() { Id = "leases", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/id" } } }); return(new OkObjectResult("Successfully create the database schema")); }
private static void Cleanup() { _client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName)).Wait(); }
// ADD THIS PART TO YOUR CODE private async Task GetStartedDemo() { this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey); // ADD THIS PART TO YOUR CODE await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB_oa" }); // ADD THIS PART TO YOUR CODE await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("FamilyDB_oa"), new DocumentCollection { Id = "FamilyCollection_oa" }); // Add Data // ADD THIS PART TO YOUR CODE Family andersenFamily = new Family { Id = "Andersen.1", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay" } }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; await this.CreateFamilyDocumentIfNotExists("FamilyDB_oa", "FamilyCollection_oa", andersenFamily); Family wakefieldFamily = new Family { Id = "Wakefield.7", LastName = "Wakefield", Parents = new Parent[] { new Parent { FamilyName = "Wakefield", FirstName = "Robin" }, new Parent { FamilyName = "Miller", FirstName = "Ben" } }, Children = new Child[] { new Child { FamilyName = "Merriam", FirstName = "Jesse", Gender = "female", Grade = 8, Pets = new Pet[] { new Pet { GivenName = "Goofy" }, new Pet { GivenName = "Shadow" } } }, new Child { FamilyName = "Miller", FirstName = "Lisa", Gender = "female", Grade = 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; await this.CreateFamilyDocumentIfNotExists("FamilyDB_oa", "FamilyCollection_oa", wakefieldFamily); // Query The Data // ADD THIS PART TO YOUR CODE this.ExecuteSimpleQuery("FamilyDB_oa", "FamilyCollection_oa"); // Update document and query // ADD THIS PART TO YOUR CODE // Update the Grade of the Andersen Family child andersenFamily.Children[0].Grade = 6; await this.ReplaceFamilyDocument("FamilyDB_oa", "FamilyCollection_oa", "Andersen.1", andersenFamily); this.ExecuteSimpleQuery("FamilyDB_oa", "FamilyCollection_oa"); // Delete JSON document from collection // ADD THIS PART TO CODE await this.DeleteFamilyDocument("FamilyDB_oa", "FamilyCollection_oa", "Andersen.1"); // ADD THIS PART TO CODE // Clean up/delete the database await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri("FamilyDB_oa")); }
private void Run() { // get config values for CosmosDB var endpointUrl = Configuration["AppSettings:EndpointUrl"]; var authorizationKey = Configuration["AppSettings:AuthorizationKey"]; var databaseName = Configuration["AppSettings:DatabaseName"]; var collectionName = typeof(Profile).Name; // instantiate IRepository DocumentClient documentClient = new DocumentClient(new Uri(endpointUrl), authorizationKey); IRepository <Profile> repository = new DocumentDbRepository <Profile>(documentClient, databaseName, collectionName); // instantiate service. Note: Inherit from ICrudservice to add more functionality & use the repository var service = new CrudService <Profile>(repository); // create 1 var milo = new Profile { Id = "1", FirstName = "Milo", LastName = "Aukerman", Email = "*****@*****.**", Occupation = "" }; var createResponse = service.CreateAsync(milo).Result; if (createResponse.Success) { System.Console.WriteLine($"CreateAsync {createResponse.StatusCode}"); ShowObject(createResponse); } // create with duplicate ID var bill = new Profile { Id = "2", FirstName = "Bill", LastName = "Stevenson", Email = "*****@*****.**" }; createResponse = service.CreateAsync(bill).Result; System.Console.WriteLine($"CreateAsync {createResponse.StatusCode}"); if (createResponse is ConflictResponse <Profile> typedConflictRes) { ShowObject(typedConflictRes); } var stephen = new Profile { // id will be generated by database server FirstName = "Stephen", LastName = "Egerton", Email = "*****@*****.**", Occupation = "Guitarist" }; createResponse = service.CreateAsync(stephen).Result; if (createResponse.Success) { System.Console.WriteLine($"CreateAsync {createResponse.StatusCode}"); ShowObject(createResponse); } // get var getResponse = service.GetByIdAsync("1").Result; System.Console.WriteLine($"\nGetByIdAsync {getResponse.StatusCode}"); if (getResponse is GetResponse <Profile> typedGetRes) { ShowObject(typedGetRes); } // update var docToUpdate = service.GetByIdAsync("1").Result as GetResponse <Profile>; var modifiedModel = docToUpdate.Data; modifiedModel.Occupation = "Singer"; var updateResponse = service.UpdateAsync(modifiedModel).Result; System.Console.WriteLine($"\nUpdateAsync {updateResponse.StatusCode}"); ShowObject(updateResponse); var nonExistingDoc = new Profile { Id = "Not-a-real-id" }; updateResponse = service.UpdateAsync(nonExistingDoc).Result; System.Console.WriteLine($"\nUpdateAsync {updateResponse.StatusCode}"); if (updateResponse is UpdateNotFoundResponse <Profile> typedNotFoundRes) { ShowObject(typedNotFoundRes); } // get all var responseQueryable = service.GetAllAsync().Result; System.Console.WriteLine($"\nGetAllAsync {responseQueryable.Success} {responseQueryable.StatusCode}"); responseQueryable.Data.ToList().ForEach(ShowObject); // query responseQueryable = service.QueryAsync("SELECT * FROM Profile p WHERE p.firstName = 'Milo'").Result; System.Console.Write($"\nQueryAsync {responseQueryable.Success} {responseQueryable.StatusCode}"); if (responseQueryable is QueryResponse <Profile> typedQueryRes) { typedQueryRes.Data.ToList().ForEach(ShowObject); } // count var countResponse = service.CountAsync().Result; System.Console.WriteLine($"CountAsync {countResponse.StatusCode}"); ShowObject(countResponse); // count by query countResponse = service.CountAsync("SELECT * FROM Profile p WHERE p.firstName = 'Milo'").Result; System.Console.WriteLine($"\nCountAsync by SQL {countResponse.StatusCode}"); ShowObject(countResponse); // first or default by query var firstResponse = service.FirstOrDefaultAsync("SELECT * FROM Profile p WHERE p.firstName = 'Milo'").Result; System.Console.WriteLine($"\nFirstOrDefaultAsync {firstResponse.StatusCode}"); ShowObject(firstResponse); // delete var responseDelete = service.DeleteAsync("1").Result; System.Console.WriteLine($"\nDeleteAsync {responseDelete.StatusCode}"); ShowObject(responseDelete); // delete responseDelete = service.DeleteAsync("Not-a-real-ID").Result; System.Console.WriteLine($"\nDeleteAsync {responseDelete.StatusCode}"); if (responseDelete is DeleteNotFoundResponse typedNotFoundDelRes) { ShowObject(responseDelete); } AddStoredProc(documentClient, databaseName, collectionName, "my_sproc"); var responseSproc = service.ExecuteStoredProcedureAsync <string>("my_sproc", "Milo").Result; System.Console.WriteLine($"\nExecuteStoredProcedureAsync {responseSproc.StatusCode}"); ShowObject(responseSproc); // cleanup System.Console.WriteLine($"\nDeleting {databaseName}"); documentClient.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName)).Wait(); System.Console.WriteLine($"\nDone"); }
private async Task BasicOperations() { // Cosmo DB Validation and creation ifNotExist this.client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["accountEndpoint"]), ConfigurationManager.AppSettings["accountKey"]); await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "Users" }); await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Users"), new DocumentCollection { Id = "WebCustomers" }); Console.WriteLine("Database and collection validation complete"); // User Creation - ifNotExist User yanhe = new User { Id = "1", ttl = -1, UserId = "yanhe", SDTag = "n", LastName = "He", FirstName = "Yan", Email = "*****@*****.**", OrderHistory = new OrderHistory[] { new OrderHistory { OrderId = "1000", DateShipped = "08/17/2018", Total = "52.49" } }, ShippingPreference = new ShippingPreference[] { new ShippingPreference { Priority = 1, AddressLine1 = "90 W 8th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" } }, }; await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", yanhe); User nelapin = new User { Id = "2", ttl = -1, UserId = "nelapin", SDTag = "n", LastName = "Pindakova", FirstName = "Nela", Email = "*****@*****.**", Dividend = "8.50", OrderHistory = new OrderHistory[] { new OrderHistory { OrderId = "1001", DateShipped = "08/17/2018", Total = "105.89" } }, ShippingPreference = new ShippingPreference[] { new ShippingPreference { Priority = 1, AddressLine1 = "505 NW 5th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" }, new ShippingPreference { Priority = 2, AddressLine1 = "505 NW 5th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" } }, Coupons = new CouponsUsed[] { new CouponsUsed { CouponCode = "Fall2018" } } }; await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin); // Replace User Document yanhe.LastName = "Suh"; await this.ReplaceUserDocument("Users", "WebCustomers", yanhe); // Read a user from Collection where userId = "xxxx" User myUser = await this.ReadUserDocument("Users", "WebCustomers", yanhe); this.WriteToConsoleAndPromptToContinue("Read user {0} - {1} {2} - sd: {3}", myUser.Id, myUser.FirstName, myUser.LastName, myUser.SDTag); User myUser2 = await this.ReadUserDocument("Users", "WebCustomers", nelapin); this.WriteToConsoleAndPromptToContinue("Read user {0} - {1} {2} - sd: {3}", myUser2.Id, myUser2.FirstName, myUser2.LastName, myUser2.SDTag); // Soft Delete User Console.WriteLine("STOP Before Soft Delete ..."); Console.ReadKey(); nelapin.SDTag = "y"; await this.SoftDeleteUserDocumentWithTTL("Users", "WebCustomers", nelapin, 60); Console.WriteLine("STOP After Soft Delete ..."); Console.ReadKey(); // Hard Delete UserS Console.WriteLine("STOP Before Hard Delete ..."); await this.DeleteUserDocument("Users", "WebCustomers", yanhe); await this.DeleteUserDocument("Users", "WebCustomers", nelapin); // Execute Request with LINK and SQL //this.ExecuteSimpleQuery("Users", "WebCustomers"); // Call Store Procedure //await this.RunStoredProcedure("Users", "WebCustomers", yanhe); }
private void CreateDocumentCollectionIfNotExists() { string databaseId = Guid.NewGuid().ToString(); Database db = new Database { Id = databaseId }; // Create the database with this unique id Database createdDatabase = this.client.CreateDatabaseIfNotExistsAsync(db).Result; string collectionId = Guid.NewGuid().ToString(); DocumentCollection collection = new DocumentCollection { Id = collectionId }; DocumentCollection createdCollection = this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(createdDatabase.Id), collection).Result; // CreateDocumentCollectionIfNotExistsAsync should create the new collection Assert.AreEqual(collectionId, createdCollection.Id); string collectionId2 = Guid.NewGuid().ToString(); collection = new DocumentCollection { Id = collectionId2 }; // Pre-create the collection with this unique id createdCollection = this.client.CreateDocumentCollectionIfNotExistsAsync(createdDatabase.SelfLink, collection).Result; DocumentCollection readCollection = this.client.CreateDocumentCollectionIfNotExistsAsync(createdDatabase.SelfLink, collection).Result; // CreateDocumentCollectionIfNotExistsAsync should return the same collection Assert.AreEqual(createdCollection.SelfLink, readCollection.SelfLink); // cleanup created database this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseId)).Wait(); }
public void Cleanup() { Client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(Database)).Wait(); Client.Dispose(); }
private void SetCollectionLink() { databaseLink = UriFactory.CreateDatabaseUri(databaseId); collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionName); }
async static Task DoWork(string endpoint, string key) { var client = new DocumentClient(new Uri(endpoint), key); var databaseLink = UriFactory.CreateDatabaseUri(DATABASE_ID); var collectionLink = UriFactory.CreateDocumentCollectionUri(DATABASE_ID, COLLECTION_ID); var database = await client.CreateDatabaseIfNotExistsAsync(new Database() { Id = DATABASE_ID }); var collection = new DocumentCollection() { Id = COLLECTION_ID }; collection.PartitionKey.Paths.Add("/Country"); collection = await client.CreateDocumentCollectionIfNotExistsAsync(databaseLink, collection); var person1 = new Person("A", "A", "AT"); await client.UpsertDocumentAsync(collectionLink, person1); var person2 = new Person("B", "B", "AT"); await client.UpsertDocumentAsync(collectionLink, person2); var person3 = new Person("C", "C", "AT"); await client.UpsertDocumentAsync(collectionLink, person3); var person4 = new Person("D", "D", "DE"); await client.UpsertDocumentAsync(collectionLink, person4); var allPersonList = client .CreateDocumentQuery <Person>(collectionLink) .ToList(); var personWithFirstNameDList = client .CreateDocumentQuery <Person>(collectionLink, new FeedOptions() { EnableCrossPartitionQuery = true }) .Where(c => c.FirstName == "D") .ToList(); foreach (var item in personWithFirstNameDList) { item.FirstName = "DD"; await client.ReplaceDocumentAsync( UriFactory.CreateDocumentUri(DATABASE_ID, COLLECTION_ID, item.Id), item, new RequestOptions() { PartitionKey = new PartitionKey(item.Country) }); } var personWithPartitionKeyATList = client .CreateDocumentQuery <Person>(collectionLink, new FeedOptions() { PartitionKey = new PartitionKey("AT") }) .ToList(); foreach (var item in personWithPartitionKeyATList) { await client.DeleteDocumentAsync( UriFactory.CreateDocumentUri(DATABASE_ID, COLLECTION_ID, item.Id), new RequestOptions() { PartitionKey = new PartitionKey(item.Country) }); } }
private void Initialize() { ILog logger = LogProvider.For <DocumentDbStorage>(); // create database logger.Info($"Creating database : {Options.DatabaseName}"); Task <ResourceResponse <Database> > databaseTask = Client.CreateDatabaseIfNotExistsAsync(new Database { Id = Options.DatabaseName }); // create document collection Task <ResourceResponse <DocumentCollection> > collectionTask = databaseTask.ContinueWith(t => { logger.Info($"Creating document collection : {t.Result.Resource.Id}"); Uri databaseUri = UriFactory.CreateDatabaseUri(t.Result.Resource.Id); DocumentCollection documentCollection = new DocumentCollection { Id = Options.CollectionName }; // if the partition option is enable if (Options.EnablePartition) { documentCollection.PartitionKey = new PartitionKeyDefinition { Paths = new System.Collections.ObjectModel.Collection <string> { "/type" } }; } return(Client.CreateDocumentCollectionIfNotExistsAsync(databaseUri, documentCollection)); }, TaskContinuationOptions.OnlyOnRanToCompletion).Unwrap(); // create stored procedures Task continueTask = collectionTask.ContinueWith(t => { CollectionUri = UriFactory.CreateDocumentCollectionUri(Options.DatabaseName, t.Result.Resource.Id); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); string[] storedProcedureFiles = assembly.GetManifestResourceNames().Where(n => n.EndsWith(".js")).ToArray(); foreach (string storedProcedureFile in storedProcedureFiles) { logger.Info($"Creating storedprocedure : {storedProcedureFile}"); Stream stream = assembly.GetManifestResourceStream(storedProcedureFile); using (MemoryStream memoryStream = new MemoryStream()) { stream?.CopyTo(memoryStream); StoredProcedure sp = new StoredProcedure { Body = Encoding.UTF8.GetString(memoryStream.ToArray()), Id = Path.GetFileNameWithoutExtension(storedProcedureFile)? .Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) .Last() }; Uri storedProcedureUri = UriFactory.CreateStoredProcedureUri(Options.DatabaseName, t.Result.Resource.Id, sp.Id); Task <ResourceResponse <StoredProcedure> > spTask = Client.ReplaceStoredProcedureAsync(storedProcedureUri, sp); spTask.ContinueWith(x => { if (x.Status == TaskStatus.Faulted && x.Exception.InnerException is DocumentClientException ex && ex.StatusCode == System.Net.HttpStatusCode.NotFound) { return(Client.CreateStoredProcedureAsync(CollectionUri, sp)); } return(Task.FromResult(x.Result)); }).Unwrap().Wait(); } stream?.Close(); } }, TaskContinuationOptions.OnlyOnRanToCompletion); continueTask.Wait(); if (continueTask.IsFaulted || continueTask.IsCanceled) { throw new ApplicationException("Unable to create the stored procedures", databaseTask.Exception); } }
private static async Task RunDemoAsync(string databaseId, string collectionId) { Database database = await GetNewDatabaseAsync(databaseId); DocumentCollection collection = await GetOrCreateCollectionAsync(databaseId, collectionId); Uri collectionUri = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId); await CreateDocuments(collectionUri); //-------------------------------------------------------------------------------------------------------- // There are three ways of writing queries in the .NET SDK for DocumentDB, // using the SQL Query Grammar, using LINQ Provider with Query and with Lambda. // This sample will show each query using all methods. // It is entirely up to you which style of query you write as they result in exactly the same query being // executed on the service. // // There are some occasions when one syntax has advantages over others, but it's your choice which to use when //-------------------------------------------------------------------------------------------------------- // Querying for all documents QueryAllDocuments(collectionUri); // Querying for equality using == QueryWithEquality(collectionUri); // Querying for inequality using != and NOT QueryWithInequality(collectionUri); // Querying using range operators like >, <, >=, <= QueryWithRangeOperatorsOnNumbers(collectionUri); // Querying using range operators against strings. Needs a different indexing policy or the EnableScanInQuery directive. QueryWithRangeOperatorsOnStrings(collectionUri); // Querying with order by QueryWithOrderBy(collectionUri); // Work with subdocuments QueryWithSubdocuments(collectionUri); // Query with Intra-document Joins QueryWithJoins(collectionUri); // Query with string, math and array operators QueryWithStringMathAndArrayOperators(collectionUri); // Query with parameterized SQL using SqlQuerySpec QueryWithSqlQuerySpec(collectionUri); // Query with explict Paging await QueryWithPagingAsync(collectionUri); // Query across multiple partitions in parallel await QueryPartitionedCollectionInParallelAsync(collectionUri); // Query using order by across multiple partitions await QueryWithOrderByForPartitionedCollectionAsync(collectionUri); // Cleanup await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseId)); }
private static DocumentCollection GetCollection(string databaseName, string collectionName) { DocumentCollection collection = docDbClient.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri(databaseName)).Where(c => c.Id == collectionName).AsEnumerable().FirstOrDefault(); return(collection); }
/// <summary> /// Builds a URI for the database. /// </summary> /// <returns> /// The URI to use for the database. /// </returns> private Uri BuildDatabaseUri() => UriFactory.CreateDatabaseUri(_databaseName);
public async Task Teardown() { await _documentClient.DeleteDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName)).ConfigureAwait(false); await _documentClient.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(_databaseName)).ConfigureAwait(false); }
private async Task BasicOperations() { this.client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["accountEndpoint"]), ConfigurationManager.AppSettings["accountKey"]); await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "Users" }); await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Users"), new DocumentCollection { Id = "WebCustomers" }); Console.WriteLine("Database and collection validation complete"); User yanhe = new User { Id = "1", UserId = "yanhe", LastName = "He", FirstName = "Yan", Email = "*****@*****.**", OrderHistory = new OrderHistory[] { new OrderHistory { OrderId = "1000", DateShipped = "08/17/2018", Total = "52.49" } }, ShippingPreference = new ShippingPreference[] { new ShippingPreference { Priority = 1, AddressLine1 = "90 W 8th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" } }, }; await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", yanhe); User nelapin = new User { Id = "2", UserId = "nelapin", LastName = "Pindakova", FirstName = "Nela", Email = "*****@*****.**", Dividend = "8.50", OrderHistory = new OrderHistory[] { new OrderHistory { OrderId = "1001", DateShipped = "08/17/2018", Total = "105.89" } }, ShippingPreference = new ShippingPreference[] { new ShippingPreference { Priority = 1, AddressLine1 = "505 NW 5th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" }, new ShippingPreference { Priority = 2, AddressLine1 = "505 NW 5th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" } }, Coupons = new CouponsUsed[] { new CouponsUsed { CouponCode = "Fall2018" } } }; await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin); yanhe.LastName = "Suh"; await this.ReplaceUserDocument("Users", "WebCustomers", yanhe); await this.ReadUserDocument("Users", "WebCustomers", yanhe); await this.DeleteUserDocument("Users", "WebCustomers", yanhe); this.ExecuteSimpleQuery("Users", "WebCustomers"); await this.RunStoredProcedure("Users", "WebCustomers", yanhe); }
private static async Task DeleteDatabase(DocumentClient documentClient, string databaseId) { await documentClient.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseId)); Console.WriteLine("\n5. Database {0} deleted.", databaseId); }
/// <summary> /// Run the get started demo for Azure Cosmos DB. This creates a database, collection, two documents, executes a simple query /// and cleans up. /// </summary> /// <returns>The Task for asynchronous completion.</returns> private async Task GetStartedDemo() { // Create a new instance of the DocumentClient this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey); Database databaseInfo = new Database { Id = "FamilyDB_og" }; await this.client.CreateDatabaseIfNotExistsAsync(databaseInfo); DocumentCollection collectionInfo = new DocumentCollection(); collectionInfo.Id = "FamilyCollection_og"; // We choose LastName as the partition key since we're storing family information. Data is seamlessly scaled out based on the last name of // the inserted entity. collectionInfo.PartitionKey.Paths.Add("/LastName"); // Optionally, you can configure the indexing policy of a collection. Here we configure collections for maximum query flexibility // including string range queries. collectionInfo.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 }); // Collections can be reserved with throughput specified in request units/second. 1 RU is a normalized request equivalent to the read // of a 1KB document. Here we create a collection with 400 RU/s. await this.client.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri(databaseInfo.Id), collectionInfo, new RequestOptions { OfferThroughput = 400 }); // Insert a document, here we create a Family object Family andersenFamily = new Family { Id = "Andersen.1", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay" } }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; await this.CreateFamilyDocumentIfNotExists("FamilyDB_og", "FamilyCollection_og", andersenFamily); Family wakefieldFamily = new Family { Id = "Wakefield.7", LastName = "Wakefield", Parents = new Parent[] { new Parent { FamilyName = "Wakefield", FirstName = "Robin" }, new Parent { FamilyName = "Miller", FirstName = "Ben" } }, Children = new Child[] { new Child { FamilyName = "Merriam", FirstName = "Jesse", Gender = "female", Grade = 8, Pets = new Pet[] { new Pet { GivenName = "Goofy" }, new Pet { GivenName = "Shadow" } } }, new Child { FamilyName = "Miller", FirstName = "Lisa", Gender = "female", Grade = 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; await this.CreateFamilyDocumentIfNotExists("FamilyDB_og", "FamilyCollection_og", wakefieldFamily); this.ExecuteSimpleQuery("FamilyDB_og", "FamilyCollection_og"); // Update the Grade of the Andersen Family child andersenFamily.Children[0].Grade = 6; await this.ReplaceFamilyDocument("FamilyDB_og", "FamilyCollection_og", andersenFamily); this.ExecuteSimpleQuery("FamilyDB_og", "FamilyCollection_og"); // Delete the document await this.DeleteFamilyDocument("FamilyDB_og", "FamilyCollection_og", "Andersen", "Andersen.1"); // Clean up/delete the database and client await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri("FamilyDB_og")); }
public async static Task CreateCollection(string database, string collection) { var databasecollection = await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(database), new DocumentCollection { Id = collection }); }
/// <summary> /// Creates or Updates a <see cref="User"/> in the database. /// <para/>Note: Should only be called from a mid-tier service. /// </summary> /// <param name="user"></param> /// <returns>A CosmosDB <see cref="User"/></returns> public async Task <User> UpsertUserAsync(User user) { return(await documentClient.UpsertUserAsync(UriFactory.CreateDatabaseUri(_database), user)); }
/// <summary> /// Gets the next available partition for a particular tier to assign a new or upgraded account to, return partition id in SuccessMessage. /// </summary> /// <returns></returns> public static DataAccessResponseType CreateDocumentCollectionAccountPartition(string accountNameKey, IReliableReadWriteDocumentClient client, string databaseId) { DataAccessResponseType response = new DataAccessResponseType(); Uri databaseUri = UriFactory.CreateDatabaseUri(databaseId); #region Create DocumentCollection object DocumentCollection newCollection = null; try { newCollection = client.CreateDocumentCollectionQuery(databaseUri.ToString()).Where(c => c.Id == accountNameKey).ToArray().FirstOrDefault(); } catch (DocumentClientException de) { PlatformExceptionsHelper.LogExceptionAndAlertAdmins( de.GetBaseException(), "attempting to create new Collection on DocumentDB for '" + accountNameKey + "'", System.Reflection.MethodBase.GetCurrentMethod() ); } if (newCollection == null) { //Collection is null so create it: var requestOptions = new RequestOptions { //OfferType = Sahara.Core.Settings.Azure.DocumentDB.DefaultCollectionOfferType_AccountPartitions, //<-- Depricated (Standard is the default) OfferThroughput = Sahara.Core.Settings.Azure.DocumentDB.DefaultCollectionOfferThroughput_AccountPartitions }; newCollection = client.CreateDocumentCollectionAsync(databaseUri.ToString(), new DocumentCollection { Id = accountNameKey }, requestOptions).Result; if (newCollection != null) { //Used to access embedded resources var assembly = Assembly.GetExecutingAssembly(); #region Create Triggers on the new Document Collection (REMOVED - NO LONGER REQUIRED TO MAINTAIN COUNTS) /* * #region Increment/Decrement Count Triggers * * //Allows us to track document counts for each Accont as well as the entire collection whenever a document type such as "Product" is added or removed from the collection * #region Create Increment Trigger * * //Delete if exists #region Delete * Microsoft.Azure.Documents.Trigger incrementTriggerExists = client.CreateTriggerQuery(newCollection.SelfLink).Where(t => t.Id == "IncrementProductCount").AsEnumerable().FirstOrDefault(); * if (incrementTriggerExists != null) * { * client.DeleteTriggerAsync(incrementTriggerExists.SelfLink); * } #endregion * * string incrementProductCount_FileContents = string.Empty; * * using (Stream stream = assembly.GetManifestResourceStream("Sahara.Core.Platform.Partitioning.DocumentScripts.Triggers.IncrementProductCount.js")) * using (StreamReader reader = new StreamReader(stream)) * { * incrementProductCount_FileContents = reader.ReadToEnd(); * } * * //Create new increment trigger * //string incrementTriggerPath = @"DocumentScripts\Triggers\IncrementProductCount.js"; * //string incrementTriggerId = System.IO.Path.GetFileNameWithoutExtension(incrementTriggerPath); * //string incrementTriggerBody = File.ReadAllText(incrementTriggerPath); * Microsoft.Azure.Documents.Trigger incrementTrigger = new Microsoft.Azure.Documents.Trigger * { * Id = "IncrementProductCount", * Body = incrementProductCount_FileContents, * TriggerOperation = TriggerOperation.Create, //<-- Can only be used as part of a Create call * TriggerType = TriggerType.Post //<-- Runs after the Create is complete * }; * * client.CreateTriggerAsync(newCollection.SelfLink, incrementTrigger); * #endregion * #region Create Decrement Trigger * * //Delete if exists #region Delete * Microsoft.Azure.Documents.Trigger decrementTriggerExists = client.CreateTriggerQuery(newCollection.SelfLink).Where(t => t.Id == "DecrementProductCount").AsEnumerable().FirstOrDefault(); * if (decrementTriggerExists != null) * { * client.DeleteTriggerAsync(decrementTriggerExists.SelfLink); * } #endregion * * string decrementProductCount_FileContents = string.Empty; * * using (Stream stream = assembly.GetManifestResourceStream("Sahara.Core.Platform.Partitioning.DocumentScripts.Triggers.DecrementProductCount.js")) * using (StreamReader reader = new StreamReader(stream)) * { * decrementProductCount_FileContents = reader.ReadToEnd(); * } * * //Create new decrement trigger * //string decrementTriggerPath = @"DocumentScripts\Triggers\DecrementProductCount.js"; * //string decrementTriggerId = System.IO.Path.GetFileNameWithoutExtension(decrementTriggerPath); * //string decrementTriggerBody = File.ReadAllText(decrementTriggerPath); * Microsoft.Azure.Documents.Trigger decrementTrigger = new Microsoft.Azure.Documents.Trigger * { * Id = "DecrementProductCount", * Body = decrementProductCount_FileContents, * TriggerOperation = TriggerOperation.Delete, //<-- Can only be used as part of a Delete call * TriggerType = TriggerType.Post //<-- Runs after the Delete is complete * }; * * client.CreateTriggerAsync(newCollection.SelfLink, decrementTrigger); * #endregion * #endregion */ #endregion #region Create the 'CollectionProperties' Document on the new Document Collection (REMOVED - NO LONGER REQUIRED) /* * * //This document is used to track various properties on the collection such as overall document counts. It is updated by the increment/decrmemnt count triggers when a document is added or removed for an account, etc... * * var _docId = "CollectionProperties"; * #region TryDelete (If Exists) * * var existingCollectionPropertiesDoc = client.CreateDocumentQuery(newCollection.SelfLink).Where(s => s.Id == _docId).AsEnumerable().FirstOrDefault(); * if (existingCollectionPropertiesDoc != null) * { * client.DeleteDocumentAsync(existingCollectionPropertiesDoc.SelfLink).ConfigureAwait(false); * } * #endregion * * var collectionPropertiesDocument = new CollectionPropertiesDocumentModel { Id = _docId, DocumentCount = 0, ProductCount = 0 }; * var result = client.CreateDocumentAsync(newCollection.SelfLink, collectionPropertiesDocument); */ #endregion } else { PlatformExceptionsHelper.LogErrorAndAlertAdmins( "Could not create new collection on DocumentDB account", "attempting to create new collection on DocumentDB account for '" + accountNameKey + "'", System.Reflection.MethodBase.GetCurrentMethod() ); } } #endregion response.isSuccess = true; response.ResponseObject = newCollection; return(response); }
/// <summary> /// The GetDBList /// </summary> /// <returns></returns> public async Task <MenuItem> GetDBList() { MenuItem rootItem = new MenuItem { Title = this.endpoint, Level = 0, Secret = this.secret }; try { var dbList = await client.ReadDatabaseFeedAsync().ConfigureAwait(false); foreach (var dbItem in dbList) { var dbModel = new MenuItem { Title = dbItem.Id, Level = 1 }; var dbCollectionList = await client.ReadDocumentCollectionFeedAsync(UriFactory.CreateDatabaseUri(dbItem.Id)).ConfigureAwait(false); foreach (var collectionItem in dbCollectionList) { var collectionItemModel = new MenuItem { Title = collectionItem.Id, Level = 2, DbName = dbItem.Id, CollectioName = collectionItem.Id }; var docCollectionList = await client.ReadDocumentFeedAsync(UriFactory.CreateDocumentCollectionUri(dbItem.Id, collectionItem.Id)).ConfigureAwait(false); foreach (Document docItem in docCollectionList) { collectionItemModel.Items.Add(new MenuItem { Title = docItem.Id, DocSelfLink = docItem.SelfLink, CollectionSelfLink = collectionItem.SelfLink, Level = 3, DbName = dbItem.Id, CollectioName = collectionItem.Id }); } dbModel.Items.Add(collectionItemModel); } rootItem.Items.Add(dbModel); } } catch (Exception ex) { } return(rootItem); }
private static async Task CleanDB(DocumentClient client) { Console.WriteLine("U ready to delete DB?"); Console.ReadKey(); await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseId)); }
public static void CreateCollection(IDocumentClient client, string databaseId, string collectionId, string partitionKeyName = "") { var result = client.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseId }).GetAwaiter().GetResult(); if (result.StatusCode == System.Net.HttpStatusCode.Accepted || result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode == System.Net.HttpStatusCode.Created) { var collection = new DocumentCollection { Id = collectionId }; if (!string.IsNullOrEmpty(partitionKeyName)) { if (!partitionKeyName.StartsWith("/")) { partitionKeyName = "/" + partitionKeyName; } collection.PartitionKey = new PartitionKeyDefinition { Paths = new Collection <string> { partitionKeyName } }; } var collectionCreationResult = client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(databaseId), collection, new RequestOptions { OfferThroughput = DEFAULT_RUS }).GetAwaiter().GetResult(); if (collectionCreationResult.StatusCode == System.Net.HttpStatusCode.Accepted || collectionCreationResult.StatusCode == System.Net.HttpStatusCode.OK || collectionCreationResult.StatusCode == System.Net.HttpStatusCode.Created) { Task.Delay(500).GetAwaiter().GetResult(); } else { throw new NotSupportedException($"Collection '{collection}' cannot be created. ({collectionCreationResult.StatusCode})"); } } else { throw new NotSupportedException($"Database '{databaseId}' cannot be created. Wrong Url or Key? ({result.StatusCode})"); } }
/// <summary> /// Run samples for Order By queries. /// </summary> /// <returns>a Task object.</returns> private async Task RunAsync() { DocumentCollection dataCollection = GetCollectionIfExists(DatabaseName, DataCollectionName); int currentCollectionThroughput = 0; if (bool.Parse(ConfigurationManager.AppSettings["ShouldCleanupOnStart"]) || dataCollection == null) { Database database = GetDatabaseIfExists(DatabaseName); if (database != null) { await client.DeleteDatabaseAsync(database.SelfLink); } Console.WriteLine("Creating database {0}", DatabaseName); database = await client.CreateDatabaseAsync(new Database { Id = DatabaseName }); Console.WriteLine("Creating collection {0} with {1} RU/s", DataCollectionName, CollectionThroughput); dataCollection = await this.CreatePartitionedCollectionAsync(DatabaseName, DataCollectionName); currentCollectionThroughput = CollectionThroughput; } else { OfferV2 offer = (OfferV2)client.CreateOfferQuery().Where(o => o.ResourceLink == dataCollection.SelfLink).AsEnumerable().FirstOrDefault(); currentCollectionThroughput = offer.Content.OfferThroughput; Console.WriteLine("Found collection {0} with {1} RU/s", DataCollectionName, currentCollectionThroughput); } int taskCount; int degreeOfParallelism = int.Parse(ConfigurationManager.AppSettings["DegreeOfParallelism"]); if (degreeOfParallelism == -1) { // set TaskCount = 10 for each 10k RUs taskCount = currentCollectionThroughput / 1000; if (taskCount >= 250) { taskCount = 250; } } else { taskCount = degreeOfParallelism; } Console.WriteLine("Starting Inserts with {0} tasks", taskCount); string sampleDocument = File.ReadAllText(ConfigurationManager.AppSettings["DocumentTemplateFile"]); pendingTaskCount = taskCount; var tasks = new List <Task>(); tasks.Add(this.LogOutputStats()); long numberOfDocumentsToInsert = long.Parse(ConfigurationManager.AppSettings["NumberOfDocumentsToInsert"]) / taskCount; for (var i = 0; i < taskCount; i++) { tasks.Add(this.InsertDocument(i, client, dataCollection, sampleDocument, numberOfDocumentsToInsert)); } await Task.WhenAll(tasks); if (bool.Parse(ConfigurationManager.AppSettings["ShouldCleanupOnFinish"])) { Console.WriteLine("Deleting Database {0}", DatabaseName); await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseName)); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, [CosmosDB( databaseName: "QuestionsData", collectionName: "QuestionsData", ConnectionStringSetting = "QuestionsDBConnection")] DocumentClient outputTable, [Queue("NewQuestionsData")] IAsyncCollector <KeyValuePair <string, string> > outputQueue, ILogger log) { log.LogInformation("Try to add a new question."); QuestionData questionsToSave = null; try { questionsToSave = await System.Text.Json.JsonSerializer.DeserializeAsync <QuestionData>(req.Body, new JsonSerializerOptions() { AllowTrailingCommas = true, } ); } catch (JsonException ex) { return(new BadRequestObjectResult($"There was an error in the provided json: {ex.Message} -> {ex.InnerException.Message}")); } questionsToSave.Source = "covapp.charite"; await outputTable.CreateDatabaseIfNotExistsAsync(new Database() { Id = "QuestionsData" }); await outputTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("QuestionsData"), new DocumentCollection() { Id = "QuestionsData", PartitionKey = new PartitionKeyDefinition() { Paths = new Collection <string>() { "/Source" } }, UniqueKeyPolicy = new UniqueKeyPolicy() { UniqueKeys = new Collection <UniqueKey>() { new UniqueKey() { Paths = new Collection <string>() { "/Token" } } } } }); await outputTable.CreateDocumentAsync("dbs/QuestionsData/colls/QuestionsData", questionsToSave); await outputQueue.AddAsync(questionsToSave.GetIdentifier()); return(new OkObjectResult(questionsToSave.Token)); }
static internal DocumentCollection GetCollectionIfExists(DocumentClient client, string databaseName, string collectionName) { return(client.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri(databaseName)) .Where(c => c.Id == collectionName).AsEnumerable().FirstOrDefault()); }