public async Task <Order> UpdateOrderAsync(string Id, [FromBody] Order Order) { Shop shop = await client.ReadDocumentAsync <Shop>(UriFactory.CreateDocumentUri(databaseName, collectionName, Id)); shop.Orders[Order.Id] = Order; //update shop await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, shop.Id), shop); return(Order); }
public async Task <Product> UpdateProductAsync(string Id, [FromBody] Product product) { Shop shop = await client.ReadDocumentAsync <Shop>(UriFactory.CreateDocumentUri(databaseName, collectionName, Id)); shop.Products[product.Name] = product; //update shop await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, shop.Id), shop); return(product); }
public async Task <Item> UpdateItemAsync(string Id, string OrderId, [FromBody] Item Item) { Shop shop = await client.ReadDocumentAsync <Shop>(UriFactory.CreateDocumentUri(databaseName, collectionName, Id)); shop.Orders[OrderId].Items[Item.Id] = Item; //update shop await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, shop.Id), shop); return(Item); }
public async Task <TModel> UpdateItemAsync(string id, TModel item) { var documentUri = UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id); var resourceResponse = await documentClient.ReplaceDocumentAsync(documentUri, item); return((TModel)((dynamic)resourceResponse.Resource)); }
public static async Task <TransactionItem> SagaOrchestratorActivity( [ActivityTrigger] TransactionItem item, [CosmosDB( databaseName: @"%CosmosDbDatabaseName%", collectionName: @"%CosmosDbOrchestratorCollectionName%", ConnectionStringSetting = @"CosmosDbConnectionString")] IAsyncCollector <TransactionItem> documentCollector, [CosmosDB( databaseName: @"%CosmosDbDatabaseName%", collectionName: @"%CosmosDbOrchestratorCollectionName%", ConnectionStringSetting = @"CosmosDbConnectionString")] IDocumentClient client) { if (item.State == SagaState.Pending.ToString()) { await documentCollector.AddAsync(item); return(item); } Uri collectionUri = UriUtils.CreateTransactionCollectionUri(); var document = client .CreateDocumentQuery(collectionUri) .Where(t => t.Id == item.Id) .AsEnumerable() .FirstOrDefault(); document.SetPropertyValue("state", item.State); await client.ReplaceDocumentAsync(document); return(item); }
public async Task <Document> ReplaceDocumentAsync(string documentId, object document, RequestOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { var uri = UriFactory.CreateDocumentUri(_databaseName, _collectionName, documentId); return(await _documentClient.ReplaceDocumentAsync(uri, document, options, cancellationToken)); }
public async Task UpdateTodoAsync(string id, Todo todo) { todo.Id = id; await documentClient.ReplaceDocumentAsync( UriFactory.CreateDocumentUri(dbName, collectionName, id), todo); }
public async Task <T> UpdateAsync(string id, T item) { var documentUri = UriFactory.CreateDocumentUri(_databaseId, _collectionId, id); var result = await _client.ReplaceDocumentAsync(documentUri, item).ConfigureAwait(false); return(JsonConvert.DeserializeObject <T>(result.Resource.ToString())); }
public async Task <IActionResult> Put(string id, [FromBody] PublicHouseProductsViewModel item) { await _documentClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, id), item); return(Ok()); }
public Task UpdateMovie(Movie movie) { if (movie == null) { throw new ArgumentNullException(nameof(movie)); } if (movie.ETag == null) { string message = $"ETag should not be null."; throw new ArgumentException(message, nameof(movie)); } string databaseId = _collection.DatabaseId; string collectionId = _collection.CollectionId; Uri uri = UriFactory.CreateDocumentUri( databaseId, collectionId, $"{movie.Id}"); var options = new RequestOptions { AccessCondition = new AccessCondition { Type = AccessConditionType.IfMatch, Condition = movie.ETag, }, }; return(_client.ReplaceDocumentAsync(uri, Translate(movie), options)); }
public async Task <TModel> UpdateItemAsync(string id, TModel item) { var documentUri = UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id); var model = await documentClient.ReplaceDocumentAsync(documentUri, item); return(model as TModel); }
public async Task <TModel> UpdateItemAsync(TKey partitionKey, string id, TModel item) { var documentUri = UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id); var resourceResponse = await documentClient.ReplaceDocumentAsync(documentUri, item, BuildRequestOptions(partitionKey)); logger.LogDebug($"Replace cost (in RU/s) : {resourceResponse.RequestCharge}"); return((TModel)((dynamic)resourceResponse.Resource)); }
public async Task <IActionResult> Put(string id, [FromBody] Expense expense) { var response = await _documentClient.ReplaceDocumentAsync( UriFactory.CreateDocumentUri(databaseId, collectionId, id), expense ); return(Ok()); }
async Task IBotDataStore <BotData> .SaveAsync(IAddress key, BotStoreType botStoreType, BotData botData, CancellationToken cancellationToken) { try { var requestOptions = new RequestOptions() { AccessCondition = new AccessCondition() { Type = AccessConditionType.IfMatch, Condition = botData.ETag } }; var entity = new DocDbBotDataEntity(key, botStoreType, botData); var entityKey = DocDbBotDataEntity.GetEntityKey(key, botStoreType); if (string.IsNullOrEmpty(botData.ETag)) { await documentClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), entity, requestOptions); } else if (botData.ETag == "*") { if (botData.Data != null) { await documentClient.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), entity, requestOptions); } else { await documentClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, entityKey), requestOptions); } } else { if (botData.Data != null) { await documentClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, entityKey), entity, requestOptions); } else { await documentClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, entityKey), requestOptions); } } } catch (DocumentClientException e) { //if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.Conflict) //{ // throw new HttpException((int)HttpStatusCode.PreconditionFailed, e.Message, e); //} //throw new HttpException(e.StatusCode.HasValue ? (int)e.StatusCode.Value : 0, e.Message, e); throw; } }
public async Task <ExportJobOutcome> ReplaceExportJobAsync(ExportJobRecord jobRecord, WeakETag eTag, CancellationToken cancellationToken) { EnsureArg.IsNotNull(jobRecord, nameof(jobRecord)); var cosmosExportJob = new CosmosExportJobRecordWrapper(jobRecord); var requestOptions = new RequestOptions() { PartitionKey = new PartitionKey(CosmosDbExportConstants.ExportJobPartitionKey), }; // Create access condition so that record is replaced only if eTag matches. if (eTag != null) { requestOptions.AccessCondition = new AccessCondition() { Type = AccessConditionType.IfMatch, Condition = eTag.ToString(), }; } try { ResourceResponse <Document> replaceResult = await _documentClient.ReplaceDocumentAsync( UriFactory.CreateDocumentUri(_cosmosDataStoreConfiguration.DatabaseId, _collectionConfiguration.CollectionId, jobRecord.Id), cosmosExportJob, requestOptions, cancellationToken : cancellationToken); var latestETag = replaceResult.Resource.ETag; return(new ExportJobOutcome(jobRecord, WeakETag.FromVersionId(latestETag))); } catch (DocumentClientException dce) { if (dce.StatusCode == HttpStatusCode.RequestEntityTooLarge) { throw new RequestRateExceededException(dce.RetryAfter); } if (dce.StatusCode == HttpStatusCode.PreconditionFailed) { throw new ResourceConflictException(eTag); } if (dce.StatusCode == HttpStatusCode.NotFound) { throw new JobNotFoundException(string.Format(Core.Resources.JobNotFound, jobRecord.Id)); } _logger.LogError(dce, "Unhandled Document Client Exception"); throw; } }
public async Task <T> DeleteItemAsync(string id, T item, HttpRequestMessage req) { //TODO: Should be trigger or stored proc. var before = await GetItemAsync(id); var digest = await _userDigestService.CurrentUserAsync(req); var now = DateTime.Now; item.changedById = digest.Id; item.changedByName = digest.DisplayName; item.changedOn = now; var doc = await _documentClient.ReplaceDocumentAsync(GetDocumentUri(id), item); var changeRecord = await AddChangeRecord($"Removed {item.name}", digest, "Deleted", before, null, now); var deletedItem = (T)(dynamic)doc.Resource; return(deletedItem); }
public virtual async Task <TDocument> Update(TDocument document) { var selfLink = await GetDocumentSelfLink(document); if (string.IsNullOrWhiteSpace(selfLink)) { throw new InvalidOperationException("Document does not exist in collection"); } return((TDocument)(dynamic)(await _documentClient.ReplaceDocumentAsync( selfLink, document)) .Resource); }
public virtual async Task <IdentityResult> UpdateAsync(TRole role, CancellationToken token) { var oldRole = await FindByIdAsync(role.DocId, token); if (UsesPartitioning && oldRole.NormalizedName != role.NormalizedName) { await DeleteMapping(oldRole.NormalizedName); await CreateMapping(role.NormalizedName, role.PartitionKey); } var result = await _Client.ReplaceDocumentAsync(GetRoleUri(role.DocId), role); // todo low priority result based on replace result return(IdentityResult.Success); }
public static async Task <ResourceResponse <Document> > HandleEntityReplaceOnlyAsync(string tableName, string partitionKey, string rowKey, string ifMatch, IDocumentClient client, Document document, RequestOptions requestOptions, CancellationToken cancellationToken) { Uri uri = UriFactory.CreateDocumentUri("TablesDB", tableName, rowKey); requestOptions = SetPartitionKey(requestOptions, partitionKey); if (!string.IsNullOrEmpty(ifMatch)) { requestOptions.AccessCondition = new AccessCondition { Type = AccessConditionType.IfMatch, Condition = ifMatch }; } return(await client.ReplaceDocumentAsync(uri.ToString(), document, requestOptions, cancellationToken)); }
/// <summary> /// Replaces a document. /// </summary> /// <param name="dbId">Database id.</param> /// <param name="collectionId">Collection id.</param> /// <param name="docId">Document id</param> /// <param name="entity">Entity to replace in document db collection.</param> /// <param name="requestOptions">Request options</param> /// <returns>Replaced document.</returns> public async Task <ResourceResponse <Document> > ReplaceDocumentAsync <T>( string dbId, string collectionId, string docId, T entity, RequestOptions requestOptions = null) { Code.ExpectsNotNullOrWhiteSpaceArgument(dbId, nameof(dbId), TaggingUtilities.ReserveTag(0x2381b19a /* tag_961g0 */)); Code.ExpectsNotNullOrWhiteSpaceArgument(collectionId, nameof(collectionId), TaggingUtilities.ReserveTag(0x2381b19b /* tag_961g1 */)); Code.ExpectsNotNullOrWhiteSpaceArgument(docId, nameof(docId), TaggingUtilities.ReserveTag(0x2381b19c /* tag_961g2 */)); Code.ExpectsArgument(entity, nameof(entity), TaggingUtilities.ReserveTag(0x2381b19d /* tag_961g3 */)); IDocumentClient client = await GetDocumentClientAsync().ConfigureAwait(false); return(await DocumentDbAdapter.ExecuteAndLogAsync(TaggingUtilities.ReserveTag(0x2381b19e /* tag_961g4 */), () => client.ReplaceDocumentAsync( UriFactory.CreateDocumentUri(dbId, collectionId, docId), entity, requestOptions)) .ConfigureAwait(false)); }
async Task UpdateDocumentDbSaga(PipeContext context, TSaga instance) { // DocumentDb Optimistic Concurrency https://codeopinion.com/documentdb-optimistic-concurrency/ var ac = new AccessCondition { Condition = instance.ETag, Type = AccessConditionType.IfMatch }; try { await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_databaseName, _collectionName, instance.CorrelationId.ToString()), instance, new RequestOptions { AccessCondition = ac, JsonSerializerSettings = _jsonSerializerSettings }).ConfigureAwait(false); } catch (DocumentClientException e) when(e.StatusCode == System.Net.HttpStatusCode.PreconditionFailed) { throw new DocumentDbConcurrencyException("Unable to update saga. It may not have been found or may have been updated by another process."); } }
public async Task UpdateAsync <TDocument>(TDocument document, CancellationToken cancellationToken = default ) where TDocument : EventStoreDocument { await ExecuteAsync(async dbCol => { await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(dbCol.DatabaseId, dbCol.CollectionId, document.StreamId), document, new RequestOptions { PartitionKey = new PartitionKey(document.StreamId), JsonSerializerSettings = _jsonSettings }, cancellationToken ); }, cancellationToken ); }
public Task Replace(List list) { try { var uri = UriFactory.CreateDocumentUri(db, collection, list.Id); return(documentClient.ReplaceDocumentAsync(uri, list, new RequestOptions { PartitionKey = new PartitionKey(list.Id) })); } catch (DocumentClientException ex) { if (ex.StatusCode == HttpStatusCode.NotFound) { throw ResourceNotFoundException.FromResourceId(list.Id); } throw DataAccessException.FromInnerException(ex); } }
async Task UpdateDocumentDbSaga(PipeContext context, TSaga instance, Document document) { if (document == null) { throw new DocumentDbConcurrencyException("Document didn't pre-exist, shouldn't have reached here."); } // DocumentDb Optimistic Concurrency https://codeopinion.com/documentdb-optimistic-concurrency/ var ac = new AccessCondition { Condition = document.ETag, Type = AccessConditionType.IfMatch }; try { await _client.ReplaceDocumentAsync(document.SelfLink, instance, new RequestOptions { AccessCondition = ac, JsonSerializerSettings = _jsonSerializerSettings }).ConfigureAwait(false); } catch (DocumentClientException e) when(e.StatusCode == System.Net.HttpStatusCode.PreconditionFailed) { throw new DocumentDbConcurrencyException("Unable to update saga. It may not have been found or may have been updated by another process."); } }
/// <inheritdoc /> public async Task <LeaseStoreResult> TryUpdateLeaseAsync(ILease lease) { return(await _retryPolicy.ExecuteAsync(async() => { var cosmosLease = (CosmosDbLease)lease; if (cosmosLease == null) { throw new ArgumentException("Invalid lease type"); } try { var response = await _documentClient.ReplaceDocumentAsync( UriFactory.CreateDocumentUri(_options.Value.Database, _options.Value.LeasesCollection, cosmosLease.Id), cosmosLease, new RequestOptions { ConsistencyLevel = _options.Value.ConsistencyLevel, AccessCondition = new AccessCondition { Condition = cosmosLease.ETag, Type = AccessConditionType.IfMatch } }).ConfigureAwait(false); return new LeaseStoreResult(MapResource(response), response.StatusCode == HttpStatusCode.OK); } catch (DocumentClientException ex) when(ex.StatusCode == HttpStatusCode.Conflict || ex.StatusCode == HttpStatusCode.PreconditionFailed) { return new LeaseStoreResult(null, false); } }).ConfigureAwait(false)); }
public virtual async Task <IdentityResult> UpdateAsync(TUser user, CancellationToken token) { var oldUser = await FindByIdAsync(user.PartitionKey, token); if (UsesPartitioning) { if (oldUser.NormalizedUserName != user.NormalizedUserName) { await DeleteMapping(oldUser.NormalizedUserName, TypeEnum.UserMappingUsername); await CreateMapping(user.NormalizedUserName, user.PartitionKey, TypeEnum.UserMappingUsername); } if (oldUser.NormalizedEmail != user.NormalizedEmail) { await DeleteMapping(oldUser.NormalizedEmail, TypeEnum.UserMappingEmail); await CreateMapping(user.NormalizedEmail, user.PartitionKey, TypeEnum.UserMappingEmail); } } // todo should add an optimistic concurrency check await _Client.ReplaceDocumentAsync(GetUserUri(user), user); return(IdentityResult.Success); }
public async Task <Document> UpdateItemAsync(string id, Image image) { return(await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), image)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "stripe")] HttpRequest req, [CosmosDB(ConnectionStringSetting = "CosmosDBConnection")] IDocumentClient client, ILogger log, ExecutionContext context) { var config = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var secret = config["Stripe:WebhookSecret"]; string json = await new StreamReader(req.Body).ReadToEndAsync(); try { var stripeEvent = EventUtility.ConstructEvent(json, req.Headers["Stripe-Signature"], secret); if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var session = stripeEvent.Data.Object as Stripe.Checkout.Session; log.LogInformation($"Searching for inschrijving with: {session.Id}"); Uri collectionUri = UriFactory.CreateDocumentCollectionUri("sinterklaas", "inschrijvingen"); var inschrijving = client.CreateDocumentQuery <InschrijvingDataModel>(collectionUri, new FeedOptions() { PartitionKey = new Microsoft.Azure.Documents.PartitionKey("Sinterklaas") }) .Where(i => i.SessionId.Contains(session.Id)) .AsEnumerable() .SingleOrDefault(); inschrijving.Betaald = true; inschrijving.BetaaldOpUtc = DateTime.UtcNow; await client.ReplaceDocumentAsync(inschrijving._self, inschrijving); var mailService = new MailgunMailService(config["MailgunApiKey"], log); var mailConfigConfirmEmail = config.GetSection("ConfirmEmail"); var mailModelConfirmEmail = new InschrijvingEmailModel { Naam = inschrijving.Naam, Email = inschrijving.Email, KindOpSchool = inschrijving.KindOpSchool, LidVanClub = inschrijving.LidVanClub, Lidmaatschap = (!inschrijving.KindOpSchool && !inschrijving.LidVanClub) || inschrijving.GratisLidmaatschap, GratisLidmaatschap = inschrijving.GratisLidmaatschap, Straatnaam = inschrijving.Straatnaam, Postcode = inschrijving.Postcode, Plaats = inschrijving.Plaats, Telefoon = inschrijving.Telefoon, AantalKinderen = inschrijving.Kinderen.Length, Kinderen = inschrijving.Kinderen.Select(k => new KindEmailModel { Roepnaam = k.Voornaam, Achternaam = k.Achternaam, Leeftijd = k.Leeftijd, Geslacht = k.Geslacht, Anekdote = k.Anekdote }).ToArray(), Commentaar = inschrijving.Commentaar }; await mailService.SendMailAsync(mailConfigConfirmEmail["FromName"], mailConfigConfirmEmail["FromEmail"], inschrijving.Naam, inschrijving.Email, mailConfigConfirmEmail["Bcc"], mailConfigConfirmEmail["Subject"], mailConfigConfirmEmail["TemplateId"], mailModelConfirmEmail); if ((!inschrijving.KindOpSchool && !inschrijving.LidVanClub) || inschrijving.GratisLidmaatschap) { var mailConfigMembershipEmail = config.GetSection("MembershipEmail"); var mailModelMembershipEmail = new LidmaatschapEmailViewModel { Naam = inschrijving.Naam, Email = inschrijving.Email, GratisLidmaatschap = inschrijving.GratisLidmaatschap, Straatnaam = inschrijving.Straatnaam, Postcode = inschrijving.Postcode, Plaats = inschrijving.Plaats, Telefoon = inschrijving.Telefoon }; await mailService.SendMailAsync(mailConfigMembershipEmail["FromName"], mailConfigMembershipEmail["FromEmail"], mailConfigMembershipEmail["ToName"], mailConfigMembershipEmail["ToEmail"], mailConfigMembershipEmail["Bcc"], mailConfigMembershipEmail["Subject"], mailConfigMembershipEmail["TemplateId"], mailModelMembershipEmail); } } } catch (Exception e) { log.LogError(e, "Error in Stripe Webhook"); return(new BadRequestResult()); } return(new OkResult()); }
public async Task <ResourceResponse <Document> > UpdateResourceAsync(string jsonString, string resourceId) { var childResourceDocumentAsJObject = JObject.Parse(jsonString); return(await _documentClient.ReplaceDocumentAsync(CreateDocumentUri(resourceId), childResourceDocumentAsJObject)); }
/// <inheritdoc/> public async Task UpdateAsync <T>(T item) where T : BaseEntity { Uri uri = UriFactory.CreateDocumentUri(_database, _collection, item.Id); await _documentClient.ReplaceDocumentAsync(uri, item); }