public static async Task <ChannelAccount> GetBotId() { var properties = new Dictionary <string, string> { { "function", "GetBotId" }, { "memberType", BotMemberType }, }; ChannelAccount account = null; try { // Construct the query operation for all customer entities where PartitionKey="Smith". TableQuery <IdEntity> rangeQuery = new TableQuery <IdEntity>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, BotMemberType)); // Execute the retrieve operation. var queryResults = await IdTableClient.ExecuteQueryAsync(rangeQuery); if (queryResults != null) { account = queryResults.Select(r => new ChannelAccount(r.RowKey, r.Id)).FirstOrDefault(); } properties.Add("botId", account != null ? account.Id : "not set"); properties.Add("botName", account != null ? account.Name : "not set"); WebApiConfig.TelemetryClient.TrackEvent("OnlineStatus", properties); } catch (System.Exception e) { WebApiConfig.TelemetryClient.TrackException(e, properties); } return(account); }
public Task <IList <GameRow> > GetGameRows(string playerID) { var query = new TableQuery <GameRow>().Where( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, playerID)); return(_gamesTable.ExecuteQueryAsync(query)); }
public Task <IList <PlayerRow> > GetPlayerRows() { var query = new TableQuery <PlayerRow>().Where( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "0")); return(_playersTable.ExecuteQueryAsync(query)); }
/// <summary> /// Deletes an entities from the table with the specified partitionKey /// </summary> /// <param name="partitionKey"> /// The partition key of the entity to be deleted. /// Note that a partition key can return more than one entity. /// If more than one are returned, the first one is deleted. /// </param> public async Task DeleteEntitiesByPartitionKeyAsync(string partitionKey) { Validate.TablePropertyValue(partitionKey, "partitionKey"); var query = new TableQuery <T>() .Where(TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey)); var results = await cloudTable.ExecuteQueryAsync(query); var batchOperation = new TableBatchOperation(); var counter = 0; foreach (var entity in results) { batchOperation.Delete(entity); counter++; //Batch operations are limited to 100 items //when we reach 100, we commit and clear the operation if (counter == 100) { await cloudTable.ExecuteBatchAsync(batchOperation); batchOperation = new TableBatchOperation(); counter = 0; } } }
public async Task <IEnumerable <SampleObject> > GetSampleObjectsAsync() { TableQuery <SampleObjectEntity> query = new TableQuery <SampleObjectEntity>(); var items = await _table.ExecuteQueryAsync(query, CancellationToken.None); return(_mapper.Map <IEnumerable <SampleObject> >(items)); }
public async Task <IEnumerable <T> > GetAsync(string partitionKey) { _logger?.LogTrace("AsyncTableStorageRepository: GetAsync - getting items for a partition for table {TABLENAME}", _tableName); TableQuery <T> query = new TableQuery <T>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey)); IEnumerable <T> result = await _table.ExecuteQueryAsync(query); return(result); }
public async Task <bool> ExistsEndpoint(string vertexName, string endPoint) => (await _cloudTable.ExecuteQueryAsync( new TableQuery <EndpointTable>() .Where(TableQuery.CombineFilters( TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, vertexName), TableOperators.And, TableQuery.GenerateFilterCondition( "RowKey", QueryComparisons.Equal, endPoint))))) .Any();
private async Task <bool> HasRecords <T>(CloudTable table) where T : ITableEntity, new() { var query = new TableQuery <T>().Take(1); var records = await table.ExecuteQueryAsync(query); return(records.Any()); }
public async Task <IEnumerable <OrganizationApplicationKey> > Execute(ListApplicationKeys query, CancellationToken cancellationToken = new CancellationToken()) { if (query == null) { throw new ArgumentNullException("query"); } if (string.IsNullOrWhiteSpace(query.UserId)) { throw new AggregateException("UserId must be specified"); } if (string.IsNullOrWhiteSpace(query.ApplicationId)) { throw new AggregateException("ApplicationId must be specified"); } await _getApplication.Execute(new GetApplicationQuery(query.UserId, query.ApplicationId), cancellationToken); CloudTable appKeyTable = _tableProvider.GetTable(_settings.OrganizationApplicationKeyTableName); TableQuery <OrganizationApplicationKeyEntity> appKeyQuery = new TableQuery <OrganizationApplicationKeyEntity>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, query.ApplicationId)); return(await appKeyTable.ExecuteQueryAsync(appKeyQuery, x => (OrganizationApplicationKey)x, cancellationToken)); }
public static async Task <IActionResult> GetLectures( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "lectures")] HttpRequest req, [Table("Lectures")] CloudTable table, ILogger log) { if (req.Query.TryGetValue("seminar", out var seminar) && req.Query.TryGetValue("day", out var day)) { log.LogInformation($"Looking up available lectures for day {day} of seminar {seminar}"); var results = await table.ExecuteQueryAsync(new TableQuery <SeminarTableEntity>(), CancellationToken.None); if (!results.Any()) { return(new NotFoundResult()); } var result = new LectureSearchResultModel(); result.Items = results.Select(x => new LectureSearchResultModel.LectureSearchResultItem() { Id = x.Id, Name = x.Name }).ToList(); return(new OkObjectResult(result)); } throw new NotImplementedException(); }
public static async Task <IList <T> > ExecuteQueryAsync <T>( this CloudTable table, TableQuery <T> query, CancellationToken ct = default(CancellationToken), Action <IList <T> > onProgress = null) where T : ITableEntity, new() { var items = new List <T>(); TableContinuationToken token = null; do { TableQuerySegment <T> seg = await table.ExecuteQueryAsync(query, token, ct); token = seg.ContinuationToken; items.AddRange(seg); if (onProgress != null) { onProgress(items); } } while (token != null && !ct.IsCancellationRequested); return(items); }
public static async Task <IActionResult> UpdateSeminar( [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "seminars/{id}")] HttpRequest req, [Table("Seminars")] CloudTable table, ILogger log, string id) { log.LogInformation($"Updating seminar with ID {id}"); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var input = JsonConvert.DeserializeObject <SeminarUpdateModel>(requestBody); var filter = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, id); var result = await table.ExecuteQueryAsync(new TableQuery <SeminarTableEntity>().Where(filter)); if (!result.Any()) { return(new NotFoundResult()); } var original = result.First().ToModel(); var entity = new Seminar() { Id = original.Id, Name = input.Name ?? original.Name, Information = input.Information ?? original.Information, Duration = input.Duration ?? original.Duration, StartDate = input.StartDate ?? original.StartDate }; await table.ExecuteAsync(TableOperation.Replace(entity.ToTableEntity())); return(new OkObjectResult(entity)); }
public async Task <IEnumerable <ICodeFeatureState> > Execute(IListApplicationCodeFeatures query, CancellationToken cancellationToken = new CancellationToken()) { CloudTable featureStateTable = _tableProvider.GetTable(_settings.ApplicationCodeFeatureStateTableName); TableQuery <ApplicationCodeFeatureStateEntity> featureStateQuery = new TableQuery <ApplicationCodeFeatureStateEntity>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, ApplicationCodeFeatureStateEntity.GetCurrentPartitionKey(query.ApplicationId))); IEnumerable <CodeFeatureState> featureStates = await featureStateTable.ExecuteQueryAsync(featureStateQuery, entity => new CodeFeatureState(new CodeFeatureId(entity.CodeFeatureId), entity.Timestamp.UtcDateTime, entity.Enabled), cancellationToken); CloudTable featureTable = _tableProvider.GetTable(_settings.ApplicationCodeFeatureTableName); TableQuery <ApplicationCodeFeatureEntity> featureQuery = new TableQuery <ApplicationCodeFeatureEntity>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, query.ApplicationId)); IEnumerable <CodeFeatureState> features = await featureTable.ExecuteQueryAsync(featureQuery, entity => new CodeFeatureState(new CodeFeatureId(entity.CodeFeatureId), entity.Timestamp.UtcDateTime, false), cancellationToken); // include the default (not-enabled) feature states for features which have not been initialized return(featureStates.Union(features)); }
/// <summary> /// Looks up a saga data instance of the given type that has the specified property name/value /// </summary> public async Task <ISagaData> Find(Type sagaDataType, string propertyName, object propertyValue) { if (propertyName.Equals(IdPropertyName, StringComparison.InvariantCultureIgnoreCase)) { var sagaId = propertyValue is string ?(string)propertyValue : ((Guid)propertyValue).ToString("N"); var sagaData = await ReadSaga(sagaId, sagaDataType); // in this case, we need to filter on the saga data type if (!sagaDataType.IsInstanceOfType(sagaData)) { return(null); } return(sagaData); } var query = CreateFindQuery(sagaDataType, propertyName, propertyValue); var sagas = await _tableReference.ExecuteQueryAsync(query, DefaultTableRequestOptions, DefaultOperationContext); var id = sagas.Select(x => x.Properties["SagaId"].StringValue).FirstOrDefault(); if (string.IsNullOrEmpty(id)) { return(null); } return(await ReadSaga(id, sagaDataType)); }
public async Task <UserOrganizationApplication> Execute(GetApplication query, CancellationToken cancellationToken = new CancellationToken()) { if (query == null) { throw new ArgumentNullException("query"); } if (string.IsNullOrWhiteSpace(query.UserId)) { throw new ArgumentException("UserId is required"); } if (string.IsNullOrWhiteSpace(query.ApplicationId)) { throw new ArgumentException("ApplicationId is required"); } CloudTable userAppIndexTable = _tableProvider.GetTable(_settings.UserApplicationIndexTableName); TableQuery <UserApplicationIndexEntity> userAppQuery = new TableQuery <UserApplicationIndexEntity>() .Where(TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, query.UserId), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, query.ApplicationId))).Take(1); IEnumerable <UserApplicationIndexEntity> userApps = await userAppIndexTable.ExecuteQueryAsync(userAppQuery, cancellationToken); UserApplicationIndexEntity userApp = userApps.SingleOrDefault(); if (userApp == null) { throw new ApplicationNotFoundException(query.UserId, query.ApplicationId); } return(userApp); }
public async Task <OrganizationApplicationKey> Execute(GetApplicationKey query, CancellationToken cancellationToken = new CancellationToken()) { if (query == null) { throw new ArgumentNullException("query"); } if (string.IsNullOrWhiteSpace(query.Key)) { throw new ArgumentException("Key is required"); } CloudTable keyIndexTable = _tableProvider.GetTable(_settings.KeyOrganizationApplicationIndexTableName); TableQuery <KeyOrganizationApplicationIndexEntity> userAppQuery = new TableQuery <KeyOrganizationApplicationIndexEntity>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, query.Key)).Take(1); IEnumerable <KeyOrganizationApplicationIndexEntity> keyApps = await keyIndexTable.ExecuteQueryAsync(userAppQuery, cancellationToken); KeyOrganizationApplicationIndexEntity keyApp = keyApps.SingleOrDefault(); if (keyApp == null) { throw new ApplicationNotFoundException(string.Format("The key was not found: {0}", query.Key)); } return(keyApp); }
public static async Task <IActionResult> OnNext( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "slack/commands/next")] HttpRequest req, [Table("plans")] CloudTable plansTable, IBinder binder, ExecutionContext context) { Utils.SetCulture(); var body = await SlackHelper.ReadSlackRequest(req, context); var parameters = SlackHelper.ParseBody(body); var partitionKey = Utils.GetPartitionKey(parameters["team_id"], parameters["channel_id"]); var futurePlansQuery = new TableQuery <Plan>() .Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", "eq", partitionKey), "and", TableQuery.GenerateFilterConditionForDate("Date", "ge", DateTime.Now)) ); var futurePlans = await plansTable.ExecuteQueryAsync(futurePlansQuery); var attachmentTasks = futurePlans.OrderBy(x => x.Date).Select(x => MessageHelpers.GetPlanAttachment(binder, x)); var message = new SlackMessage { Text = futurePlans.Any() ? "Voici les Lunch & Watch planifiés :" : "Aucun Lunch & Watch n'est à l'horaire. Utilisez `/edu:plan` pour en planifier un!", Attachments = (await Task.WhenAll(attachmentTasks)).ToList() }; message.Attachments.Add(MessageHelpers.GetRemoveMessageAttachment()); return(Utils.Ok(message)); }
public async Task <IReadOnlyCollection <Calendar> > Read(string userName) { CloudTable table = client.GetTableReference("Calendars"); var query = new TableQuery <Calendar>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, userName)); return((await table.ExecuteQueryAsync(query)).ToArray()); }
public async Task <List <Subscription> > GetSubscriptions() { //https://stackoverflow.com/questions/23940246/how-to-query-all-rows-in-windows-azure-table-storage var queryResult = await _subcriptionTable.ExecuteQueryAsync(new TableQuery <Subscription>().Where( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, PartitionName))); return(queryResult.ToList()); }
public async Task <IEnumerable <T> > GetEntities(int takeCount) { CloudTable table = _tableClient.GetTableReference(TableName); TableQuery <T> query = new TableQuery <T>().Take(takeCount); IList <T> tableQueryResult = await table.ExecuteQueryAsync(query); return(tableQueryResult); }
public async Task <IEnumerable <ICachedCodeFeatureState> > Load() { CloudTable table = _tableProvider.GetTable("codeFeatureState"); TableQuery <CodeFeatureStateEntity> query = new TableQuery <CodeFeatureStateEntity>() .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Current")); return(await table.ExecuteQueryAsync(query, entity => (ICachedCodeFeatureState) new CachedCodeFeatureState(new CodeFeatureId(entity.CodeFeatureId), entity.Enabled))); }
public static Task <IEnumerable <T> > AllByPartitionKey <T>(this CloudTable table, string partitionKey) where T : ITableEntity, new() { TableQuery <T> query = new TableQuery <T>() .Where(TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey)); return(table.ExecuteQueryAsync(query)); }
public static async Task <DateTime?> GetTimeWhenMemberWasLastActive(string memberType) { var properties = new Dictionary <string, string> { { "function", "GetTimeWhenMemberWasLastActive" }, { "memberType", memberType }, }; DateTime?timeStamp = null; try { // Create the OnlineStatusTableClient if it doesn't exist. await OnlineStatusTableClient.CreateIfNotExistsAsync(); // Construct the query operation for all customer entities where PartitionKey="Smith". TableQuery <MemberOnlineStatusEntity> rangeQuery = new TableQuery <MemberOnlineStatusEntity>().Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, MemberOnlineStatusTablePartitionKey), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, AgentMemberType))); // Execute the retrieve operation. var queryResults = await OnlineStatusTableClient.ExecuteQueryAsync(rangeQuery); if (queryResults != null) { timeStamp = queryResults .OrderByDescending(result => result.LastActiveOn) .Select(r => r.LastActiveOn) .FirstOrDefault(); } properties.Add("timeStamp", timeStamp != null ? timeStamp.ToString() : "not set"); WebApiConfig.TelemetryClient.TrackEvent("OnlineStatus", properties); } catch (System.Exception e) { WebApiConfig.TelemetryClient.TrackException(e, properties); } return(timeStamp); }
/// <summary> /// Executes expression query asynchronously. /// </summary> /// <param name="expression"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <IEnumerable <T> > ExecuteAsync(Expression expression, CancellationToken cancellationToken = default(CancellationToken)) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var result = _queryTranslator.Translate(expression); return(_cloudTable.ExecuteQueryAsync <T>(result.TableQuery, cancellationToken)); }
/// <summary> /// Executes a query on a table asynchronously. /// </summary> /// <param name="tableQuery">Table query.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// An enumerable collection of <see cref="T:Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity" /> objects, representing table entities returned by the query. /// </returns> public Task <IEnumerable <DynamicTableEntity> > ExecuteQueryAsync(ITableQuery tableQuery, CancellationToken cancellationToken) { var query = new TableQuery { FilterString = tableQuery.FilterString, SelectColumns = tableQuery.SelectColumns, TakeCount = tableQuery.TakeCount }; return(_cloudTable.ExecuteQueryAsync(query, cancellationToken)); }
public static async Task <IList <Proposal> > GetActiveProposals(CloudTable proposals, string partitionKey) { var query = new TableQuery <Proposal>() .Where(TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", "eq", partitionKey), "and", TableQuery.GenerateFilterConditionForBool("Complete", "eq", false) )); return(await proposals.ExecuteQueryAsync(query)); }
/// <summary> /// Get Entities By Partition Key /// </summary> /// <param name="partitionKey">partitionKey</param> /// <returns></returns> public async Task <IEnumerable <T> > GetEntitiesByPartitionKey(string partitionKey) { var query = new TableQuery <T>() .Where(TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey)); Log.Info("Query Entities"); DateTime startTime = DateTime.Now; IEnumerable <T> result = await cloudTable.ExecuteQueryAsync(query); DateTime endTime = DateTime.Now; GetEntitiesByPartitionKeyElapsedTime = endTime - startTime; Log.Info("GetEntitiesByPartitionKey from Table count: {0}, Elapsed time = {1}", result.Count(), GetEntitiesByPartitionKeyElapsedTime.ToString()); return(result); }
/// <summary> /// Gets a resource of a given type and with the provided id from a given table /// </summary> /// <param name="table"></param> /// <param name="typeName"></param> /// <param name="id"></param> /// <returns></returns> private async Task <dynamic> Get(CloudTable table, string typeName, string id) { var tableQuery = new TableQuery().Where( TableQuery.CombineFilters( TypeCondition(table.Name, typeName), "AND", TableQuery.GenerateFilterCondition(TableConfigProvider.GetRowKeyFieldName(table.Name), QueryComparisons.Equal, id))); Logger.Debug("Getting item with hash key {0} and range key {1} from table {2}...", typeName, id, table.Name); return((await table.ExecuteQueryAsync(TableConfigProvider, tableQuery)).FirstOrDefault()); }
/// <summary> /// Retrieves all entities in the given table, optionally taking only the top number of entities /// </summary> /// <typeparam name="EntityType"></typeparam> /// <param name="table"></param> /// <param name="takeLimit"></param> /// <returns></returns> public static Task <IList <EntityType> > RetrieveEntitiesAsync <EntityType>(this CloudTable table, int?takeLimit = null) where EntityType : ITableEntity, new() { System.Diagnostics.Trace.TraceInformation("Retrieving all entities from azure table '{0}'", table.Name); var query = new TableQuery <EntityType>(); if (takeLimit.HasValue) { query = query.Take(takeLimit.Value); } return(table.ExecuteQueryAsync <EntityType>(query, takeLimit)); }
/// <summary> /// Retrieves all entities in the given partition from the given table, optionally taking only the top number of entities /// </summary> /// <typeparam name="EntityType"></typeparam> /// <param name="table"></param> /// <param name="partitionKey"></param> /// <param name="takeLimit"></param> /// <returns></returns> public static Task <IList <EntityType> > RetrieveEntitiesAsync <EntityType>(this CloudTable table, string partitionKey, int?takeLimit = null) where EntityType : ITableEntity, new() { System.Diagnostics.Trace.TraceInformation("Retrieving all entities from azure table '{0}' in partition '{1}'", table.Name, partitionKey); var query = new TableQuery <EntityType>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey)); if (takeLimit.HasValue) { query = query.Take(takeLimit.Value); } return(table.ExecuteQueryAsync <EntityType>(query, takeLimit)); }