public async Task <bool> EnsurePreviousLoadedAsync(OrderedBalanceChange change) { if (!NeedLoading(change)) { return(true); } var parentIds = change.SpentOutpoints.Select(s => s.Hash).ToArray(); var parents = await GetTransactionsAsync(false, ColoredBalance, parentIds).ConfigureAwait(false); if (change.SpentCoins == null) { var success = await change.EnsureSpentCoinsLoadedAsync(parentIds, parents.Select(t => t == null ? null : t.Transaction).ToArray()).ConfigureAwait(false); if (!success) { return(false); } } if (ColoredBalance && change.ColoredTransaction == null) { var success = await change.EnsureColoredTransactionLoadedAsync(new IndexerColoredTransactionRepository(Configuration)).ConfigureAwait(false); if (!success) { return(false); } } var entity = change.ToEntity(); await Configuration.GetBalanceTable().ExecuteAsync(TableOperation.Merge(entity)).ConfigureAwait(false); return(true); }
public async Task EditStudent(StudentEntity student) { student.ETag = "*"; var editStudent = TableOperation.Merge(student); await _studentsTable.ExecuteAsync(editStudent); }
/// <summary> /// Merges the input entity with the stored entity with the same RowKey /// by updating any non-null property in the input entity. /// </summary> /// <typeparam name="TEntity">The type of the entity</typeparam> /// <param name="entity">The entity to merge</param> /// <param name="cancellationToken">The cancellation token assigned for the operation</param> /// <returns><value>true</value> if the entity was updated, <value>false</value> otherwise</returns> public async Task <bool> MergeEntityAsync <TEntity>(TEntity entity, CancellationToken cancellationToken) where TEntity : TableEntity { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } try { Trace.TraceVerbose($"Merging entity {entity.RowKey} to the table"); TableResult result = await _cloudTable.ExecuteAsync(TableOperation.Merge(entity), cancellationToken); // a successful operation returns status code 204 (No Content). Trace.TraceVerbose($"Done merging entity {entity.RowKey}. StatusCode: {result.HttpStatusCode}"); return(result.HttpStatusCode == (int)HttpStatusCode.NoContent); } catch (StorageException exception) { // check if failed because of a conflict if (exception.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed) { Trace.TraceInformation($"Failed merging entity {entity.RowKey} due to conflicts. StatusCode: {HttpStatusCode.PreconditionFailed}"); return(false); } // other errors, rethrow Trace.TraceError($"Failed merging entity {entity.RowKey}. Exception: {exception}"); throw; } }
public void MakeEventLive(Event eventObj) { string partitionKey = eventObj.Organizer; string rowKey = eventObj.Id.ToString(); var eventToUpdate = new DynamicTableEntity() { PartitionKey = partitionKey, RowKey = rowKey, ETag = "*" }; Dictionary <string, EntityProperty> newProperties = new Dictionary <string, EntityProperty> { { "Status", new EntityProperty("Live") } }; eventToUpdate.Properties = newProperties; TableOperation updateOperation = TableOperation.Merge(eventToUpdate); _tableMyEvents.Execute(updateOperation); // Add the new live event to All Events table var eventToAdd = eventObj.ToEventRead(); eventToAdd.Status = "Live"; TableOperation addOperation = TableOperation.InsertOrReplace(eventToAdd); _tableEvents.Execute(addOperation); _cacheService.InvalidateCache(GenerateLiveEventsKey(eventToAdd.PartitionKey)); _cacheService.InvalidateCache(GenerateMyEventsKey(eventToAdd.Organizer)); }
public override async Task UpdateStatusForRewindAsync(string instanceId) { DynamicTableEntity entity = new DynamicTableEntity(instanceId, "") { ETag = "*", Properties = { ["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Pending.ToString()), ["LastUpdatedTime"] = new EntityProperty(DateTime.UtcNow), } }; await this.CompressLargeMessageAsync(entity); Stopwatch stopwatch = Stopwatch.StartNew(); await this.InstancesTable.ExecuteAsync(TableOperation.Merge(entity)); this.stats.StorageRequests.Increment(); this.stats.TableEntitiesWritten.Increment(1); AnalyticsEventSource.Log.InstanceStatusUpdate( this.storageAccountName, this.taskHubName, instanceId, string.Empty, nameof(EventType.GenericEvent), stopwatch.ElapsedMilliseconds, Utils.ExtensionVersion); }
public async Task UpdateRecord(ImageEntity imageEntity) { // initialize await Initialzie(); var result = await CloudTable.ExecuteAsync(TableOperation.Merge(imageEntity)); }
/// <inheritdoc /> public async Task <TElement> UpdateAsync( TElement entity, TableStorageStrategy strategy = TableStorageStrategy.InsertOrReplace) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (entity.PartitionKey == null) { throw new PropNullException(nameof(entity.PartitionKey)); } if (entity.RowKey == null) { throw new PropNullException(nameof(entity.RowKey)); } try { await CreateTableIfNotExistsAsync(); if (strategy == TableStorageStrategy.Merge || strategy == TableStorageStrategy.Replace) { var any = await AnyAsync(entity.PartitionKey, entity.RowKey); if (!any) { throw new InvalidOperationException( UtilResources.Get("TableStorageEntityNotExists", entity.PartitionKey, entity.RowKey)); } entity.ETag ??= "*"; } var operation = strategy switch { TableStorageStrategy.InsertOrMerge => TableOperation.InsertOrMerge(entity), TableStorageStrategy.Merge => TableOperation.Merge(entity), TableStorageStrategy.Replace => TableOperation.Replace(entity), _ => TableOperation.InsertOrReplace(entity), }; var result = await ExecuteAsync(operation); ExceptionChecker.AssertHttp200Code(result.HttpStatusCode); entity = (TElement)(dynamic)result.Result; return(entity); } catch (Exception ex) { throw new TableStorageException(nameof(UpdateAsync), ex); } }
async Task StartProcessing(CancellationToken token) { while (!token.IsCancellationRequested) { while (toProcess.TryPeek(out var request)) { try { log.Info($"Processing request with ID {request.RequestId} and estimated processing time {request.EstimatedProcessingTime}."); request.StartedAt = DateTime.UtcNow; #region failed-scenario // emulate failure if (DateTime.UtcNow.Ticks % 2 == 0) { throw new Exception("Some exception during processing."); } #endregion // process var estimatedProcessingTime = TimeSpan.Parse(request.EstimatedProcessingTime); await Task.Delay(estimatedProcessingTime, token) .ConfigureAwait(false); log.Info($"Request with ID {request.RequestId} processed."); request.Status = Status.Finished.ToString(); request.FinishedAt = DateTime.UtcNow; await table.ExecuteAsync(TableOperation.Merge(request), token) .ConfigureAwait(false); toProcess.TryDequeue(out request); var processingFinished = new LongProcessingFinished { Id = request.RequestId }; await endpoint.Publish(processingFinished) .ConfigureAwait(false); } catch (Exception ex) { log.Info($"Request with ID {request.RequestId} threw an exception."); request.Status = Status.Failed.ToString(); await table.ExecuteAsync(TableOperation.Merge(request), token) .ConfigureAwait(false); toProcess.TryDequeue(out request); var processingFailed = new LongProcessingFailed { Id = request.RequestId, Reason = ex.Message }; await endpoint.Publish(processingFailed) .ConfigureAwait(false); } } } }
// XXX: Preserve the entity type without the caller having to specify it? public static TableOperation CopyOperation <TEntity>(TableOperation op) where TEntity : ITableEntity, new() { ITableEntity newEntity = CopyEntity <TEntity>(op.GetEntity()); switch (op.GetOperationType()) { case TableOperationType.Insert: return(TableOperation.Insert(newEntity)); case TableOperationType.Replace: return(TableOperation.Replace(newEntity)); case TableOperationType.Merge: return(TableOperation.Merge(newEntity)); case TableOperationType.Delete: return(TableOperation.Delete(newEntity)); case TableOperationType.InsertOrReplace: return(TableOperation.InsertOrReplace(newEntity)); case TableOperationType.InsertOrMerge: return(TableOperation.InsertOrMerge(newEntity)); default: throw new NotImplementedException(); } }
public static async Task <CustomerEntity> MergeEntityAsync(CloudTable table, CustomerEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } try { // Create the InsertOrReplace table operation TableOperation insertOrMergeOperation = TableOperation.Merge(entity); // Execute the operation. TableResult result = await table.ExecuteAsync(insertOrMergeOperation); CustomerEntity insertedCustomer = result.Result as CustomerEntity; if (result.RequestCharge.HasValue) { Console.WriteLine("Request Charge of Merge Operation: " + result.RequestCharge); } return(insertedCustomer); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
private static void AddTableOperationToBatch(TableOperationType tableOperationType, TableBatchOperation batch, T item) { // TODO: check if a function like this is already available in the azure storage package. switch (tableOperationType) { case TableOperationType.InsertOrMerge: batch.Add(TableOperation.InsertOrMerge(item)); break; case TableOperationType.Delete: batch.Add(TableOperation.Delete(item)); break; case TableOperationType.Insert: batch.Add(TableOperation.Insert(item)); break; case TableOperationType.Replace: batch.Add(TableOperation.Replace(item)); break; case TableOperationType.Merge: batch.Add(TableOperation.Merge(item)); break; case TableOperationType.InsertOrReplace: batch.Add(TableOperation.InsertOrReplace(item)); break; case TableOperationType.Retrieve: case TableOperationType.Invalid: throw new ArgumentOutOfRangeException(nameof(tableOperationType), $"TableOperationType {tableOperationType} not supported for {nameof(AddTableOperationToBatch)}."); } }
public static async Task Update(this CloudTable cloudTable, string rowKey, string responseBytes, Del updateItem, int count = 0) { try { var retrieve = TableOperation.Retrieve <Image>(rowKey, rowKey); var tableResult = await cloudTable.ExecuteAsync(retrieve); var existingImage = tableResult.Result as Image; updateItem.Invoke(existingImage, responseBytes); var mergeOperation = TableOperation.Merge(existingImage); await cloudTable.ExecuteAsync(mergeOperation); } catch (Exception ex) { if (count < 5) { var r = new Random().Next(0, 5); Thread.Sleep(r * 1000); await Update(cloudTable, rowKey, responseBytes, updateItem, ++count); } else { throw ex; } } }
public static Task <TableResult <TEntity> > MergeEntityAsync <TEntity>(this CloudTable table, TEntity entity, CancellationToken cancellationToken) where TEntity : ITableEntity { var operation = TableOperation.Merge(entity); return(ExecuteAsync <TEntity>(table, operation, cancellationToken)); }
public async Task <bool> UpdateLogger(string id, string name, bool canPublic) { var tableClient = _storageAccount.CreateCloudTableClient(); var loggerTable = tableClient.GetTableReference("SwingLogger"); var tableQuery = new TableQuery <SwingLoggerEntity>(); tableQuery.FilterString = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "0"), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, id)); var userEntities = await loggerTable.ExecuteQuerySegmentedAsync(tableQuery, null); var user = userEntities.FirstOrDefault(); if (user == null) { return(false); } user.Name = name; user.Public = canPublic; await loggerTable.ExecuteAsync(TableOperation.Merge(user)); return(true); }
public async Task <Result> MergeOne(string pk, string rk, IDictionary <string, object> props) { var dte = new DynamicTableEntity(pk, rk) { ETag = "*" }; foreach (var kv in props) { dte.Properties.Add(kv.Key, EntityProperty.CreateEntityPropertyFromObject(kv.Value)); } var op = TableOperation.Merge(dte); try { var r = await table.ExecuteAsync(op); return(Result.EmptyOk); } catch (StorageException ex) { int status = ex.RequestInformation.HttpStatusCode; if (status == (int)HttpStatusCode.PreconditionFailed || status == (int)HttpStatusCode.Conflict ) { return(Result.Error(status)); } throw; } }
public void UpdateRoleOperationStatus(Entities.RoleOperationStatusEntity entity) { // Now update the entity var updateOp = TableOperation.Merge(entity); _azureTable.Execute(updateOp); }
internal static async void InsertOrIncrementTrackTag(TrackTag trackTag) { try { // get the table CloudTable table = tableClient.GetTableReference(TrackTagsTable); await table.CreateIfNotExistsAsync(); var exists = await GetTrackTag(trackTag.PartitionKey, trackTag.RowKey); if (exists != null) { // update exists.count++; TableOperation op = TableOperation.Merge(exists); await table.ExecuteAsync(op); } else { // insert trackTag.count = 1; TableOperation op = TableOperation.InsertOrReplace(trackTag); await table.ExecuteAsync(op); } } catch (StorageException e) { throw; } }
public async Task <bool> UpdateQuestion(Question question) { var table = _tableClient.GetTableReference(TableNames.Player); // Get old entity QuestionEntity oldEntity = await GetQuestionEntity(question.Id); if (oldEntity == null) { _logger.LogError($"Could not update question, no question with ID {question.Id} found."); return(false); } QuestionEntity newQuestion = new QuestionEntity(question) { ETag = oldEntity.ETag }; TableOperation mergeOperation = TableOperation.Merge(newQuestion); TableResult result = await table.ExecuteAsync(mergeOperation); if (result.HttpStatusCode != 204) { return(false); } return(true); }
private static int Delete(string partitionKey, CloudTable itemTable, List <string> itemKeys) { int numOperations = 0; var batch = new TableBatchOperation(); foreach (var itemKey in itemKeys) { var entity = new DynamicTableEntity(partitionKey, itemKey); entity.ETag = "*"; entity.Properties.Add("IsActive", new EntityProperty(false)); batch.Add(TableOperation.Merge(entity)); if (batch.Count == 100) { itemTable.ExecuteBatch(batch); batch.Clear(); numOperations++; } } if (batch.Count > 0) { itemTable.ExecuteBatch(batch); numOperations++; } return(numOperations); }
public static async Task <IActionResult> RunGeoHash( [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "interventions/{latitude}/{longitude}/{interventionId}/comments/{commentId}")] [RequestBodyType(typeof(DeletionRequest), "DeletionRequest")] DeletionRequest request, [Table(Config.InterventionsTableName, Connection = Config.StorageConnectionName)] CloudTable interventionsTable, string latitude, string longitude, string interventionId, string commentId, ILogger log) { var geoHash = GeoHasher.GetGeoHash(latitude, longitude); var finalFilter = InterventionFilterBuilder.GetInterventionGeoHashFilter(geoHash, interventionId); var queryResult = await interventionsTable.ExecuteQuerySegmentedAsync(new TableQuery <InterventionEntity>().Where( finalFilter).Take(1), null); var requestedIntervention = queryResult.Results.FirstOrDefault(); if (requestedIntervention == null) { return(new StatusCodeResult(StatusCodes.Status404NotFound)); } try { requestedIntervention.DeleteComment(commentId); await interventionsTable.ExecuteAsync(TableOperation.Merge(requestedIntervention)); } catch (InvalidOperationException e) { return(new StatusCodeResult(StatusCodes.Status404NotFound)); } return(new StatusCodeResult(StatusCodes.Status200OK)); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = null)] HttpRequest req) { var user = _authService.GetClientPrincipalFromRequest(req); var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var data = JsonConvert.DeserializeObject <UpdateTodoItemDto>(requestBody); var entity = _mapper.Map <TodoItemEntity>(data); var listId = data.ListId; if (_todoListService.CanUserAccessList(user, listId)) { return(new UnauthorizedResult()); } entity.PartitionKey = listId; entity.ETag = "*"; _cloudTable.Execute(TableOperation.Merge(entity)); return(new OkResult()); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "interventions/{interventionId}/comments/{commentId}")] [RequestBodyType(typeof(DeletionRequest), "DeletionRequest")] DeletionRequest request, [Table(Config.InterventionsTableName, Connection = Config.StorageConnectionName)] CloudTable interventionsTable, string interventionId, string commentId, ILogger log) { var queryResult = await interventionsTable.ExecuteQuerySegmentedAsync(new TableQuery <InterventionEntity>().Where( TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, interventionId)).Take(1), null); var requestedIntervention = queryResult.Results.FirstOrDefault(); if (requestedIntervention == null) { return(new StatusCodeResult(StatusCodes.Status404NotFound)); } try { requestedIntervention.DeleteComment(commentId); await interventionsTable.ExecuteAsync(TableOperation.Merge(requestedIntervention)); } catch (InvalidOperationException e) { return(new StatusCodeResult(StatusCodes.Status404NotFound)); } return(new StatusCodeResult(StatusCodes.Status200OK)); }
public virtual async Task <TModel> MergeAsync(TModel item) { var insertOperation = TableOperation.Merge(item); var result = await ExecuteTableOperationAsync(insertOperation); return(result.Result as TModel); }
public static int Next(CloudTable table, string partition_key) { TableResult result = table.Execute(TableOperation.Retrieve(partition_key, SandId.MakeRevisionId(0))); DynamicTableEntity entity = (DynamicTableEntity)result.Result; if (entity == null) { return(0); } EntityProperty ep; int version = 1; if (entity.Properties.TryGetValue("nextid", out ep)) { version = (int)ep.Int32Value; ep.Int32Value = version + 1; } else { entity["nextid"] = new EntityProperty(version + 1); } table.Execute(TableOperation.Merge(entity)); return(version); }
/// <summary> /// Delete the provided object from the table /// </summary> /// <typeparam name="T">Type of business object</typeparam> /// <param name="item">Business object</param> /// <returns>Zero if nothing was deleted, One if the object was deleted</returns> public ulong Delete <T>(T item) where T : class { if (item != null) { // we need to check if we are soft-deleting! ClassInformation?objectInfo = TypeInspector.InspectForAzureTables <T>(); if (objectInfo == null) { throw new TypeLoadException($"Type '{typeof(T).FullName}' is not anotated with the '{typeof(TableAttribute).FullName}' attribute."); } TableAttribute tableAttribute = objectInfo.TableAttribute; AzureTableEntity entity = AzureTableEntity.From(item); TableOperation updateOrDeleteOperation; if (tableAttribute.UseSoftDelete) { entity.AddOrUpdateProperty(AzureTableEntity.PROPERTY_NAME_ISDELETED, true); updateOrDeleteOperation = TableOperation.Merge(entity); } else { updateOrDeleteOperation = TableOperation.Delete(entity); } ExecuteNonQuery <T>(updateOrDeleteOperation); return(1L); } return(0L); }
private static void upgradeFlags() { string pkFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, ""); TableQuery query = new TableQuery().Where(pkFilter).Select(new string[] { "flags" }); int count = 0; foreach (DynamicTableEntity entity in Warehouse.DiscussionLoadTable.ExecuteQuery(query)) { string flags = entity.GetFlags(); StringBuilder builder = new StringBuilder("\n"); SandFlags.SplitFlags(flags, (meta_title, meta_value) => { builder.Append(meta_title + "=" + meta_value + "\n"); count++; }); if (builder.Length > 1) { entity["flags2"] = new EntityProperty(builder.ToString()); Warehouse.DiscussionLoadTable.Execute(TableOperation.Merge(entity)); } } }
public MergeRowRequest([NotNull] AtsTable table, [NotNull] ITableEntity entity) : base( table, TableOperation.Merge(ResetETag(Check.NotNull(entity, "entity"))) ) { }
public override async Task <bool> DeleteAsync(string id) { if (id == null) { throw new ArgumentNullException("id"); } CompositeTableKey key = this.GetStorageKey(id); TableOperation operation = null; TData data = await this.GetCurrentItem(key, includeDeleted : !this.IncludeDeleted); if (this.EnableSoftDelete) { data.Deleted = true; operation = TableOperation.Merge(data); } else { operation = TableOperation.Delete(data); } bool deleted = false; if (operation != null) { await this.ExecuteOperationAsync(operation, OperationType.Delete); deleted = true; } return(deleted); }
protected async Task <T> Merge(T entity) { var insertOperation = TableOperation.Merge(entity); await Table.ExecuteAsync(insertOperation); return(entity); }
/// <summary> /// Merges the specified azure shardlet. /// </summary> /// <param name="azureShardlet">The azure shardlet.</param> public void Merge(AzureShardlet azureShardlet) { RetryPolicyFactory.GetDefaultAzureStorageRetryPolicy() .ExecuteAction(() => _table.Execute(TableOperation.Merge(azureShardlet))); Cache(azureShardlet); }