public async Task <List <T> > OutputData <T>(string accountName, string accountKey, string tableName) where T : TableEntity, new() { var DataList = new List <T>(); var tableService = new CloudTableService(); var table = tableService.GetAuthTable(accountName, accountKey, tableName); var condition = ""; if (tableName == "PreliminaryData") { condition = TableQuery.GenerateFilterConditionForBool("IsProcessed", QueryComparisons.Equal, false); } else { condition = TableQuery.GenerateFilterConditionForInt("ManuallyEvalutate", QueryComparisons.Equal, 0); } var query = new TableQuery <T>().Where(condition); TableContinuationToken token = null; do { var segment = await table.ExecuteQuerySegmentedAsync(query, token); foreach (T entity in segment) { DataList.Add(entity); } token = segment.ContinuationToken; }while (token != null); return(DataList); }
public async Task <List <PingMessage> > GetStatusAsync(int?status, string customerId) { List <string> filters = new List <string>(); if (status != null) { filters.Add(TableQuery.GenerateFilterConditionForInt("", QueryComparisons.Equal, status.Value)); } if (!string.IsNullOrEmpty(customerId)) { filters.Add(TableQuery.GenerateFilterConditionForInt("", QueryComparisons.Equal, status.Value)); } TableQuery <PingMessageEntity> query = new TableQuery <PingMessageEntity>(); if (filters.Count > 0) { query = query.Where(string.Join(" and ", filters.ToArray())); } var result = await tableStatus.ExecuteQuerySegmentedAsync(query, null); var lst = new List <PingMessageEntity>(); lst.AddRange(result); return(mapper.Map <List <PingMessage> >(lst)); }
/// <summary> /// Decreases the kind action scales for all users. /// </summary> /// <returns></returns> public Task <OperationResult> DecreaseKindActionScales() { return (_azureManager.UpdateEntitiesAsync( new TableQuery <UserAzure>().Where( TableQuery.GenerateFilterConditionForInt("KindScale", QueryComparisons.GreaterThan, 0)) .Select(new[] { "KindScale", "KindScaleHighCurrentDays", "KindScaleHighMaxDays" }), async users => { foreach (var user in users) { if (user.KindScale < GameConstants.KindScale.DailyRegression) { user.KindScale = 0; user.KindScaleHighCurrentDays = 0; } else { if (user.KindScale > GameConstants.KindScale.AchievementLimit) { user.KindScaleHighCurrentDays = (user.KindScaleHighCurrentDays ?? 0) + 1; if (!user.KindScaleHighMaxDays.HasValue || user.KindScaleHighCurrentDays > user.KindScaleHighMaxDays) { user.KindScaleHighMaxDays = user.KindScaleHighCurrentDays; } } user.KindScale -= GameConstants.KindScale.DailyRegression; } await _azureManager.UpdateEntityAsync(user, replace: false); } })); }
public async Task <List <T> > RetrieveEntities <T>(string field, string queryComp, int searchValue, string tableName) where T : TableEntity, new() { CloudTable table = this.tableClient.GetTableReference(tableName); try { // Create the Table Query Object for Azure Table Storage TableQuery <T> DataTableQuery = new TableQuery <T>(); List <T> DataList = new List <T>(); TableQuerySegment <T> segment; TableContinuationToken continuationToken = null; TableQuery <T> query = new TableQuery <T>() .Where(TableQuery.GenerateFilterConditionForInt(field, queryComp, searchValue)); do { segment = await table.ExecuteQuerySegmentedAsync(query, continuationToken); if (segment == null) { break; } DataList.AddRange(segment); } while (continuationToken != null); return(DataList); } catch (Exception ExceptionObj) { throw ExceptionObj; } }
/// <summary> /// Check if the new generated appointment is conflicting with the any of the apppointments booked before /// In case the generated event type is Booking Appointment , we will query the events table to check if there is any appointment conflicting with the new one /// I am assuming that every appointment will have a range of 30 minutes, so if any new appointment is booked within this range /// it shoud be marked as a conflicted one, for example if we have an appointment at 17 , any appointment between /// 17 and 17:30 will be marked as a conflicted one /// </summary> /// <param name="currentEvents"></param> /// <param name="eventDate"></param> /// <param name="doctorId"></param> /// <returns></returns> public static async Task <Event> CheckIfAppointmentIsConflicting(CloudTable currentEvents, DateTime eventDate, int doctorId) { DateTimeOffset eventStartDateTimeOffset = new DateTimeOffset(eventDate); DateTimeOffset eventEndDateTimeOffset = new DateTimeOffset(eventDate).AddMinutes(-30); var partitionFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "BookingAppointmentEvent"); var doctorFilter = TableQuery.GenerateFilterConditionForInt("DoctorId", QueryComparisons.Equal, doctorId); var isConflictedFilter = TableQuery.GenerateFilterConditionForBool("IsConflicted", QueryComparisons.Equal, false); var dateLessThanFilter = TableQuery.GenerateFilterConditionForDate("EventDate", QueryComparisons.LessThanOrEqual, eventStartDateTimeOffset); var dateGreaterThanFilter = TableQuery.GenerateFilterConditionForDate("EventDate", QueryComparisons.GreaterThanOrEqual, eventEndDateTimeOffset); var filter = TableQuery.CombineFilters(dateLessThanFilter, TableOperators.And, TableQuery.CombineFilters( TableQuery.CombineFilters(partitionFilter, TableOperators.And, doctorFilter), TableOperators.And, isConflictedFilter)); var finalFilter = TableQuery.CombineFilters(filter, TableOperators.And, dateGreaterThanFilter); TableQuery <Event> rangeQuery = new TableQuery <Event>().Where(finalFilter); var conflictedEvents = await currentEvents.ExecuteQuerySegmentedAsync(rangeQuery, null); if (conflictedEvents.Results.Count > 0) { return(conflictedEvents.Results[0]); } return(null); }
/// <summary> /// This method is used to get filtered review introductions details for a given hiring manager. /// </summary> /// <param name="hiringManagerAadObjectId">Azure Active Directory object id of hiring manager .</param> /// <returns>List of filtered new hire introduction details.</returns> public async Task <IEnumerable <IntroductionEntity> > GetFilteredIntroductionsAsync(string hiringManagerAadObjectId) { if (string.IsNullOrWhiteSpace(hiringManagerAadObjectId)) { return(null); } await this.EnsureInitializedAsync(); var introductionEntity = new List <IntroductionEntity>(); string partitionKeyCondition = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, hiringManagerAadObjectId); string pendingForApprovalCondition = TableQuery.GenerateFilterConditionForInt(nameof(IntroductionEntity.ApprovalStatus), QueryComparisons.Equal, (int)IntroductionStatus.PendingForApproval); string tellMeMoreCondition = TableQuery.GenerateFilterConditionForInt(nameof(IntroductionEntity.ApprovalStatus), QueryComparisons.Equal, (int)IntroductionStatus.TellMeMore); var combinedStatusFilter = TableQuery.CombineFilters(pendingForApprovalCondition, TableOperators.Or, tellMeMoreCondition); var combinedFilter = TableQuery.CombineFilters(partitionKeyCondition, TableOperators.And, combinedStatusFilter); TableQuery <IntroductionEntity> query = new TableQuery <IntroductionEntity>().Where(combinedFilter); TableContinuationToken tableContinuationToken = null; do { var queryResponse = await this.CloudTable.ExecuteQuerySegmentedAsync(query, tableContinuationToken); tableContinuationToken = queryResponse.ContinuationToken; introductionEntity.AddRange(queryResponse?.Results); }while (tableContinuationToken != null); return(introductionEntity as List <IntroductionEntity>); }
public async Task <List <ItemRecord> > GetRangeItemRecords(List <int> itemIds) { var resolver = GetItemRecordResolver(); var query = new TableQuery(); var filter = string.Empty; foreach (var itemId in itemIds) { var itemFilter = TableQuery.GenerateFilterConditionForInt("Id", QueryComparisons.Equal, itemId); if (string.IsNullOrWhiteSpace(filter)) { filter = itemFilter; } else { filter = TableQuery.CombineFilters(filter, TableOperators.Or, itemFilter); } } query.FilterString = filter; return(await _adapter.GetAll(_tableName, query, resolver)); }
public SubmittedSessionsViewModel GetSubmittedSessions() { var tableClient = GetTableClient(); var sessionTable = tableClient.GetTableReference(_sessionsTableName); var sessionQuery = (new TableQuery <SessionSubmission>()).Where(TableQuery.GenerateFilterConditionForInt("Status", QueryComparisons.Equal, 1)); var sessions = sessionTable.ExecuteQuery(sessionQuery).ToList(); var viewModel = new SubmittedSessionsViewModel(); foreach (var sessionSubmission in sessions) { var session = new SessionSubmissionViewModel { SessionTitle = sessionSubmission.SessionTitle, SessionAbstract = sessionSubmission.SessionAbstract.FormatForHtml(), PresenterName = AbbreviatePresenterName(sessionSubmission.PresenterName), PresenterTwitterAlias = sessionSubmission.PresenterTwitterAlias, PresenterWebsite = sessionSubmission.PresenterWebsite, PresenterBio = sessionSubmission.PresenterBio, RecommendedAudience = sessionSubmission.RecommendedAudience }; viewModel.Sessions.Add(session); } return(viewModel); }
public static string CreateAzureTableQueryPropertyFilter(string propertyName, object value, string queryComparison) { Assert.IsNotNull(value, "value != null"); // When DCA pushes data into Azure, if any property has a '.' in it, it is replaced by '_'. We are taking care of it // below while creating filter for query to Azure table. propertyName = propertyName.Replace('.', '_'); if (value.GetType() == typeof(Guid)) { if ((Guid)value != Guid.Empty) { return(TableQuery.GenerateFilterConditionForGuid(propertyName, queryComparison, (Guid)value)); } } if (value.GetType() == typeof(string)) { if ((string)value != null) { return(TableQuery.GenerateFilterCondition(propertyName, queryComparison, (string)value)); } } if (value.GetType() == typeof(int)) { return(TableQuery.GenerateFilterConditionForInt(propertyName, queryComparison, (int)value)); } if (value.GetType() == typeof(Int64)) { return(TableQuery.GenerateFilterConditionForLong(propertyName, queryComparison, (long)value)); } throw new ArgumentException(string.Format("Type {0} Not supported in Filter Creation", value.GetType())); }
public async Task <IEnumerable <ICombat> > GetCombat(Guid sessionId, UInt32 round) { CloudTable dataTable = SessionRepository.GetTableForSessionData(TableClient, sessionId); TableQuery <CombatTableEntry> query = new TableQuery <CombatTableEntry>() .Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, sessionId.ToString()), TableOperators.And, TableQuery.GenerateFilterConditionForInt("Round", QueryComparisons.Equal, (Int32)round) )); // Initialize the continuation token to null to start from the beginning of the table. TableContinuationToken continuationToken = null; // Loop until the continuation token comes back as null List <CombatTableEntry> results = new List <CombatTableEntry>(); do { var queryResults = await dataTable.ExecuteQuerySegmentedAsync(query, continuationToken); continuationToken = queryResults.ContinuationToken; results.AddRange(queryResults.Results); }while (continuationToken != null); foreach (CombatTableEntry combat in results) { combat.IsValid(); } return(results); }
protected string GenerateConditionInt(string key, int val, string comparisonOperator = QueryComparisons.Equal) { return(TableQuery.GenerateFilterConditionForInt( key, comparisonOperator, val)); }
public bool ValidateAdminForGroup(string groupID, string adminID) { TableQuery <AdminUser> query = null; List <AdminUser> adminUsers = null; query = new TableQuery <AdminUser>().Where(TableQuery.GenerateFilterConditionForInt("AdminID", QueryComparisons.Equal, Int32.Parse(adminID))); base.LoadTable(Constants.GroupAdminsTableName); adminUsers = base.EntityTable.ExecuteQuery(query).ToList(); if (adminUsers != null && adminUsers.Count == 1) { foreach (var admin in adminUsers) { string[] IDs = admin.GroupIDCSV.Split(','); var selectedIDs = IDs.Select(id => id == groupID).ToList(); if (selectedIDs != null && selectedIDs.Count > 0) { return(true); } } } return(false); }
public static string Column(string columnName, int value, ColumnOperator op = ColumnOperator.Equal) { return(TableQuery.GenerateFilterConditionForInt( columnName, ToQueryComparison(op), value)); }
private static async Task SelectFiveSeatsHatchbackFromAfrica(CloudTable table) { Console.WriteLine("Wyszukiwanie danych spelniajacych wybrane kryteria..."); Console.WriteLine("-----------------------------------------------------"); var fiveSeatsCondition = TableQuery.GenerateFilterConditionForInt("SeatsCount", QueryComparisons.Equal, 5); var hatchbackCondition = TableQuery.GenerateFilterCondition("BodyType", QueryComparisons.Equal, "Hatchback"); var africaCondition = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Africa"); var combinedFiveSeatsAndHatchbackCondition = TableQuery.CombineFilters(fiveSeatsCondition, TableOperators.And, hatchbackCondition); var combinedCondition = TableQuery.CombineFilters(combinedFiveSeatsAndHatchbackCondition, TableOperators.And, africaCondition); var query = new TableQuery <CarEntity>() .Where(combinedCondition); await table.ExecuteAsync(query, async segment => { foreach (var car in segment.Results) { await Console.Out.WriteLineAsync(car.ToString()); } }); Console.WriteLine("Dane wyswietlone poprawnie!"); }
/// <summary> /// Get all team goal details for sending goal reminder. /// </summary> /// <returns>Returns collection of team goal details.</returns> public async Task <IEnumerable <TeamGoalDetail> > GetTeamGoalReminderDetailsAsync() { try { await this.EnsureInitializedAsync(); var today = DateTime.UtcNow; int weeklyReminder = today.DayOfWeek == CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 1 ? 0 : -1; // Check if its Monday for weekly reminder frequency. int biweeklyReminder = today.Day == 1 || today.Day == 16 ? 1 : -1; // Check if its 1st or 16th day of month for bi-weekly reminder frequency. int monthlyReminder = today.Day == 1 ? 2 : -1; // Check if its 1st day of month for monthly reminder frequency. int quarterlyReminder = today.Day == 1 && ((today.Month + 2) % 3) == 0 ? 3 : -1; // Check if its 1st day of quarter for quarterly reminder frequency. // Get team goals from storage whose end date or end date after 3 days is equal to today's date. string endDatePassedFilter = TableQuery.GenerateFilterCondition(nameof(TeamGoalDetail.TeamGoalEndDateUTC), QueryComparisons.Equal, today.AddDays(-1).ToString(Constants.UTCDateFormat, CultureInfo.InvariantCulture)); string endDateAfterThreeDaysFilter = TableQuery.GenerateFilterCondition(nameof(TeamGoalDetail.TeamGoalEndDateUTC), QueryComparisons.Equal, today.AddDays(+3).ToString(Constants.UTCDateFormat, CultureInfo.InvariantCulture)); // Get team goals as per reminder frequency set. string weeklyReminderFilter = TableQuery.GenerateFilterConditionForInt(nameof(TeamGoalDetail.ReminderFrequency), QueryComparisons.Equal, weeklyReminder); string biweeklyReminderFilter = TableQuery.GenerateFilterConditionForInt(nameof(TeamGoalDetail.ReminderFrequency), QueryComparisons.Equal, biweeklyReminder); string monthlyReminderFilter = TableQuery.GenerateFilterConditionForInt(nameof(TeamGoalDetail.ReminderFrequency), QueryComparisons.Equal, monthlyReminder); string quarterlyReminderFilter = TableQuery.GenerateFilterConditionForInt(nameof(TeamGoalDetail.ReminderFrequency), QueryComparisons.Equal, quarterlyReminder); // Get only active goals whose reminder frequency is active. string isActiveFilter = TableQuery.GenerateFilterConditionForBool(nameof(TeamGoalDetail.IsActive), QueryComparisons.Equal, true); string isDeletedFilter = TableQuery.GenerateFilterConditionForBool(nameof(TeamGoalDetail.IsDeleted), QueryComparisons.Equal, false); string isReminderActiveFilter = TableQuery.GenerateFilterConditionForBool(nameof(TeamGoalDetail.IsReminderActive), QueryComparisons.Equal, true); var query = new TableQuery <TeamGoalDetail>().Where($"({endDatePassedFilter} or {endDateAfterThreeDaysFilter} or {weeklyReminderFilter} or {biweeklyReminderFilter} or {monthlyReminderFilter} or {quarterlyReminderFilter}) and {isActiveFilter} and {isDeletedFilter} and {isReminderActiveFilter}"); return(await this.GetTeamGoalDetailsAsync(query)); } catch (Exception ex) { this.logger.LogError(ex, $"An error occurred in {nameof(this.GetTeamGoalReminderDetailsAsync)} while getting team goal details."); throw; } }
public void UpdateData() { int id = -1; CloudTable table = GetTable(); VehicleTE vte = new VehicleTE(id, id, "Ding", "Dong"); var result = table.Execute(TableOperation.InsertOrReplace(vte)); TableQuery <VehicleTE> searchQuery = new TableQuery <VehicleTE>() .Where(TableQuery.GenerateFilterConditionForInt("Id", QueryComparisons.Equal, id)); var queryResult = table.ExecuteQuery(searchQuery); Assert.IsNotNull(queryResult.FirstOrDefault()); result = table.Execute(TableOperation.Delete(vte)); vte = new VehicleTE(id, id, "John", "Doe"); result = table.Execute(TableOperation.Insert(vte)); result = table.Execute(TableOperation.Delete(vte)); //TableOperation insertOperation = TableOperation.InsertOrReplace(test); }
/// <summary> /// This method is used to start reward cycle is the start date matches the current date and stops the reward cycle based on the flags. /// </summary> /// <returns><see cref="Task"/> that represents reward cycle entity is saved or updated.</returns> public async Task <bool> UpdateCycleStatusAsync() { await this.EnsureInitializedAsync(); // Get all unpublished reward cycle string filterPublish = TableQuery.GenerateFilterConditionForInt("ResultPublished", QueryComparisons.Equal, (int)ResultPublishState.Unpublished); var query = new TableQuery <RewardCycleEntity>().Where(filterPublish); TableContinuationToken continuationToken = null; var activeCycles = new List <RewardCycleEntity>(); do { var queryResult = await this.CloudTable.ExecuteQuerySegmentedAsync(query, continuationToken); activeCycles.AddRange(queryResult?.Results); continuationToken = queryResult?.ContinuationToken; }while (continuationToken != null); // update reward cycle state foreach (RewardCycleEntity currentCycle in activeCycles) { var newCycle = this.SetAwardCycle(currentCycle); TableOperation updateOperation = TableOperation.InsertOrReplace(newCycle); var result = await this.CloudTable.ExecuteAsync(updateOperation); } return(true); }
/// <summary> /// Shortcut method that queries the table based on a given PartitionKey and given property with /// the same property name. Handles the continuation token scenario as well. Overloaded to accept /// all appropriate table entity types. /// </summary> /// <param name="partitionKey"></param> /// <param name="propertyName"></param> /// <param name="property"></param> /// <returns></returns> public async Task <List <TAzureTableEntity> > WherePropertyEqualsAsync(string partitionKey, string propertyName, int property) { var propertyFilter = TableQuery.GenerateFilterConditionForInt(propertyName, QueryComparisons.Equal, property); var query = PartitionKeyAndPropertyFilterQuery(partitionKey, propertyFilter); return(await RunQuerySegmentAsync(query).ConfigureAwait(false)); }
public static async void Run( [TimerTrigger("%Timer%")] TimerInfo myTimer, // variable Timer set at local.settings.json [Table("people", Connection = "PeopleTable")] CloudTable cloudTable, [ServiceBus("birthdayalert", Connection = "PeopleServiceBusConnection")] IAsyncCollector <Person> messages, ILogger log) { log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); try { var rangeQuery = new TableQuery <Person>() .Where( TableQuery.CombineFilters( TableQuery.GenerateFilterConditionForInt("month", QueryComparisons.Equal, DateTime.Now.Month), TableOperators.And, TableQuery.GenerateFilterConditionForInt("day", QueryComparisons.Equal, DateTime.Now.Day))); // Execute the query and loop through the results foreach (var entity in await cloudTable.ExecuteQuerySegmentedAsync(rangeQuery, null)) { // log.LogInformation($"{entity.Name}\t{entity.BirthMonth}\t{entity.BirthDay}"); // string entityJsonString = JsonSerializer.Serialize(entity); await messages.AddAsync(entity); } } catch (Exception e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ", e.Message); } }
static async Task Main(string[] args) { var connectionString = "YOUR_PRIMARY_CONNECTION_STRING_HERE"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("students"); TableQuery <Student> tableQuery = new TableQuery <Student>(); string filter = TableQuery.CombineFilters( TableQuery.GenerateFilterConditionForInt("Score", QueryComparisons.GreaterThan, 150), TableOperators.And, TableQuery.GenerateFilterCondition("Name", QueryComparisons.Equal, "Hassan")); tableQuery.Where(filter); tableQuery.OrderBy("Name"); tableQuery.Select(new List <string> { "Score" }); tableQuery.Take(take: 3); TableQuerySegment <Student> studentsSegment = await table.ExecuteQuerySegmentedAsync(tableQuery, token : null); studentsSegment.Results.ForEach(i => Console.WriteLine("{0,5} {1,10} {2,-10}", i.PartitionKey, i.Name, i.Score)); Console.ReadKey(); }
/// <summary> /// Get all issues in the specified label which don't have an assignee and / or a milestone. /// </summary> public async Task <List <RoachIssue> > GetTriageIssues(RoachRepoId repoId, string label, CancellationToken cancellationToken) { var unassignedFilter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(TableEntity.PartitionKey), QueryComparisons.Equal, EntityKeyUtil.ToKey(repoId)), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(RoachIssueEntity.Assignee), QueryComparisons.Equal, TheBugsConstants.UnassignedName)); var unassignedList = await AzureUtil.QueryAsync(_issueTable, new TableQuery <RoachIssueEntity>().Where(unassignedFilter), cancellationToken); var unknownMilestoneFilter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(TableEntity.PartitionKey), QueryComparisons.Equal, EntityKeyUtil.ToKey(repoId)), TableOperators.And, TableQuery.GenerateFilterConditionForInt(nameof(RoachIssueEntity.MilestoneNumber), QueryComparisons.Equal, RoachMilestoneId.NoneNumber)); var unknownMilestoneList = await AzureUtil.QueryAsync(_issueTable, new TableQuery <RoachIssueEntity>().Where(unknownMilestoneFilter), cancellationToken); var list = new List <RoachIssue>(); var hashSet = new HashSet <int>(); foreach (var entity in unassignedList.Concat(unknownMilestoneList)) { if (hashSet.Add(entity.Number) && entity.Labels.Contains(label) && entity.IssueType == IssueType.Issue) { list.Add(entity.Issue); } } return(list); }
/// <summary> /// Get the skip query. /// </summary> /// <returns>The skip query string.</returns> public string GetSkipQuery() { // Select the skip type. switch (typeof(T).Name.ToLower()) { case "system.boolean": case "boolean": case "bool": return(TableQuery.GenerateFilterConditionForBool( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (Boolean)Convert.ChangeType(_skipValue, typeof(Boolean)))); case "system.byte[]": case "byte[]": return(TableQuery.GenerateFilterConditionForBinary( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (Byte[])Convert.ChangeType(_skipValue, typeof(Byte[])))); case "system.datetimeoffset": case "datetimeoffset": return(TableQuery.GenerateFilterConditionForDate( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (DateTimeOffset)Convert.ChangeType(_skipValue, typeof(DateTimeOffset)))); case "system.double": case "double": return(TableQuery.GenerateFilterConditionForDouble( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (Double)Convert.ChangeType(_skipValue, typeof(Double)))); case "system.guid": case "guid": return(TableQuery.GenerateFilterConditionForGuid( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (Guid)Convert.ChangeType(_skipValue, typeof(Guid)))); case "system.int32": case "int32": case "int": return(TableQuery.GenerateFilterConditionForInt( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (Int32)Convert.ChangeType(_skipValue, typeof(Int32)))); case "system.int64": case "int64": case "long": return(TableQuery.GenerateFilterConditionForLong( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (Int64)Convert.ChangeType(_skipValue, typeof(Int64)))); case "system.string": case "string": return(TableQuery.GenerateFilterCondition( _skipPropertyName, QueryComparisons.GreaterThanOrEqual, (String)Convert.ChangeType(_skipValue, typeof(String)))); default: throw new Exception("The skip value type is not supported."); } }
/// <summary> /// Get async. /// </summary> /// <typeparam name="ST">The skip type.</typeparam> /// <param name="value">The value.</param> /// <param name="propertyName">The property name.</param> /// <param name="operation">The operation.</param> /// <param name="take">The number of items to return.</param> /// <param name="skip">The number of items to skip.</param> /// <returns>The array or items.</returns> public async Task <T[]> GetAsync <ST>(int value, string propertyName = "PartitionKey", string operation = QueryComparisons.Equal, int take = 100, SkipCount <ST> skip = null) { TableQuery <T> scanQuery = null; if (skip == null) { // Create the query. scanQuery = new TableQuery <T>().Where (TableQuery.GenerateFilterConditionForInt(propertyName, operation, value)); } else { // Create the query. scanQuery = new TableQuery <T>().Where (TableQuery.CombineFilters( TableQuery.GenerateFilterConditionForInt(propertyName, operation, value), TableOperators.And, skip.GetSkipQuery() )); } // Return the array return(await ScanAsyncEx(scanQuery, take)); }
/// <summary> /// Get all resource group entities from the table storage /// based on group type. /// </summary> /// <param name="groupType">Resource group type.</param> /// <returns>All resource groups based on group type.</returns> public async Task <IEnumerable <EmployeeResourceGroupEntity> > GetResourceGroupsByTypeAsync(int groupType) { string groupTypeCondition = TableQuery.GenerateFilterConditionForInt("GroupType", QueryComparisons.Equal, groupType); var entities = await this.GetWithFilterAsync(groupTypeCondition); return(entities); }
private List <string> GetAllPossibleAvailabilityZoneRegionCombination() { var possibleAvailabilityZoneRegionCombinationVmCount = new Dictionary <string, int>(); var crawledAvailabilityZoneVmQuery = TableQuery.GenerateFilterConditionForInt("AvailabilityZone", QueryComparisons.GreaterThan, 0); var availabilityZoneTableQuery = new TableQuery <VirtualMachineCrawlerResponse>().Where(crawledAvailabilityZoneVmQuery); var crawledVirtualMachinesResults = StorageAccountProvider.GetEntities(availabilityZoneTableQuery, StorageTableNames.VirtualMachineCrawlerTableName); crawledVirtualMachinesResults = crawledVirtualMachinesResults.Where(x => PowerState.Parse(x.State) == PowerState.Running); foreach (var eachCrawledVirtualMachinesResult in crawledVirtualMachinesResults) { var entryIntoPossibleAvailabilityZoneRegionCombinationVmCount = eachCrawledVirtualMachinesResult.RegionName + "!" + eachCrawledVirtualMachinesResult.AvailabilityZone.ToString(); if (possibleAvailabilityZoneRegionCombinationVmCount.ContainsKey(entryIntoPossibleAvailabilityZoneRegionCombinationVmCount)) { possibleAvailabilityZoneRegionCombinationVmCount[entryIntoPossibleAvailabilityZoneRegionCombinationVmCount] += 1; } else { possibleAvailabilityZoneRegionCombinationVmCount[entryIntoPossibleAvailabilityZoneRegionCombinationVmCount] = 1; } } return(new List <string>(possibleAvailabilityZoneRegionCombinationVmCount.Keys)); }
public void AddEventsForPatient3ToTestTable() { var eventsTestTable = TestFactory.GetClientForTable("EventsTestTable"); // Delete rows of patient Id 3 if already exists TableQuery <Event> rangeQuery = new TableQuery <Event>(); rangeQuery.Where(TableQuery.GenerateFilterConditionForInt("PatientId", QueryComparisons.Equal, 3)); var existingEvents = eventsTestTable.ExecuteQuerySegmentedAsync(rangeQuery, null).GetAwaiter().GetResult(); if (existingEvents.Any()) { TableBatchOperation batchDeleteOperation = new TableBatchOperation(); foreach (var item in existingEvents) { batchDeleteOperation.Delete(item); } eventsTestTable.ExecuteBatchAsync(batchDeleteOperation).GetAwaiter().GetResult(); } // Insert 2 events for patient Id = 3 var rowId = Guid.NewGuid(); var testEvent1 = new Event { RowKey = rowId.ToString(), PartitionKey = "BookingAppointmentEvent", EventId = rowId, PatientId = 3, DoctorId = 1, EventDate = DateTime.Now, EventCreationDate = DateTime.Now, EventType = "Booking Appointment", IsConflicted = false, IsConflictShown = false, }; rowId = Guid.NewGuid(); var testEvent2 = new Event { RowKey = rowId.ToString(), PartitionKey = "BookingAppointmentEvent", EventId = rowId, PatientId = 3, DoctorId = 1, EventDate = DateTime.Now, EventCreationDate = DateTime.Now.AddMinutes(-6), EventType = "Booking Appointment", IsConflicted = false, IsConflictShown = false }; TableBatchOperation batchInsertOperation = new TableBatchOperation(); batchInsertOperation.Insert(testEvent1); batchInsertOperation.Insert(testEvent2); eventsTestTable.ExecuteBatchAsync(batchInsertOperation).GetAwaiter().GetResult(); }
/// <summary> /// Updates the last ratings places for all users. /// </summary> /// <returns></returns> public Task <OperationResult> UpdateLastRatingsPlaces() { return (_azureManager.UpdateEntitiesAsync( new TableQuery <UserAzure>().Where( TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.GreaterThan, 0)) .Select(new[] { "LastRatingPlace", "Points", "UpInRatingCurrentDays", "UpInRatingMaxDays" }), async users => { var orderedUsers = users.OrderByDescending(u => u.Points).ThenBy(u => u.LastRatingPlace).ToArray(); for (var index = 0; index < orderedUsers.Length; index++) { var user = orderedUsers[index]; if (index < user.LastRatingPlace) { user.UpInRatingCurrentDays = (user.UpInRatingCurrentDays ?? 0) + 1; if (user.UpInRatingMaxDays == null || user.UpInRatingCurrentDays > user.UpInRatingMaxDays) { user.UpInRatingMaxDays = user.UpInRatingCurrentDays; } } user.LastRatingPlace = index; await _azureManager.UpdateEntityAsync(user, replace: false); } })); }
public static IEnumerable <WebhookRegistrationEntity> GetAllWebhooksForBundleType(this CloudTable existingWebhooks, BundleTypes type, bool isUpdate) { var filter = TableQuery.CombineFilters( TypeEquals(type), TableOperators.And, TableQuery.GenerateFilterConditionForInt("WebhookType", QueryComparisons.Equal, (int)WebhookType.Discord) ); if (isUpdate) { filter = TableQuery.CombineFilters( filter, TableOperators.And, TableQuery.GenerateFilterConditionForBool("ShouldRecieveUpdates", QueryComparisons.Equal, true)); } var query = new TableQuery <WebhookRegistrationEntity>().Where(filter); TableContinuationToken token = null; do { // TODO: When we upgrade to C# 8.0, use await var queryResult = existingWebhooks.ExecuteQuerySegmentedAsync(query, token).GetAwaiter().GetResult(); foreach (var item in queryResult.Results) { yield return(item); } token = queryResult.ContinuationToken; } while (token != null); }
private static VehicleTE GetVTEByID(int id) { var queryResult = _Table.ExecuteQuery(new TableQuery <VehicleTE>() .Where(TableQuery.GenerateFilterConditionForInt("Id", QueryComparisons.Equal, id))); return(queryResult.FirstOrDefault()); }
public VotingSessionsViewModel GetSessionsForVoting() { var viewModel = new VotingSessionsViewModel(); var tableClient = GetTableClient(); var sessionTable = tableClient.GetTableReference(_sessionsTableName); var sessionQuery = (new TableQuery <SessionSubmission>()).Where( TableQuery.GenerateFilterConditionForInt("Status", QueryComparisons.Equal, 1)); var sessions = sessionTable.ExecuteQuery(sessionQuery).ToList(); foreach (var sessionSubmission in sessions) { var session = new VotingSubmissionViewModel(); session.SessionId = sessionSubmission.RowKey; session.SessionTitle = sessionSubmission.SessionTitle; session.SessionAbstract = sessionSubmission.SessionAbstract.FormatForHtml(); session.PresenterName = sessionSubmission.PresenterName; session.PresenterTwitterAlias = sessionSubmission.PresenterTwitterAlias; session.PresenterWebsite = sessionSubmission.PresenterWebsite; session.PresenterBio = sessionSubmission.PresenterBio; session.RecommendedAudience = sessionSubmission.RecommendedAudience; viewModel.SessionsToVoteFor.Add(session); } return(viewModel); }