public async Task <SdkClientResult <T> > ExecSprocAsync <T>(string databaseId, string collectionId, string sprocName, string documentId, string partitionKey) { SdkClientResult <T> result = new SdkClientResult <T>(); // Local proxy objects Database database = this.CosmosClient.GetDatabase(databaseId); Container container = database.GetContainer(collectionId); // Enable sproc logging which we set to the result below - this is not enabled by default StoredProcedureRequestOptions sprocRequestOptions = new StoredProcedureRequestOptions() { EnableScriptLogging = true }; StoredProcedureExecuteResponse <string> response = await container.Scripts.ExecuteStoredProcedureAsync <string> ( sprocName, new PartitionKey(partitionKey), new[] { documentId }, sprocRequestOptions ); result.Content = JsonConvert.DeserializeObject <T>(response.Resource); result.RequestInfo.RequestCharge = response.RequestCharge; result.RequestInfo.Logging = response.ScriptLog; return(result); }
private static async Task LoadData(Benchmark benchmark) { try { List <SampleCustomer> customers = SampleCustomer.GenerateCustomers(benchmark.partitionKeyValue, 100); //Stored Proc for bulk inserting data string scriptId = "BulkImport"; string body = File.ReadAllText(@"spBulkUpload.js"); StoredProcedureResponse sproc = await benchmark.container.Scripts.CreateStoredProcedureAsync(new StoredProcedureProperties(scriptId, body)); int inserted = 0; while (inserted < customers.Count) { dynamic[] args = new dynamic[] { customers.Skip(inserted) }; StoredProcedureExecuteResponse <int> result = await benchmark.container.Scripts.ExecuteStoredProcedureAsync <int>(scriptId, new PartitionKey(benchmark.partitionKeyValue), args); inserted += result.Resource; Console.WriteLine($"Inserted {inserted} items."); } } catch (Exception e) { Console.WriteLine(e.Message + "\nPress any key to continue"); Console.ReadKey(); } }
/// <summary> /// Runs a simple script which just does a server side query /// </summary> private static async Task RunSimpleScript(CosmosContainer container) { // 1. Create stored procedure for script. string scriptFileName = @"js\SimpleScript.js"; string scriptId = Path.GetFileNameWithoutExtension(scriptFileName); await TryDeleteStoredProcedure(container, scriptId); CosmosScripts cosmosScripts = container.GetScripts(); StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new CosmosStoredProcedureSettings(scriptId, File.ReadAllText(scriptFileName))); // 2. Create a document. SampleDocument doc = new SampleDocument { Id = Guid.NewGuid().ToString(), LastName = "Estel", Headquarters = "Russia", Locations = new Location[] { new Location { Country = "Russia", City = "Novosibirsk" } }, Income = 50000 }; ItemResponse <SampleDocument> created = await container.CreateItemAsync(doc, new PartitionKey(doc.LastName)); // 3. Run the script. Pass "Hello, " as parameter. // The script will take the 1st document and echo: Hello, <document as json>. StoredProcedureExecuteResponse <string> response = await container.GetScripts().ExecuteStoredProcedureAsync <string, string>(new PartitionKey(doc.LastName), scriptId, "Hello"); Console.WriteLine("Result from script: {0}\r\n", response.Resource); await container.DeleteItemAsync <SampleDocument>(new PartitionKey(doc.LastName), doc.Id); }
// </RunBulkImport> /// <summary> /// Get documents ordered by some doc property. This is done using OrderBy stored procedure. /// </summary> // <RunOrderBy> private static async Task RunOrderBy(Container container) { // 1. Create or get the stored procedure. string body = File.ReadAllText(@"js\OrderBy.js"); string scriptId = "OrderBy"; await TryDeleteStoredProcedure(container, scriptId); Scripts cosmosScripts = container.Scripts; StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new StoredProcedureProperties(scriptId, body)); // 2. Prepare to run stored procedure. string orderByFieldName = "FamilyId"; string filterQuery = string.Format(CultureInfo.InvariantCulture, "SELECT r.FamilyId FROM root r WHERE r.{0} > 10", orderByFieldName); // Note: in order to do a range query (> 10) on this field, the collection must have a range index set for this path (see ReadOrCreateCollection). int?continuationToken = null; int batchCount = 0; do { // 3. Run the stored procedure. StoredProcedureExecuteResponse <OrderByResult> response = await cosmosScripts.ExecuteStoredProcedureAsync <OrderByResult>( scriptId, new PartitionKey("Andersen"), new dynamic[] { filterQuery, orderByFieldName, continuationToken }); // 4. Process stored procedure response. continuationToken = response.Resource.Continuation; Console.WriteLine($"Printing documents filtered/ordered by '{filterQuery}' and ordered by '{orderByFieldName}', batch #{batchCount++}, count #{response.Resource.Result.Length}"); } while (continuationToken != null); // 5. To take care of big response, loop until Response.continuation token is null (see OrderBy.js for details). }
public async Task ExecuteTestWithParameter() { string sprocId = Guid.NewGuid().ToString(); string sprocBody = @"function(param1) { var context = getContext(); var response = context.getResponse(); response.setBody(param1); }"; StoredProcedureResponse storedProcedureResponse = await this.scripts.CreateStoredProcedureAsync(new StoredProcedureProperties(sprocId, sprocBody)); Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode); StoredProcedureTests.ValidateStoredProcedureSettings(sprocId, sprocBody, storedProcedureResponse); // Insert document and then query string testPartitionId = Guid.NewGuid().ToString(); var payload = new { id = testPartitionId, user = testPartitionId }; ItemResponse <dynamic> createItemResponse = await this.container.CreateItemAsync <dynamic>(payload); Assert.AreEqual(HttpStatusCode.Created, createItemResponse.StatusCode); StoredProcedureExecuteResponse <string> sprocResponse = await this.scripts.ExecuteStoredProcedureAsync <string>( sprocId, new Cosmos.PartitionKey(testPartitionId), parameters : new dynamic[] { "one" }); Assert.AreEqual(HttpStatusCode.OK, sprocResponse.StatusCode); string stringResponse = sprocResponse.Resource; Assert.IsNotNull(stringResponse); Assert.AreEqual("one", stringResponse); ResponseMessage response = await this.scripts.ExecuteStoredProcedureStreamAsync( sprocId, new Cosmos.PartitionKey(testPartitionId), parameters : new dynamic[] { null }); using (StreamReader reader = new StreamReader(response.Content)) { string text = await reader.ReadToEndAsync(); Assert.AreEqual("null", text); } sprocResponse = await this.scripts.ExecuteStoredProcedureAsync <string>( sprocId, new Cosmos.PartitionKey(testPartitionId), parameters : new dynamic[] { null }); Assert.AreEqual(HttpStatusCode.OK, sprocResponse.StatusCode); stringResponse = sprocResponse.Resource; Assert.IsNull(stringResponse); StoredProcedureResponse deleteResponse = await this.scripts.DeleteStoredProcedureAsync(sprocId); Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode); }
public async Task ExecutionLogsTests() { const string testLogsText = "this is a test"; const string testPartitionId = "1"; string sprocId = Guid.NewGuid().ToString(); string sprocBody = @"function(name) { var context = getContext(); console.log('" + testLogsText + "'); var response = context.getResponse(); response.setBody('hello there ' + name); }"; StoredProcedureResponse storedProcedureResponse = await this.scripts.CreateStoredProcedureAsync(new StoredProcedureProperties(sprocId, sprocBody)); double requestCharge = storedProcedureResponse.RequestCharge; Assert.IsTrue(requestCharge > 0); Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode); StoredProcedureTests.ValidateStoredProcedureSettings(sprocId, sprocBody, storedProcedureResponse); StoredProcedureProperties storedProcedure = storedProcedureResponse; StoredProcedureExecuteResponse <string> sprocResponse = await this.scripts.ExecuteStoredProcedureAsync <string>( sprocId, new Cosmos.PartitionKey(testPartitionId), new dynamic[] { Guid.NewGuid().ToString() }, new StoredProcedureRequestOptions() { EnableScriptLogging = true }); Assert.AreEqual(HttpStatusCode.OK, sprocResponse.StatusCode); Assert.AreEqual(testLogsText, sprocResponse.ScriptLog); }
public async Task HardDeleteAsync(ResourceKey key, CancellationToken cancellationToken) { EnsureArg.IsNotNull(key, nameof(key)); try { _logger.LogDebug($"Obliterating {key.ResourceType}/{key.Id}"); StoredProcedureExecuteResponse <IList <string> > response = await _retryExceptionPolicyFactory.CreateRetryPolicy().ExecuteAsync( async ct => await _hardDelete.Execute( _containerScope.Value.Scripts, key, ct), cancellationToken); _logger.LogDebug($"Hard-deleted {response.Resource.Count} documents, which consumed {response.RequestCharge} RUs. The list of hard-deleted documents: {string.Join(", ", response.Resource)}."); } catch (CosmosException exception) { if (exception.IsRequestEntityTooLarge()) { throw; } _logger.LogError(exception, "Unhandled Document Client Exception"); throw; } }
private static async Task ValidateSprocResultsAsync(ContainerCore containerCore, TestDoc expectedDoc) { string sprocId = Guid.NewGuid().ToString(); string sprocBody = @"function(docId) { var context = getContext(); var collection = context.getCollection(); var docUri = collection.getAltLink() + '/docs/' + docId; var response = context.getResponse(); collection.readDocument(docUri, { }, function(error, resource, options) { response.setBody(resource); }); }"; StoredProcedureResponse storedProcedureResponse = await containerCore.Scripts.CreateStoredProcedureAsync(new StoredProcedureProperties(sprocId, sprocBody)); Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode); StoredProcedureExecuteResponse <TestDoc> sprocResponse = await containerCore.Scripts.ExecuteStoredProcedureAsync <TestDoc>( sprocId, new PartitionKey(expectedDoc.PK), parameters : new dynamic[] { expectedDoc.Id }); Assert.AreEqual(expectedDoc, sprocResponse.Resource); }
private static async Task Execute_spSetNorthAmerica3() { Console.WriteLine(); Console.WriteLine("Execute spSetNorthAmerica (no country)"); var id = Guid.NewGuid().ToString(); dynamic documentDefinition = new { id, name = "James Smith", address = new { postalCode = "12345" } }; var container = Shared.Client.GetContainer("mydb", "mystore"); var pk = new PartitionKey(documentDefinition.address.postalCode); try { // Should fail with no country and enforceSchema = true StoredProcedureExecuteResponse <dynamic> result = await container.Scripts.ExecuteStoredProcedureAsync <dynamic>("spSetNorthAmerica", pk, new[] { documentDefinition, true }); } catch (CosmosException exception) { Console.WriteLine($"Error: {exception.Message}"); } }
private static async Task Execute_spSetNorthAmerica1() { Console.WriteLine("\nExecute spSetNorthAmerica (country = United States)\n"); // Should succeed with isNorthAmerica = true var id = Guid.NewGuid().ToString(); dynamic documentDefinition = new { id, name = "John Doe", address = new { countryRegionName = "United States", postalCode = "12345" } }; Container container = Shared.Client.GetContainer("mydb", "mystore"); PartitionKey partitionKey = new PartitionKey(documentDefinition.address.postalCode); StoredProcedureExecuteResponse <dynamic> result = await container.Scripts.ExecuteStoredProcedureAsync <dynamic>("spSetNorthAmerica", partitionKey, new[] { documentDefinition, true }); var document = result.Resource; var country = document.address.countryRegionName; var isNorthAmerica = document.address.isNorthAmerica; Console.WriteLine("Result:"); Console.WriteLine($" Country = {country}"); Console.WriteLine($" Is North America = {isNorthAmerica}"); await container.DeleteItemAsync <dynamic>(id, partitionKey); }
public async Task<HttpStatusCode> BulkUpdateAsync<T>(IEnumerable<T> entities, string storedProcedureName) where T : IIdentifiable { Guard.ArgumentNotNull(entities, nameof(entities)); string documentType = GetDocumentType<T>(); IList<DocumentEntity<T>> documents = new List<DocumentEntity<T>>(); foreach (T entity in entities) { DocumentEntity<T> doc = new DocumentEntity<T>(entity); if (doc.DocumentType != null && doc.DocumentType != documentType) { throw new ArgumentException($"Cannot change {entity.Id} from {doc.DocumentType} to {typeof(T).Name}"); } doc.DocumentType = documentType; doc.UpdatedAt = DateTimeOffset.Now; documents.Add(doc); } string documentsAsJson = JsonConvert.SerializeObject(documents); dynamic[] args = new dynamic[] { JsonConvert.DeserializeObject<dynamic>(documentsAsJson) }; Scripts cosmosScripts = RepositoryContainer.Scripts; StoredProcedureExecuteResponse<string> response = await cosmosScripts.ExecuteStoredProcedureAsync<string>( storedProcedureId: storedProcedureName, partitionKey: PartitionKey.Null, requestOptions: null, parameters: args); return response.StatusCode; }
public async Task <UpsertWithHistoryModel> Execute(Scripts client, FhirCosmosResourceWrapper resource, string matchVersionId, bool allowCreate, bool keepHistory, CancellationToken cancellationToken) { EnsureArg.IsNotNull(client, nameof(client)); EnsureArg.IsNotNull(resource, nameof(resource)); StoredProcedureExecuteResponse <UpsertWithHistoryModel> results = await ExecuteStoredProc <UpsertWithHistoryModel>(client, resource.PartitionKey, cancellationToken, resource, matchVersionId, allowCreate, keepHistory); return(results.Resource); }
public async Task ExecuteNonePkTest() { // Create a container in v2 without a partition key string containerId = "SprocPkNone" + Guid.NewGuid().ToString(); ContainerInternal containerNonePk = await NonPartitionedContainerHelper.CreateNonPartitionedContainer(this.database, containerId); Scripts scriptsNonePk = containerNonePk.Scripts; string sprocId = Guid.NewGuid().ToString(); string sprocBody = @"function() { var context = getContext(); var response = context.getResponse(); var collection = context.getCollection(); var collectionLink = collection.getSelfLink(); var filterQuery = 'SELECT * FROM c'; collection.queryDocuments(collectionLink, filterQuery, { }, function(err, documents) { response.setBody(documents); } ); }"; StoredProcedureResponse storedProcedureResponse = await scriptsNonePk.CreateStoredProcedureAsync(new StoredProcedureProperties(sprocId, sprocBody)); Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode); StoredProcedureTests.ValidateStoredProcedureSettings(sprocId, sprocBody, storedProcedureResponse); // Insert document and then query string testPartitionId = Guid.NewGuid().ToString(); var payload = new { id = testPartitionId, user = testPartitionId }; ItemResponse <dynamic> createItemResponse = await containerNonePk.CreateItemAsync <dynamic>(payload); Assert.AreEqual(HttpStatusCode.Created, createItemResponse.StatusCode); StoredProcedureProperties storedProcedure = storedProcedureResponse; StoredProcedureExecuteResponse <JArray> sprocResponse = await scriptsNonePk.ExecuteStoredProcedureAsync <JArray>( sprocId, Cosmos.PartitionKey.None, parameters : null); Assert.AreEqual(HttpStatusCode.OK, sprocResponse.StatusCode); JArray jArray = sprocResponse; Assert.AreEqual(1, jArray.Count); Assert.AreEqual(testPartitionId, jArray[0]["id"]); StoredProcedureResponse deleteResponse = await scriptsNonePk.DeleteStoredProcedureAsync(sprocId); Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode); }
public async Task UpdateWishlistItemDescriptionAsync(WishlistItem wishlistItem) { StoredProcedureExecuteResponse <string> response = await _container.Scripts.ExecuteStoredProcedureAsync <string>( "updateWishlistItem", new PartitionKey(wishlistItem.UserId), new dynamic[] { wishlistItem.Id, wishlistItem.Description }); _logger.LogInformation("Request charge of edit operation: {0}", response.RequestCharge); _logger.LogInformation("StatusCode of operation: {0}", response.StatusCode); }
public async Task ExecuteSPGreeting(string name) { string message = "Execute SPGreeting"; Printer.PrintLine(message: message); Scripts scripts = _container.Scripts; StoredProcedureExecuteResponse <string> sprocResponse = await scripts.ExecuteStoredProcedureAsync <string>("Greetings", new PartitionKey("/pizzaType"), new dynamic[] { name }); WriteLine($"SP Greeting Result: {sprocResponse.Resource}"); Printer.PrintLine(noOfTimes: (101 + message.Length)); }
public async Task ExecuteGetPizzaCount(string partitionKey) { string message = "Execute GetPizzaCount"; Printer.PrintLine(message: message); Scripts scripts = _container.Scripts; StoredProcedureExecuteResponse <string> sprocResponse = await scripts.ExecuteStoredProcedureAsync <string>("GetPizzaCount", new PartitionKey($"{partitionKey}"), new dynamic[] { }); WriteLine($"SP GetPizzaCount Result: {JsonConvert.DeserializeObject(sprocResponse.Resource)}"); Printer.PrintLine(noOfTimes: (101 + message.Length)); }
public async Task ExecuteSPDeletePizza(string pizzaType, string pizzaId) { string message = "Execute SPDeletePizza"; Printer.PrintLine(message: message); Scripts scripts = _container.Scripts; StoredProcedureExecuteResponse <string> sprocResponse = await scripts.ExecuteStoredProcedureAsync <string>("DeletePizza", new PartitionKey(pizzaType), new dynamic[] { pizzaId }); WriteLine($"SP DeletePizza Result: \n{JsonConvert.DeserializeObject(sprocResponse.Resource)}"); Printer.PrintLine(noOfTimes: (101 + message.Length)); }
private static async Task Execute_spHelloWorld() { Console.WriteLine("\nExecute spHelloWorld stored procedure"); Scripts scripts = Shared.Client.GetContainer("mydb", "mystore").Scripts; PartitionKey partitionKey = new PartitionKey(string.Empty); StoredProcedureExecuteResponse <string> result = await scripts.ExecuteStoredProcedureAsync <string>("spHelloWorld", partitionKey, null); string message = result.Resource; Console.WriteLine($"Result: {message}"); }
public async Task ExecuteSPCreateNewPizza(string pizzaType, string pizzaFileName) { string newPizza = File.ReadAllText($"Models/PizzaData/{pizzaFileName}.json"); string message = "Execute SPCreateNewPizza"; Printer.PrintLine(message: message); Scripts scripts = _container.Scripts; StoredProcedureExecuteResponse <string> sprocResponse = await scripts.ExecuteStoredProcedureAsync <string>("CreateNewPizza", new PartitionKey(pizzaType), new dynamic[] { newPizza }); WriteLine($"SP Create New Pizza Result: \n{JsonConvert.DeserializeObject(sprocResponse.Resource)}"); Printer.PrintLine(noOfTimes: (100 + message.Length)); }
public async Task ExecuteSPBulkPizzaCreate(string pizzaFile, string partitionKey) { var jsonArray = JArray.Parse(File.ReadAllText($@"Models/PizzaData/PizzaCollection/{pizzaFile}PizzaCollection.json")); string message = "Execute SPBulkPizzaCreate"; Printer.PrintLine(message: message); Scripts scripts = _container.Scripts; StoredProcedureExecuteResponse <string> sprocResponse = await scripts.ExecuteStoredProcedureAsync <string>("BulkPizzaCreate", new PartitionKey($"{partitionKey}"), new dynamic[] { jsonArray }); WriteLine($"SP Bulk Pizza Create Result: \n{JsonConvert.DeserializeObject(sprocResponse.Resource)}"); Printer.PrintLine(noOfTimes: (100 + message.Length)); }
protected async Task <StoredProcedureExecuteResponse <T> > ExecuteStoredProc <T>(Scripts client, string partitionId, CancellationToken cancellationToken, params object[] parameters) { EnsureArg.IsNotNull(client, nameof(client)); EnsureArg.IsNotNull(partitionId, nameof(partitionId)); StoredProcedureExecuteResponse <T> results = await client.ExecuteStoredProcedureAsync <T>( FullName, new PartitionKey(partitionId), parameters, cancellationToken : cancellationToken); return(results); }
public async Task ExecuteSPGetPizzas(string pizzaType = "Veg", decimal price = 300) { string message = "Execute SPGetPizzas"; Printer.PrintLine(message: message); Scripts scripts = _container.Scripts; StoredProcedureExecuteResponse <string> sprocResponse = await scripts.ExecuteStoredProcedureAsync <string>("GetPizzas", new PartitionKey(pizzaType), new dynamic[] { pizzaType, price }); // StoredProcedureExecuteResponse<string> sprocResponse = await scripts.ExecuteStoredProcedureAsync<string>("GetPizzas", new PartitionKey(pizzaType), new dynamic[] { pizzaType }); // StoredProcedureExecuteResponse<string> sprocResponse = await scripts.ExecuteStoredProcedureAsync<string>("GetPizzas", new PartitionKey(pizzaType), new dynamic[] { }); WriteLine($"SP Get VegPizza Result: \n{JsonConvert.DeserializeObject(sprocResponse.Resource)}"); Printer.PrintLine(noOfTimes: (101 + message.Length)); }
private static async Task BulkDelete(Container container) { bool resume = true; do { string query = "SELECT * FROM foods f WHERE f.foodGroup = 'Energy Bars'"; StoredProcedureExecuteResponse <DeleteStatus> result = await container.Scripts.ExecuteStoredProcedureAsync <DeleteStatus>("bulkDelete", new PartitionKey("Energy Bars"), new dynamic[] { query }); await Console.Out.WriteLineAsync($"Batch Delete Completed.\tDeleted: {result.Resource.Deleted}\tContinue: {result.Resource.Continuation}"); resume = result.Resource.Continuation; }while (resume); }
public async Task <FhirCosmosResourceWrapper> Execute(Scripts client, FhirCosmosResourceWrapper resource, string matchVersionId, CancellationToken cancellationToken) { EnsureArg.IsNotNull(client, nameof(client)); EnsureArg.IsNotNull(resource, nameof(resource)); StoredProcedureExecuteResponse <FhirCosmosResourceWrapper> result = await ExecuteStoredProc <FhirCosmosResourceWrapper>( client, resource.PartitionKey, cancellationToken, resource, matchVersionId); return(result.Resource); }
public async Task ExecuteTest() { string sprocId = Guid.NewGuid().ToString(); string sprocBody = @"function() { var context = getContext(); var response = context.getResponse(); var collection = context.getCollection(); var collectionLink = collection.getSelfLink(); var filterQuery = 'SELECT * FROM c'; collection.queryDocuments(collectionLink, filterQuery, { }, function(err, documents) { response.setBody(documents); } ); }"; StoredProcedureResponse storedProcedureResponse = await this.scripts.CreateStoredProcedureAsync(new StoredProcedureProperties(sprocId, sprocBody)); Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode); StoredProcedureTests.ValidateStoredProcedureSettings(sprocId, sprocBody, storedProcedureResponse); // Insert document and then query string testPartitionId = Guid.NewGuid().ToString(); var payload = new { id = testPartitionId, user = testPartitionId }; ItemResponse <dynamic> createItemResponse = await this.container.CreateItemAsync <dynamic>(payload); Assert.AreEqual(HttpStatusCode.Created, createItemResponse.StatusCode); StoredProcedureProperties storedProcedure = storedProcedureResponse; StoredProcedureExecuteResponse <JArray> sprocResponse = await this.scripts.ExecuteStoredProcedureAsync <JArray>( sprocId, new Cosmos.PartitionKey(testPartitionId), parameters : null); Assert.AreEqual(HttpStatusCode.OK, sprocResponse.StatusCode); JArray jArray = sprocResponse; Assert.AreEqual(1, jArray.Count); StoredProcedureResponse deleteResponse = await this.scripts.DeleteStoredProcedureAsync(sprocId); Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode); }
private static async Task Execute_spGenerateId() { Console.WriteLine(); Console.WriteLine("Execute spGenerateId"); dynamic docDef1 = new { firstName = "Albert", lastName = "Einstein", address = new { postalCode = "12345" } }; dynamic docDef2 = new { firstName = "Alfred", lastName = "Einstein", address = new { postalCode = "12345" } }; dynamic docDef3 = new { firstName = "Ashton", lastName = "Einstein", address = new { postalCode = "12345" } }; dynamic docDef4 = new { firstName = "Albert", lastName = "Einstein", address = new { postalCode = "54321" } }; var container = Shared.Client.GetContainer("mydb", "mystore"); var pk12345 = new PartitionKey("12345"); var pk54321 = new PartitionKey("54321"); StoredProcedureExecuteResponse <dynamic> result1 = await container.Scripts.ExecuteStoredProcedureAsync <dynamic>("spGenerateId", pk12345, new[] { docDef1 }); var doc1 = result1.Resource; Console.WriteLine($"New document in PK '{doc1.address.postalCode}', generated ID '{doc1.id}' for '{doc1.firstName} {doc1.lastName}'"); StoredProcedureExecuteResponse <dynamic> result2 = await container.Scripts.ExecuteStoredProcedureAsync <dynamic>("spGenerateId", pk12345, new[] { docDef2 }); var doc2 = result2.Resource; Console.WriteLine($"New document in PK '{doc2.address.postalCode}', generated ID '{doc2.id}' for '{doc2.firstName} {doc2.lastName}'"); StoredProcedureExecuteResponse <dynamic> result3 = await container.Scripts.ExecuteStoredProcedureAsync <dynamic>("spGenerateId", pk12345, new[] { docDef3 }); var doc3 = result3.Resource; Console.WriteLine($"New document in PK '{doc3.address.postalCode}', generated ID '{doc3.id}' for '{doc3.firstName} {doc3.lastName}'"); StoredProcedureExecuteResponse <dynamic> result4 = await container.Scripts.ExecuteStoredProcedureAsync <dynamic>("spGenerateId", pk54321, new[] { docDef4 }); var doc4 = result4.Resource; Console.WriteLine($"New document in PK '{doc4.address.postalCode}', generated ID '{doc4.id}' for '{doc4.firstName} {doc4.lastName}'"); await container.DeleteItemAsync <dynamic>(doc1.id.ToString(), pk12345); await container.DeleteItemAsync <dynamic>(doc2.id.ToString(), pk12345); await container.DeleteItemAsync <dynamic>(doc3.id.ToString(), pk12345); await container.DeleteItemAsync <dynamic>(doc4.id.ToString(), pk54321); }
public async Task ExecuteTestWithParameter() { string sprocId = Guid.NewGuid().ToString(); string sprocBody = @"function(param1) { var context = getContext(); var response = context.getResponse(); response.setBody(param1); }"; StoredProcedureResponse storedProcedureResponse = await this.scripts.CreateStoredProcedureAsync(new CosmosStoredProcedureSettings(sprocId, sprocBody)); Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode); StoredProcedureTests.ValidateStoredProcedureSettings(sprocId, sprocBody, storedProcedureResponse); // Insert document and then query string testPartitionId = Guid.NewGuid().ToString(); var payload = new { id = testPartitionId, user = testPartitionId }; ItemResponse <dynamic> createItemResponse = await this.container.CreateItemAsync <dynamic>(testPartitionId, payload); Assert.AreEqual(HttpStatusCode.Created, createItemResponse.StatusCode); StoredProcedureExecuteResponse <string> sprocResponse = await this.scripts.ExecuteStoredProcedureAsync <string[], string>(testPartitionId, sprocId, new string[] { "one" }); Assert.AreEqual(HttpStatusCode.OK, sprocResponse.StatusCode); string stringResponse = sprocResponse.Resource; Assert.IsNotNull(stringResponse); Assert.AreEqual("one", stringResponse); StoredProcedureExecuteResponse <string> sprocResponse2 = await this.scripts.ExecuteStoredProcedureAsync <string, string>(testPartitionId, sprocId, "one"); Assert.AreEqual(HttpStatusCode.OK, sprocResponse2.StatusCode); string stringResponse2 = sprocResponse2.Resource; Assert.IsNotNull(stringResponse2); Assert.AreEqual("one", stringResponse2); StoredProcedureResponse deleteResponse = await this.scripts.DeleteStoredProcedureAsync(sprocId); Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode); }
private static async Task BulkUpload(Container container) { List <Food> foods = new Bogus.Faker <Food>() .RuleFor(p => p.Id, f => (-1 - f.IndexGlobal).ToString()) .RuleFor(p => p.Description, f => f.Commerce.ProductName()) .RuleFor(p => p.ManufacturerName, f => f.Company.CompanyName()) .RuleFor(p => p.FoodGroup, f => "Energy Bars") .Generate(1000); int pointer = 0; while (pointer < foods.Count) { StoredProcedureExecuteResponse <int> result = await container.Scripts.ExecuteStoredProcedureAsync <int>("bulkUpload", new PartitionKey("Energy Bars"), new dynamic[] { foods.Skip(pointer) }); pointer += result.Resource; await Console.Out.WriteLineAsync($"{pointer} Total Items\t{result.Resource} Items Uploaded in this Iteration"); } }
public void MergeRecordsStoredProc(List <DailyDeviceReading> records) { List <Task> tasks = new List <Task>(); foreach (DailyDeviceReading record in records) { tasks.Add(_container.Scripts.ExecuteStoredProcedureAsync <string>( "spMerge", new PartitionKey(record.tag), new dynamic[] { record.deviceId, JsonConvert.SerializeObject(record) })); } Task.WaitAll(tasks.ToArray()); foreach (Task <StoredProcedureExecuteResponse <string> > task in tasks) { StoredProcedureExecuteResponse <string> response = task.Result; response.GetRawResponse().Headers.TryGetValue("x-ms-request-charge", out string requestCharge); _logger.LogInformation("Total Merge Stored Proc Request Charge:" + requestCharge); } }
private static async Task <int> Execute_spBulkDelete(string sql) { var container = Shared.Client.GetContainer("mydb", "mystore"); var pk = new PartitionKey("12345"); var continuationFlag = true; var totalDeleted = 0; while (continuationFlag) { StoredProcedureExecuteResponse <BulkDeleteResponse> result = await container.Scripts.ExecuteStoredProcedureAsync <BulkDeleteResponse>("spBulkDelete", pk, new[] { sql }); var response = result.Resource; continuationFlag = response.ContinuationFlag; var deleted = response.Count; totalDeleted += deleted; Console.WriteLine($"Deleted {deleted} documents ({totalDeleted} total, more: {continuationFlag})"); } Console.WriteLine(); return(totalDeleted); }