public virtual void DeleteRemindingList(EntityCollection entities) { while (entities.Any()) { entities.First().Delete(); } }
public DateTime GetPreviousWorkingTimeIntervalEnd(DateTime registrationDateTime) { KeyValuePair <DateTime, DayInCalendar> foundDay = GetNearestNotWeekendDay(registrationDateTime, false); DayInCalendar day = foundDay.Value; DateTime dateTime = foundDay.Key; var esq = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "WorkingTimeInterval"); esq.AddColumn("To"); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "DayInCalendar", day.PrimaryColumnValue)); if (dateTime.TimeOfDay != TimeSpan.Zero) { esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.LessOrEqual, "To", dateTime.TimeOfDay)); } EntityCollection timeIntervals = esq.GetEntityCollection(UserConnection); if (!timeIntervals.Any()) { return(GetPreviousWorkingTimeIntervalEnd(dateTime.Date.AddDays(-1))); } return(dateTime.Date + timeIntervals.Max(d => d.GetTypedColumnValue <DateTime>("To").TimeOfDay)); }
/// <summary> /// Checks whether the <paramref name="queryDate"/> is excluded either for a tournament OR optionally for a round or team. /// If the excluded table row contains a <paramref name="roundId"/> or <paramref name="teamId"/>, it is NOT excluded for the tournament, /// but only for the team or round. /// </summary> /// <remarks> /// Same behavior as with <see cref="ExcludedMatchDateRepository.GetExcludedMatchDateAsync"/>. /// </remarks> /// <param name="queryDate">Date to test, whether it is excluded.</param> /// <param name="roundId">OR excluded on the round level. If <see langword="null" />, there is no round restriction.</param> /// <param name="teamId">OR excluded on the team level. If <see langword="null" />, there is no team restriction.</param> /// <returns>Returns <see langword="true"/>, if criteria match, else <see langword="false"/>.</returns> private bool IsExcludedDate(DateTime queryDate, long?roundId, long?teamId) { return // Excluded for the whole tournament... (_excludedMatchDateEntities.Any( excl => queryDate >= excl.DateFrom && queryDate <= excl.DateTo && excl.TournamentId == _tenantContext.TournamentContext.MatchPlanTournamentId && !excl.RoundId.HasValue && !excl.TeamId.HasValue) || // OR excluded for a round... _excludedMatchDateEntities.Any( excl => queryDate >= excl.DateFrom && queryDate <= excl.DateTo && excl.TournamentId == _tenantContext.TournamentContext.MatchPlanTournamentId && excl.RoundId.HasValue && roundId.HasValue && excl.RoundId == roundId) || // OR excluded for a team _excludedMatchDateEntities.Any( excl => queryDate >= excl.DateFrom && queryDate <= excl.DateTo && excl.TournamentId == _tenantContext.TournamentContext.MatchPlanTournamentId && excl.TeamId.HasValue && teamId.HasValue && excl.TeamId == teamId) ); }
public static void DeleteAll <TEntity>( this DbContext context, EntityCollection <TEntity> collection) where TEntity : class, IEntityWithRelationships { if (!collection.IsLoaded) { collection.Load( ); } while (collection.Any( )) { var entity = collection.First( ); context.Set <TEntity>( ).Remove(entity); } }
public static void DeleteHelper(EntityCollection <TEntity> entityCollection) { if (entityCollection != null && entityCollection.Any()) { using (var context = (entityCollection.FirstOrDefault() as ERP_Core.BaseEntityObject).GetContext() as TObjectContext) { DeleteHelper(context, entityCollection); } //Int32 count = entityCollection.Count(); //for (int i = 0; i < count; i++) //{ // Object entity = entityCollection.Skip(0).Take(1).Single(); // context.DeleteObject(entity); //} } }
/// <summary> /// Gets Search execution info from log /// </summary> /// <param name="schemaName">Schema name.</param> /// <returns>Instance <see cref="DuplicatesSearchResponse"/> results info search process execution.</returns> public virtual DuplicatesSearchResponse GetInfo(string schemaName) { DuplicatesSearchResponse result = new DuplicatesSearchResponse(); var esq = new EntitySchemaQuery(_userConnection.EntitySchemaManager, "DeduplicateExecLocker"); esq.PrimaryQueryColumn.IsAlwaysSelect = true; esq.AddColumn(esq.RootSchema.GetPrimaryColumnName()); EntitySchemaQueryColumn completedOnColumn = esq.AddColumn("Conversation.ExecutedOn"); EntitySchemaQueryColumn isInProgressColumn = esq.AddColumn("IsInProgress"); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "EntitySchemaName", new object[] { schemaName })); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Operation", new object[] { DeduplicationConsts.SearchOperationId })); EntityCollection esqCollection = esq.GetEntityCollection(_userConnection); bool isExists = CheckExistsSearchDuplicatesJob(schemaName); if (esqCollection.Any()) { Entity entity = esqCollection[0]; bool isInProgress = entity.GetTypedColumnValue <bool>(isInProgressColumn.Name) || isExists; DateTime completedOnValue = entity.GetTypedColumnValue <DateTime>(completedOnColumn.Name); result.Success = true; result.Response = new Dictionary <string, string>() { { "LastExecutionDate", DateTimeDataValueType.Serialize(completedOnValue, TimeZoneInfo.Utc) }, { "IsInProgress", JsonConvert.SerializeObject(isInProgress) } }; } else { if (isExists) { result.Success = true; result.Response = new Dictionary <string, string>() { { "IsInProgress", JsonConvert.SerializeObject(true) } }; } } return(result); }
public DateTime GetNextWorkingTimeIntervalStart(DateTime registrationDateTime) { KeyValuePair <DateTime, DayInCalendar> foundDay = GetNearestNotWeekendDay(registrationDateTime); DayInCalendar day = foundDay.Value; DateTime dateTime = foundDay.Key; var esq = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "WorkingTimeInterval"); esq.AddColumn("From"); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "DayInCalendar", day.PrimaryColumnValue)); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.GreaterOrEqual, "From", dateTime.TimeOfDay)); EntityCollection timeIntervals = esq.GetEntityCollection(UserConnection); if (!timeIntervals.Any()) { return(GetNextWorkingTimeIntervalStart(dateTime.Date.AddDays(1))); } return(dateTime.Date + timeIntervals.Min(d => d.GetTypedColumnValue <DateTime>("From").TimeOfDay)); }
private static void AddDynamicGroupFilters( IDictionary <string, Guid> localFolderUIds, UserConnection userConnection, EntitySchemaQueryFilterCollection filters) { if (!localFolderUIds.Any()) { return; } EntitySchemaManager entitySchemaManager = userConnection.EntitySchemaManager; var foldersEsq = new EntitySchemaQuery(entitySchemaManager, "ActivityFolder"); string searchDataColumnName = foldersEsq.AddColumn("SearchData").Name; string[] folderIdsStrArray = (from folderId in localFolderUIds.Values select folderId.ToString()).ToArray(); foldersEsq.Filters.Add(foldersEsq.CreateFilterWithParameters(FilterComparisonType.Equal, false, "Id", folderIdsStrArray)); EntityCollection folderEntities = foldersEsq.GetEntityCollection(userConnection); if (!folderEntities.Any()) { return; } EntitySchema entitySchema = entitySchemaManager.GetInstanceByName("Activity"); Guid schemaUId = entitySchema.UId; foreach (Entity folderEntity in folderEntities) { byte[] data = folderEntity.GetBytesValue(searchDataColumnName); string serializedFilters = Encoding.UTF8.GetString(data, 0, data.Length); var dataSourceFilters = Json.Deserialize <Terrasoft.Nui.ServiceModel.DataContract.Filters>( serializedFilters); IEntitySchemaQueryFilterItem esqFilters = dataSourceFilters.BuildEsqFilter(schemaUId, userConnection); if (esqFilters != null) { filters.Add(esqFilters); } } }
/// <summary> /// Generates round match combinations for the Round Robin system, /// assigns optimized match dates and stores the matches to /// the persistent storage. /// </summary> public async Task GenerateFixturesForRound(RoundEntity round, bool keepExisting, CancellationToken cancellationToken) { if (!AreEntitiesLoaded) { await LoadEntitiesAsync(cancellationToken); } round = _tournament.Rounds.First(r => r.Id == round.Id); if (_appDb.MatchRepository.AnyCompleteMatchesExist(round)) { throw new Exception($"Completed matches exist for round '{round.Id}'. Generating fixtures aborted."); } // generated matches will be stored here var roundMatches = new EntityCollection <MatchEntity>(); if (keepExisting) { roundMatches = _appDb.MatchRepository.GetMatches(round); } else { var bucket = new RelationPredicateBucket(new PredicateExpression( new FieldCompareRangePredicate(MatchFields.RoundId, null, false, new[] { round.Id }))); await _appDb.GenericRepository.DeleteEntitiesDirectlyAsync(typeof(MatchEntity), bucket, cancellationToken); } await GenerateAvailableMatchDatesAsync(ClearMatchDates.OnlyAutoGenerated, round, cancellationToken); // get the team ids because TeamEntity lacks IComparable // and cannot be used directly var teams = new Collection <long>(round.TeamCollectionViaTeamInRound.Select(t => t.Id).ToList()); // now calculate matches for each leg of a round foreach (var roundLeg in round.RoundLegs) { // build up match combinations for the teams of round var roundRobin = new RoundRobinSystem <long>(teams); var bundledGroups = roundRobin.GetBundledGroups(RefereeType.HomeTeam, roundLeg.SequenceNo % 2 == 1 ? LegType.First : LegType.Return, CombinationGroupOptimization.GroupWithAlternatingHomeGuest); /* * Special treatment for teams which do not have home matches */ foreach (var teamCombinationGroup in bundledGroups) { foreach (var combination in teamCombinationGroup) { if (!TeamsWithoutHomeMatches.Contains(combination.HomeTeam)) { continue; } // swap home and guest team, keep referee unchanged (combination.HomeTeam, combination.GuestTeam) = (combination.GuestTeam, combination.HomeTeam); } } /* * Assign desired from/to dates to bundled groups for later orientation * in which period matches should take place */ AssignRoundDatePeriods(roundLeg, bundledGroups); if (bundledGroups.Any(g => !g.DateTimePeriod.Start.HasValue)) { throw new Exception( "Not all bundled groups got a date period assigned. Probably not enough dates available for assignment."); } // process each team combination (match) that shall take place in the same week (if possible) foreach (var teamCombinationGroup in bundledGroups) { // get match dates for every combination of a group. // matches in the same teamCombinationGroup can even take place on the same day. // matchDates contains calculated dates in the same order as combinations, // so the index can be used for both. var availableDates = GetMatchDates(roundLeg, teamCombinationGroup, roundMatches); _logger.LogTrace("Selected dates: {0}", string.Join(", ", availableDates.OrderBy(bd => bd?.MatchStartTime).Select(bd => bd?.MatchStartTime.ToShortDateString())).TrimEnd(',', ' ')); for (var index = 0; index < teamCombinationGroup.Count; index++) { var combination = teamCombinationGroup[index]; // If existing matches were loaded from database, we have to skip such combinations! // Note: Home team and guest team of combinations could have been swapped for TeamsWithoutHomeMatches if (roundMatches.Any(rm => rm.HomeTeamId == combination.HomeTeam && rm.GuestTeamId == combination.GuestTeam && rm.LegSequenceNo == roundLeg.SequenceNo || rm.GuestTeamId == combination.HomeTeam && rm.HomeTeamId == combination.GuestTeam && rm.LegSequenceNo == roundLeg.SequenceNo)) { continue; } var match = new MatchEntity { HomeTeamId = combination.HomeTeam, GuestTeamId = combination.GuestTeam, RefereeId = combination.Referee, PlannedStart = availableDates[index] != null ? availableDates[index] !.MatchStartTime : default(DateTime?), PlannedEnd = availableDates[index] != null ? availableDates[index] !.MatchStartTime .Add(_tenantContext.TournamentContext.FixtureRuleSet.PlannedDurationOfMatch) : default(DateTime?), VenueId = availableDates[index] != null ? availableDates[index] !.VenueId // take over the venue stored in the team entity (may also be null!) : _tournament.Rounds[_tournament.Rounds.FindMatches(RoundFields.Id == roundLeg.RoundId).First()].TeamCollectionViaTeamInRound.First(t => t.Id == combination.HomeTeam).VenueId, RoundId = round.Id, IsComplete = false, LegSequenceNo = roundLeg.SequenceNo, ChangeSerial = 0, Remarks = string.Empty }; roundMatches.Add(match); } } } // save the matches for the group await _appDb.GenericRepository.SaveEntitiesAsync(roundMatches, true, false, cancellationToken); await _availableMatchDates.ClearAsync(ClearMatchDates.OnlyAutoGenerated, cancellationToken); }