public async Task <bool> UpdateConversationStatusAsync(ConversationStatus obj) { var tableClient = StorageAccount.CreateCloudTableClient(); var tableRef = tableClient.GetTableReference(TABLENAME_AGENT_CONVERSATION_STATUS); await tableRef.CreateIfNotExistsAsync(); var blobClient = StorageAccount.CreateCloudBlobClient(); var blobContainer = blobClient.GetContainerReference(CONTAINERNAME_AGNET_LEASE_LOCK); blobContainer.CreateIfNotExists(); var lockBlob = blobContainer.GetBlockBlobReference($"conversation{obj.ConversationId}.lock"); if (!lockBlob.Exists()) { lockBlob.UploadText(""); } try { var leaseId = lockBlob.AcquireLease( TimeSpan.FromSeconds(15), null); try { var tableOperation = TableOperation.InsertOrMerge(obj); var result = tableRef.Execute(tableOperation); return(true); } catch (Exception exp) { throw; } finally { lockBlob.ReleaseLease(AccessCondition.GenerateLeaseCondition(leaseId)); } } catch (Exception exp) { throw; } finally { } }
private static async Task <PersistenceModel.Subject> InsertOrMergeAsync(CloudTable table, PersistenceModel.Subject entity) { if (entity == null) { throw new ArgumentNullException("entity"); } // Create the InsertOrReplace TableOperation TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity); // Execute the operation. TableResult result = await table.ExecuteAsync(insertOrMergeOperation); var insertedRate = result.Result as PersistenceModel.Subject; return(insertedRate); }
public static async Task <bool> SaveSong(Song song) { try { await ConnectToTable(); var operation = TableOperation.InsertOrMerge(song); var upsert = await songsTable.ExecuteAsync(operation); return(upsert.HttpStatusCode == 204); } catch (Exception ex) { } return(false); }
/// <summary> /// The Table Service supports two main types of insert operations. /// 1. Insert - insert a new entity. If an entity already exists with the same PK + RK an exception will be thrown. /// 2. Replace - replace an existing entity. Replace an existing entity with a new entity. /// 3. Insert or Replace - insert the entity if the entity does not exist, or if the entity exists, replace the existing one. /// 4. Insert or Merge - insert the entity if the entity does not exist or, if the entity exists, merges the provided entity properties with the already existing ones. /// </summary> /// <param name="table">The sample table name</param> /// <param name="entity">The entity to insert or merge</param> /// <returns></returns> private static async Task <CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } // Create the InsertOrReplace TableOperation TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity); // Execute the operation. TableResult result = await table.ExecuteAsync(insertOrMergeOperation); CustomerEntity insertedCustomer = result.Result as CustomerEntity; return(insertedCustomer); }
private string createRefreshToken(FunctionContext <dynamic> fc, string accessToken) { DateTime expiresIn = DateTime.Now; expiresIn.AddSeconds(JWTService.Expires_In_AccessToken); string refreshToken = Guid.NewGuid().ToString(); RefreshTokenTE rtTE = new RefreshTokenTE(); rtTE.AccessToken = accessToken; rtTE.Expires = expiresIn; rtTE.RowKey = refreshToken; rtTE.PartitionKey = "REFRESH_TOKEN"; TableOperation insertOrMerge = TableOperation.InsertOrMerge(rtTE); fc.Table.ExecuteAsync(insertOrMerge); return(refreshToken); }
private static async Task SeedTableEntity() { var storageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount.Parse(SourceConnectionString); var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration()); foreach (var table in SourceTables) { CloudTable cloudTable = tableClient.GetTableReference(table); await cloudTable.CreateIfNotExistsAsync(); var customer = new CustomerEntity("Frank", "Folsche") { }; var insertOrMergeOperation = TableOperation.InsertOrMerge(customer); await cloudTable.ExecuteAsync(insertOrMergeOperation); } }
public static async void Run([QueueTrigger("slitemstats")] string myQueueItemJson, [Table("slitemstats")] CloudTable table, ILogger log) { var myQueueItem = JsonConvert.DeserializeObject(((dynamic)myQueueItemJson)).template; log.LogInformation($"C# Queue trigger function processed: {myQueueItem}"); string mainFilter1 = TableQuery.GenerateFilterCondition("template", QueryComparisons.Equal, myQueueItem.ToString()); TableQuery <SLItemStats> query = new TableQuery <SLItemStats>().Where(mainFilter1); TableContinuationToken continuationToken = null; List <SLItemStats> entities = new List <SLItemStats>(); var opContext = new OperationContext(); do { TableQuerySegment <SLItemStats> queryResults = await(table).ExecuteQuerySegmentedAsync <SLItemStats>(query, continuationToken, tableRequestRetry, opContext); continuationToken = queryResults.ContinuationToken; entities.AddRange(queryResults.Results); } while (continuationToken != null); if (entities.Count == 0) { // Create a new itemStats entity. SLItemStats item = new SLItemStats() { PartitionKey = Guid.NewGuid().ToString(), RowKey = Guid.NewGuid().ToString(), template = myQueueItem, totalDownloads = 1, downloadsThisMonth = 1, downloadsThisWeek = 1, downloadsToday = 1, lastUpdated = DateTime.UtcNow }; // Create the TableOperation that inserts the itemStats entity. TableOperation insertOperation = TableOperation.Insert(item); // Execute the insert operation. await table.ExecuteAsync(insertOperation); } else { //increment var item = entities[0]; item.downloadsThisMonth += 1; item.downloadsThisWeek += 1; item.downloadsToday += 1; item.totalDownloads += 1; TableOperation operation = TableOperation.InsertOrMerge(item); await table.ExecuteAsync(operation); } }
public static void UpdateSystemStat(DataConfig providerConfig, POCO.System system, POCO.SystemStat systemStat) { switch (providerConfig.ProviderType) { case "azure.tableservice": AzureSystemStatUpdate az = new AzureSystemStatUpdate(system, systemStat); CloudTable table = Utils.GetCloudTable(providerConfig, System.TableNames.System); TableOperation operation = TableOperation.InsertOrMerge(az); Task tUpdate = table.ExecuteAsync(operation); tUpdate.Wait(); break; case "internal.mongodb": IMongoCollection <MongoSystemStatUpdate> collection = Utils.GetMongoCollection <MongoSystemStatUpdate>(providerConfig, "stlpsystems"); MongoSystemStatUpdate mongoObject = Utils.ConvertType <MongoSystemStatUpdate>(system); // Create the update filter List <DataFactory.Filter> filters = new List <DataFactory.Filter>(); DataFactory.Filter pkFilter = new DataFactory.Filter("PartitionKey", Utils.CleanTableKey(mongoObject.PartitionKey), "eq"); //DataFactory.Filter rkFilter = new DataFactory.Filter("RowKey", Utils.CleanTableKey(mongoObject.RowKey), "eq"); filters.Add(pkFilter); //filters.Add(rkFilter); FilterDefinition <MongoSystemStatUpdate> filter = Utils.GenerateMongoFilter <MongoSystemStatUpdate>(filters); // Serialize the stats object string jsonStatsSerialized = JsonConvert.SerializeObject(systemStat); //string updateParam = "{$set: {JsonSystemStats: '" + jsonStatsSerialized + "'}}"; //BsonDocument updateDoc = BsonDocument.Parse(updateParam); var update = Builders <MongoSystemStatUpdate> .Update .Set("JsonSystemStats", jsonStatsSerialized); // Update the batch status UpdateResult result = collection.UpdateOne(filter, update); return; default: throw new ApplicationException("Data provider not recognised: " + providerConfig.ProviderType); } return; }
public async Task SaveAnswer(ParticipantsTableEntity participant) { //CloudStorageAccount var conectionString = Configuration.GetValue<string>("StorageConfig:StringConnection"); var storageAccount = CloudStorageAccount.Parse(conectionString); //CloudTableClient var tableClient = storageAccount.CreateCloudTableClient(); //CloudTable var table = tableClient.GetTableReference("Participants"); await table.CreateIfNotExistsAsync(); //TableOperation var insertOperation = TableOperation.InsertOrMerge(participant); await table.ExecuteAsync(insertOperation); }
public bool AddIccid(Iccid iccid, string providerName) { try { var incomingEntity = new IccidTableEntity() { Iccid = iccid.Id, ProviderName = providerName, RowKey = iccid.Id }; _azureTableStorageClient.Execute(TableOperation.InsertOrMerge(incomingEntity)); } catch (StorageException) { return(false); } return(true); }
public async Task InsertOrMergeAsync(T item) { try { var table = await GetTable(); await table.ExecuteAsync(TableOperation.InsertOrMerge(item)); } catch (Exception ex) { if (_log != null) { await _log.WriteFatalErrorAsync("Table storage: " + _tableName, "InsertOrMerge item", AzureStorageUtils.PrintItem(item), ex); } } }
public HttpResponseMessage Post(string id, [FromBody] string status) { //if (!_games.ContainsKey(id)) return new HttpResponseMessage(HttpStatusCode.NotFound); TableOperation operation = TableOperation.Retrieve <GameStatus>("status", id); GameStatus currentStatus = _table.Execute(operation).Result as GameStatus; if (currentStatus == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } currentStatus.Status = status; operation = TableOperation.InsertOrMerge(currentStatus); _table.Execute(operation); return(new HttpResponseMessage(HttpStatusCode.OK)); }
private static void insertEntity(CloudTable table, string lensType, string partNumber, string focalLength, string aperture) { // Create an entity and set properties LensEntity lens = new LensEntity(lensType, partNumber) { LensType = lensType, PartNumber = partNumber, FocalLength = focalLength, Aperture = aperture }; // Add the entity TableOperation insertOrMerge = TableOperation.InsertOrMerge(lens); TableResult result = table.Execute(insertOrMerge); }
public async Task <MealSettingsModel> InsertMealSettingsIntoTable(MealSettingsModel model) { var table = await _tableStorage.GetTableReference(_mealSettingTable); model.IdMealSettings = Guid.NewGuid().ToString(); var entity = new MealSettingsEntity() { PartitionKey = model.IdMealSettings, RowKey = new Guid().ToString(), MealSettingsModelData = model }; var tableOperation = TableOperation.InsertOrMerge(entity); await table.ExecuteAsync(tableOperation); return(model); }
public ChiragInfo InsertOrMergeEntity(ChiragInfo entity) { if (entity == null) { throw new ArgumentNullException("entity"); } try { TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity); TableResult result = EmployeeTable.Execute(insertOrMergeOperation); ChiragInfo insertedCustomer = result.Result as ChiragInfo; return(insertedCustomer); } catch (StorageException StorageExceptionObj) { throw StorageExceptionObj; } }
public async Task UpdateEntry(GameServerStatusStatsDto model) { var gameServerStatusStats = new GameServerStatusStatsEntity { PartitionKey = model.ServerId.ToString(), GameType = model.GameType, PlayerCount = model.PlayerCount, MapName = model.MapName }; if (string.IsNullOrWhiteSpace(gameServerStatusStats.RowKey)) { gameServerStatusStats.RowKey = Guid.NewGuid().ToString(); } var operation = TableOperation.InsertOrMerge(gameServerStatusStats); await _statsTable.ExecuteAsync(operation); }
public static async void AddFacultyList(IList <Faculty> list) { try { CloudTable table = await CreateTableAsync("Faculty"); TableBatchOperation tableOperations = new TableBatchOperation(); foreach (var i in list) { tableOperations.Add(TableOperation.InsertOrMerge(i)); } IList <TableResult> tableResult = await table.ExecuteBatchAsync(tableOperations); } catch (Exception ex) { throw ex; } }
public async Task InsertOrMergeAsync <T>(string tableName, T entity) where T : TableEntity, new() { if (entity == null) { throw new CloudTableEntityNullException(); } var cloudTable = _cloudTableClient.GetTableReference(tableName); var tableExists = await cloudTable.ExistsAsync(); if (!tableExists) { throw new CloudTableNotExistsException(); } var upsertOperation = TableOperation.InsertOrMerge(entity); await cloudTable.ExecuteAsync(upsertOperation); }
private async Task <TableEntryEntity> InsertOrMergeTableEntryAsync(TableEntryEntity tableEntry) { if (tableEntry == null) { throw new ArgumentNullException("tableEntry"); } // Create the InsertOrReplace TableOperation TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(tableEntry); // Execute the operation. TableResult result = await CloudTable.ExecuteAsync(insertOrMergeOperation); TableEntryEntity insertedTableEntry = result.Result as TableEntryEntity; Console.WriteLine("Inserted/Updated table entry:\n\t[Version\\PartitionKey = {0}]\n\t[Date\\Rowkey = {1}]\n\t[ModuleTotalToDate = {2}]\n\t[VersionTotalToDate = {3}\n\t[VersionDayCount = {4}]", insertedTableEntry.PartitionKey, insertedTableEntry.RowKey, insertedTableEntry.ModuleTotalToDate, insertedTableEntry.VersionTotalToDate, insertedTableEntry.VersionDayCount); return(insertedTableEntry); }
public async Task StopClass(string id) { var table = await GetTable("program"); var retrieveOperation = TableOperation.Retrieve <CurrentClassInfoEntity>("class", id); var result = await table.ExecuteAsync(retrieveOperation); var entity = result.Result as CurrentClassInfoEntity; if (entity == null) { throw new ArgumentException($"class {id} not found"); } entity.IsRunning = false; var saveOperation = TableOperation.InsertOrMerge(entity); await table.ExecuteAsync(saveOperation); }
//public static List<POCO.O365.SPFolder> GetFolders(DataConfig providerConfig, List<Filter> filters) //{ // List<POCO.O365.SPFolder> webInfo = new List<POCO.O365.SPFolder>(); // switch (providerConfig.ProviderType) // { // case "azure.tableservice": // string combinedFilter = Utils.GenerateAzureFilter(filters); // List<AzureSPFolder> azdata = new List<AzureSPFolder>(); // AzureTableAdaptor<AzureSPFolder> adaptor = new AzureTableAdaptor<AzureSPFolder>(); // azdata = adaptor.ReadTableData(providerConfig, AzureTableNames.SPFolder, combinedFilter); // foreach (var doc in azdata) // { // webInfo.Add(doc.Value); // } // break; // case "internal.mongodb": // var collection = Utils.GetMongoCollection<MongoSPFolder>(providerConfig, MongoTableNames.SPFolder); // FilterDefinition<MongoSPFolder> filter = Utils.GenerateMongoFilter<MongoSPFolder>(filters); // //TODO paging // var documents = collection.Find(filter).Sort("{\"_id\":1}").Limit(1000).ToList(); // foreach (var doc in documents) // { // webInfo.Add(doc); // } // break; // default: // throw new ApplicationException("Data provider not recognised: " + providerConfig.ProviderType); // } // return webInfo; //} //public static void UpdateSPOWebInfoLastProcessed(DataConfig providerConfig, POCO.O365.SPOWebInfoEntity webInfo) //{ // switch (providerConfig.ProviderType) // { // case "azure.tableservice": // AzureSPOWebInfoEntity az = new AzureSPOWebInfoEntity(webInfo); // CloudTable table = Utils.GetCloudTable(providerConfig, AzureTableNames.SPOTracking); // TableOperation operation = TableOperation.InsertOrMerge(az); // Task tUpdate = table.ExecuteAsync(operation); // tUpdate.Wait(); // break; // case "internal.mongodb": // IMongoCollection<MongoSPOWebInfoEntity> collection = Utils.GetMongoCollection<MongoSPOWebInfoEntity>(providerConfig, MongoTableNames.SPOTracking); // MongoSPOWebInfoEntity mongoObject = Utils.ConvertType<MongoSPOWebInfoEntity>(webInfo); // // Create the update filter // List<DataFactory.Filter> filters = new List<DataFactory.Filter>(); // DataFactory.Filter pkFilter = new DataFactory.Filter("PartitionKey", Utils.CleanTableKey(mongoObject.PartitionKey), "eq"); // DataFactory.Filter rkFilter = new DataFactory.Filter("RowKey", Utils.CleanTableKey(mongoObject.RowKey), "eq"); // filters.Add(pkFilter); // filters.Add(rkFilter); // FilterDefinition<MongoSPOWebInfoEntity> filter = Utils.GenerateMongoFilter<MongoSPOWebInfoEntity>(filters); // var update = Builders<MongoSPOWebInfoEntity>.Update // .Set("LastItemModifiedDate", webInfo.LastItemModifiedDate) // .Set("LastItemUserModifiedDate", webInfo.LastItemUserModifiedDate); // // Update the batch status // UpdateResult result = collection.UpdateOne(filter, update); // return; // default: // throw new ApplicationException("Data provider not recognised: " + providerConfig.ProviderType); // } // return; //} public static void UpdateEOFolder(DataConfig providerConfig, POCO.O365.EOFolderUpdate folderUpdate) { switch (providerConfig.ProviderType) { case "azure.tableservice": AzureEOFolderUpdate az = new AzureEOFolderUpdate(folderUpdate); CloudTable table = Utils.GetCloudTable(providerConfig, AzureTableNames.EOFolder); TableOperation operation = TableOperation.InsertOrMerge(az); Task tUpdate = table.ExecuteAsync(operation); tUpdate.Wait(); break; case "internal.mongodb": IMongoCollection <MongoEOFolderUpdate> collection = Utils.GetMongoCollection <MongoEOFolderUpdate>(providerConfig, MongoTableNames.EOFolder); MongoEOFolderUpdate mongoObject = Utils.ConvertType <MongoEOFolderUpdate>(folderUpdate); // Create the update filter List <DataFactory.Filter> filters = new List <DataFactory.Filter>(); DataFactory.Filter pkFilter = new DataFactory.Filter("PartitionKey", Utils.CleanTableKey(mongoObject.PartitionKey), "eq"); DataFactory.Filter rkFilter = new DataFactory.Filter("RowKey", Utils.CleanTableKey(mongoObject.RowKey), "eq"); filters.Add(pkFilter); filters.Add(rkFilter); FilterDefinition <MongoEOFolderUpdate> filter = Utils.GenerateMongoFilter <MongoEOFolderUpdate>(filters); var update = Builders <MongoEOFolderUpdate> .Update .Set("TimeCreated", folderUpdate.TimeCreated) .Set("TimeLastModified", folderUpdate.TimeLastModified) .Set("ItemCount", folderUpdate.ItemCount) .Set("Name", folderUpdate.Name) .Set("CPFolderStatus", folderUpdate.CPFolderStatus); // Update the batch status UpdateResult result = collection.UpdateOne(filter, update); return; default: throw new ApplicationException("Data provider not recognised: " + providerConfig.ProviderType); } return; }
private void RegisterAttendance(String surveyCode, string eventCode, string userid, string today, string eventName, string status, string name) { var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]); var tableClient = storageAccount.CreateCloudTableClient(); CloudTable cloudTable = tableClient.GetTableReference("Attendance"); cloudTable.CreateIfNotExists(); String filterA = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, eventCode); String filterD = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, userid); TableQuery <AttendanceEntity> query = new TableQuery <AttendanceEntity>().Where(TableQuery.CombineFilters(filterA, TableOperators.And, filterD)); var results = cloudTable.ExecuteQuery(query); AttendanceEntity attendance = new AttendanceEntity(eventCode, userid); attendance.SurveyCode = surveyCode; attendance.Date = today; attendance.EventName = eventName; attendance.Name = name; foreach (AttendanceEntity a in results) { attendance.Morning = a.Morning; attendance.Afternoon = a.Afternoon; attendance.Survey = a.Survey; } if (status == "1") { attendance.Morning = true; } else if (status == "2") { attendance.Afternoon = true; } else if (status == "3") { attendance.Survey = true; } TableOperation insertOperation = TableOperation.InsertOrMerge(attendance); cloudTable.Execute(insertOperation); }
/// <summary> /// Get table storage operation from store operation /// </summary> /// <param name="operation">Store operation</param> /// <returns>Table storage operation</returns> private async Task <TableOperation> GetTableOperation(Operation operation) { if (operation.OperationType == OperationType.Insert) { var tableEntity = this.GetTableEntity(operation); return(TableOperation.Insert(tableEntity)); } else if (operation.OperationType == OperationType.Delete) { var tableEntity = this.GetTableEntity(operation); return(TableOperation.Delete(tableEntity)); } else if (operation.OperationType == OperationType.DeleteIfExists) { return(await this.GetDeleteIfExistsOperation(operation)); } else if (operation.OperationType == OperationType.Replace) { var tableEntity = this.GetTableEntity(operation); return(TableOperation.Replace(tableEntity)); } else if (operation.OperationType == OperationType.InsertOrReplace) { var tableEntity = this.GetTableEntity(operation); return(TableOperation.InsertOrReplace(tableEntity)); } else if (operation.OperationType == OperationType.Merge) { var tableEntity = this.GetTableEntity(operation); return(TableOperation.Merge(tableEntity)); } else if (operation.OperationType == OperationType.InsertOrMerge) { var tableEntity = this.GetTableEntity(operation); return(TableOperation.InsertOrMerge(tableEntity)); } else if (operation.OperationType == OperationType.Increment || operation.OperationType == OperationType.InsertOrIncrement) { return(await this.GetCountTableOperation(operation, operation.Score)); } throw new NotSupportedException(); }
public async Task Run( [TimerTrigger("%SubscriptionInventorySchedule%")] TimerInfo timerInfo, [Table("InventorySubscription", Connection = "StorageConnectionAppSetting")] CloudTable inventorySubscription, [Queue("outqueue", Connection = "StorageConnectionAppSetting")] ICollector <string> msg, ILogger log) { log.LogInformation($"C# Timer trigger function executed at: {DateTime.UtcNow}. Next occurrence: {timerInfo.FormatNextOccurrences(1)}"); IReadOnlyList <SubscriptionDto> subscriptions = await _subscriptionInventoryService.GetSubscriptionsAsync(); foreach (SubscriptionDto sub in subscriptions) { await inventorySubscription.CreateIfNotExistsAsync(); DateTime init = DateTime.Now; SubscriptionEntity subEntity = new SubscriptionEntity() { PartitionKey = sub.SubscriptionId, RowKey = Constants.SubscriptionEntitySummaryRowKey, SubscriptionName = sub.SubscriptionName, CreatedOn = init, LastSeenOn = init }; TableOperation retrieveOperation = TableOperation.Retrieve <SubscriptionEntity>(sub.SubscriptionId, Constants.SubscriptionEntitySummaryRowKey); TableResult retrievedEntity = await inventorySubscription.ExecuteAsync(retrieveOperation); if (retrievedEntity.Result == null) { TableOperation insertOperation = TableOperation.Insert(subEntity); await inventorySubscription.ExecuteAsync(insertOperation); } else { subEntity.CreatedOn = ((SubscriptionEntity)retrievedEntity.Result).CreatedOn; TableOperation mergeOperation = TableOperation.InsertOrMerge(subEntity); await inventorySubscription.ExecuteAsync(mergeOperation); } msg.Add(sub.SubscriptionId); } }
public async Task SaveContractInfoToTableStorage(EthereumContractInfo contractInfo) { if (!string.IsNullOrEmpty(contractInfo.ContractAddress)) { contractInfo.RowKey = contractInfo.ContractAddress; } else { throw new InvalidOperationException("Can't save a contract without a TransactionHash."); } CloudStorageAccount account = CloudStorageAccount.Parse(_storageAccountConnectionstring); var client = account.CreateCloudTableClient(); var tableRef = client.GetTableReference("ethtransactions"); await tableRef.CreateIfNotExistsAsync(); TableOperation ops = TableOperation.InsertOrMerge(contractInfo); await tableRef.ExecuteAsync(ops); }
public static async Task <T> InsertOrMergeEntityAsync(CloudTable table, T entity) { try { TableOperation tableop = TableOperation.InsertOrMerge(entity); TableResult result = await table.ExecuteAsync(tableop); return(result.Result as T); //T insertedCustomer = result.Result as T; //return insertedCustomer; } catch (StorageException sex) { //log //throw; return(null); } }
public async Task StoreAsync(Transport transport) { if (transport is null) { throw new ArgumentNullException(nameof(transport)); } var transportId = Guid.NewGuid().ToString(); var entity = TransportEntity.FromTransport(transportId, transport); try { await _table.ExecuteAsync(TableOperation.InsertOrMerge(entity)); } catch (Exception e) { _logger.LogError($"Unexpected error while saving to {_tableName}: {e}"); throw; } }
private async Task SetEmptyNotificationDataEntity(string notificationId) { var notificationDataEntityUpdate = new UpdateNotificationDataEntity { PartitionKey = PartitionKeyNames.NotificationDataTable.SentNotificationsPartition, RowKey = notificationId, Succeeded = 0, Failed = 0, Throttled = 0, Unknown = 0, }; notificationDataEntityUpdate.IsCompleted = true; notificationDataEntityUpdate.SentDate = DateTime.UtcNow; var operation = TableOperation.InsertOrMerge(notificationDataEntityUpdate); await CompanyCommunicatorDataFunction.notificationDataRepository.Table.ExecuteAsync(operation); }
public async Task UpdatePortalClaim(string userId, PortalClaimDto portalClaimDto) { var portalClaimEntity = new PortalClaimEntity { RowKey = portalClaimDto.RowKey, ClaimType = portalClaimDto.ClaimType, ClaimValue = portalClaimDto.ClaimValue }; if (string.IsNullOrWhiteSpace(portalClaimEntity.RowKey)) { portalClaimEntity.RowKey = Guid.NewGuid().ToString(); } portalClaimEntity.PartitionKey = userId; var operation = TableOperation.InsertOrMerge(portalClaimEntity); await _additionalClaimsTable.ExecuteAsync(operation); }
protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events) { var table = _cloudTableProvider.GetCloudTable(_storageAccount, _storageTableName, _bypassTableCreationValidation); string lastPartitionKey = null; TableBatchOperation operation = null; var insertsPerOperation = 0; foreach (var logEvent in events) { var tableEntity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, _formatProvider, _additionalRowKeyPostfix, _keyGenerator, _propertyColumns); // If partition changed, store the new and force an execution if (lastPartitionKey != tableEntity.PartitionKey) { lastPartitionKey = tableEntity.PartitionKey; // Force a new execution insertsPerOperation = _maxAzureOperationsPerBatch; } // If reached max operations per batch, we need a new batch operation if (insertsPerOperation == _maxAzureOperationsPerBatch) { // If there is an operation currently in use, execute it if (operation != null) { await table.ExecuteBatchAsync(operation).ConfigureAwait(false); } // Create a new batch operation and zero count operation = new TableBatchOperation(); insertsPerOperation = 0; } // Add current entry to the batch operation.Add(TableOperation.InsertOrMerge(tableEntity)); insertsPerOperation++; } // Execute last batch await table.ExecuteBatchAsync(operation).ConfigureAwait(false); }